bundle.js 2.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029
  1. (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){
  2. "use strict";
  3. module.exports = asPromise;
  4. /**
  5. * Callback as used by {@link util.asPromise}.
  6. * @typedef asPromiseCallback
  7. * @type {function}
  8. * @param {Error|null} error Error, if any
  9. * @param {...*} params Additional arguments
  10. * @returns {undefined}
  11. */
  12. /**
  13. * Returns a promise from a node-style callback function.
  14. * @memberof util
  15. * @param {asPromiseCallback} fn Function to call
  16. * @param {*} ctx Function context
  17. * @param {...*} params Function arguments
  18. * @returns {Promise<*>} Promisified function
  19. */
  20. function asPromise(fn, ctx/*, varargs */) {
  21. var params = new Array(arguments.length - 1),
  22. offset = 0,
  23. index = 2,
  24. pending = true;
  25. while (index < arguments.length)
  26. params[offset++] = arguments[index++];
  27. return new Promise(function executor(resolve, reject) {
  28. params[offset] = function callback(err/*, varargs */) {
  29. if (pending) {
  30. pending = false;
  31. if (err)
  32. reject(err);
  33. else {
  34. var params = new Array(arguments.length - 1),
  35. offset = 0;
  36. while (offset < params.length)
  37. params[offset++] = arguments[offset];
  38. resolve.apply(null, params);
  39. }
  40. }
  41. };
  42. try {
  43. fn.apply(ctx || null, params);
  44. } catch (err) {
  45. if (pending) {
  46. pending = false;
  47. reject(err);
  48. }
  49. }
  50. });
  51. }
  52. },{}],2:[function(require,module,exports){
  53. "use strict";
  54. /**
  55. * A minimal base64 implementation for number arrays.
  56. * @memberof util
  57. * @namespace
  58. */
  59. var base64 = exports;
  60. /**
  61. * Calculates the byte length of a base64 encoded string.
  62. * @param {string} string Base64 encoded string
  63. * @returns {number} Byte length
  64. */
  65. base64.length = function length(string) {
  66. var p = string.length;
  67. if (!p)
  68. return 0;
  69. var n = 0;
  70. while (--p % 4 > 1 && string.charAt(p) === "=")
  71. ++n;
  72. return Math.ceil(string.length * 3) / 4 - n;
  73. };
  74. // Base64 encoding table
  75. var b64 = new Array(64);
  76. // Base64 decoding table
  77. var s64 = new Array(123);
  78. // 65..90, 97..122, 48..57, 43, 47
  79. for (var i = 0; i < 64;)
  80. s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
  81. /**
  82. * Encodes a buffer to a base64 encoded string.
  83. * @param {Uint8Array} buffer Source buffer
  84. * @param {number} start Source start
  85. * @param {number} end Source end
  86. * @returns {string} Base64 encoded string
  87. */
  88. base64.encode = function encode(buffer, start, end) {
  89. var parts = null,
  90. chunk = [];
  91. var i = 0, // output index
  92. j = 0, // goto index
  93. t; // temporary
  94. while (start < end) {
  95. var b = buffer[start++];
  96. switch (j) {
  97. case 0:
  98. chunk[i++] = b64[b >> 2];
  99. t = (b & 3) << 4;
  100. j = 1;
  101. break;
  102. case 1:
  103. chunk[i++] = b64[t | b >> 4];
  104. t = (b & 15) << 2;
  105. j = 2;
  106. break;
  107. case 2:
  108. chunk[i++] = b64[t | b >> 6];
  109. chunk[i++] = b64[b & 63];
  110. j = 0;
  111. break;
  112. }
  113. if (i > 8191) {
  114. (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
  115. i = 0;
  116. }
  117. }
  118. if (j) {
  119. chunk[i++] = b64[t];
  120. chunk[i++] = 61;
  121. if (j === 1)
  122. chunk[i++] = 61;
  123. }
  124. if (parts) {
  125. if (i)
  126. parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
  127. return parts.join("");
  128. }
  129. return String.fromCharCode.apply(String, chunk.slice(0, i));
  130. };
  131. var invalidEncoding = "invalid encoding";
  132. /**
  133. * Decodes a base64 encoded string to a buffer.
  134. * @param {string} string Source string
  135. * @param {Uint8Array} buffer Destination buffer
  136. * @param {number} offset Destination offset
  137. * @returns {number} Number of bytes written
  138. * @throws {Error} If encoding is invalid
  139. */
  140. base64.decode = function decode(string, buffer, offset) {
  141. var start = offset;
  142. var j = 0, // goto index
  143. t; // temporary
  144. for (var i = 0; i < string.length;) {
  145. var c = string.charCodeAt(i++);
  146. if (c === 61 && j > 1)
  147. break;
  148. if ((c = s64[c]) === undefined)
  149. throw Error(invalidEncoding);
  150. switch (j) {
  151. case 0:
  152. t = c;
  153. j = 1;
  154. break;
  155. case 1:
  156. buffer[offset++] = t << 2 | (c & 48) >> 4;
  157. t = c;
  158. j = 2;
  159. break;
  160. case 2:
  161. buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
  162. t = c;
  163. j = 3;
  164. break;
  165. case 3:
  166. buffer[offset++] = (t & 3) << 6 | c;
  167. j = 0;
  168. break;
  169. }
  170. }
  171. if (j === 1)
  172. throw Error(invalidEncoding);
  173. return offset - start;
  174. };
  175. /**
  176. * Tests if the specified string appears to be base64 encoded.
  177. * @param {string} string String to test
  178. * @returns {boolean} `true` if probably base64 encoded, otherwise false
  179. */
  180. base64.test = function test(string) {
  181. return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
  182. };
  183. },{}],3:[function(require,module,exports){
  184. "use strict";
  185. module.exports = EventEmitter;
  186. /**
  187. * Constructs a new event emitter instance.
  188. * @classdesc A minimal event emitter.
  189. * @memberof util
  190. * @constructor
  191. */
  192. function EventEmitter() {
  193. /**
  194. * Registered listeners.
  195. * @type {Object.<string,*>}
  196. * @private
  197. */
  198. this._listeners = {};
  199. }
  200. /**
  201. * Registers an event listener.
  202. * @param {string} evt Event name
  203. * @param {function} fn Listener
  204. * @param {*} [ctx] Listener context
  205. * @returns {util.EventEmitter} `this`
  206. */
  207. EventEmitter.prototype.on = function on(evt, fn, ctx) {
  208. (this._listeners[evt] || (this._listeners[evt] = [])).push({
  209. fn : fn,
  210. ctx : ctx || this
  211. });
  212. return this;
  213. };
  214. /**
  215. * Removes an event listener or any matching listeners if arguments are omitted.
  216. * @param {string} [evt] Event name. Removes all listeners if omitted.
  217. * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
  218. * @returns {util.EventEmitter} `this`
  219. */
  220. EventEmitter.prototype.off = function off(evt, fn) {
  221. if (evt === undefined)
  222. this._listeners = {};
  223. else {
  224. if (fn === undefined)
  225. this._listeners[evt] = [];
  226. else {
  227. var listeners = this._listeners[evt];
  228. for (var i = 0; i < listeners.length;)
  229. if (listeners[i].fn === fn)
  230. listeners.splice(i, 1);
  231. else
  232. ++i;
  233. }
  234. }
  235. return this;
  236. };
  237. /**
  238. * Emits an event by calling its listeners with the specified arguments.
  239. * @param {string} evt Event name
  240. * @param {...*} args Arguments
  241. * @returns {util.EventEmitter} `this`
  242. */
  243. EventEmitter.prototype.emit = function emit(evt) {
  244. var listeners = this._listeners[evt];
  245. if (listeners) {
  246. var args = [],
  247. i = 1;
  248. for (; i < arguments.length;)
  249. args.push(arguments[i++]);
  250. for (i = 0; i < listeners.length;)
  251. listeners[i].fn.apply(listeners[i++].ctx, args);
  252. }
  253. return this;
  254. };
  255. },{}],4:[function(require,module,exports){
  256. "use strict";
  257. module.exports = factory(factory);
  258. /**
  259. * Reads / writes floats / doubles from / to buffers.
  260. * @name util.float
  261. * @namespace
  262. */
  263. /**
  264. * Writes a 32 bit float to a buffer using little endian byte order.
  265. * @name util.float.writeFloatLE
  266. * @function
  267. * @param {number} val Value to write
  268. * @param {Uint8Array} buf Target buffer
  269. * @param {number} pos Target buffer offset
  270. * @returns {undefined}
  271. */
  272. /**
  273. * Writes a 32 bit float to a buffer using big endian byte order.
  274. * @name util.float.writeFloatBE
  275. * @function
  276. * @param {number} val Value to write
  277. * @param {Uint8Array} buf Target buffer
  278. * @param {number} pos Target buffer offset
  279. * @returns {undefined}
  280. */
  281. /**
  282. * Reads a 32 bit float from a buffer using little endian byte order.
  283. * @name util.float.readFloatLE
  284. * @function
  285. * @param {Uint8Array} buf Source buffer
  286. * @param {number} pos Source buffer offset
  287. * @returns {number} Value read
  288. */
  289. /**
  290. * Reads a 32 bit float from a buffer using big endian byte order.
  291. * @name util.float.readFloatBE
  292. * @function
  293. * @param {Uint8Array} buf Source buffer
  294. * @param {number} pos Source buffer offset
  295. * @returns {number} Value read
  296. */
  297. /**
  298. * Writes a 64 bit double to a buffer using little endian byte order.
  299. * @name util.float.writeDoubleLE
  300. * @function
  301. * @param {number} val Value to write
  302. * @param {Uint8Array} buf Target buffer
  303. * @param {number} pos Target buffer offset
  304. * @returns {undefined}
  305. */
  306. /**
  307. * Writes a 64 bit double to a buffer using big endian byte order.
  308. * @name util.float.writeDoubleBE
  309. * @function
  310. * @param {number} val Value to write
  311. * @param {Uint8Array} buf Target buffer
  312. * @param {number} pos Target buffer offset
  313. * @returns {undefined}
  314. */
  315. /**
  316. * Reads a 64 bit double from a buffer using little endian byte order.
  317. * @name util.float.readDoubleLE
  318. * @function
  319. * @param {Uint8Array} buf Source buffer
  320. * @param {number} pos Source buffer offset
  321. * @returns {number} Value read
  322. */
  323. /**
  324. * Reads a 64 bit double from a buffer using big endian byte order.
  325. * @name util.float.readDoubleBE
  326. * @function
  327. * @param {Uint8Array} buf Source buffer
  328. * @param {number} pos Source buffer offset
  329. * @returns {number} Value read
  330. */
  331. // Factory function for the purpose of node-based testing in modified global environments
  332. function factory(exports) {
  333. // float: typed array
  334. if (typeof Float32Array !== "undefined") (function() {
  335. var f32 = new Float32Array([ -0 ]),
  336. f8b = new Uint8Array(f32.buffer),
  337. le = f8b[3] === 128;
  338. function writeFloat_f32_cpy(val, buf, pos) {
  339. f32[0] = val;
  340. buf[pos ] = f8b[0];
  341. buf[pos + 1] = f8b[1];
  342. buf[pos + 2] = f8b[2];
  343. buf[pos + 3] = f8b[3];
  344. }
  345. function writeFloat_f32_rev(val, buf, pos) {
  346. f32[0] = val;
  347. buf[pos ] = f8b[3];
  348. buf[pos + 1] = f8b[2];
  349. buf[pos + 2] = f8b[1];
  350. buf[pos + 3] = f8b[0];
  351. }
  352. /* istanbul ignore next */
  353. exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
  354. /* istanbul ignore next */
  355. exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
  356. function readFloat_f32_cpy(buf, pos) {
  357. f8b[0] = buf[pos ];
  358. f8b[1] = buf[pos + 1];
  359. f8b[2] = buf[pos + 2];
  360. f8b[3] = buf[pos + 3];
  361. return f32[0];
  362. }
  363. function readFloat_f32_rev(buf, pos) {
  364. f8b[3] = buf[pos ];
  365. f8b[2] = buf[pos + 1];
  366. f8b[1] = buf[pos + 2];
  367. f8b[0] = buf[pos + 3];
  368. return f32[0];
  369. }
  370. /* istanbul ignore next */
  371. exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
  372. /* istanbul ignore next */
  373. exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
  374. // float: ieee754
  375. })(); else (function() {
  376. function writeFloat_ieee754(writeUint, val, buf, pos) {
  377. var sign = val < 0 ? 1 : 0;
  378. if (sign)
  379. val = -val;
  380. if (val === 0)
  381. writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
  382. else if (isNaN(val))
  383. writeUint(2143289344, buf, pos);
  384. else if (val > 3.4028234663852886e+38) // +-Infinity
  385. writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
  386. else if (val < 1.1754943508222875e-38) // denormal
  387. writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
  388. else {
  389. var exponent = Math.floor(Math.log(val) / Math.LN2),
  390. mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
  391. writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
  392. }
  393. }
  394. exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
  395. exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
  396. function readFloat_ieee754(readUint, buf, pos) {
  397. var uint = readUint(buf, pos),
  398. sign = (uint >> 31) * 2 + 1,
  399. exponent = uint >>> 23 & 255,
  400. mantissa = uint & 8388607;
  401. return exponent === 255
  402. ? mantissa
  403. ? NaN
  404. : sign * Infinity
  405. : exponent === 0 // denormal
  406. ? sign * 1.401298464324817e-45 * mantissa
  407. : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
  408. }
  409. exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
  410. exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
  411. })();
  412. // double: typed array
  413. if (typeof Float64Array !== "undefined") (function() {
  414. var f64 = new Float64Array([-0]),
  415. f8b = new Uint8Array(f64.buffer),
  416. le = f8b[7] === 128;
  417. function writeDouble_f64_cpy(val, buf, pos) {
  418. f64[0] = val;
  419. buf[pos ] = f8b[0];
  420. buf[pos + 1] = f8b[1];
  421. buf[pos + 2] = f8b[2];
  422. buf[pos + 3] = f8b[3];
  423. buf[pos + 4] = f8b[4];
  424. buf[pos + 5] = f8b[5];
  425. buf[pos + 6] = f8b[6];
  426. buf[pos + 7] = f8b[7];
  427. }
  428. function writeDouble_f64_rev(val, buf, pos) {
  429. f64[0] = val;
  430. buf[pos ] = f8b[7];
  431. buf[pos + 1] = f8b[6];
  432. buf[pos + 2] = f8b[5];
  433. buf[pos + 3] = f8b[4];
  434. buf[pos + 4] = f8b[3];
  435. buf[pos + 5] = f8b[2];
  436. buf[pos + 6] = f8b[1];
  437. buf[pos + 7] = f8b[0];
  438. }
  439. /* istanbul ignore next */
  440. exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
  441. /* istanbul ignore next */
  442. exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
  443. function readDouble_f64_cpy(buf, pos) {
  444. f8b[0] = buf[pos ];
  445. f8b[1] = buf[pos + 1];
  446. f8b[2] = buf[pos + 2];
  447. f8b[3] = buf[pos + 3];
  448. f8b[4] = buf[pos + 4];
  449. f8b[5] = buf[pos + 5];
  450. f8b[6] = buf[pos + 6];
  451. f8b[7] = buf[pos + 7];
  452. return f64[0];
  453. }
  454. function readDouble_f64_rev(buf, pos) {
  455. f8b[7] = buf[pos ];
  456. f8b[6] = buf[pos + 1];
  457. f8b[5] = buf[pos + 2];
  458. f8b[4] = buf[pos + 3];
  459. f8b[3] = buf[pos + 4];
  460. f8b[2] = buf[pos + 5];
  461. f8b[1] = buf[pos + 6];
  462. f8b[0] = buf[pos + 7];
  463. return f64[0];
  464. }
  465. /* istanbul ignore next */
  466. exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
  467. /* istanbul ignore next */
  468. exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
  469. // double: ieee754
  470. })(); else (function() {
  471. function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
  472. var sign = val < 0 ? 1 : 0;
  473. if (sign)
  474. val = -val;
  475. if (val === 0) {
  476. writeUint(0, buf, pos + off0);
  477. writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
  478. } else if (isNaN(val)) {
  479. writeUint(0, buf, pos + off0);
  480. writeUint(2146959360, buf, pos + off1);
  481. } else if (val > 1.7976931348623157e+308) { // +-Infinity
  482. writeUint(0, buf, pos + off0);
  483. writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
  484. } else {
  485. var mantissa;
  486. if (val < 2.2250738585072014e-308) { // denormal
  487. mantissa = val / 5e-324;
  488. writeUint(mantissa >>> 0, buf, pos + off0);
  489. writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
  490. } else {
  491. var exponent = Math.floor(Math.log(val) / Math.LN2);
  492. if (exponent === 1024)
  493. exponent = 1023;
  494. mantissa = val * Math.pow(2, -exponent);
  495. writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
  496. writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
  497. }
  498. }
  499. }
  500. exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
  501. exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
  502. function readDouble_ieee754(readUint, off0, off1, buf, pos) {
  503. var lo = readUint(buf, pos + off0),
  504. hi = readUint(buf, pos + off1);
  505. var sign = (hi >> 31) * 2 + 1,
  506. exponent = hi >>> 20 & 2047,
  507. mantissa = 4294967296 * (hi & 1048575) + lo;
  508. return exponent === 2047
  509. ? mantissa
  510. ? NaN
  511. : sign * Infinity
  512. : exponent === 0 // denormal
  513. ? sign * 5e-324 * mantissa
  514. : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
  515. }
  516. exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
  517. exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
  518. })();
  519. return exports;
  520. }
  521. // uint helpers
  522. function writeUintLE(val, buf, pos) {
  523. buf[pos ] = val & 255;
  524. buf[pos + 1] = val >>> 8 & 255;
  525. buf[pos + 2] = val >>> 16 & 255;
  526. buf[pos + 3] = val >>> 24;
  527. }
  528. function writeUintBE(val, buf, pos) {
  529. buf[pos ] = val >>> 24;
  530. buf[pos + 1] = val >>> 16 & 255;
  531. buf[pos + 2] = val >>> 8 & 255;
  532. buf[pos + 3] = val & 255;
  533. }
  534. function readUintLE(buf, pos) {
  535. return (buf[pos ]
  536. | buf[pos + 1] << 8
  537. | buf[pos + 2] << 16
  538. | buf[pos + 3] << 24) >>> 0;
  539. }
  540. function readUintBE(buf, pos) {
  541. return (buf[pos ] << 24
  542. | buf[pos + 1] << 16
  543. | buf[pos + 2] << 8
  544. | buf[pos + 3]) >>> 0;
  545. }
  546. },{}],5:[function(require,module,exports){
  547. "use strict";
  548. module.exports = inquire;
  549. /**
  550. * Requires a module only if available.
  551. * @memberof util
  552. * @param {string} moduleName Module to require
  553. * @returns {?Object} Required module if available and not empty, otherwise `null`
  554. */
  555. function inquire(moduleName) {
  556. try {
  557. var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval
  558. if (mod && (mod.length || Object.keys(mod).length))
  559. return mod;
  560. } catch (e) {} // eslint-disable-line no-empty
  561. return null;
  562. }
  563. },{}],6:[function(require,module,exports){
  564. "use strict";
  565. module.exports = pool;
  566. /**
  567. * An allocator as used by {@link util.pool}.
  568. * @typedef PoolAllocator
  569. * @type {function}
  570. * @param {number} size Buffer size
  571. * @returns {Uint8Array} Buffer
  572. */
  573. /**
  574. * A slicer as used by {@link util.pool}.
  575. * @typedef PoolSlicer
  576. * @type {function}
  577. * @param {number} start Start offset
  578. * @param {number} end End offset
  579. * @returns {Uint8Array} Buffer slice
  580. * @this {Uint8Array}
  581. */
  582. /**
  583. * A general purpose buffer pool.
  584. * @memberof util
  585. * @function
  586. * @param {PoolAllocator} alloc Allocator
  587. * @param {PoolSlicer} slice Slicer
  588. * @param {number} [size=8192] Slab size
  589. * @returns {PoolAllocator} Pooled allocator
  590. */
  591. function pool(alloc, slice, size) {
  592. var SIZE = size || 8192;
  593. var MAX = SIZE >>> 1;
  594. var slab = null;
  595. var offset = SIZE;
  596. return function pool_alloc(size) {
  597. if (size < 1 || size > MAX)
  598. return alloc(size);
  599. if (offset + size > SIZE) {
  600. slab = alloc(SIZE);
  601. offset = 0;
  602. }
  603. var buf = slice.call(slab, offset, offset += size);
  604. if (offset & 7) // align to 32 bit
  605. offset = (offset | 7) + 1;
  606. return buf;
  607. };
  608. }
  609. },{}],7:[function(require,module,exports){
  610. "use strict";
  611. /**
  612. * A minimal UTF8 implementation for number arrays.
  613. * @memberof util
  614. * @namespace
  615. */
  616. var utf8 = exports;
  617. /**
  618. * Calculates the UTF8 byte length of a string.
  619. * @param {string} string String
  620. * @returns {number} Byte length
  621. */
  622. utf8.length = function utf8_length(string) {
  623. var len = 0,
  624. c = 0;
  625. for (var i = 0; i < string.length; ++i) {
  626. c = string.charCodeAt(i);
  627. if (c < 128)
  628. len += 1;
  629. else if (c < 2048)
  630. len += 2;
  631. else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
  632. ++i;
  633. len += 4;
  634. } else
  635. len += 3;
  636. }
  637. return len;
  638. };
  639. /**
  640. * Reads UTF8 bytes as a string.
  641. * @param {Uint8Array} buffer Source buffer
  642. * @param {number} start Source start
  643. * @param {number} end Source end
  644. * @returns {string} String read
  645. */
  646. utf8.read = function utf8_read(buffer, start, end) {
  647. var len = end - start;
  648. if (len < 1)
  649. return "";
  650. var parts = null,
  651. chunk = [],
  652. i = 0, // char offset
  653. t; // temporary
  654. while (start < end) {
  655. t = buffer[start++];
  656. if (t < 128)
  657. chunk[i++] = t;
  658. else if (t > 191 && t < 224)
  659. chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
  660. else if (t > 239 && t < 365) {
  661. t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
  662. chunk[i++] = 0xD800 + (t >> 10);
  663. chunk[i++] = 0xDC00 + (t & 1023);
  664. } else
  665. chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
  666. if (i > 8191) {
  667. (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
  668. i = 0;
  669. }
  670. }
  671. if (parts) {
  672. if (i)
  673. parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
  674. return parts.join("");
  675. }
  676. return String.fromCharCode.apply(String, chunk.slice(0, i));
  677. };
  678. /**
  679. * Writes a string as UTF8 bytes.
  680. * @param {string} string Source string
  681. * @param {Uint8Array} buffer Destination buffer
  682. * @param {number} offset Destination offset
  683. * @returns {number} Bytes written
  684. */
  685. utf8.write = function utf8_write(string, buffer, offset) {
  686. var start = offset,
  687. c1, // character 1
  688. c2; // character 2
  689. for (var i = 0; i < string.length; ++i) {
  690. c1 = string.charCodeAt(i);
  691. if (c1 < 128) {
  692. buffer[offset++] = c1;
  693. } else if (c1 < 2048) {
  694. buffer[offset++] = c1 >> 6 | 192;
  695. buffer[offset++] = c1 & 63 | 128;
  696. } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
  697. c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
  698. ++i;
  699. buffer[offset++] = c1 >> 18 | 240;
  700. buffer[offset++] = c1 >> 12 & 63 | 128;
  701. buffer[offset++] = c1 >> 6 & 63 | 128;
  702. buffer[offset++] = c1 & 63 | 128;
  703. } else {
  704. buffer[offset++] = c1 >> 12 | 224;
  705. buffer[offset++] = c1 >> 6 & 63 | 128;
  706. buffer[offset++] = c1 & 63 | 128;
  707. }
  708. }
  709. return offset - start;
  710. };
  711. },{}],8:[function(require,module,exports){
  712. "use strict";
  713. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  714. return new (P || (P = Promise))(function (resolve, reject) {
  715. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  716. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  717. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  718. step((generator = generator.apply(thisArg, _arguments || [])).next());
  719. });
  720. };
  721. var __generator = (this && this.__generator) || function (thisArg, body) {
  722. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  723. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  724. function verb(n) { return function (v) { return step([n, v]); }; }
  725. function step(op) {
  726. if (f) throw new TypeError("Generator is already executing.");
  727. while (_) try {
  728. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  729. if (y = 0, t) op = [op[0] & 2, t.value];
  730. switch (op[0]) {
  731. case 0: case 1: t = op; break;
  732. case 4: _.label++; return { value: op[1], done: false };
  733. case 5: _.label++; y = op[1]; op = [0]; continue;
  734. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  735. default:
  736. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  737. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  738. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  739. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  740. if (t[2]) _.ops.pop();
  741. _.trys.pop(); continue;
  742. }
  743. op = body.call(thisArg, _);
  744. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  745. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  746. }
  747. };
  748. Object.defineProperty(exports, "__esModule", { value: true });
  749. var tf = require("@tensorflow/tfjs");
  750. var tfjs_1 = require("@tensorflow/tfjs");
  751. var util_1 = require("./util");
  752. var KNNClassifier = (function () {
  753. function KNNClassifier() {
  754. this.classDatasetMatrices = {};
  755. this.classExampleCount = {};
  756. }
  757. KNNClassifier.prototype.addExample = function (example, classIndex) {
  758. var _this = this;
  759. if (this.exampleShape == null) {
  760. this.exampleShape = example.shape;
  761. }
  762. if (!tfjs_1.util.arraysEqual(this.exampleShape, example.shape)) {
  763. throw new Error("Example shape provided, " + example.shape + " does not match " +
  764. ("previously provided example shapes " + this.exampleShape + "."));
  765. }
  766. if (!Number.isInteger(classIndex)) {
  767. throw new Error("classIndex must be an integer, got " + classIndex + ".");
  768. }
  769. this.clearTrainDatasetMatrix();
  770. tf.tidy(function () {
  771. var normalizedExample = _this.normalizeVectorToUnitLength(example.flatten());
  772. var exampleSize = normalizedExample.shape[0];
  773. if (_this.classDatasetMatrices[classIndex] == null) {
  774. _this.classDatasetMatrices[classIndex] =
  775. normalizedExample.as2D(1, exampleSize);
  776. }
  777. else {
  778. var newTrainLogitsMatrix = _this.classDatasetMatrices[classIndex]
  779. .as2D(_this.classExampleCount[classIndex], exampleSize)
  780. .concat(normalizedExample.as2D(1, exampleSize), 0);
  781. _this.classDatasetMatrices[classIndex].dispose();
  782. _this.classDatasetMatrices[classIndex] = newTrainLogitsMatrix;
  783. }
  784. tf.keep(_this.classDatasetMatrices[classIndex]);
  785. if (_this.classExampleCount[classIndex] == null) {
  786. _this.classExampleCount[classIndex] = 0;
  787. }
  788. _this.classExampleCount[classIndex]++;
  789. });
  790. };
  791. KNNClassifier.prototype.similarities = function (input) {
  792. var _this = this;
  793. return tf.tidy(function () {
  794. var normalizedExample = _this.normalizeVectorToUnitLength(input.flatten());
  795. var exampleSize = normalizedExample.shape[0];
  796. if (_this.trainDatasetMatrix == null) {
  797. var newTrainLogitsMatrix = null;
  798. for (var i in _this.classDatasetMatrices) {
  799. newTrainLogitsMatrix = util_1.concatWithNulls(newTrainLogitsMatrix, _this.classDatasetMatrices[i]);
  800. }
  801. _this.trainDatasetMatrix = newTrainLogitsMatrix;
  802. }
  803. if (_this.trainDatasetMatrix == null) {
  804. console.warn('Cannot predict without providing training examples.');
  805. return null;
  806. }
  807. tf.keep(_this.trainDatasetMatrix);
  808. var numExamples = _this.getNumExamples();
  809. return _this.trainDatasetMatrix.as2D(numExamples, exampleSize)
  810. .matMul(normalizedExample.as2D(exampleSize, 1))
  811. .as1D();
  812. });
  813. };
  814. KNNClassifier.prototype.predictClass = function (input, k) {
  815. if (k === void 0) { k = 3; }
  816. return __awaiter(this, void 0, void 0, function () {
  817. var knn, kVal, topKIndices, _a;
  818. var _this = this;
  819. return __generator(this, function (_b) {
  820. switch (_b.label) {
  821. case 0:
  822. if (k < 1) {
  823. throw new Error("Please provide a positive integer k value to predictClass.");
  824. }
  825. knn = tf.tidy(function () { return _this.similarities(input).asType('float32'); });
  826. kVal = Math.min(k, this.getNumExamples());
  827. _a = util_1.topK;
  828. return [4, knn.data()];
  829. case 1:
  830. topKIndices = _a.apply(void 0, [_b.sent(), kVal]).indices;
  831. knn.dispose();
  832. return [2, this.calculateTopClass(topKIndices, kVal)];
  833. }
  834. });
  835. });
  836. };
  837. KNNClassifier.prototype.clearClass = function (classIndex) {
  838. if (this.classDatasetMatrices[classIndex] == null) {
  839. throw new Error('Cannot clear invalid class ${classIndex}');
  840. }
  841. delete this.classDatasetMatrices[classIndex];
  842. delete this.classExampleCount[classIndex];
  843. this.clearTrainDatasetMatrix();
  844. };
  845. KNNClassifier.prototype.clearAllClasses = function () {
  846. for (var i in this.classDatasetMatrices) {
  847. this.clearClass(+i);
  848. }
  849. };
  850. KNNClassifier.prototype.getClassExampleCount = function () {
  851. return this.classExampleCount;
  852. };
  853. KNNClassifier.prototype.getClassifierDataset = function () {
  854. return this.classDatasetMatrices;
  855. };
  856. KNNClassifier.prototype.getNumClasses = function () {
  857. return Object.keys(this.classExampleCount).length;
  858. };
  859. KNNClassifier.prototype.setClassifierDataset = function (classDatasetMatrices) {
  860. this.clearTrainDatasetMatrix();
  861. this.classDatasetMatrices = classDatasetMatrices;
  862. for (var i in classDatasetMatrices) {
  863. this.classExampleCount[i] = classDatasetMatrices[i].shape[0];
  864. }
  865. };
  866. KNNClassifier.prototype.calculateTopClass = function (topKIndices, kVal) {
  867. var exampleClass = -1;
  868. var confidences = {};
  869. if (topKIndices == null) {
  870. return { classIndex: exampleClass, confidences: confidences };
  871. }
  872. var indicesForClasses = [];
  873. for (var i in this.classDatasetMatrices) {
  874. var num = this.classExampleCount[i];
  875. if (+i > 0) {
  876. num += indicesForClasses[+i - 1];
  877. }
  878. indicesForClasses.push(num);
  879. }
  880. var topKCountsForClasses = Array(Object.keys(this.classDatasetMatrices).length).fill(0);
  881. for (var i = 0; i < topKIndices.length; i++) {
  882. for (var classId = 0; classId < indicesForClasses.length; classId++) {
  883. if (topKIndices[i] < indicesForClasses[classId]) {
  884. topKCountsForClasses[classId]++;
  885. break;
  886. }
  887. }
  888. }
  889. var topConfidence = 0;
  890. for (var i in this.classDatasetMatrices) {
  891. var probability = topKCountsForClasses[i] / kVal;
  892. if (probability > topConfidence) {
  893. topConfidence = probability;
  894. exampleClass = +i;
  895. }
  896. confidences[i] = probability;
  897. }
  898. return { classIndex: exampleClass, confidences: confidences };
  899. };
  900. KNNClassifier.prototype.clearTrainDatasetMatrix = function () {
  901. if (this.trainDatasetMatrix != null) {
  902. this.trainDatasetMatrix.dispose();
  903. this.trainDatasetMatrix = null;
  904. }
  905. };
  906. KNNClassifier.prototype.normalizeVectorToUnitLength = function (vec) {
  907. return tf.tidy(function () {
  908. var sqrtSum = vec.norm();
  909. return tf.div(vec, sqrtSum);
  910. });
  911. };
  912. KNNClassifier.prototype.getNumExamples = function () {
  913. var total = 0;
  914. for (var i in this.classDatasetMatrices) {
  915. total += this.classExampleCount[+i];
  916. }
  917. return total;
  918. };
  919. KNNClassifier.prototype.dispose = function () {
  920. this.clearTrainDatasetMatrix();
  921. for (var i in this.classDatasetMatrices) {
  922. this.classDatasetMatrices[i].dispose();
  923. }
  924. };
  925. return KNNClassifier;
  926. }());
  927. exports.KNNClassifier = KNNClassifier;
  928. function create() {
  929. return new KNNClassifier();
  930. }
  931. exports.create = create;
  932. },{"./util":9,"@tensorflow/tfjs":205}],9:[function(require,module,exports){
  933. "use strict";
  934. Object.defineProperty(exports, "__esModule", { value: true });
  935. function concatWithNulls(ndarray1, ndarray2) {
  936. if (ndarray1 == null && ndarray2 == null) {
  937. return null;
  938. }
  939. if (ndarray1 == null) {
  940. return ndarray2.clone();
  941. }
  942. else if (ndarray2 === null) {
  943. return ndarray1.clone();
  944. }
  945. return ndarray1.concat(ndarray2, 0);
  946. }
  947. exports.concatWithNulls = concatWithNulls;
  948. function topK(values, k) {
  949. var valuesAndIndices = [];
  950. for (var i = 0; i < values.length; i++) {
  951. valuesAndIndices.push({ value: values[i], index: i });
  952. }
  953. valuesAndIndices.sort(function (a, b) {
  954. return b.value - a.value;
  955. });
  956. var topkValues = new Float32Array(k);
  957. var topkIndices = new Int32Array(k);
  958. for (var i = 0; i < k; i++) {
  959. topkValues[i] = valuesAndIndices[i].value;
  960. topkIndices[i] = valuesAndIndices[i].index;
  961. }
  962. return { values: topkValues, indices: topkIndices };
  963. }
  964. exports.topK = topK;
  965. },{}],10:[function(require,module,exports){
  966. "use strict";
  967. Object.defineProperty(exports, "__esModule", { value: true });
  968. exports.IMAGENET_CLASSES = {
  969. 0: 'tench, Tinca tinca',
  970. 1: 'goldfish, Carassius auratus',
  971. 2: 'great white shark, white shark, man-eater, man-eating shark, ' +
  972. 'Carcharodon carcharias',
  973. 3: 'tiger shark, Galeocerdo cuvieri',
  974. 4: 'hammerhead, hammerhead shark',
  975. 5: 'electric ray, crampfish, numbfish, torpedo',
  976. 6: 'stingray',
  977. 7: 'cock',
  978. 8: 'hen',
  979. 9: 'ostrich, Struthio camelus',
  980. 10: 'brambling, Fringilla montifringilla',
  981. 11: 'goldfinch, Carduelis carduelis',
  982. 12: 'house finch, linnet, Carpodacus mexicanus',
  983. 13: 'junco, snowbird',
  984. 14: 'indigo bunting, indigo finch, indigo bird, Passerina cyanea',
  985. 15: 'robin, American robin, Turdus migratorius',
  986. 16: 'bulbul',
  987. 17: 'jay',
  988. 18: 'magpie',
  989. 19: 'chickadee',
  990. 20: 'water ouzel, dipper',
  991. 21: 'kite',
  992. 22: 'bald eagle, American eagle, Haliaeetus leucocephalus',
  993. 23: 'vulture',
  994. 24: 'great grey owl, great gray owl, Strix nebulosa',
  995. 25: 'European fire salamander, Salamandra salamandra',
  996. 26: 'common newt, Triturus vulgaris',
  997. 27: 'eft',
  998. 28: 'spotted salamander, Ambystoma maculatum',
  999. 29: 'axolotl, mud puppy, Ambystoma mexicanum',
  1000. 30: 'bullfrog, Rana catesbeiana',
  1001. 31: 'tree frog, tree-frog',
  1002. 32: 'tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui',
  1003. 33: 'loggerhead, loggerhead turtle, Caretta caretta',
  1004. 34: 'leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea',
  1005. 35: 'mud turtle',
  1006. 36: 'terrapin',
  1007. 37: 'box turtle, box tortoise',
  1008. 38: 'banded gecko',
  1009. 39: 'common iguana, iguana, Iguana iguana',
  1010. 40: 'American chameleon, anole, Anolis carolinensis',
  1011. 41: 'whiptail, whiptail lizard',
  1012. 42: 'agama',
  1013. 43: 'frilled lizard, Chlamydosaurus kingi',
  1014. 44: 'alligator lizard',
  1015. 45: 'Gila monster, Heloderma suspectum',
  1016. 46: 'green lizard, Lacerta viridis',
  1017. 47: 'African chameleon, Chamaeleo chamaeleon',
  1018. 48: 'Komodo dragon, Komodo lizard, dragon lizard, giant lizard, ' +
  1019. 'Varanus komodoensis',
  1020. 49: 'African crocodile, Nile crocodile, Crocodylus niloticus',
  1021. 50: 'American alligator, Alligator mississipiensis',
  1022. 51: 'triceratops',
  1023. 52: 'thunder snake, worm snake, Carphophis amoenus',
  1024. 53: 'ringneck snake, ring-necked snake, ring snake',
  1025. 54: 'hognose snake, puff adder, sand viper',
  1026. 55: 'green snake, grass snake',
  1027. 56: 'king snake, kingsnake',
  1028. 57: 'garter snake, grass snake',
  1029. 58: 'water snake',
  1030. 59: 'vine snake',
  1031. 60: 'night snake, Hypsiglena torquata',
  1032. 61: 'boa constrictor, Constrictor constrictor',
  1033. 62: 'rock python, rock snake, Python sebae',
  1034. 63: 'Indian cobra, Naja naja',
  1035. 64: 'green mamba',
  1036. 65: 'sea snake',
  1037. 66: 'horned viper, cerastes, sand viper, horned asp, Cerastes cornutus',
  1038. 67: 'diamondback, diamondback rattlesnake, Crotalus adamanteus',
  1039. 68: 'sidewinder, horned rattlesnake, Crotalus cerastes',
  1040. 69: 'trilobite',
  1041. 70: 'harvestman, daddy longlegs, Phalangium opilio',
  1042. 71: 'scorpion',
  1043. 72: 'black and gold garden spider, Argiope aurantia',
  1044. 73: 'barn spider, Araneus cavaticus',
  1045. 74: 'garden spider, Aranea diademata',
  1046. 75: 'black widow, Latrodectus mactans',
  1047. 76: 'tarantula',
  1048. 77: 'wolf spider, hunting spider',
  1049. 78: 'tick',
  1050. 79: 'centipede',
  1051. 80: 'black grouse',
  1052. 81: 'ptarmigan',
  1053. 82: 'ruffed grouse, partridge, Bonasa umbellus',
  1054. 83: 'prairie chicken, prairie grouse, prairie fowl',
  1055. 84: 'peacock',
  1056. 85: 'quail',
  1057. 86: 'partridge',
  1058. 87: 'African grey, African gray, Psittacus erithacus',
  1059. 88: 'macaw',
  1060. 89: 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
  1061. 90: 'lorikeet',
  1062. 91: 'coucal',
  1063. 92: 'bee eater',
  1064. 93: 'hornbill',
  1065. 94: 'hummingbird',
  1066. 95: 'jacamar',
  1067. 96: 'toucan',
  1068. 97: 'drake',
  1069. 98: 'red-breasted merganser, Mergus serrator',
  1070. 99: 'goose',
  1071. 100: 'black swan, Cygnus atratus',
  1072. 101: 'tusker',
  1073. 102: 'echidna, spiny anteater, anteater',
  1074. 103: 'platypus, duckbill, duckbilled platypus, duck-billed platypus, ' +
  1075. 'Ornithorhynchus anatinus',
  1076. 104: 'wallaby, brush kangaroo',
  1077. 105: 'koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus',
  1078. 106: 'wombat',
  1079. 107: 'jelly fish',
  1080. 108: 'sea anemone, anemone',
  1081. 109: 'brain coral',
  1082. 110: 'flatworm, platyhelminth',
  1083. 111: 'nematode, nematode worm, roundworm',
  1084. 112: 'conch',
  1085. 113: 'snail',
  1086. 114: 'slug',
  1087. 115: 'sea slug, nudibranch',
  1088. 116: 'chiton, coat-of-mail shell, sea cradle, polyplacophore',
  1089. 117: 'chambered nautilus, pearly nautilus, nautilus',
  1090. 118: 'Dungeness crab, Cancer magister',
  1091. 119: 'rock crab, Cancer irroratus',
  1092. 120: 'fiddler crab',
  1093. 121: 'king crab, Alaska crab, Alaskan king crab, Alaska king crab, ' +
  1094. 'Paralithodes camtschatica',
  1095. 122: 'American lobster, Northern lobster, Maine lobster, Homarus americanus',
  1096. 123: 'spiny lobster, langouste, rock lobster, crawfish, crayfish, sea ' +
  1097. 'crawfish',
  1098. 124: 'crayfish, crawfish, crawdad, crawdaddy',
  1099. 125: 'hermit crab',
  1100. 126: 'isopod',
  1101. 127: 'white stork, Ciconia ciconia',
  1102. 128: 'black stork, Ciconia nigra',
  1103. 129: 'spoonbill',
  1104. 130: 'flamingo',
  1105. 131: 'little blue heron, Egretta caerulea',
  1106. 132: 'American egret, great white heron, Egretta albus',
  1107. 133: 'bittern',
  1108. 134: 'crane',
  1109. 135: 'limpkin, Aramus pictus',
  1110. 136: 'European gallinule, Porphyrio porphyrio',
  1111. 137: 'American coot, marsh hen, mud hen, water hen, Fulica americana',
  1112. 138: 'bustard',
  1113. 139: 'ruddy turnstone, Arenaria interpres',
  1114. 140: 'red-backed sandpiper, dunlin, Erolia alpina',
  1115. 141: 'redshank, Tringa totanus',
  1116. 142: 'dowitcher',
  1117. 143: 'oystercatcher, oyster catcher',
  1118. 144: 'pelican',
  1119. 145: 'king penguin, Aptenodytes patagonica',
  1120. 146: 'albatross, mollymawk',
  1121. 147: 'grey whale, gray whale, devilfish, Eschrichtius gibbosus, ' +
  1122. 'Eschrichtius robustus',
  1123. 148: 'killer whale, killer, orca, grampus, sea wolf, Orcinus orca',
  1124. 149: 'dugong, Dugong dugon',
  1125. 150: 'sea lion',
  1126. 151: 'Chihuahua',
  1127. 152: 'Japanese spaniel',
  1128. 153: 'Maltese dog, Maltese terrier, Maltese',
  1129. 154: 'Pekinese, Pekingese, Peke',
  1130. 155: 'Shih-Tzu',
  1131. 156: 'Blenheim spaniel',
  1132. 157: 'papillon',
  1133. 158: 'toy terrier',
  1134. 159: 'Rhodesian ridgeback',
  1135. 160: 'Afghan hound, Afghan',
  1136. 161: 'basset, basset hound',
  1137. 162: 'beagle',
  1138. 163: 'bloodhound, sleuthhound',
  1139. 164: 'bluetick',
  1140. 165: 'black-and-tan coonhound',
  1141. 166: 'Walker hound, Walker foxhound',
  1142. 167: 'English foxhound',
  1143. 168: 'redbone',
  1144. 169: 'borzoi, Russian wolfhound',
  1145. 170: 'Irish wolfhound',
  1146. 171: 'Italian greyhound',
  1147. 172: 'whippet',
  1148. 173: 'Ibizan hound, Ibizan Podenco',
  1149. 174: 'Norwegian elkhound, elkhound',
  1150. 175: 'otterhound, otter hound',
  1151. 176: 'Saluki, gazelle hound',
  1152. 177: 'Scottish deerhound, deerhound',
  1153. 178: 'Weimaraner',
  1154. 179: 'Staffordshire bullterrier, Staffordshire bull terrier',
  1155. 180: 'American Staffordshire terrier, Staffordshire terrier, American pit ' +
  1156. 'bull terrier, pit bull terrier',
  1157. 181: 'Bedlington terrier',
  1158. 182: 'Border terrier',
  1159. 183: 'Kerry blue terrier',
  1160. 184: 'Irish terrier',
  1161. 185: 'Norfolk terrier',
  1162. 186: 'Norwich terrier',
  1163. 187: 'Yorkshire terrier',
  1164. 188: 'wire-haired fox terrier',
  1165. 189: 'Lakeland terrier',
  1166. 190: 'Sealyham terrier, Sealyham',
  1167. 191: 'Airedale, Airedale terrier',
  1168. 192: 'cairn, cairn terrier',
  1169. 193: 'Australian terrier',
  1170. 194: 'Dandie Dinmont, Dandie Dinmont terrier',
  1171. 195: 'Boston bull, Boston terrier',
  1172. 196: 'miniature schnauzer',
  1173. 197: 'giant schnauzer',
  1174. 198: 'standard schnauzer',
  1175. 199: 'Scotch terrier, Scottish terrier, Scottie',
  1176. 200: 'Tibetan terrier, chrysanthemum dog',
  1177. 201: 'silky terrier, Sydney silky',
  1178. 202: 'soft-coated wheaten terrier',
  1179. 203: 'West Highland white terrier',
  1180. 204: 'Lhasa, Lhasa apso',
  1181. 205: 'flat-coated retriever',
  1182. 206: 'curly-coated retriever',
  1183. 207: 'golden retriever',
  1184. 208: 'Labrador retriever',
  1185. 209: 'Chesapeake Bay retriever',
  1186. 210: 'German short-haired pointer',
  1187. 211: 'vizsla, Hungarian pointer',
  1188. 212: 'English setter',
  1189. 213: 'Irish setter, red setter',
  1190. 214: 'Gordon setter',
  1191. 215: 'Brittany spaniel',
  1192. 216: 'clumber, clumber spaniel',
  1193. 217: 'English springer, English springer spaniel',
  1194. 218: 'Welsh springer spaniel',
  1195. 219: 'cocker spaniel, English cocker spaniel, cocker',
  1196. 220: 'Sussex spaniel',
  1197. 221: 'Irish water spaniel',
  1198. 222: 'kuvasz',
  1199. 223: 'schipperke',
  1200. 224: 'groenendael',
  1201. 225: 'malinois',
  1202. 226: 'briard',
  1203. 227: 'kelpie',
  1204. 228: 'komondor',
  1205. 229: 'Old English sheepdog, bobtail',
  1206. 230: 'Shetland sheepdog, Shetland sheep dog, Shetland',
  1207. 231: 'collie',
  1208. 232: 'Border collie',
  1209. 233: 'Bouvier des Flandres, Bouviers des Flandres',
  1210. 234: 'Rottweiler',
  1211. 235: 'German shepherd, German shepherd dog, German police dog, alsatian',
  1212. 236: 'Doberman, Doberman pinscher',
  1213. 237: 'miniature pinscher',
  1214. 238: 'Greater Swiss Mountain dog',
  1215. 239: 'Bernese mountain dog',
  1216. 240: 'Appenzeller',
  1217. 241: 'EntleBucher',
  1218. 242: 'boxer',
  1219. 243: 'bull mastiff',
  1220. 244: 'Tibetan mastiff',
  1221. 245: 'French bulldog',
  1222. 246: 'Great Dane',
  1223. 247: 'Saint Bernard, St Bernard',
  1224. 248: 'Eskimo dog, husky',
  1225. 249: 'malamute, malemute, Alaskan malamute',
  1226. 250: 'Siberian husky',
  1227. 251: 'dalmatian, coach dog, carriage dog',
  1228. 252: 'affenpinscher, monkey pinscher, monkey dog',
  1229. 253: 'basenji',
  1230. 254: 'pug, pug-dog',
  1231. 255: 'Leonberg',
  1232. 256: 'Newfoundland, Newfoundland dog',
  1233. 257: 'Great Pyrenees',
  1234. 258: 'Samoyed, Samoyede',
  1235. 259: 'Pomeranian',
  1236. 260: 'chow, chow chow',
  1237. 261: 'keeshond',
  1238. 262: 'Brabancon griffon',
  1239. 263: 'Pembroke, Pembroke Welsh corgi',
  1240. 264: 'Cardigan, Cardigan Welsh corgi',
  1241. 265: 'toy poodle',
  1242. 266: 'miniature poodle',
  1243. 267: 'standard poodle',
  1244. 268: 'Mexican hairless',
  1245. 269: 'timber wolf, grey wolf, gray wolf, Canis lupus',
  1246. 270: 'white wolf, Arctic wolf, Canis lupus tundrarum',
  1247. 271: 'red wolf, maned wolf, Canis rufus, Canis niger',
  1248. 272: 'coyote, prairie wolf, brush wolf, Canis latrans',
  1249. 273: 'dingo, warrigal, warragal, Canis dingo',
  1250. 274: 'dhole, Cuon alpinus',
  1251. 275: 'African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus',
  1252. 276: 'hyena, hyaena',
  1253. 277: 'red fox, Vulpes vulpes',
  1254. 278: 'kit fox, Vulpes macrotis',
  1255. 279: 'Arctic fox, white fox, Alopex lagopus',
  1256. 280: 'grey fox, gray fox, Urocyon cinereoargenteus',
  1257. 281: 'tabby, tabby cat',
  1258. 282: 'tiger cat',
  1259. 283: 'Persian cat',
  1260. 284: 'Siamese cat, Siamese',
  1261. 285: 'Egyptian cat',
  1262. 286: 'cougar, puma, catamount, mountain lion, painter, panther, ' +
  1263. 'Felis concolor',
  1264. 287: 'lynx, catamount',
  1265. 288: 'leopard, Panthera pardus',
  1266. 289: 'snow leopard, ounce, Panthera uncia',
  1267. 290: 'jaguar, panther, Panthera onca, Felis onca',
  1268. 291: 'lion, king of beasts, Panthera leo',
  1269. 292: 'tiger, Panthera tigris',
  1270. 293: 'cheetah, chetah, Acinonyx jubatus',
  1271. 294: 'brown bear, bruin, Ursus arctos',
  1272. 295: 'American black bear, black bear, Ursus americanus, Euarctos ' +
  1273. 'americanus',
  1274. 296: 'ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus',
  1275. 297: 'sloth bear, Melursus ursinus, Ursus ursinus',
  1276. 298: 'mongoose',
  1277. 299: 'meerkat, mierkat',
  1278. 300: 'tiger beetle',
  1279. 301: 'ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle',
  1280. 302: 'ground beetle, carabid beetle',
  1281. 303: 'long-horned beetle, longicorn, longicorn beetle',
  1282. 304: 'leaf beetle, chrysomelid',
  1283. 305: 'dung beetle',
  1284. 306: 'rhinoceros beetle',
  1285. 307: 'weevil',
  1286. 308: 'fly',
  1287. 309: 'bee',
  1288. 310: 'ant, emmet, pismire',
  1289. 311: 'grasshopper, hopper',
  1290. 312: 'cricket',
  1291. 313: 'walking stick, walkingstick, stick insect',
  1292. 314: 'cockroach, roach',
  1293. 315: 'mantis, mantid',
  1294. 316: 'cicada, cicala',
  1295. 317: 'leafhopper',
  1296. 318: 'lacewing, lacewing fly',
  1297. 319: 'dragonfly, darning needle, devil\'s darning needle, sewing needle, ' +
  1298. 'snake feeder, snake doctor, mosquito hawk, skeeter hawk',
  1299. 320: 'damselfly',
  1300. 321: 'admiral',
  1301. 322: 'ringlet, ringlet butterfly',
  1302. 323: 'monarch, monarch butterfly, milkweed butterfly, Danaus plexippus',
  1303. 324: 'cabbage butterfly',
  1304. 325: 'sulphur butterfly, sulfur butterfly',
  1305. 326: 'lycaenid, lycaenid butterfly',
  1306. 327: 'starfish, sea star',
  1307. 328: 'sea urchin',
  1308. 329: 'sea cucumber, holothurian',
  1309. 330: 'wood rabbit, cottontail, cottontail rabbit',
  1310. 331: 'hare',
  1311. 332: 'Angora, Angora rabbit',
  1312. 333: 'hamster',
  1313. 334: 'porcupine, hedgehog',
  1314. 335: 'fox squirrel, eastern fox squirrel, Sciurus niger',
  1315. 336: 'marmot',
  1316. 337: 'beaver',
  1317. 338: 'guinea pig, Cavia cobaya',
  1318. 339: 'sorrel',
  1319. 340: 'zebra',
  1320. 341: 'hog, pig, grunter, squealer, Sus scrofa',
  1321. 342: 'wild boar, boar, Sus scrofa',
  1322. 343: 'warthog',
  1323. 344: 'hippopotamus, hippo, river horse, Hippopotamus amphibius',
  1324. 345: 'ox',
  1325. 346: 'water buffalo, water ox, Asiatic buffalo, Bubalus bubalis',
  1326. 347: 'bison',
  1327. 348: 'ram, tup',
  1328. 349: 'bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky ' +
  1329. 'Mountain sheep, Ovis canadensis',
  1330. 350: 'ibex, Capra ibex',
  1331. 351: 'hartebeest',
  1332. 352: 'impala, Aepyceros melampus',
  1333. 353: 'gazelle',
  1334. 354: 'Arabian camel, dromedary, Camelus dromedarius',
  1335. 355: 'llama',
  1336. 356: 'weasel',
  1337. 357: 'mink',
  1338. 358: 'polecat, fitch, foulmart, foumart, Mustela putorius',
  1339. 359: 'black-footed ferret, ferret, Mustela nigripes',
  1340. 360: 'otter',
  1341. 361: 'skunk, polecat, wood pussy',
  1342. 362: 'badger',
  1343. 363: 'armadillo',
  1344. 364: 'three-toed sloth, ai, Bradypus tridactylus',
  1345. 365: 'orangutan, orang, orangutang, Pongo pygmaeus',
  1346. 366: 'gorilla, Gorilla gorilla',
  1347. 367: 'chimpanzee, chimp, Pan troglodytes',
  1348. 368: 'gibbon, Hylobates lar',
  1349. 369: 'siamang, Hylobates syndactylus, Symphalangus syndactylus',
  1350. 370: 'guenon, guenon monkey',
  1351. 371: 'patas, hussar monkey, Erythrocebus patas',
  1352. 372: 'baboon',
  1353. 373: 'macaque',
  1354. 374: 'langur',
  1355. 375: 'colobus, colobus monkey',
  1356. 376: 'proboscis monkey, Nasalis larvatus',
  1357. 377: 'marmoset',
  1358. 378: 'capuchin, ringtail, Cebus capucinus',
  1359. 379: 'howler monkey, howler',
  1360. 380: 'titi, titi monkey',
  1361. 381: 'spider monkey, Ateles geoffroyi',
  1362. 382: 'squirrel monkey, Saimiri sciureus',
  1363. 383: 'Madagascar cat, ring-tailed lemur, Lemur catta',
  1364. 384: 'indri, indris, Indri indri, Indri brevicaudatus',
  1365. 385: 'Indian elephant, Elephas maximus',
  1366. 386: 'African elephant, Loxodonta africana',
  1367. 387: 'lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens',
  1368. 388: 'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca',
  1369. 389: 'barracouta, snoek',
  1370. 390: 'eel',
  1371. 391: 'coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus ' +
  1372. 'kisutch',
  1373. 392: 'rock beauty, Holocanthus tricolor',
  1374. 393: 'anemone fish',
  1375. 394: 'sturgeon',
  1376. 395: 'gar, garfish, garpike, billfish, Lepisosteus osseus',
  1377. 396: 'lionfish',
  1378. 397: 'puffer, pufferfish, blowfish, globefish',
  1379. 398: 'abacus',
  1380. 399: 'abaya',
  1381. 400: 'academic gown, academic robe, judge\'s robe',
  1382. 401: 'accordion, piano accordion, squeeze box',
  1383. 402: 'acoustic guitar',
  1384. 403: 'aircraft carrier, carrier, flattop, attack aircraft carrier',
  1385. 404: 'airliner',
  1386. 405: 'airship, dirigible',
  1387. 406: 'altar',
  1388. 407: 'ambulance',
  1389. 408: 'amphibian, amphibious vehicle',
  1390. 409: 'analog clock',
  1391. 410: 'apiary, bee house',
  1392. 411: 'apron',
  1393. 412: 'ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, ' +
  1394. 'dustbin, trash barrel, trash bin',
  1395. 413: 'assault rifle, assault gun',
  1396. 414: 'backpack, back pack, knapsack, packsack, rucksack, haversack',
  1397. 415: 'bakery, bakeshop, bakehouse',
  1398. 416: 'balance beam, beam',
  1399. 417: 'balloon',
  1400. 418: 'ballpoint, ballpoint pen, ballpen, Biro',
  1401. 419: 'Band Aid',
  1402. 420: 'banjo',
  1403. 421: 'bannister, banister, balustrade, balusters, handrail',
  1404. 422: 'barbell',
  1405. 423: 'barber chair',
  1406. 424: 'barbershop',
  1407. 425: 'barn',
  1408. 426: 'barometer',
  1409. 427: 'barrel, cask',
  1410. 428: 'barrow, garden cart, lawn cart, wheelbarrow',
  1411. 429: 'baseball',
  1412. 430: 'basketball',
  1413. 431: 'bassinet',
  1414. 432: 'bassoon',
  1415. 433: 'bathing cap, swimming cap',
  1416. 434: 'bath towel',
  1417. 435: 'bathtub, bathing tub, bath, tub',
  1418. 436: 'beach wagon, station wagon, wagon, estate car, beach waggon, station ' +
  1419. 'waggon, waggon',
  1420. 437: 'beacon, lighthouse, beacon light, pharos',
  1421. 438: 'beaker',
  1422. 439: 'bearskin, busby, shako',
  1423. 440: 'beer bottle',
  1424. 441: 'beer glass',
  1425. 442: 'bell cote, bell cot',
  1426. 443: 'bib',
  1427. 444: 'bicycle-built-for-two, tandem bicycle, tandem',
  1428. 445: 'bikini, two-piece',
  1429. 446: 'binder, ring-binder',
  1430. 447: 'binoculars, field glasses, opera glasses',
  1431. 448: 'birdhouse',
  1432. 449: 'boathouse',
  1433. 450: 'bobsled, bobsleigh, bob',
  1434. 451: 'bolo tie, bolo, bola tie, bola',
  1435. 452: 'bonnet, poke bonnet',
  1436. 453: 'bookcase',
  1437. 454: 'bookshop, bookstore, bookstall',
  1438. 455: 'bottlecap',
  1439. 456: 'bow',
  1440. 457: 'bow tie, bow-tie, bowtie',
  1441. 458: 'brass, memorial tablet, plaque',
  1442. 459: 'brassiere, bra, bandeau',
  1443. 460: 'breakwater, groin, groyne, mole, bulwark, seawall, jetty',
  1444. 461: 'breastplate, aegis, egis',
  1445. 462: 'broom',
  1446. 463: 'bucket, pail',
  1447. 464: 'buckle',
  1448. 465: 'bulletproof vest',
  1449. 466: 'bullet train, bullet',
  1450. 467: 'butcher shop, meat market',
  1451. 468: 'cab, hack, taxi, taxicab',
  1452. 469: 'caldron, cauldron',
  1453. 470: 'candle, taper, wax light',
  1454. 471: 'cannon',
  1455. 472: 'canoe',
  1456. 473: 'can opener, tin opener',
  1457. 474: 'cardigan',
  1458. 475: 'car mirror',
  1459. 476: 'carousel, carrousel, merry-go-round, roundabout, whirligig',
  1460. 477: 'carpenter\'s kit, tool kit',
  1461. 478: 'carton',
  1462. 479: 'car wheel',
  1463. 480: 'cash machine, cash dispenser, automated teller machine, automatic ' +
  1464. 'teller machine, automated teller, automatic teller, ATM',
  1465. 481: 'cassette',
  1466. 482: 'cassette player',
  1467. 483: 'castle',
  1468. 484: 'catamaran',
  1469. 485: 'CD player',
  1470. 486: 'cello, violoncello',
  1471. 487: 'cellular telephone, cellular phone, cellphone, cell, mobile phone',
  1472. 488: 'chain',
  1473. 489: 'chainlink fence',
  1474. 490: 'chain mail, ring mail, mail, chain armor, chain armour, ring armor, ' +
  1475. 'ring armour',
  1476. 491: 'chain saw, chainsaw',
  1477. 492: 'chest',
  1478. 493: 'chiffonier, commode',
  1479. 494: 'chime, bell, gong',
  1480. 495: 'china cabinet, china closet',
  1481. 496: 'Christmas stocking',
  1482. 497: 'church, church building',
  1483. 498: 'cinema, movie theater, movie theatre, movie house, picture palace',
  1484. 499: 'cleaver, meat cleaver, chopper',
  1485. 500: 'cliff dwelling',
  1486. 501: 'cloak',
  1487. 502: 'clog, geta, patten, sabot',
  1488. 503: 'cocktail shaker',
  1489. 504: 'coffee mug',
  1490. 505: 'coffeepot',
  1491. 506: 'coil, spiral, volute, whorl, helix',
  1492. 507: 'combination lock',
  1493. 508: 'computer keyboard, keypad',
  1494. 509: 'confectionery, confectionary, candy store',
  1495. 510: 'container ship, containership, container vessel',
  1496. 511: 'convertible',
  1497. 512: 'corkscrew, bottle screw',
  1498. 513: 'cornet, horn, trumpet, trump',
  1499. 514: 'cowboy boot',
  1500. 515: 'cowboy hat, ten-gallon hat',
  1501. 516: 'cradle',
  1502. 517: 'crane',
  1503. 518: 'crash helmet',
  1504. 519: 'crate',
  1505. 520: 'crib, cot',
  1506. 521: 'Crock Pot',
  1507. 522: 'croquet ball',
  1508. 523: 'crutch',
  1509. 524: 'cuirass',
  1510. 525: 'dam, dike, dyke',
  1511. 526: 'desk',
  1512. 527: 'desktop computer',
  1513. 528: 'dial telephone, dial phone',
  1514. 529: 'diaper, nappy, napkin',
  1515. 530: 'digital clock',
  1516. 531: 'digital watch',
  1517. 532: 'dining table, board',
  1518. 533: 'dishrag, dishcloth',
  1519. 534: 'dishwasher, dish washer, dishwashing machine',
  1520. 535: 'disk brake, disc brake',
  1521. 536: 'dock, dockage, docking facility',
  1522. 537: 'dogsled, dog sled, dog sleigh',
  1523. 538: 'dome',
  1524. 539: 'doormat, welcome mat',
  1525. 540: 'drilling platform, offshore rig',
  1526. 541: 'drum, membranophone, tympan',
  1527. 542: 'drumstick',
  1528. 543: 'dumbbell',
  1529. 544: 'Dutch oven',
  1530. 545: 'electric fan, blower',
  1531. 546: 'electric guitar',
  1532. 547: 'electric locomotive',
  1533. 548: 'entertainment center',
  1534. 549: 'envelope',
  1535. 550: 'espresso maker',
  1536. 551: 'face powder',
  1537. 552: 'feather boa, boa',
  1538. 553: 'file, file cabinet, filing cabinet',
  1539. 554: 'fireboat',
  1540. 555: 'fire engine, fire truck',
  1541. 556: 'fire screen, fireguard',
  1542. 557: 'flagpole, flagstaff',
  1543. 558: 'flute, transverse flute',
  1544. 559: 'folding chair',
  1545. 560: 'football helmet',
  1546. 561: 'forklift',
  1547. 562: 'fountain',
  1548. 563: 'fountain pen',
  1549. 564: 'four-poster',
  1550. 565: 'freight car',
  1551. 566: 'French horn, horn',
  1552. 567: 'frying pan, frypan, skillet',
  1553. 568: 'fur coat',
  1554. 569: 'garbage truck, dustcart',
  1555. 570: 'gasmask, respirator, gas helmet',
  1556. 571: 'gas pump, gasoline pump, petrol pump, island dispenser',
  1557. 572: 'goblet',
  1558. 573: 'go-kart',
  1559. 574: 'golf ball',
  1560. 575: 'golfcart, golf cart',
  1561. 576: 'gondola',
  1562. 577: 'gong, tam-tam',
  1563. 578: 'gown',
  1564. 579: 'grand piano, grand',
  1565. 580: 'greenhouse, nursery, glasshouse',
  1566. 581: 'grille, radiator grille',
  1567. 582: 'grocery store, grocery, food market, market',
  1568. 583: 'guillotine',
  1569. 584: 'hair slide',
  1570. 585: 'hair spray',
  1571. 586: 'half track',
  1572. 587: 'hammer',
  1573. 588: 'hamper',
  1574. 589: 'hand blower, blow dryer, blow drier, hair dryer, hair drier',
  1575. 590: 'hand-held computer, hand-held microcomputer',
  1576. 591: 'handkerchief, hankie, hanky, hankey',
  1577. 592: 'hard disc, hard disk, fixed disk',
  1578. 593: 'harmonica, mouth organ, harp, mouth harp',
  1579. 594: 'harp',
  1580. 595: 'harvester, reaper',
  1581. 596: 'hatchet',
  1582. 597: 'holster',
  1583. 598: 'home theater, home theatre',
  1584. 599: 'honeycomb',
  1585. 600: 'hook, claw',
  1586. 601: 'hoopskirt, crinoline',
  1587. 602: 'horizontal bar, high bar',
  1588. 603: 'horse cart, horse-cart',
  1589. 604: 'hourglass',
  1590. 605: 'iPod',
  1591. 606: 'iron, smoothing iron',
  1592. 607: 'jack-o\'-lantern',
  1593. 608: 'jean, blue jean, denim',
  1594. 609: 'jeep, landrover',
  1595. 610: 'jersey, T-shirt, tee shirt',
  1596. 611: 'jigsaw puzzle',
  1597. 612: 'jinrikisha, ricksha, rickshaw',
  1598. 613: 'joystick',
  1599. 614: 'kimono',
  1600. 615: 'knee pad',
  1601. 616: 'knot',
  1602. 617: 'lab coat, laboratory coat',
  1603. 618: 'ladle',
  1604. 619: 'lampshade, lamp shade',
  1605. 620: 'laptop, laptop computer',
  1606. 621: 'lawn mower, mower',
  1607. 622: 'lens cap, lens cover',
  1608. 623: 'letter opener, paper knife, paperknife',
  1609. 624: 'library',
  1610. 625: 'lifeboat',
  1611. 626: 'lighter, light, igniter, ignitor',
  1612. 627: 'limousine, limo',
  1613. 628: 'liner, ocean liner',
  1614. 629: 'lipstick, lip rouge',
  1615. 630: 'Loafer',
  1616. 631: 'lotion',
  1617. 632: 'loudspeaker, speaker, speaker unit, loudspeaker system, speaker ' +
  1618. 'system',
  1619. 633: 'loupe, jeweler\'s loupe',
  1620. 634: 'lumbermill, sawmill',
  1621. 635: 'magnetic compass',
  1622. 636: 'mailbag, postbag',
  1623. 637: 'mailbox, letter box',
  1624. 638: 'maillot',
  1625. 639: 'maillot, tank suit',
  1626. 640: 'manhole cover',
  1627. 641: 'maraca',
  1628. 642: 'marimba, xylophone',
  1629. 643: 'mask',
  1630. 644: 'matchstick',
  1631. 645: 'maypole',
  1632. 646: 'maze, labyrinth',
  1633. 647: 'measuring cup',
  1634. 648: 'medicine chest, medicine cabinet',
  1635. 649: 'megalith, megalithic structure',
  1636. 650: 'microphone, mike',
  1637. 651: 'microwave, microwave oven',
  1638. 652: 'military uniform',
  1639. 653: 'milk can',
  1640. 654: 'minibus',
  1641. 655: 'miniskirt, mini',
  1642. 656: 'minivan',
  1643. 657: 'missile',
  1644. 658: 'mitten',
  1645. 659: 'mixing bowl',
  1646. 660: 'mobile home, manufactured home',
  1647. 661: 'Model T',
  1648. 662: 'modem',
  1649. 663: 'monastery',
  1650. 664: 'monitor',
  1651. 665: 'moped',
  1652. 666: 'mortar',
  1653. 667: 'mortarboard',
  1654. 668: 'mosque',
  1655. 669: 'mosquito net',
  1656. 670: 'motor scooter, scooter',
  1657. 671: 'mountain bike, all-terrain bike, off-roader',
  1658. 672: 'mountain tent',
  1659. 673: 'mouse, computer mouse',
  1660. 674: 'mousetrap',
  1661. 675: 'moving van',
  1662. 676: 'muzzle',
  1663. 677: 'nail',
  1664. 678: 'neck brace',
  1665. 679: 'necklace',
  1666. 680: 'nipple',
  1667. 681: 'notebook, notebook computer',
  1668. 682: 'obelisk',
  1669. 683: 'oboe, hautboy, hautbois',
  1670. 684: 'ocarina, sweet potato',
  1671. 685: 'odometer, hodometer, mileometer, milometer',
  1672. 686: 'oil filter',
  1673. 687: 'organ, pipe organ',
  1674. 688: 'oscilloscope, scope, cathode-ray oscilloscope, CRO',
  1675. 689: 'overskirt',
  1676. 690: 'oxcart',
  1677. 691: 'oxygen mask',
  1678. 692: 'packet',
  1679. 693: 'paddle, boat paddle',
  1680. 694: 'paddlewheel, paddle wheel',
  1681. 695: 'padlock',
  1682. 696: 'paintbrush',
  1683. 697: 'pajama, pyjama, pj\'s, jammies',
  1684. 698: 'palace',
  1685. 699: 'panpipe, pandean pipe, syrinx',
  1686. 700: 'paper towel',
  1687. 701: 'parachute, chute',
  1688. 702: 'parallel bars, bars',
  1689. 703: 'park bench',
  1690. 704: 'parking meter',
  1691. 705: 'passenger car, coach, carriage',
  1692. 706: 'patio, terrace',
  1693. 707: 'pay-phone, pay-station',
  1694. 708: 'pedestal, plinth, footstall',
  1695. 709: 'pencil box, pencil case',
  1696. 710: 'pencil sharpener',
  1697. 711: 'perfume, essence',
  1698. 712: 'Petri dish',
  1699. 713: 'photocopier',
  1700. 714: 'pick, plectrum, plectron',
  1701. 715: 'pickelhaube',
  1702. 716: 'picket fence, paling',
  1703. 717: 'pickup, pickup truck',
  1704. 718: 'pier',
  1705. 719: 'piggy bank, penny bank',
  1706. 720: 'pill bottle',
  1707. 721: 'pillow',
  1708. 722: 'ping-pong ball',
  1709. 723: 'pinwheel',
  1710. 724: 'pirate, pirate ship',
  1711. 725: 'pitcher, ewer',
  1712. 726: 'plane, carpenter\'s plane, woodworking plane',
  1713. 727: 'planetarium',
  1714. 728: 'plastic bag',
  1715. 729: 'plate rack',
  1716. 730: 'plow, plough',
  1717. 731: 'plunger, plumber\'s helper',
  1718. 732: 'Polaroid camera, Polaroid Land camera',
  1719. 733: 'pole',
  1720. 734: 'police van, police wagon, paddy wagon, patrol wagon, wagon, black ' +
  1721. 'Maria',
  1722. 735: 'poncho',
  1723. 736: 'pool table, billiard table, snooker table',
  1724. 737: 'pop bottle, soda bottle',
  1725. 738: 'pot, flowerpot',
  1726. 739: 'potter\'s wheel',
  1727. 740: 'power drill',
  1728. 741: 'prayer rug, prayer mat',
  1729. 742: 'printer',
  1730. 743: 'prison, prison house',
  1731. 744: 'projectile, missile',
  1732. 745: 'projector',
  1733. 746: 'puck, hockey puck',
  1734. 747: 'punching bag, punch bag, punching ball, punchball',
  1735. 748: 'purse',
  1736. 749: 'quill, quill pen',
  1737. 750: 'quilt, comforter, comfort, puff',
  1738. 751: 'racer, race car, racing car',
  1739. 752: 'racket, racquet',
  1740. 753: 'radiator',
  1741. 754: 'radio, wireless',
  1742. 755: 'radio telescope, radio reflector',
  1743. 756: 'rain barrel',
  1744. 757: 'recreational vehicle, RV, R.V.',
  1745. 758: 'reel',
  1746. 759: 'reflex camera',
  1747. 760: 'refrigerator, icebox',
  1748. 761: 'remote control, remote',
  1749. 762: 'restaurant, eating house, eating place, eatery',
  1750. 763: 'revolver, six-gun, six-shooter',
  1751. 764: 'rifle',
  1752. 765: 'rocking chair, rocker',
  1753. 766: 'rotisserie',
  1754. 767: 'rubber eraser, rubber, pencil eraser',
  1755. 768: 'rugby ball',
  1756. 769: 'rule, ruler',
  1757. 770: 'running shoe',
  1758. 771: 'safe',
  1759. 772: 'safety pin',
  1760. 773: 'saltshaker, salt shaker',
  1761. 774: 'sandal',
  1762. 775: 'sarong',
  1763. 776: 'sax, saxophone',
  1764. 777: 'scabbard',
  1765. 778: 'scale, weighing machine',
  1766. 779: 'school bus',
  1767. 780: 'schooner',
  1768. 781: 'scoreboard',
  1769. 782: 'screen, CRT screen',
  1770. 783: 'screw',
  1771. 784: 'screwdriver',
  1772. 785: 'seat belt, seatbelt',
  1773. 786: 'sewing machine',
  1774. 787: 'shield, buckler',
  1775. 788: 'shoe shop, shoe-shop, shoe store',
  1776. 789: 'shoji',
  1777. 790: 'shopping basket',
  1778. 791: 'shopping cart',
  1779. 792: 'shovel',
  1780. 793: 'shower cap',
  1781. 794: 'shower curtain',
  1782. 795: 'ski',
  1783. 796: 'ski mask',
  1784. 797: 'sleeping bag',
  1785. 798: 'slide rule, slipstick',
  1786. 799: 'sliding door',
  1787. 800: 'slot, one-armed bandit',
  1788. 801: 'snorkel',
  1789. 802: 'snowmobile',
  1790. 803: 'snowplow, snowplough',
  1791. 804: 'soap dispenser',
  1792. 805: 'soccer ball',
  1793. 806: 'sock',
  1794. 807: 'solar dish, solar collector, solar furnace',
  1795. 808: 'sombrero',
  1796. 809: 'soup bowl',
  1797. 810: 'space bar',
  1798. 811: 'space heater',
  1799. 812: 'space shuttle',
  1800. 813: 'spatula',
  1801. 814: 'speedboat',
  1802. 815: 'spider web, spider\'s web',
  1803. 816: 'spindle',
  1804. 817: 'sports car, sport car',
  1805. 818: 'spotlight, spot',
  1806. 819: 'stage',
  1807. 820: 'steam locomotive',
  1808. 821: 'steel arch bridge',
  1809. 822: 'steel drum',
  1810. 823: 'stethoscope',
  1811. 824: 'stole',
  1812. 825: 'stone wall',
  1813. 826: 'stopwatch, stop watch',
  1814. 827: 'stove',
  1815. 828: 'strainer',
  1816. 829: 'streetcar, tram, tramcar, trolley, trolley car',
  1817. 830: 'stretcher',
  1818. 831: 'studio couch, day bed',
  1819. 832: 'stupa, tope',
  1820. 833: 'submarine, pigboat, sub, U-boat',
  1821. 834: 'suit, suit of clothes',
  1822. 835: 'sundial',
  1823. 836: 'sunglass',
  1824. 837: 'sunglasses, dark glasses, shades',
  1825. 838: 'sunscreen, sunblock, sun blocker',
  1826. 839: 'suspension bridge',
  1827. 840: 'swab, swob, mop',
  1828. 841: 'sweatshirt',
  1829. 842: 'swimming trunks, bathing trunks',
  1830. 843: 'swing',
  1831. 844: 'switch, electric switch, electrical switch',
  1832. 845: 'syringe',
  1833. 846: 'table lamp',
  1834. 847: 'tank, army tank, armored combat vehicle, armoured combat vehicle',
  1835. 848: 'tape player',
  1836. 849: 'teapot',
  1837. 850: 'teddy, teddy bear',
  1838. 851: 'television, television system',
  1839. 852: 'tennis ball',
  1840. 853: 'thatch, thatched roof',
  1841. 854: 'theater curtain, theatre curtain',
  1842. 855: 'thimble',
  1843. 856: 'thresher, thrasher, threshing machine',
  1844. 857: 'throne',
  1845. 858: 'tile roof',
  1846. 859: 'toaster',
  1847. 860: 'tobacco shop, tobacconist shop, tobacconist',
  1848. 861: 'toilet seat',
  1849. 862: 'torch',
  1850. 863: 'totem pole',
  1851. 864: 'tow truck, tow car, wrecker',
  1852. 865: 'toyshop',
  1853. 866: 'tractor',
  1854. 867: 'trailer truck, tractor trailer, trucking rig, rig, articulated ' +
  1855. 'lorry, semi',
  1856. 868: 'tray',
  1857. 869: 'trench coat',
  1858. 870: 'tricycle, trike, velocipede',
  1859. 871: 'trimaran',
  1860. 872: 'tripod',
  1861. 873: 'triumphal arch',
  1862. 874: 'trolleybus, trolley coach, trackless trolley',
  1863. 875: 'trombone',
  1864. 876: 'tub, vat',
  1865. 877: 'turnstile',
  1866. 878: 'typewriter keyboard',
  1867. 879: 'umbrella',
  1868. 880: 'unicycle, monocycle',
  1869. 881: 'upright, upright piano',
  1870. 882: 'vacuum, vacuum cleaner',
  1871. 883: 'vase',
  1872. 884: 'vault',
  1873. 885: 'velvet',
  1874. 886: 'vending machine',
  1875. 887: 'vestment',
  1876. 888: 'viaduct',
  1877. 889: 'violin, fiddle',
  1878. 890: 'volleyball',
  1879. 891: 'waffle iron',
  1880. 892: 'wall clock',
  1881. 893: 'wallet, billfold, notecase, pocketbook',
  1882. 894: 'wardrobe, closet, press',
  1883. 895: 'warplane, military plane',
  1884. 896: 'washbasin, handbasin, washbowl, lavabo, wash-hand basin',
  1885. 897: 'washer, automatic washer, washing machine',
  1886. 898: 'water bottle',
  1887. 899: 'water jug',
  1888. 900: 'water tower',
  1889. 901: 'whiskey jug',
  1890. 902: 'whistle',
  1891. 903: 'wig',
  1892. 904: 'window screen',
  1893. 905: 'window shade',
  1894. 906: 'Windsor tie',
  1895. 907: 'wine bottle',
  1896. 908: 'wing',
  1897. 909: 'wok',
  1898. 910: 'wooden spoon',
  1899. 911: 'wool, woolen, woollen',
  1900. 912: 'worm fence, snake fence, snake-rail fence, Virginia fence',
  1901. 913: 'wreck',
  1902. 914: 'yawl',
  1903. 915: 'yurt',
  1904. 916: 'web site, website, internet site, site',
  1905. 917: 'comic book',
  1906. 918: 'crossword puzzle, crossword',
  1907. 919: 'street sign',
  1908. 920: 'traffic light, traffic signal, stoplight',
  1909. 921: 'book jacket, dust cover, dust jacket, dust wrapper',
  1910. 922: 'menu',
  1911. 923: 'plate',
  1912. 924: 'guacamole',
  1913. 925: 'consomme',
  1914. 926: 'hot pot, hotpot',
  1915. 927: 'trifle',
  1916. 928: 'ice cream, icecream',
  1917. 929: 'ice lolly, lolly, lollipop, popsicle',
  1918. 930: 'French loaf',
  1919. 931: 'bagel, beigel',
  1920. 932: 'pretzel',
  1921. 933: 'cheeseburger',
  1922. 934: 'hotdog, hot dog, red hot',
  1923. 935: 'mashed potato',
  1924. 936: 'head cabbage',
  1925. 937: 'broccoli',
  1926. 938: 'cauliflower',
  1927. 939: 'zucchini, courgette',
  1928. 940: 'spaghetti squash',
  1929. 941: 'acorn squash',
  1930. 942: 'butternut squash',
  1931. 943: 'cucumber, cuke',
  1932. 944: 'artichoke, globe artichoke',
  1933. 945: 'bell pepper',
  1934. 946: 'cardoon',
  1935. 947: 'mushroom',
  1936. 948: 'Granny Smith',
  1937. 949: 'strawberry',
  1938. 950: 'orange',
  1939. 951: 'lemon',
  1940. 952: 'fig',
  1941. 953: 'pineapple, ananas',
  1942. 954: 'banana',
  1943. 955: 'jackfruit, jak, jack',
  1944. 956: 'custard apple',
  1945. 957: 'pomegranate',
  1946. 958: 'hay',
  1947. 959: 'carbonara',
  1948. 960: 'chocolate sauce, chocolate syrup',
  1949. 961: 'dough',
  1950. 962: 'meat loaf, meatloaf',
  1951. 963: 'pizza, pizza pie',
  1952. 964: 'potpie',
  1953. 965: 'burrito',
  1954. 966: 'red wine',
  1955. 967: 'espresso',
  1956. 968: 'cup',
  1957. 969: 'eggnog',
  1958. 970: 'alp',
  1959. 971: 'bubble',
  1960. 972: 'cliff, drop, drop-off',
  1961. 973: 'coral reef',
  1962. 974: 'geyser',
  1963. 975: 'lakeside, lakeshore',
  1964. 976: 'promontory, headland, head, foreland',
  1965. 977: 'sandbar, sand bar',
  1966. 978: 'seashore, coast, seacoast, sea-coast',
  1967. 979: 'valley, vale',
  1968. 980: 'volcano',
  1969. 981: 'ballplayer, baseball player',
  1970. 982: 'groom, bridegroom',
  1971. 983: 'scuba diver',
  1972. 984: 'rapeseed',
  1973. 985: 'daisy',
  1974. 986: 'yellow lady\'s slipper, yellow lady-slipper, Cypripedium calceolus, ' +
  1975. 'Cypripedium parviflorum',
  1976. 987: 'corn',
  1977. 988: 'acorn',
  1978. 989: 'hip, rose hip, rosehip',
  1979. 990: 'buckeye, horse chestnut, conker',
  1980. 991: 'coral fungus',
  1981. 992: 'agaric',
  1982. 993: 'gyromitra',
  1983. 994: 'stinkhorn, carrion fungus',
  1984. 995: 'earthstar',
  1985. 996: 'hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola ' +
  1986. 'frondosa',
  1987. 997: 'bolete',
  1988. 998: 'ear, spike, capitulum',
  1989. 999: 'toilet tissue, toilet paper, bathroom tissue'
  1990. };
  1991. },{}],11:[function(require,module,exports){
  1992. "use strict";
  1993. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  1994. return new (P || (P = Promise))(function (resolve, reject) {
  1995. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1996. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1997. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  1998. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1999. });
  2000. };
  2001. var __generator = (this && this.__generator) || function (thisArg, body) {
  2002. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  2003. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  2004. function verb(n) { return function (v) { return step([n, v]); }; }
  2005. function step(op) {
  2006. if (f) throw new TypeError("Generator is already executing.");
  2007. while (_) try {
  2008. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  2009. if (y = 0, t) op = [0, t.value];
  2010. switch (op[0]) {
  2011. case 0: case 1: t = op; break;
  2012. case 4: _.label++; return { value: op[1], done: false };
  2013. case 5: _.label++; y = op[1]; op = [0]; continue;
  2014. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  2015. default:
  2016. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  2017. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  2018. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  2019. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  2020. if (t[2]) _.ops.pop();
  2021. _.trys.pop(); continue;
  2022. }
  2023. op = body.call(thisArg, _);
  2024. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  2025. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  2026. }
  2027. };
  2028. Object.defineProperty(exports, "__esModule", { value: true });
  2029. var tf = require("@tensorflow/tfjs");
  2030. var imagenet_classes_1 = require("./imagenet_classes");
  2031. // var BASE_PATH = 'https://storage.googleapis.com/tfjs-models/tfjs/';
  2032. var BASE_PATH = 'https://cocorobo.cn/model/';
  2033. var IMAGE_SIZE = 224;
  2034. function load(version, alpha) {
  2035. if (version === void 0) { version = 1; }
  2036. if (alpha === void 0) { alpha = 1.0; }
  2037. return __awaiter(this, void 0, void 0, function () {
  2038. var mobilenet;
  2039. return __generator(this, function (_a) {
  2040. switch (_a.label) {
  2041. case 0:
  2042. if (tf == null) {
  2043. throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please " +
  2044. "also include @tensorflow/tfjs on the page before using this model.");
  2045. }
  2046. if (version !== 1) {
  2047. throw new Error("Currently only MobileNet V1 is supported. Got version " + version + ".");
  2048. }
  2049. if ([0.25, 0.50, 0.75, 1.0].indexOf(alpha) === -1) {
  2050. throw new Error("MobileNet constructed with invalid alpha " +
  2051. (alpha + ". Valid multipliers are 0.25, 0.50, 0.75, and 1.0."));
  2052. }
  2053. mobilenet = new MobileNet(version, alpha);
  2054. return [4, mobilenet.load()];
  2055. case 1:
  2056. _a.sent();
  2057. return [2, mobilenet];
  2058. }
  2059. });
  2060. });
  2061. }
  2062. exports.load = load;
  2063. var MobileNet = (function () {
  2064. function MobileNet(version, alpha) {
  2065. this.intermediateModels = {};
  2066. var multiplierStr = ({ 0.25: '0.25', 0.50: '0.50', 0.75: '0.75', 1.0: '1.0' })[alpha];
  2067. this.path = BASE_PATH + "model.json";
  2068. // this.path =
  2069. // BASE_PATH + "mobilenet_v" + version + "_" + multiplierStr + "_" + IMAGE_SIZE + "/" +
  2070. // "model.json";
  2071. this.normalizationOffset = tf.scalar(127.5);
  2072. }
  2073. MobileNet.prototype.load = function () {
  2074. return __awaiter(this, void 0, void 0, function () {
  2075. var _a, result;
  2076. return __generator(this, function (_b) {
  2077. switch (_b.label) {
  2078. case 0:
  2079. _a = this;
  2080. return [4, tf.loadModel(this.path)];
  2081. case 1:
  2082. _a.model = _b.sent();
  2083. this.endpoints = this.model.layers.map(function (l) { return l.name; });
  2084. result = this.model.predict(tf.zeros([1, IMAGE_SIZE, IMAGE_SIZE, 3]));
  2085. return [4, result.data()];
  2086. case 2:
  2087. _b.sent();
  2088. result.dispose();
  2089. return [2];
  2090. }
  2091. });
  2092. });
  2093. };
  2094. MobileNet.prototype.infer = function (img, endpoint) {
  2095. var _this = this;
  2096. if (endpoint != null && this.endpoints.indexOf(endpoint) === -1) {
  2097. throw new Error("Unknown endpoint " + endpoint + ". Available endpoints: " +
  2098. (this.endpoints + "."));
  2099. }
  2100. return tf.tidy(function () {
  2101. if (!(img instanceof tf.Tensor)) {
  2102. img = tf.fromPixels(img);
  2103. }
  2104. var normalized = img.toFloat()
  2105. .sub(_this.normalizationOffset)
  2106. .div(_this.normalizationOffset);
  2107. var resized = normalized;
  2108. if (img.shape[0] !== IMAGE_SIZE || img.shape[1] !== IMAGE_SIZE) {
  2109. var alignCorners = true;
  2110. resized = tf.image.resizeBilinear(normalized, [IMAGE_SIZE, IMAGE_SIZE], alignCorners);
  2111. }
  2112. var batched = resized.reshape([1, IMAGE_SIZE, IMAGE_SIZE, 3]);
  2113. var model;
  2114. if (endpoint == null) {
  2115. model = _this.model;
  2116. }
  2117. else {
  2118. if (_this.intermediateModels[endpoint] == null) {
  2119. var layer = _this.model.layers.find(function (l) { return l.name === endpoint; });
  2120. _this.intermediateModels[endpoint] =
  2121. tf.model({ inputs: _this.model.inputs, outputs: layer.output });
  2122. }
  2123. model = _this.intermediateModels[endpoint];
  2124. }
  2125. return model.predict(batched);
  2126. });
  2127. };
  2128. MobileNet.prototype.classify = function (img, topk) {
  2129. if (topk === void 0) { topk = 3; }
  2130. return __awaiter(this, void 0, void 0, function () {
  2131. var logits, classes;
  2132. return __generator(this, function (_a) {
  2133. switch (_a.label) {
  2134. case 0:
  2135. logits = this.infer(img);
  2136. return [4, getTopKClasses(logits, topk)];
  2137. case 1:
  2138. classes = _a.sent();
  2139. logits.dispose();
  2140. return [2, classes];
  2141. }
  2142. });
  2143. });
  2144. };
  2145. return MobileNet;
  2146. }());
  2147. exports.MobileNet = MobileNet;
  2148. function getTopKClasses(logits, topK) {
  2149. return __awaiter(this, void 0, void 0, function () {
  2150. var values, valuesAndIndices, i, topkValues, topkIndices, i, topClassesAndProbs, i;
  2151. return __generator(this, function (_a) {
  2152. switch (_a.label) {
  2153. case 0: return [4, logits.data()];
  2154. case 1:
  2155. values = _a.sent();
  2156. valuesAndIndices = [];
  2157. for (i = 0; i < values.length; i++) {
  2158. valuesAndIndices.push({ value: values[i], index: i });
  2159. }
  2160. valuesAndIndices.sort(function (a, b) {
  2161. return b.value - a.value;
  2162. });
  2163. topkValues = new Float32Array(topK);
  2164. topkIndices = new Int32Array(topK);
  2165. for (i = 0; i < topK; i++) {
  2166. topkValues[i] = valuesAndIndices[i].value;
  2167. topkIndices[i] = valuesAndIndices[i].index;
  2168. }
  2169. topClassesAndProbs = [];
  2170. for (i = 0; i < topkIndices.length; i++) {
  2171. topClassesAndProbs.push({
  2172. className: imagenet_classes_1.IMAGENET_CLASSES[topkIndices[i]],
  2173. probability: topkValues[i]
  2174. });
  2175. }
  2176. return [2, topClassesAndProbs];
  2177. }
  2178. });
  2179. });
  2180. }
  2181. },{"./imagenet_classes":10,"@tensorflow/tfjs":205}],12:[function(require,module,exports){
  2182. /*eslint-disable block-scoped-var, no-redeclare, no-control-regex, no-prototype-builtins*/
  2183. "use strict";
  2184. var $protobuf = require("protobufjs/minimal");
  2185. var $Reader = $protobuf.Reader, $util = $protobuf.util;
  2186. var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});
  2187. $root.tensorflow = (function() {
  2188. var tensorflow = {};
  2189. tensorflow.Any = (function() {
  2190. function Any(p) {
  2191. if (p)
  2192. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2193. if (p[ks[i]] != null)
  2194. this[ks[i]] = p[ks[i]];
  2195. }
  2196. Any.prototype.typeUrl = "";
  2197. Any.prototype.value = $util.newBuffer([]);
  2198. Any.decode = function decode(r, l) {
  2199. if (!(r instanceof $Reader))
  2200. r = $Reader.create(r);
  2201. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.Any();
  2202. while (r.pos < c) {
  2203. var t = r.uint32();
  2204. switch (t >>> 3) {
  2205. case 1:
  2206. m.typeUrl = r.string();
  2207. break;
  2208. case 2:
  2209. m.value = r.bytes();
  2210. break;
  2211. default:
  2212. r.skipType(t & 7);
  2213. break;
  2214. }
  2215. }
  2216. return m;
  2217. };
  2218. return Any;
  2219. })();
  2220. tensorflow.DataType = (function() {
  2221. var valuesById = {}, values = Object.create(valuesById);
  2222. values[valuesById[0] = "DT_INVALID"] = 0;
  2223. values[valuesById[1] = "DT_FLOAT"] = 1;
  2224. values[valuesById[2] = "DT_DOUBLE"] = 2;
  2225. values[valuesById[3] = "DT_INT32"] = 3;
  2226. values[valuesById[4] = "DT_UINT8"] = 4;
  2227. values[valuesById[5] = "DT_INT16"] = 5;
  2228. values[valuesById[6] = "DT_INT8"] = 6;
  2229. values[valuesById[7] = "DT_STRING"] = 7;
  2230. values[valuesById[8] = "DT_COMPLEX64"] = 8;
  2231. values[valuesById[9] = "DT_INT64"] = 9;
  2232. values[valuesById[10] = "DT_BOOL"] = 10;
  2233. values[valuesById[11] = "DT_QINT8"] = 11;
  2234. values[valuesById[12] = "DT_QUINT8"] = 12;
  2235. values[valuesById[13] = "DT_QINT32"] = 13;
  2236. values[valuesById[14] = "DT_BFLOAT16"] = 14;
  2237. values[valuesById[101] = "DT_FLOAT_REF"] = 101;
  2238. values[valuesById[102] = "DT_DOUBLE_REF"] = 102;
  2239. values[valuesById[103] = "DT_INT32_REF"] = 103;
  2240. values[valuesById[104] = "DT_UINT8_REF"] = 104;
  2241. values[valuesById[105] = "DT_INT16_REF"] = 105;
  2242. values[valuesById[106] = "DT_INT8_REF"] = 106;
  2243. values[valuesById[107] = "DT_STRING_REF"] = 107;
  2244. values[valuesById[108] = "DT_COMPLEX64_REF"] = 108;
  2245. values[valuesById[109] = "DT_INT64_REF"] = 109;
  2246. values[valuesById[110] = "DT_BOOL_REF"] = 110;
  2247. values[valuesById[111] = "DT_QINT8_REF"] = 111;
  2248. values[valuesById[112] = "DT_QUINT8_REF"] = 112;
  2249. values[valuesById[113] = "DT_QINT32_REF"] = 113;
  2250. values[valuesById[114] = "DT_BFLOAT16_REF"] = 114;
  2251. return values;
  2252. })();
  2253. tensorflow.TensorShape = (function() {
  2254. function TensorShape(p) {
  2255. this.dim = [];
  2256. if (p)
  2257. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2258. if (p[ks[i]] != null)
  2259. this[ks[i]] = p[ks[i]];
  2260. }
  2261. TensorShape.prototype.dim = $util.emptyArray;
  2262. TensorShape.prototype.unknownRank = false;
  2263. TensorShape.decode = function decode(r, l) {
  2264. if (!(r instanceof $Reader))
  2265. r = $Reader.create(r);
  2266. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.TensorShape();
  2267. while (r.pos < c) {
  2268. var t = r.uint32();
  2269. switch (t >>> 3) {
  2270. case 2:
  2271. if (!(m.dim && m.dim.length))
  2272. m.dim = [];
  2273. m.dim.push($root.tensorflow.TensorShape.Dim.decode(r, r.uint32()));
  2274. break;
  2275. case 3:
  2276. m.unknownRank = r.bool();
  2277. break;
  2278. default:
  2279. r.skipType(t & 7);
  2280. break;
  2281. }
  2282. }
  2283. return m;
  2284. };
  2285. TensorShape.Dim = (function() {
  2286. function Dim(p) {
  2287. if (p)
  2288. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2289. if (p[ks[i]] != null)
  2290. this[ks[i]] = p[ks[i]];
  2291. }
  2292. Dim.prototype.size = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
  2293. Dim.prototype.name = "";
  2294. Dim.decode = function decode(r, l) {
  2295. if (!(r instanceof $Reader))
  2296. r = $Reader.create(r);
  2297. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.TensorShape.Dim();
  2298. while (r.pos < c) {
  2299. var t = r.uint32();
  2300. switch (t >>> 3) {
  2301. case 1:
  2302. m.size = r.int64();
  2303. break;
  2304. case 2:
  2305. m.name = r.string();
  2306. break;
  2307. default:
  2308. r.skipType(t & 7);
  2309. break;
  2310. }
  2311. }
  2312. return m;
  2313. };
  2314. return Dim;
  2315. })();
  2316. return TensorShape;
  2317. })();
  2318. tensorflow.Tensor = (function() {
  2319. function Tensor(p) {
  2320. this.floatVal = [];
  2321. this.doubleVal = [];
  2322. this.intVal = [];
  2323. this.stringVal = [];
  2324. this.scomplexVal = [];
  2325. this.int64Val = [];
  2326. this.boolVal = [];
  2327. this.uint32Val = [];
  2328. this.uint64Val = [];
  2329. if (p)
  2330. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2331. if (p[ks[i]] != null)
  2332. this[ks[i]] = p[ks[i]];
  2333. }
  2334. Tensor.prototype.dtype = 0;
  2335. Tensor.prototype.tensorShape = null;
  2336. Tensor.prototype.versionNumber = 0;
  2337. Tensor.prototype.tensorContent = $util.newBuffer([]);
  2338. Tensor.prototype.floatVal = $util.emptyArray;
  2339. Tensor.prototype.doubleVal = $util.emptyArray;
  2340. Tensor.prototype.intVal = $util.emptyArray;
  2341. Tensor.prototype.stringVal = $util.emptyArray;
  2342. Tensor.prototype.scomplexVal = $util.emptyArray;
  2343. Tensor.prototype.int64Val = $util.emptyArray;
  2344. Tensor.prototype.boolVal = $util.emptyArray;
  2345. Tensor.prototype.uint32Val = $util.emptyArray;
  2346. Tensor.prototype.uint64Val = $util.emptyArray;
  2347. Tensor.decode = function decode(r, l) {
  2348. if (!(r instanceof $Reader))
  2349. r = $Reader.create(r);
  2350. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.Tensor();
  2351. while (r.pos < c) {
  2352. var t = r.uint32();
  2353. switch (t >>> 3) {
  2354. case 1:
  2355. m.dtype = r.int32();
  2356. break;
  2357. case 2:
  2358. m.tensorShape = $root.tensorflow.TensorShape.decode(r, r.uint32());
  2359. break;
  2360. case 3:
  2361. m.versionNumber = r.int32();
  2362. break;
  2363. case 4:
  2364. m.tensorContent = r.bytes();
  2365. break;
  2366. case 5:
  2367. if (!(m.floatVal && m.floatVal.length))
  2368. m.floatVal = [];
  2369. if ((t & 7) === 2) {
  2370. var c2 = r.uint32() + r.pos;
  2371. while (r.pos < c2)
  2372. m.floatVal.push(r.float());
  2373. } else
  2374. m.floatVal.push(r.float());
  2375. break;
  2376. case 6:
  2377. if (!(m.doubleVal && m.doubleVal.length))
  2378. m.doubleVal = [];
  2379. if ((t & 7) === 2) {
  2380. var c2 = r.uint32() + r.pos;
  2381. while (r.pos < c2)
  2382. m.doubleVal.push(r.double());
  2383. } else
  2384. m.doubleVal.push(r.double());
  2385. break;
  2386. case 7:
  2387. if (!(m.intVal && m.intVal.length))
  2388. m.intVal = [];
  2389. if ((t & 7) === 2) {
  2390. var c2 = r.uint32() + r.pos;
  2391. while (r.pos < c2)
  2392. m.intVal.push(r.int32());
  2393. } else
  2394. m.intVal.push(r.int32());
  2395. break;
  2396. case 8:
  2397. if (!(m.stringVal && m.stringVal.length))
  2398. m.stringVal = [];
  2399. m.stringVal.push(r.bytes());
  2400. break;
  2401. case 9:
  2402. if (!(m.scomplexVal && m.scomplexVal.length))
  2403. m.scomplexVal = [];
  2404. if ((t & 7) === 2) {
  2405. var c2 = r.uint32() + r.pos;
  2406. while (r.pos < c2)
  2407. m.scomplexVal.push(r.float());
  2408. } else
  2409. m.scomplexVal.push(r.float());
  2410. break;
  2411. case 10:
  2412. if (!(m.int64Val && m.int64Val.length))
  2413. m.int64Val = [];
  2414. if ((t & 7) === 2) {
  2415. var c2 = r.uint32() + r.pos;
  2416. while (r.pos < c2)
  2417. m.int64Val.push(r.int64());
  2418. } else
  2419. m.int64Val.push(r.int64());
  2420. break;
  2421. case 11:
  2422. if (!(m.boolVal && m.boolVal.length))
  2423. m.boolVal = [];
  2424. if ((t & 7) === 2) {
  2425. var c2 = r.uint32() + r.pos;
  2426. while (r.pos < c2)
  2427. m.boolVal.push(r.bool());
  2428. } else
  2429. m.boolVal.push(r.bool());
  2430. break;
  2431. case 16:
  2432. if (!(m.uint32Val && m.uint32Val.length))
  2433. m.uint32Val = [];
  2434. if ((t & 7) === 2) {
  2435. var c2 = r.uint32() + r.pos;
  2436. while (r.pos < c2)
  2437. m.uint32Val.push(r.uint32());
  2438. } else
  2439. m.uint32Val.push(r.uint32());
  2440. break;
  2441. case 17:
  2442. if (!(m.uint64Val && m.uint64Val.length))
  2443. m.uint64Val = [];
  2444. if ((t & 7) === 2) {
  2445. var c2 = r.uint32() + r.pos;
  2446. while (r.pos < c2)
  2447. m.uint64Val.push(r.uint64());
  2448. } else
  2449. m.uint64Val.push(r.uint64());
  2450. break;
  2451. default:
  2452. r.skipType(t & 7);
  2453. break;
  2454. }
  2455. }
  2456. return m;
  2457. };
  2458. return Tensor;
  2459. })();
  2460. tensorflow.AttrValue = (function() {
  2461. function AttrValue(p) {
  2462. if (p)
  2463. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2464. if (p[ks[i]] != null)
  2465. this[ks[i]] = p[ks[i]];
  2466. }
  2467. AttrValue.prototype.list = null;
  2468. AttrValue.prototype.s = $util.newBuffer([]);
  2469. AttrValue.prototype.i = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
  2470. AttrValue.prototype.f = 0;
  2471. AttrValue.prototype.b = false;
  2472. AttrValue.prototype.type = 0;
  2473. AttrValue.prototype.shape = null;
  2474. AttrValue.prototype.tensor = null;
  2475. AttrValue.prototype.placeholder = "";
  2476. AttrValue.prototype.func = null;
  2477. var $oneOfFields;
  2478. Object.defineProperty(AttrValue.prototype, "value", {
  2479. get: $util.oneOfGetter($oneOfFields = ["list", "s", "i", "f", "b", "type", "shape", "tensor", "placeholder", "func"]),
  2480. set: $util.oneOfSetter($oneOfFields)
  2481. });
  2482. AttrValue.decode = function decode(r, l) {
  2483. if (!(r instanceof $Reader))
  2484. r = $Reader.create(r);
  2485. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.AttrValue();
  2486. while (r.pos < c) {
  2487. var t = r.uint32();
  2488. switch (t >>> 3) {
  2489. case 1:
  2490. m.list = $root.tensorflow.AttrValue.ListValue.decode(r, r.uint32());
  2491. break;
  2492. case 2:
  2493. m.s = r.bytes();
  2494. break;
  2495. case 3:
  2496. m.i = r.int64();
  2497. break;
  2498. case 4:
  2499. m.f = r.float();
  2500. break;
  2501. case 5:
  2502. m.b = r.bool();
  2503. break;
  2504. case 6:
  2505. m.type = r.int32();
  2506. break;
  2507. case 7:
  2508. m.shape = $root.tensorflow.TensorShape.decode(r, r.uint32());
  2509. break;
  2510. case 8:
  2511. m.tensor = $root.tensorflow.Tensor.decode(r, r.uint32());
  2512. break;
  2513. case 9:
  2514. m.placeholder = r.string();
  2515. break;
  2516. case 10:
  2517. m.func = $root.tensorflow.NameAttrList.decode(r, r.uint32());
  2518. break;
  2519. default:
  2520. r.skipType(t & 7);
  2521. break;
  2522. }
  2523. }
  2524. return m;
  2525. };
  2526. AttrValue.ListValue = (function() {
  2527. function ListValue(p) {
  2528. this.s = [];
  2529. this.i = [];
  2530. this.f = [];
  2531. this.b = [];
  2532. this.type = [];
  2533. this.shape = [];
  2534. this.tensor = [];
  2535. this.func = [];
  2536. if (p)
  2537. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2538. if (p[ks[i]] != null)
  2539. this[ks[i]] = p[ks[i]];
  2540. }
  2541. ListValue.prototype.s = $util.emptyArray;
  2542. ListValue.prototype.i = $util.emptyArray;
  2543. ListValue.prototype.f = $util.emptyArray;
  2544. ListValue.prototype.b = $util.emptyArray;
  2545. ListValue.prototype.type = $util.emptyArray;
  2546. ListValue.prototype.shape = $util.emptyArray;
  2547. ListValue.prototype.tensor = $util.emptyArray;
  2548. ListValue.prototype.func = $util.emptyArray;
  2549. ListValue.decode = function decode(r, l) {
  2550. if (!(r instanceof $Reader))
  2551. r = $Reader.create(r);
  2552. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.AttrValue.ListValue();
  2553. while (r.pos < c) {
  2554. var t = r.uint32();
  2555. switch (t >>> 3) {
  2556. case 2:
  2557. if (!(m.s && m.s.length))
  2558. m.s = [];
  2559. m.s.push(r.bytes());
  2560. break;
  2561. case 3:
  2562. if (!(m.i && m.i.length))
  2563. m.i = [];
  2564. if ((t & 7) === 2) {
  2565. var c2 = r.uint32() + r.pos;
  2566. while (r.pos < c2)
  2567. m.i.push(r.int64());
  2568. } else
  2569. m.i.push(r.int64());
  2570. break;
  2571. case 4:
  2572. if (!(m.f && m.f.length))
  2573. m.f = [];
  2574. if ((t & 7) === 2) {
  2575. var c2 = r.uint32() + r.pos;
  2576. while (r.pos < c2)
  2577. m.f.push(r.float());
  2578. } else
  2579. m.f.push(r.float());
  2580. break;
  2581. case 5:
  2582. if (!(m.b && m.b.length))
  2583. m.b = [];
  2584. if ((t & 7) === 2) {
  2585. var c2 = r.uint32() + r.pos;
  2586. while (r.pos < c2)
  2587. m.b.push(r.bool());
  2588. } else
  2589. m.b.push(r.bool());
  2590. break;
  2591. case 6:
  2592. if (!(m.type && m.type.length))
  2593. m.type = [];
  2594. if ((t & 7) === 2) {
  2595. var c2 = r.uint32() + r.pos;
  2596. while (r.pos < c2)
  2597. m.type.push(r.int32());
  2598. } else
  2599. m.type.push(r.int32());
  2600. break;
  2601. case 7:
  2602. if (!(m.shape && m.shape.length))
  2603. m.shape = [];
  2604. m.shape.push($root.tensorflow.TensorShape.decode(r, r.uint32()));
  2605. break;
  2606. case 8:
  2607. if (!(m.tensor && m.tensor.length))
  2608. m.tensor = [];
  2609. m.tensor.push($root.tensorflow.Tensor.decode(r, r.uint32()));
  2610. break;
  2611. case 9:
  2612. if (!(m.func && m.func.length))
  2613. m.func = [];
  2614. m.func.push($root.tensorflow.NameAttrList.decode(r, r.uint32()));
  2615. break;
  2616. default:
  2617. r.skipType(t & 7);
  2618. break;
  2619. }
  2620. }
  2621. return m;
  2622. };
  2623. return ListValue;
  2624. })();
  2625. return AttrValue;
  2626. })();
  2627. tensorflow.NameAttrList = (function() {
  2628. function NameAttrList(p) {
  2629. this.attr = {};
  2630. if (p)
  2631. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2632. if (p[ks[i]] != null)
  2633. this[ks[i]] = p[ks[i]];
  2634. }
  2635. NameAttrList.prototype.name = "";
  2636. NameAttrList.prototype.attr = $util.emptyObject;
  2637. NameAttrList.decode = function decode(r, l) {
  2638. if (!(r instanceof $Reader))
  2639. r = $Reader.create(r);
  2640. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.NameAttrList(), k;
  2641. while (r.pos < c) {
  2642. var t = r.uint32();
  2643. switch (t >>> 3) {
  2644. case 1:
  2645. m.name = r.string();
  2646. break;
  2647. case 2:
  2648. r.skip().pos++;
  2649. if (m.attr === $util.emptyObject)
  2650. m.attr = {};
  2651. k = r.string();
  2652. r.pos++;
  2653. m.attr[k] = $root.tensorflow.AttrValue.decode(r, r.uint32());
  2654. break;
  2655. default:
  2656. r.skipType(t & 7);
  2657. break;
  2658. }
  2659. }
  2660. return m;
  2661. };
  2662. return NameAttrList;
  2663. })();
  2664. tensorflow.NodeDef = (function() {
  2665. function NodeDef(p) {
  2666. this.input = [];
  2667. this.attr = {};
  2668. if (p)
  2669. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2670. if (p[ks[i]] != null)
  2671. this[ks[i]] = p[ks[i]];
  2672. }
  2673. NodeDef.prototype.name = "";
  2674. NodeDef.prototype.op = "";
  2675. NodeDef.prototype.input = $util.emptyArray;
  2676. NodeDef.prototype.device = "";
  2677. NodeDef.prototype.attr = $util.emptyObject;
  2678. NodeDef.decode = function decode(r, l) {
  2679. if (!(r instanceof $Reader))
  2680. r = $Reader.create(r);
  2681. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.NodeDef(), k;
  2682. while (r.pos < c) {
  2683. var t = r.uint32();
  2684. switch (t >>> 3) {
  2685. case 1:
  2686. m.name = r.string();
  2687. break;
  2688. case 2:
  2689. m.op = r.string();
  2690. break;
  2691. case 3:
  2692. if (!(m.input && m.input.length))
  2693. m.input = [];
  2694. m.input.push(r.string());
  2695. break;
  2696. case 4:
  2697. m.device = r.string();
  2698. break;
  2699. case 5:
  2700. r.skip().pos++;
  2701. if (m.attr === $util.emptyObject)
  2702. m.attr = {};
  2703. k = r.string();
  2704. r.pos++;
  2705. m.attr[k] = $root.tensorflow.AttrValue.decode(r, r.uint32());
  2706. break;
  2707. default:
  2708. r.skipType(t & 7);
  2709. break;
  2710. }
  2711. }
  2712. return m;
  2713. };
  2714. return NodeDef;
  2715. })();
  2716. tensorflow.VersionDef = (function() {
  2717. function VersionDef(p) {
  2718. this.badConsumers = [];
  2719. if (p)
  2720. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2721. if (p[ks[i]] != null)
  2722. this[ks[i]] = p[ks[i]];
  2723. }
  2724. VersionDef.prototype.producer = 0;
  2725. VersionDef.prototype.minConsumer = 0;
  2726. VersionDef.prototype.badConsumers = $util.emptyArray;
  2727. VersionDef.decode = function decode(r, l) {
  2728. if (!(r instanceof $Reader))
  2729. r = $Reader.create(r);
  2730. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.VersionDef();
  2731. while (r.pos < c) {
  2732. var t = r.uint32();
  2733. switch (t >>> 3) {
  2734. case 1:
  2735. m.producer = r.int32();
  2736. break;
  2737. case 2:
  2738. m.minConsumer = r.int32();
  2739. break;
  2740. case 3:
  2741. if (!(m.badConsumers && m.badConsumers.length))
  2742. m.badConsumers = [];
  2743. if ((t & 7) === 2) {
  2744. var c2 = r.uint32() + r.pos;
  2745. while (r.pos < c2)
  2746. m.badConsumers.push(r.int32());
  2747. } else
  2748. m.badConsumers.push(r.int32());
  2749. break;
  2750. default:
  2751. r.skipType(t & 7);
  2752. break;
  2753. }
  2754. }
  2755. return m;
  2756. };
  2757. return VersionDef;
  2758. })();
  2759. tensorflow.GraphDef = (function() {
  2760. function GraphDef(p) {
  2761. this.node = [];
  2762. if (p)
  2763. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2764. if (p[ks[i]] != null)
  2765. this[ks[i]] = p[ks[i]];
  2766. }
  2767. GraphDef.prototype.node = $util.emptyArray;
  2768. GraphDef.prototype.versions = null;
  2769. GraphDef.prototype.library = null;
  2770. GraphDef.decode = function decode(r, l) {
  2771. if (!(r instanceof $Reader))
  2772. r = $Reader.create(r);
  2773. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.GraphDef();
  2774. while (r.pos < c) {
  2775. var t = r.uint32();
  2776. switch (t >>> 3) {
  2777. case 1:
  2778. if (!(m.node && m.node.length))
  2779. m.node = [];
  2780. m.node.push($root.tensorflow.NodeDef.decode(r, r.uint32()));
  2781. break;
  2782. case 4:
  2783. m.versions = $root.tensorflow.VersionDef.decode(r, r.uint32());
  2784. break;
  2785. case 2:
  2786. m.library = $root.tensorflow.FunctionDefLibrary.decode(r, r.uint32());
  2787. break;
  2788. default:
  2789. r.skipType(t & 7);
  2790. break;
  2791. }
  2792. }
  2793. return m;
  2794. };
  2795. return GraphDef;
  2796. })();
  2797. tensorflow.CollectionDef = (function() {
  2798. function CollectionDef(p) {
  2799. if (p)
  2800. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2801. if (p[ks[i]] != null)
  2802. this[ks[i]] = p[ks[i]];
  2803. }
  2804. CollectionDef.prototype.nodeList = null;
  2805. CollectionDef.prototype.bytesList = null;
  2806. CollectionDef.prototype.int64List = null;
  2807. CollectionDef.prototype.floatList = null;
  2808. CollectionDef.prototype.anyList = null;
  2809. var $oneOfFields;
  2810. Object.defineProperty(CollectionDef.prototype, "kind", {
  2811. get: $util.oneOfGetter($oneOfFields = ["nodeList", "bytesList", "int64List", "floatList", "anyList"]),
  2812. set: $util.oneOfSetter($oneOfFields)
  2813. });
  2814. CollectionDef.decode = function decode(r, l) {
  2815. if (!(r instanceof $Reader))
  2816. r = $Reader.create(r);
  2817. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.CollectionDef();
  2818. while (r.pos < c) {
  2819. var t = r.uint32();
  2820. switch (t >>> 3) {
  2821. case 1:
  2822. m.nodeList = $root.tensorflow.CollectionDef.NodeList.decode(r, r.uint32());
  2823. break;
  2824. case 2:
  2825. m.bytesList = $root.tensorflow.CollectionDef.BytesList.decode(r, r.uint32());
  2826. break;
  2827. case 3:
  2828. m.int64List = $root.tensorflow.CollectionDef.Int64List.decode(r, r.uint32());
  2829. break;
  2830. case 4:
  2831. m.floatList = $root.tensorflow.CollectionDef.FloatList.decode(r, r.uint32());
  2832. break;
  2833. case 5:
  2834. m.anyList = $root.tensorflow.CollectionDef.AnyList.decode(r, r.uint32());
  2835. break;
  2836. default:
  2837. r.skipType(t & 7);
  2838. break;
  2839. }
  2840. }
  2841. return m;
  2842. };
  2843. CollectionDef.NodeList = (function() {
  2844. function NodeList(p) {
  2845. this.value = [];
  2846. if (p)
  2847. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2848. if (p[ks[i]] != null)
  2849. this[ks[i]] = p[ks[i]];
  2850. }
  2851. NodeList.prototype.value = $util.emptyArray;
  2852. NodeList.decode = function decode(r, l) {
  2853. if (!(r instanceof $Reader))
  2854. r = $Reader.create(r);
  2855. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.CollectionDef.NodeList();
  2856. while (r.pos < c) {
  2857. var t = r.uint32();
  2858. switch (t >>> 3) {
  2859. case 1:
  2860. if (!(m.value && m.value.length))
  2861. m.value = [];
  2862. m.value.push(r.string());
  2863. break;
  2864. default:
  2865. r.skipType(t & 7);
  2866. break;
  2867. }
  2868. }
  2869. return m;
  2870. };
  2871. return NodeList;
  2872. })();
  2873. CollectionDef.BytesList = (function() {
  2874. function BytesList(p) {
  2875. this.value = [];
  2876. if (p)
  2877. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2878. if (p[ks[i]] != null)
  2879. this[ks[i]] = p[ks[i]];
  2880. }
  2881. BytesList.prototype.value = $util.emptyArray;
  2882. BytesList.decode = function decode(r, l) {
  2883. if (!(r instanceof $Reader))
  2884. r = $Reader.create(r);
  2885. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.CollectionDef.BytesList();
  2886. while (r.pos < c) {
  2887. var t = r.uint32();
  2888. switch (t >>> 3) {
  2889. case 1:
  2890. if (!(m.value && m.value.length))
  2891. m.value = [];
  2892. m.value.push(r.bytes());
  2893. break;
  2894. default:
  2895. r.skipType(t & 7);
  2896. break;
  2897. }
  2898. }
  2899. return m;
  2900. };
  2901. return BytesList;
  2902. })();
  2903. CollectionDef.Int64List = (function() {
  2904. function Int64List(p) {
  2905. this.value = [];
  2906. if (p)
  2907. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2908. if (p[ks[i]] != null)
  2909. this[ks[i]] = p[ks[i]];
  2910. }
  2911. Int64List.prototype.value = $util.emptyArray;
  2912. Int64List.decode = function decode(r, l) {
  2913. if (!(r instanceof $Reader))
  2914. r = $Reader.create(r);
  2915. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.CollectionDef.Int64List();
  2916. while (r.pos < c) {
  2917. var t = r.uint32();
  2918. switch (t >>> 3) {
  2919. case 1:
  2920. if (!(m.value && m.value.length))
  2921. m.value = [];
  2922. if ((t & 7) === 2) {
  2923. var c2 = r.uint32() + r.pos;
  2924. while (r.pos < c2)
  2925. m.value.push(r.int64());
  2926. } else
  2927. m.value.push(r.int64());
  2928. break;
  2929. default:
  2930. r.skipType(t & 7);
  2931. break;
  2932. }
  2933. }
  2934. return m;
  2935. };
  2936. return Int64List;
  2937. })();
  2938. CollectionDef.FloatList = (function() {
  2939. function FloatList(p) {
  2940. this.value = [];
  2941. if (p)
  2942. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2943. if (p[ks[i]] != null)
  2944. this[ks[i]] = p[ks[i]];
  2945. }
  2946. FloatList.prototype.value = $util.emptyArray;
  2947. FloatList.decode = function decode(r, l) {
  2948. if (!(r instanceof $Reader))
  2949. r = $Reader.create(r);
  2950. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.CollectionDef.FloatList();
  2951. while (r.pos < c) {
  2952. var t = r.uint32();
  2953. switch (t >>> 3) {
  2954. case 1:
  2955. if (!(m.value && m.value.length))
  2956. m.value = [];
  2957. if ((t & 7) === 2) {
  2958. var c2 = r.uint32() + r.pos;
  2959. while (r.pos < c2)
  2960. m.value.push(r.float());
  2961. } else
  2962. m.value.push(r.float());
  2963. break;
  2964. default:
  2965. r.skipType(t & 7);
  2966. break;
  2967. }
  2968. }
  2969. return m;
  2970. };
  2971. return FloatList;
  2972. })();
  2973. CollectionDef.AnyList = (function() {
  2974. function AnyList(p) {
  2975. this.value = [];
  2976. if (p)
  2977. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  2978. if (p[ks[i]] != null)
  2979. this[ks[i]] = p[ks[i]];
  2980. }
  2981. AnyList.prototype.value = $util.emptyArray;
  2982. AnyList.decode = function decode(r, l) {
  2983. if (!(r instanceof $Reader))
  2984. r = $Reader.create(r);
  2985. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.CollectionDef.AnyList();
  2986. while (r.pos < c) {
  2987. var t = r.uint32();
  2988. switch (t >>> 3) {
  2989. case 1:
  2990. if (!(m.value && m.value.length))
  2991. m.value = [];
  2992. m.value.push($root.tensorflow.Any.decode(r, r.uint32()));
  2993. break;
  2994. default:
  2995. r.skipType(t & 7);
  2996. break;
  2997. }
  2998. }
  2999. return m;
  3000. };
  3001. return AnyList;
  3002. })();
  3003. return CollectionDef;
  3004. })();
  3005. tensorflow.SaverDef = (function() {
  3006. function SaverDef(p) {
  3007. if (p)
  3008. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3009. if (p[ks[i]] != null)
  3010. this[ks[i]] = p[ks[i]];
  3011. }
  3012. SaverDef.prototype.filenameTensorName = "";
  3013. SaverDef.prototype.saveTensorName = "";
  3014. SaverDef.prototype.restoreOpName = "";
  3015. SaverDef.prototype.maxToKeep = 0;
  3016. SaverDef.prototype.sharded = false;
  3017. SaverDef.prototype.keepCheckpointEveryNHours = 0;
  3018. SaverDef.prototype.version = 0;
  3019. SaverDef.decode = function decode(r, l) {
  3020. if (!(r instanceof $Reader))
  3021. r = $Reader.create(r);
  3022. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.SaverDef();
  3023. while (r.pos < c) {
  3024. var t = r.uint32();
  3025. switch (t >>> 3) {
  3026. case 1:
  3027. m.filenameTensorName = r.string();
  3028. break;
  3029. case 2:
  3030. m.saveTensorName = r.string();
  3031. break;
  3032. case 3:
  3033. m.restoreOpName = r.string();
  3034. break;
  3035. case 4:
  3036. m.maxToKeep = r.int32();
  3037. break;
  3038. case 5:
  3039. m.sharded = r.bool();
  3040. break;
  3041. case 6:
  3042. m.keepCheckpointEveryNHours = r.float();
  3043. break;
  3044. case 7:
  3045. m.version = r.int32();
  3046. break;
  3047. default:
  3048. r.skipType(t & 7);
  3049. break;
  3050. }
  3051. }
  3052. return m;
  3053. };
  3054. SaverDef.CheckpointFormatVersion = (function() {
  3055. var valuesById = {}, values = Object.create(valuesById);
  3056. values[valuesById[0] = "LEGACY"] = 0;
  3057. values[valuesById[1] = "V1"] = 1;
  3058. values[valuesById[2] = "V2"] = 2;
  3059. return values;
  3060. })();
  3061. return SaverDef;
  3062. })();
  3063. tensorflow.TensorInfo = (function() {
  3064. function TensorInfo(p) {
  3065. if (p)
  3066. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3067. if (p[ks[i]] != null)
  3068. this[ks[i]] = p[ks[i]];
  3069. }
  3070. TensorInfo.prototype.name = "";
  3071. TensorInfo.prototype.cooSparse = null;
  3072. TensorInfo.prototype.dtype = 0;
  3073. TensorInfo.prototype.tensorShape = null;
  3074. var $oneOfFields;
  3075. Object.defineProperty(TensorInfo.prototype, "encoding", {
  3076. get: $util.oneOfGetter($oneOfFields = ["name", "cooSparse"]),
  3077. set: $util.oneOfSetter($oneOfFields)
  3078. });
  3079. TensorInfo.decode = function decode(r, l) {
  3080. if (!(r instanceof $Reader))
  3081. r = $Reader.create(r);
  3082. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.TensorInfo();
  3083. while (r.pos < c) {
  3084. var t = r.uint32();
  3085. switch (t >>> 3) {
  3086. case 1:
  3087. m.name = r.string();
  3088. break;
  3089. case 4:
  3090. m.cooSparse = $root.tensorflow.TensorInfo.CooSparse.decode(r, r.uint32());
  3091. break;
  3092. case 2:
  3093. m.dtype = r.int32();
  3094. break;
  3095. case 3:
  3096. m.tensorShape = $root.tensorflow.TensorShape.decode(r, r.uint32());
  3097. break;
  3098. default:
  3099. r.skipType(t & 7);
  3100. break;
  3101. }
  3102. }
  3103. return m;
  3104. };
  3105. TensorInfo.CooSparse = (function() {
  3106. function CooSparse(p) {
  3107. if (p)
  3108. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3109. if (p[ks[i]] != null)
  3110. this[ks[i]] = p[ks[i]];
  3111. }
  3112. CooSparse.prototype.valuesTensorName = "";
  3113. CooSparse.prototype.indicesTensorName = "";
  3114. CooSparse.prototype.denseShapeTensorName = "";
  3115. CooSparse.decode = function decode(r, l) {
  3116. if (!(r instanceof $Reader))
  3117. r = $Reader.create(r);
  3118. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.TensorInfo.CooSparse();
  3119. while (r.pos < c) {
  3120. var t = r.uint32();
  3121. switch (t >>> 3) {
  3122. case 1:
  3123. m.valuesTensorName = r.string();
  3124. break;
  3125. case 2:
  3126. m.indicesTensorName = r.string();
  3127. break;
  3128. case 3:
  3129. m.denseShapeTensorName = r.string();
  3130. break;
  3131. default:
  3132. r.skipType(t & 7);
  3133. break;
  3134. }
  3135. }
  3136. return m;
  3137. };
  3138. return CooSparse;
  3139. })();
  3140. return TensorInfo;
  3141. })();
  3142. tensorflow.SignatureDef = (function() {
  3143. function SignatureDef(p) {
  3144. this.inputs = {};
  3145. this.outputs = {};
  3146. if (p)
  3147. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3148. if (p[ks[i]] != null)
  3149. this[ks[i]] = p[ks[i]];
  3150. }
  3151. SignatureDef.prototype.inputs = $util.emptyObject;
  3152. SignatureDef.prototype.outputs = $util.emptyObject;
  3153. SignatureDef.prototype.methodName = "";
  3154. SignatureDef.decode = function decode(r, l) {
  3155. if (!(r instanceof $Reader))
  3156. r = $Reader.create(r);
  3157. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.SignatureDef(), k;
  3158. while (r.pos < c) {
  3159. var t = r.uint32();
  3160. switch (t >>> 3) {
  3161. case 1:
  3162. r.skip().pos++;
  3163. if (m.inputs === $util.emptyObject)
  3164. m.inputs = {};
  3165. k = r.string();
  3166. r.pos++;
  3167. m.inputs[k] = $root.tensorflow.TensorInfo.decode(r, r.uint32());
  3168. break;
  3169. case 2:
  3170. r.skip().pos++;
  3171. if (m.outputs === $util.emptyObject)
  3172. m.outputs = {};
  3173. k = r.string();
  3174. r.pos++;
  3175. m.outputs[k] = $root.tensorflow.TensorInfo.decode(r, r.uint32());
  3176. break;
  3177. case 3:
  3178. m.methodName = r.string();
  3179. break;
  3180. default:
  3181. r.skipType(t & 7);
  3182. break;
  3183. }
  3184. }
  3185. return m;
  3186. };
  3187. return SignatureDef;
  3188. })();
  3189. tensorflow.AssetFileDef = (function() {
  3190. function AssetFileDef(p) {
  3191. if (p)
  3192. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3193. if (p[ks[i]] != null)
  3194. this[ks[i]] = p[ks[i]];
  3195. }
  3196. AssetFileDef.prototype.tensorInfo = null;
  3197. AssetFileDef.prototype.filename = "";
  3198. AssetFileDef.decode = function decode(r, l) {
  3199. if (!(r instanceof $Reader))
  3200. r = $Reader.create(r);
  3201. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.AssetFileDef();
  3202. while (r.pos < c) {
  3203. var t = r.uint32();
  3204. switch (t >>> 3) {
  3205. case 1:
  3206. m.tensorInfo = $root.tensorflow.TensorInfo.decode(r, r.uint32());
  3207. break;
  3208. case 2:
  3209. m.filename = r.string();
  3210. break;
  3211. default:
  3212. r.skipType(t & 7);
  3213. break;
  3214. }
  3215. }
  3216. return m;
  3217. };
  3218. return AssetFileDef;
  3219. })();
  3220. tensorflow.OpDef = (function() {
  3221. function OpDef(p) {
  3222. this.inputArg = [];
  3223. this.outputArg = [];
  3224. this.attr = [];
  3225. if (p)
  3226. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3227. if (p[ks[i]] != null)
  3228. this[ks[i]] = p[ks[i]];
  3229. }
  3230. OpDef.prototype.name = "";
  3231. OpDef.prototype.inputArg = $util.emptyArray;
  3232. OpDef.prototype.outputArg = $util.emptyArray;
  3233. OpDef.prototype.attr = $util.emptyArray;
  3234. OpDef.prototype.deprecation = null;
  3235. OpDef.prototype.summary = "";
  3236. OpDef.prototype.description = "";
  3237. OpDef.prototype.isCommutative = false;
  3238. OpDef.prototype.isAggregate = false;
  3239. OpDef.prototype.isStateful = false;
  3240. OpDef.prototype.allowsUninitializedInput = false;
  3241. OpDef.decode = function decode(r, l) {
  3242. if (!(r instanceof $Reader))
  3243. r = $Reader.create(r);
  3244. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.OpDef();
  3245. while (r.pos < c) {
  3246. var t = r.uint32();
  3247. switch (t >>> 3) {
  3248. case 1:
  3249. m.name = r.string();
  3250. break;
  3251. case 2:
  3252. if (!(m.inputArg && m.inputArg.length))
  3253. m.inputArg = [];
  3254. m.inputArg.push($root.tensorflow.OpDef.ArgDef.decode(r, r.uint32()));
  3255. break;
  3256. case 3:
  3257. if (!(m.outputArg && m.outputArg.length))
  3258. m.outputArg = [];
  3259. m.outputArg.push($root.tensorflow.OpDef.ArgDef.decode(r, r.uint32()));
  3260. break;
  3261. case 4:
  3262. if (!(m.attr && m.attr.length))
  3263. m.attr = [];
  3264. m.attr.push($root.tensorflow.OpDef.AttrDef.decode(r, r.uint32()));
  3265. break;
  3266. case 8:
  3267. m.deprecation = $root.tensorflow.OpDef.OpDeprecation.decode(r, r.uint32());
  3268. break;
  3269. case 5:
  3270. m.summary = r.string();
  3271. break;
  3272. case 6:
  3273. m.description = r.string();
  3274. break;
  3275. case 18:
  3276. m.isCommutative = r.bool();
  3277. break;
  3278. case 16:
  3279. m.isAggregate = r.bool();
  3280. break;
  3281. case 17:
  3282. m.isStateful = r.bool();
  3283. break;
  3284. case 19:
  3285. m.allowsUninitializedInput = r.bool();
  3286. break;
  3287. default:
  3288. r.skipType(t & 7);
  3289. break;
  3290. }
  3291. }
  3292. return m;
  3293. };
  3294. OpDef.ArgDef = (function() {
  3295. function ArgDef(p) {
  3296. if (p)
  3297. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3298. if (p[ks[i]] != null)
  3299. this[ks[i]] = p[ks[i]];
  3300. }
  3301. ArgDef.prototype.name = "";
  3302. ArgDef.prototype.description = "";
  3303. ArgDef.prototype.type = 0;
  3304. ArgDef.prototype.typeAttr = "";
  3305. ArgDef.prototype.numberAttr = "";
  3306. ArgDef.prototype.typeListAttr = "";
  3307. ArgDef.prototype.isRef = false;
  3308. ArgDef.decode = function decode(r, l) {
  3309. if (!(r instanceof $Reader))
  3310. r = $Reader.create(r);
  3311. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.OpDef.ArgDef();
  3312. while (r.pos < c) {
  3313. var t = r.uint32();
  3314. switch (t >>> 3) {
  3315. case 1:
  3316. m.name = r.string();
  3317. break;
  3318. case 2:
  3319. m.description = r.string();
  3320. break;
  3321. case 3:
  3322. m.type = r.int32();
  3323. break;
  3324. case 4:
  3325. m.typeAttr = r.string();
  3326. break;
  3327. case 5:
  3328. m.numberAttr = r.string();
  3329. break;
  3330. case 6:
  3331. m.typeListAttr = r.string();
  3332. break;
  3333. case 16:
  3334. m.isRef = r.bool();
  3335. break;
  3336. default:
  3337. r.skipType(t & 7);
  3338. break;
  3339. }
  3340. }
  3341. return m;
  3342. };
  3343. return ArgDef;
  3344. })();
  3345. OpDef.AttrDef = (function() {
  3346. function AttrDef(p) {
  3347. if (p)
  3348. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3349. if (p[ks[i]] != null)
  3350. this[ks[i]] = p[ks[i]];
  3351. }
  3352. AttrDef.prototype.name = "";
  3353. AttrDef.prototype.type = "";
  3354. AttrDef.prototype.defaultValue = null;
  3355. AttrDef.prototype.description = "";
  3356. AttrDef.prototype.hasMinimum = false;
  3357. AttrDef.prototype.minimum = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
  3358. AttrDef.prototype.allowedValues = null;
  3359. AttrDef.decode = function decode(r, l) {
  3360. if (!(r instanceof $Reader))
  3361. r = $Reader.create(r);
  3362. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.OpDef.AttrDef();
  3363. while (r.pos < c) {
  3364. var t = r.uint32();
  3365. switch (t >>> 3) {
  3366. case 1:
  3367. m.name = r.string();
  3368. break;
  3369. case 2:
  3370. m.type = r.string();
  3371. break;
  3372. case 3:
  3373. m.defaultValue = $root.tensorflow.AttrValue.decode(r, r.uint32());
  3374. break;
  3375. case 4:
  3376. m.description = r.string();
  3377. break;
  3378. case 5:
  3379. m.hasMinimum = r.bool();
  3380. break;
  3381. case 6:
  3382. m.minimum = r.int64();
  3383. break;
  3384. case 7:
  3385. m.allowedValues = $root.tensorflow.AttrValue.decode(r, r.uint32());
  3386. break;
  3387. default:
  3388. r.skipType(t & 7);
  3389. break;
  3390. }
  3391. }
  3392. return m;
  3393. };
  3394. return AttrDef;
  3395. })();
  3396. OpDef.OpDeprecation = (function() {
  3397. function OpDeprecation(p) {
  3398. if (p)
  3399. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3400. if (p[ks[i]] != null)
  3401. this[ks[i]] = p[ks[i]];
  3402. }
  3403. OpDeprecation.prototype.version = 0;
  3404. OpDeprecation.prototype.explanation = "";
  3405. OpDeprecation.decode = function decode(r, l) {
  3406. if (!(r instanceof $Reader))
  3407. r = $Reader.create(r);
  3408. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.OpDef.OpDeprecation();
  3409. while (r.pos < c) {
  3410. var t = r.uint32();
  3411. switch (t >>> 3) {
  3412. case 1:
  3413. m.version = r.int32();
  3414. break;
  3415. case 2:
  3416. m.explanation = r.string();
  3417. break;
  3418. default:
  3419. r.skipType(t & 7);
  3420. break;
  3421. }
  3422. }
  3423. return m;
  3424. };
  3425. return OpDeprecation;
  3426. })();
  3427. return OpDef;
  3428. })();
  3429. tensorflow.OpList = (function() {
  3430. function OpList(p) {
  3431. this.op = [];
  3432. if (p)
  3433. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3434. if (p[ks[i]] != null)
  3435. this[ks[i]] = p[ks[i]];
  3436. }
  3437. OpList.prototype.op = $util.emptyArray;
  3438. OpList.decode = function decode(r, l) {
  3439. if (!(r instanceof $Reader))
  3440. r = $Reader.create(r);
  3441. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.OpList();
  3442. while (r.pos < c) {
  3443. var t = r.uint32();
  3444. switch (t >>> 3) {
  3445. case 1:
  3446. if (!(m.op && m.op.length))
  3447. m.op = [];
  3448. m.op.push($root.tensorflow.OpDef.decode(r, r.uint32()));
  3449. break;
  3450. default:
  3451. r.skipType(t & 7);
  3452. break;
  3453. }
  3454. }
  3455. return m;
  3456. };
  3457. return OpList;
  3458. })();
  3459. tensorflow.MetaGraphDef = (function() {
  3460. function MetaGraphDef(p) {
  3461. this.collectionDef = {};
  3462. this.signatureDef = {};
  3463. this.assetFileDef = [];
  3464. if (p)
  3465. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3466. if (p[ks[i]] != null)
  3467. this[ks[i]] = p[ks[i]];
  3468. }
  3469. MetaGraphDef.prototype.metaInfoDef = null;
  3470. MetaGraphDef.prototype.graphDef = null;
  3471. MetaGraphDef.prototype.saverDef = null;
  3472. MetaGraphDef.prototype.collectionDef = $util.emptyObject;
  3473. MetaGraphDef.prototype.signatureDef = $util.emptyObject;
  3474. MetaGraphDef.prototype.assetFileDef = $util.emptyArray;
  3475. MetaGraphDef.decode = function decode(r, l) {
  3476. if (!(r instanceof $Reader))
  3477. r = $Reader.create(r);
  3478. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.MetaGraphDef(), k;
  3479. while (r.pos < c) {
  3480. var t = r.uint32();
  3481. switch (t >>> 3) {
  3482. case 1:
  3483. m.metaInfoDef = $root.tensorflow.MetaGraphDef.MetaInfoDef.decode(r, r.uint32());
  3484. break;
  3485. case 2:
  3486. m.graphDef = $root.tensorflow.GraphDef.decode(r, r.uint32());
  3487. break;
  3488. case 3:
  3489. m.saverDef = $root.tensorflow.SaverDef.decode(r, r.uint32());
  3490. break;
  3491. case 4:
  3492. r.skip().pos++;
  3493. if (m.collectionDef === $util.emptyObject)
  3494. m.collectionDef = {};
  3495. k = r.string();
  3496. r.pos++;
  3497. m.collectionDef[k] = $root.tensorflow.CollectionDef.decode(r, r.uint32());
  3498. break;
  3499. case 5:
  3500. r.skip().pos++;
  3501. if (m.signatureDef === $util.emptyObject)
  3502. m.signatureDef = {};
  3503. k = r.string();
  3504. r.pos++;
  3505. m.signatureDef[k] = $root.tensorflow.SignatureDef.decode(r, r.uint32());
  3506. break;
  3507. case 6:
  3508. if (!(m.assetFileDef && m.assetFileDef.length))
  3509. m.assetFileDef = [];
  3510. m.assetFileDef.push($root.tensorflow.AssetFileDef.decode(r, r.uint32()));
  3511. break;
  3512. default:
  3513. r.skipType(t & 7);
  3514. break;
  3515. }
  3516. }
  3517. return m;
  3518. };
  3519. MetaGraphDef.MetaInfoDef = (function() {
  3520. function MetaInfoDef(p) {
  3521. this.tags = [];
  3522. if (p)
  3523. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3524. if (p[ks[i]] != null)
  3525. this[ks[i]] = p[ks[i]];
  3526. }
  3527. MetaInfoDef.prototype.metaGraphVersion = "";
  3528. MetaInfoDef.prototype.strippedOpList = null;
  3529. MetaInfoDef.prototype.anyInfo = null;
  3530. MetaInfoDef.prototype.tags = $util.emptyArray;
  3531. MetaInfoDef.prototype.tensorflowVersion = "";
  3532. MetaInfoDef.prototype.tensorflowGitVersion = "";
  3533. MetaInfoDef.decode = function decode(r, l) {
  3534. if (!(r instanceof $Reader))
  3535. r = $Reader.create(r);
  3536. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.MetaGraphDef.MetaInfoDef();
  3537. while (r.pos < c) {
  3538. var t = r.uint32();
  3539. switch (t >>> 3) {
  3540. case 1:
  3541. m.metaGraphVersion = r.string();
  3542. break;
  3543. case 2:
  3544. m.strippedOpList = $root.tensorflow.OpList.decode(r, r.uint32());
  3545. break;
  3546. case 3:
  3547. m.anyInfo = $root.tensorflow.Any.decode(r, r.uint32());
  3548. break;
  3549. case 4:
  3550. if (!(m.tags && m.tags.length))
  3551. m.tags = [];
  3552. m.tags.push(r.string());
  3553. break;
  3554. case 5:
  3555. m.tensorflowVersion = r.string();
  3556. break;
  3557. case 6:
  3558. m.tensorflowGitVersion = r.string();
  3559. break;
  3560. default:
  3561. r.skipType(t & 7);
  3562. break;
  3563. }
  3564. }
  3565. return m;
  3566. };
  3567. return MetaInfoDef;
  3568. })();
  3569. return MetaGraphDef;
  3570. })();
  3571. tensorflow.SavedModel = (function() {
  3572. function SavedModel(p) {
  3573. this.metaGraphs = [];
  3574. if (p)
  3575. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3576. if (p[ks[i]] != null)
  3577. this[ks[i]] = p[ks[i]];
  3578. }
  3579. SavedModel.prototype.savedModelSchemaVersion = $util.Long ? $util.Long.fromBits(0,0,false) : 0;
  3580. SavedModel.prototype.metaGraphs = $util.emptyArray;
  3581. SavedModel.decode = function decode(r, l) {
  3582. if (!(r instanceof $Reader))
  3583. r = $Reader.create(r);
  3584. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.SavedModel();
  3585. while (r.pos < c) {
  3586. var t = r.uint32();
  3587. switch (t >>> 3) {
  3588. case 1:
  3589. m.savedModelSchemaVersion = r.int64();
  3590. break;
  3591. case 2:
  3592. if (!(m.metaGraphs && m.metaGraphs.length))
  3593. m.metaGraphs = [];
  3594. m.metaGraphs.push($root.tensorflow.MetaGraphDef.decode(r, r.uint32()));
  3595. break;
  3596. default:
  3597. r.skipType(t & 7);
  3598. break;
  3599. }
  3600. }
  3601. return m;
  3602. };
  3603. return SavedModel;
  3604. })();
  3605. tensorflow.FunctionDefLibrary = (function() {
  3606. function FunctionDefLibrary(p) {
  3607. this["function"] = [];
  3608. this.gradient = [];
  3609. if (p)
  3610. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3611. if (p[ks[i]] != null)
  3612. this[ks[i]] = p[ks[i]];
  3613. }
  3614. FunctionDefLibrary.prototype["function"] = $util.emptyArray;
  3615. FunctionDefLibrary.prototype.gradient = $util.emptyArray;
  3616. FunctionDefLibrary.decode = function decode(r, l) {
  3617. if (!(r instanceof $Reader))
  3618. r = $Reader.create(r);
  3619. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.FunctionDefLibrary();
  3620. while (r.pos < c) {
  3621. var t = r.uint32();
  3622. switch (t >>> 3) {
  3623. case 1:
  3624. if (!(m["function"] && m["function"].length))
  3625. m["function"] = [];
  3626. m["function"].push($root.tensorflow.FunctionDef.decode(r, r.uint32()));
  3627. break;
  3628. case 2:
  3629. if (!(m.gradient && m.gradient.length))
  3630. m.gradient = [];
  3631. m.gradient.push($root.tensorflow.GradientDef.decode(r, r.uint32()));
  3632. break;
  3633. default:
  3634. r.skipType(t & 7);
  3635. break;
  3636. }
  3637. }
  3638. return m;
  3639. };
  3640. return FunctionDefLibrary;
  3641. })();
  3642. tensorflow.FunctionDef = (function() {
  3643. function FunctionDef(p) {
  3644. this.attr = {};
  3645. this.nodeDef = [];
  3646. this.ret = {};
  3647. if (p)
  3648. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3649. if (p[ks[i]] != null)
  3650. this[ks[i]] = p[ks[i]];
  3651. }
  3652. FunctionDef.prototype.signature = null;
  3653. FunctionDef.prototype.attr = $util.emptyObject;
  3654. FunctionDef.prototype.nodeDef = $util.emptyArray;
  3655. FunctionDef.prototype.ret = $util.emptyObject;
  3656. FunctionDef.decode = function decode(r, l) {
  3657. if (!(r instanceof $Reader))
  3658. r = $Reader.create(r);
  3659. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.FunctionDef(), k;
  3660. while (r.pos < c) {
  3661. var t = r.uint32();
  3662. switch (t >>> 3) {
  3663. case 1:
  3664. m.signature = $root.tensorflow.OpDef.decode(r, r.uint32());
  3665. break;
  3666. case 5:
  3667. r.skip().pos++;
  3668. if (m.attr === $util.emptyObject)
  3669. m.attr = {};
  3670. k = r.string();
  3671. r.pos++;
  3672. m.attr[k] = $root.tensorflow.AttrValue.decode(r, r.uint32());
  3673. break;
  3674. case 3:
  3675. if (!(m.nodeDef && m.nodeDef.length))
  3676. m.nodeDef = [];
  3677. m.nodeDef.push($root.tensorflow.NodeDef.decode(r, r.uint32()));
  3678. break;
  3679. case 4:
  3680. r.skip().pos++;
  3681. if (m.ret === $util.emptyObject)
  3682. m.ret = {};
  3683. k = r.string();
  3684. r.pos++;
  3685. m.ret[k] = r.string();
  3686. break;
  3687. default:
  3688. r.skipType(t & 7);
  3689. break;
  3690. }
  3691. }
  3692. return m;
  3693. };
  3694. return FunctionDef;
  3695. })();
  3696. tensorflow.GradientDef = (function() {
  3697. function GradientDef(p) {
  3698. if (p)
  3699. for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
  3700. if (p[ks[i]] != null)
  3701. this[ks[i]] = p[ks[i]];
  3702. }
  3703. GradientDef.prototype.functionName = "";
  3704. GradientDef.prototype.gradientFunc = "";
  3705. GradientDef.decode = function decode(r, l) {
  3706. if (!(r instanceof $Reader))
  3707. r = $Reader.create(r);
  3708. var c = l === undefined ? r.len : r.pos + l, m = new $root.tensorflow.GradientDef();
  3709. while (r.pos < c) {
  3710. var t = r.uint32();
  3711. switch (t >>> 3) {
  3712. case 1:
  3713. m.functionName = r.string();
  3714. break;
  3715. case 2:
  3716. m.gradientFunc = r.string();
  3717. break;
  3718. default:
  3719. r.skipType(t & 7);
  3720. break;
  3721. }
  3722. }
  3723. return m;
  3724. };
  3725. return GradientDef;
  3726. })();
  3727. return tensorflow;
  3728. })();
  3729. module.exports = $root;
  3730. },{"protobufjs/minimal":216}],13:[function(require,module,exports){
  3731. "use strict";
  3732. Object.defineProperty(exports, "__esModule", { value: true });
  3733. var ExecutionContext = (function () {
  3734. function ExecutionContext(weightMap) {
  3735. this.weightMap = weightMap;
  3736. this.rootContext = { id: 0, frameName: '', iterationId: 0 };
  3737. this.contexts = [this.rootContext];
  3738. this.lastId = 0;
  3739. this.generateCurrentContextIds();
  3740. }
  3741. ExecutionContext.prototype.newFrame = function (id, frameName) {
  3742. return { id: id, frameName: frameName, iterationId: 0 };
  3743. };
  3744. Object.defineProperty(ExecutionContext.prototype, "currentContext", {
  3745. get: function () {
  3746. return this.contexts;
  3747. },
  3748. set: function (contexts) {
  3749. if (this.contexts !== contexts) {
  3750. this.contexts = contexts;
  3751. this.generateCurrentContextIds();
  3752. }
  3753. },
  3754. enumerable: true,
  3755. configurable: true
  3756. });
  3757. Object.defineProperty(ExecutionContext.prototype, "currentContextId", {
  3758. get: function () {
  3759. return this._currentContextIds[0];
  3760. },
  3761. enumerable: true,
  3762. configurable: true
  3763. });
  3764. Object.defineProperty(ExecutionContext.prototype, "currentContextIds", {
  3765. get: function () {
  3766. return this._currentContextIds;
  3767. },
  3768. enumerable: true,
  3769. configurable: true
  3770. });
  3771. ExecutionContext.prototype.generateCurrentContextIds = function () {
  3772. var names = [];
  3773. for (var i = 0; i < this.contexts.length - 1; i++) {
  3774. var contexts = this.contexts.slice(0, this.contexts.length - i);
  3775. names.push(this.contextIdforContexts(contexts));
  3776. }
  3777. names.push('');
  3778. this._currentContextIds = names;
  3779. };
  3780. ExecutionContext.prototype.contextIdforContexts = function (contexts) {
  3781. return contexts ?
  3782. contexts
  3783. .map(function (context) { return (context.id === 0 && context.iterationId === 0) ?
  3784. '' :
  3785. context.frameName + "-" + context.iterationId; })
  3786. .join('/') :
  3787. '';
  3788. };
  3789. ExecutionContext.prototype.enterFrame = function (frameId) {
  3790. if (this.contexts) {
  3791. this.lastId++;
  3792. this.contexts = this.contexts.slice();
  3793. this.contexts.push(this.newFrame(this.lastId, frameId));
  3794. this._currentContextIds.unshift(this.contextIdforContexts(this.contexts));
  3795. }
  3796. };
  3797. ExecutionContext.prototype.exitFrame = function () {
  3798. if (this.contexts && this.contexts.length > 1) {
  3799. this.contexts = this.contexts.slice();
  3800. this.contexts.splice(-1);
  3801. this.currentContextIds.shift();
  3802. }
  3803. else {
  3804. throw new Error('Cannot exit frame, the context is empty');
  3805. }
  3806. };
  3807. ExecutionContext.prototype.nextIteration = function () {
  3808. if (this.contexts && this.contexts.length > 0) {
  3809. this.contexts = this.contexts.slice();
  3810. this.lastId++;
  3811. var context = Object.assign({}, this.contexts[this.contexts.length - 1]);
  3812. context.iterationId += 1;
  3813. context.id = this.lastId;
  3814. this.contexts.splice(-1, 1, context);
  3815. this._currentContextIds.splice(0, 1, this.contextIdforContexts(this.contexts));
  3816. }
  3817. else {
  3818. throw new Error('Cannot increase frame iteration, the context is empty');
  3819. }
  3820. };
  3821. ExecutionContext.prototype.getWeight = function (name) {
  3822. return this.weightMap[name];
  3823. };
  3824. return ExecutionContext;
  3825. }());
  3826. exports.ExecutionContext = ExecutionContext;
  3827. },{}],14:[function(require,module,exports){
  3828. "use strict";
  3829. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3830. return new (P || (P = Promise))(function (resolve, reject) {
  3831. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  3832. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  3833. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  3834. step((generator = generator.apply(thisArg, _arguments || [])).next());
  3835. });
  3836. };
  3837. var __generator = (this && this.__generator) || function (thisArg, body) {
  3838. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  3839. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  3840. function verb(n) { return function (v) { return step([n, v]); }; }
  3841. function step(op) {
  3842. if (f) throw new TypeError("Generator is already executing.");
  3843. while (_) try {
  3844. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  3845. if (y = 0, t) op = [0, t.value];
  3846. switch (op[0]) {
  3847. case 0: case 1: t = op; break;
  3848. case 4: _.label++; return { value: op[1], done: false };
  3849. case 5: _.label++; y = op[1]; op = [0]; continue;
  3850. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  3851. default:
  3852. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  3853. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  3854. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  3855. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  3856. if (t[2]) _.ops.pop();
  3857. _.trys.pop(); continue;
  3858. }
  3859. op = body.call(thisArg, _);
  3860. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  3861. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  3862. }
  3863. };
  3864. Object.defineProperty(exports, "__esModule", { value: true });
  3865. var tfc = require("@tensorflow/tfjs-core");
  3866. var Url = require("url");
  3867. var compiled_api_1 = require("../data/compiled_api");
  3868. var operation_mapper_1 = require("../operations/operation_mapper");
  3869. var graph_executor_1 = require("./graph_executor");
  3870. var FrozenModel = (function () {
  3871. function FrozenModel(modelUrl, weightManifestUrl, requestOption) {
  3872. this.modelUrl = modelUrl;
  3873. this.weightManifestUrl = weightManifestUrl;
  3874. this.requestOption = requestOption;
  3875. this.version = 'n/a';
  3876. this.pathPrefix = this.getPathPrefix();
  3877. }
  3878. Object.defineProperty(FrozenModel.prototype, "modelVersion", {
  3879. get: function () {
  3880. return this.version;
  3881. },
  3882. enumerable: true,
  3883. configurable: true
  3884. });
  3885. Object.defineProperty(FrozenModel.prototype, "inputNodes", {
  3886. get: function () {
  3887. return this.executor.inputNodes;
  3888. },
  3889. enumerable: true,
  3890. configurable: true
  3891. });
  3892. Object.defineProperty(FrozenModel.prototype, "outputNodes", {
  3893. get: function () {
  3894. return this.executor.outputNodes;
  3895. },
  3896. enumerable: true,
  3897. configurable: true
  3898. });
  3899. Object.defineProperty(FrozenModel.prototype, "inputs", {
  3900. get: function () {
  3901. return this.executor.inputs;
  3902. },
  3903. enumerable: true,
  3904. configurable: true
  3905. });
  3906. Object.defineProperty(FrozenModel.prototype, "outputs", {
  3907. get: function () {
  3908. return this.executor.outputs;
  3909. },
  3910. enumerable: true,
  3911. configurable: true
  3912. });
  3913. FrozenModel.prototype.getPathPrefix = function () {
  3914. var url = Url.parse(this.weightManifestUrl);
  3915. var segments = url.pathname.split('/');
  3916. segments.splice(-1);
  3917. url.pathname = segments.join('/');
  3918. return Url.format(url) + '/';
  3919. };
  3920. FrozenModel.prototype.loadRemoteProtoFile = function () {
  3921. return __awaiter(this, void 0, void 0, function () {
  3922. var response, _a, _b, _c, error_1;
  3923. return __generator(this, function (_d) {
  3924. switch (_d.label) {
  3925. case 0:
  3926. _d.trys.push([0, 3, , 4]);
  3927. return [4, fetch(this.modelUrl, this.requestOption)];
  3928. case 1:
  3929. response = _d.sent();
  3930. _b = (_a = compiled_api_1.tensorflow.GraphDef).decode;
  3931. _c = Uint8Array.bind;
  3932. return [4, response.arrayBuffer()];
  3933. case 2: return [2, _b.apply(_a, [new (_c.apply(Uint8Array, [void 0, _d.sent()]))()])];
  3934. case 3:
  3935. error_1 = _d.sent();
  3936. throw new Error(this.modelUrl + " not found. " + error_1);
  3937. case 4: return [2];
  3938. }
  3939. });
  3940. });
  3941. };
  3942. FrozenModel.prototype.loadWeightManifest = function () {
  3943. return __awaiter(this, void 0, void 0, function () {
  3944. var manifest, _a, error_2;
  3945. return __generator(this, function (_b) {
  3946. switch (_b.label) {
  3947. case 0:
  3948. _b.trys.push([0, 3, , 4]);
  3949. return [4, fetch(this.weightManifestUrl, this.requestOption)];
  3950. case 1:
  3951. manifest = _b.sent();
  3952. _a = this;
  3953. return [4, manifest.clone().json()];
  3954. case 2:
  3955. _a.weightManifest = _b.sent();
  3956. return [3, 4];
  3957. case 3:
  3958. error_2 = _b.sent();
  3959. throw new Error(this.weightManifestUrl + " not found. " + error_2);
  3960. case 4: return [2];
  3961. }
  3962. });
  3963. });
  3964. };
  3965. FrozenModel.prototype.load = function () {
  3966. return __awaiter(this, void 0, void 0, function () {
  3967. var graphPromise, manifestPromise, graph, weightMap;
  3968. return __generator(this, function (_a) {
  3969. switch (_a.label) {
  3970. case 0:
  3971. graphPromise = this.loadRemoteProtoFile();
  3972. manifestPromise = this.loadWeightManifest();
  3973. return [4, Promise.all([graphPromise, manifestPromise])];
  3974. case 1:
  3975. graph = (_a.sent())[0];
  3976. this.version = graph.versions.producer + "." + graph.versions.minConsumer;
  3977. return [4, tfc.io.loadWeights(this.weightManifest, this.pathPrefix, undefined, this.requestOption)];
  3978. case 2:
  3979. weightMap = _a.sent();
  3980. this.executor =
  3981. new graph_executor_1.GraphExecutor(operation_mapper_1.OperationMapper.Instance.transformGraph(graph));
  3982. this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap);
  3983. return [2, true];
  3984. }
  3985. });
  3986. });
  3987. };
  3988. FrozenModel.prototype.predict = function (inputs, config) {
  3989. return this.execute(inputs, this.outputNodes);
  3990. };
  3991. FrozenModel.prototype.constructTensorMap = function (inputs) {
  3992. var inputArray = inputs instanceof tfc.Tensor ? [inputs] : inputs;
  3993. if (inputArray.length !== this.inputNodes.length) {
  3994. throw new Error('Input tensor count mismatch,' +
  3995. ("the frozen model has " + this.inputNodes.length + " placeholders, ") +
  3996. ("while there are " + inputArray.length + " input tensors."));
  3997. }
  3998. return this.inputNodes.reduce(function (map, inputName, i) {
  3999. map[inputName] = inputArray[i];
  4000. return map;
  4001. }, {});
  4002. };
  4003. FrozenModel.prototype.execute = function (inputs, outputs) {
  4004. outputs = outputs || this.outputNodes;
  4005. if (inputs instanceof tfc.Tensor || Array.isArray(inputs)) {
  4006. inputs = this.constructTensorMap(inputs);
  4007. }
  4008. if (this.executor.isControlFlowModel) {
  4009. throw new Error('The model contains control flow ops, ' +
  4010. 'please use executeAsync method');
  4011. }
  4012. var result = this.executor.execute(this.convertTensorMapToTensorsMap(inputs), outputs);
  4013. var keys = Object.keys(result);
  4014. return (Array.isArray(outputs) && outputs.length > 1) ?
  4015. outputs.map(function (node) { return result[node]; }) :
  4016. result[keys[0]];
  4017. };
  4018. FrozenModel.prototype.executeAsync = function (inputs, outputs) {
  4019. return __awaiter(this, void 0, void 0, function () {
  4020. var result, keys;
  4021. return __generator(this, function (_a) {
  4022. switch (_a.label) {
  4023. case 0:
  4024. if (!this.executor.isControlFlowModel) {
  4025. throw new Error('The model does not contain control flow ops, ' +
  4026. 'please use execute method for better performance.');
  4027. }
  4028. outputs = outputs || this.outputNodes;
  4029. if (inputs instanceof tfc.Tensor || Array.isArray(inputs)) {
  4030. inputs = this.constructTensorMap(inputs);
  4031. }
  4032. return [4, this.executor.executeAsync(this.convertTensorMapToTensorsMap(inputs), outputs)];
  4033. case 1:
  4034. result = _a.sent();
  4035. keys = Object.keys(result);
  4036. return [2, Array.isArray(outputs) && outputs.length > 1 ?
  4037. outputs.map(function (node) { return result[node]; }) :
  4038. result[keys[0]]];
  4039. }
  4040. });
  4041. });
  4042. };
  4043. FrozenModel.prototype.convertTensorMapToTensorsMap = function (map) {
  4044. return Object.keys(map).reduce(function (newMap, key) {
  4045. newMap[key] = [map[key]];
  4046. return newMap;
  4047. }, {});
  4048. };
  4049. FrozenModel.prototype.dispose = function () {
  4050. this.executor.dispose();
  4051. };
  4052. return FrozenModel;
  4053. }());
  4054. exports.FrozenModel = FrozenModel;
  4055. function loadFrozenModel(modelUrl, weightsManifestUrl, requestOption) {
  4056. return __awaiter(this, void 0, void 0, function () {
  4057. var model;
  4058. return __generator(this, function (_a) {
  4059. switch (_a.label) {
  4060. case 0:
  4061. model = new FrozenModel(modelUrl, weightsManifestUrl, requestOption);
  4062. return [4, model.load()];
  4063. case 1:
  4064. _a.sent();
  4065. return [2, model];
  4066. }
  4067. });
  4068. });
  4069. }
  4070. exports.loadFrozenModel = loadFrozenModel;
  4071. },{"../data/compiled_api":12,"../operations/operation_mapper":45,"./graph_executor":15,"@tensorflow/tfjs-core":54,"url":239}],15:[function(require,module,exports){
  4072. "use strict";
  4073. var __assign = (this && this.__assign) || Object.assign || function(t) {
  4074. for (var s, i = 1, n = arguments.length; i < n; i++) {
  4075. s = arguments[i];
  4076. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  4077. t[p] = s[p];
  4078. }
  4079. return t;
  4080. };
  4081. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  4082. return new (P || (P = Promise))(function (resolve, reject) {
  4083. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4084. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  4085. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  4086. step((generator = generator.apply(thisArg, _arguments || [])).next());
  4087. });
  4088. };
  4089. var __generator = (this && this.__generator) || function (thisArg, body) {
  4090. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  4091. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  4092. function verb(n) { return function (v) { return step([n, v]); }; }
  4093. function step(op) {
  4094. if (f) throw new TypeError("Generator is already executing.");
  4095. while (_) try {
  4096. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  4097. if (y = 0, t) op = [0, t.value];
  4098. switch (op[0]) {
  4099. case 0: case 1: t = op; break;
  4100. case 4: _.label++; return { value: op[1], done: false };
  4101. case 5: _.label++; y = op[1]; op = [0]; continue;
  4102. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  4103. default:
  4104. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  4105. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  4106. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  4107. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  4108. if (t[2]) _.ops.pop();
  4109. _.trys.pop(); continue;
  4110. }
  4111. op = body.call(thisArg, _);
  4112. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  4113. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  4114. }
  4115. };
  4116. Object.defineProperty(exports, "__esModule", { value: true });
  4117. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  4118. var utils_1 = require("../operations/executors/utils");
  4119. var operation_executor_1 = require("../operations/operation_executor");
  4120. var execution_context_1 = require("./execution_context");
  4121. var GraphExecutor = (function () {
  4122. function GraphExecutor(graph) {
  4123. this.graph = graph;
  4124. this.compiledOrder = [];
  4125. this._weightMap = {};
  4126. this.placeholders = graph.placeholders;
  4127. this._outputs = graph.outputs;
  4128. this.compile();
  4129. }
  4130. Object.defineProperty(GraphExecutor.prototype, "weightMap", {
  4131. get: function () {
  4132. return this._weightMap;
  4133. },
  4134. set: function (weightMap) {
  4135. var weightIds = Object.keys(weightMap).map(function (key) { return weightMap[key].map(function (tensor) { return tensor.id; }); });
  4136. this.weightIds = [].concat.apply([], weightIds);
  4137. this._weightMap = weightMap;
  4138. },
  4139. enumerable: true,
  4140. configurable: true
  4141. });
  4142. Object.defineProperty(GraphExecutor.prototype, "inputs", {
  4143. get: function () {
  4144. return this.placeholders.map(function (node) {
  4145. return {
  4146. name: node.name,
  4147. shape: node.params['shape'] ? node.params['shape'].value :
  4148. undefined,
  4149. dtype: node.params['dtype'] ? node.params['dtype'].value :
  4150. undefined
  4151. };
  4152. });
  4153. },
  4154. enumerable: true,
  4155. configurable: true
  4156. });
  4157. Object.defineProperty(GraphExecutor.prototype, "outputs", {
  4158. get: function () {
  4159. return this._outputs.map(function (node) {
  4160. return {
  4161. name: node.name,
  4162. shape: node.params['shape'] ? node.params['shape'].value :
  4163. undefined,
  4164. dtype: node.params['dtype'] ? node.params['dtype'].value :
  4165. undefined
  4166. };
  4167. });
  4168. },
  4169. enumerable: true,
  4170. configurable: true
  4171. });
  4172. Object.defineProperty(GraphExecutor.prototype, "inputNodes", {
  4173. get: function () {
  4174. return this.placeholders.map(function (node) { return node.name; });
  4175. },
  4176. enumerable: true,
  4177. configurable: true
  4178. });
  4179. Object.defineProperty(GraphExecutor.prototype, "outputNodes", {
  4180. get: function () {
  4181. return this.outputs.map(function (node) { return node.name; });
  4182. },
  4183. enumerable: true,
  4184. configurable: true
  4185. });
  4186. Object.defineProperty(GraphExecutor.prototype, "isControlFlowModel", {
  4187. get: function () {
  4188. return this.graph.withControlFlow;
  4189. },
  4190. enumerable: true,
  4191. configurable: true
  4192. });
  4193. GraphExecutor.prototype.compile = function () {
  4194. if (this.graph.withControlFlow) {
  4195. return;
  4196. }
  4197. var stack = this.graph.inputs.slice();
  4198. var visited = {};
  4199. while (stack.length > 0) {
  4200. var node = stack.pop();
  4201. visited[node.name] = true;
  4202. this.compiledOrder.push(node);
  4203. node.children.forEach(function (childNode) {
  4204. if (!visited[childNode.name] && childNode.inputNames.every(function (name) {
  4205. var nodeName = utils_1.getNodeNameAndIndex(name)[0];
  4206. return visited[nodeName];
  4207. })) {
  4208. stack.push(childNode);
  4209. }
  4210. });
  4211. }
  4212. };
  4213. GraphExecutor.prototype.execute = function (inputs, outputs) {
  4214. var _this = this;
  4215. this.checkInput(inputs);
  4216. this.checkInputShapeAndType(inputs);
  4217. var result = tfjs_core_1.tidy(function () {
  4218. var context = new execution_context_1.ExecutionContext(_this._weightMap);
  4219. var tensors = _this.compiledOrder.reduce(function (map, node) {
  4220. map[node.name] = operation_executor_1.executeOp(node, map, context);
  4221. return map;
  4222. }, __assign({}, _this.weightMap, inputs));
  4223. return _this.findOutputs(tensors, context, outputs);
  4224. });
  4225. return result;
  4226. };
  4227. GraphExecutor.prototype.executeAsync = function (inputs, outputs) {
  4228. return __awaiter(this, void 0, void 0, function () {
  4229. var _this = this;
  4230. var context, tensors, results, outputIds, inputIdArray, inputIds;
  4231. return __generator(this, function (_a) {
  4232. switch (_a.label) {
  4233. case 0:
  4234. this.checkInput(inputs);
  4235. this.checkInputShapeAndType(inputs);
  4236. context = new execution_context_1.ExecutionContext(this._weightMap);
  4237. return [4, this.executeWithControlFlow(inputs, context)];
  4238. case 1:
  4239. tensors = _a.sent();
  4240. results = this.findOutputs(tensors, context, outputs);
  4241. outputIds = Object.keys(results).map(function (key) { return results[key].id; });
  4242. inputIdArray = Object.keys(inputs).map(function (key) { return inputs[key].map(function (input) { return input.id; }); });
  4243. inputIds = [].concat.apply([], inputIdArray);
  4244. Object.keys(tensors).forEach(function (key) {
  4245. var tensorArray = tensors[key];
  4246. tensorArray.forEach(function (tensor) {
  4247. if (tensor && outputIds.indexOf(tensor.id) === -1 &&
  4248. inputIds.indexOf(tensor.id) === -1 &&
  4249. _this.weightIds.indexOf(tensor.id) === -1) {
  4250. tensor.dispose();
  4251. }
  4252. });
  4253. });
  4254. return [2, results];
  4255. }
  4256. });
  4257. });
  4258. };
  4259. GraphExecutor.prototype.executeWithControlFlow = function (inputs, context) {
  4260. return __awaiter(this, void 0, void 0, function () {
  4261. var stack, tensorMap, added, item, tensors, nodeName, _a, _b;
  4262. return __generator(this, function (_c) {
  4263. switch (_c.label) {
  4264. case 0:
  4265. stack = this.graph.inputs.map(function (node) {
  4266. return { node: node, contexts: context.currentContext };
  4267. });
  4268. tensorMap = __assign({}, this.weightMap, inputs);
  4269. added = {};
  4270. _c.label = 1;
  4271. case 1:
  4272. if (!(stack.length > 0)) return [3, 3];
  4273. item = stack.pop();
  4274. context.currentContext = item.contexts;
  4275. tensors = operation_executor_1.executeOp(item.node, tensorMap, context);
  4276. nodeName = utils_1.getNodeNameAndIndex(item.node.name, context)[0];
  4277. _a = tensorMap;
  4278. _b = nodeName;
  4279. return [4, tensors];
  4280. case 2:
  4281. _a[_b] = _c.sent();
  4282. item.node.children.forEach(function (childNode) {
  4283. var nodeName = utils_1.getNodeNameAndIndex(childNode.name, context)[0];
  4284. if (!added[nodeName]) {
  4285. if (childNode.op === 'merge') {
  4286. if (childNode.inputNames.some(function (name) {
  4287. return !!utils_1.getTensor(name, tensorMap, context);
  4288. })) {
  4289. added[nodeName] = true;
  4290. stack.push({ contexts: context.currentContext, node: childNode });
  4291. }
  4292. }
  4293. else if (childNode.inputNames.every(function (name) {
  4294. return !!utils_1.getTensor(name, tensorMap, context);
  4295. })) {
  4296. added[nodeName] = true;
  4297. stack.push({ contexts: context.currentContext, node: childNode });
  4298. }
  4299. }
  4300. });
  4301. return [3, 1];
  4302. case 3: return [2, tensorMap];
  4303. }
  4304. });
  4305. });
  4306. };
  4307. GraphExecutor.prototype.findOutputs = function (tensorMap, context, outputs) {
  4308. if (outputs && !(outputs instanceof Array)) {
  4309. outputs = [outputs];
  4310. }
  4311. var requestedOutputs = (outputs || this.graph.outputs.map(function (node) { return node.name; }));
  4312. return requestedOutputs.reduce(function (map, name) {
  4313. map[name] = utils_1.getTensor(name, tensorMap, context);
  4314. return map;
  4315. }, {});
  4316. };
  4317. GraphExecutor.prototype.dispose = function () {
  4318. var _this = this;
  4319. Object.keys(this.weightMap)
  4320. .forEach(function (key) { return _this.weightMap[key].forEach(function (tensor) { return tensor.dispose(); }); });
  4321. };
  4322. GraphExecutor.prototype.checkInputShapeAndType = function (inputs) {
  4323. this.placeholders.forEach(function (node) {
  4324. var input = inputs[node.name][0];
  4325. if (node.params['shape'] && node.params['shape'].value) {
  4326. var shape_1 = node.params['shape'].value;
  4327. var match = shape_1.length === input.shape.length &&
  4328. input.shape.every(function (dim, index) { return shape_1[index] === -1 || shape_1[index] === dim; });
  4329. tfjs_core_1.util.assert(match, "The shape of dict['" + node.name + "'] provided in model.execute(dict) must be [" + shape_1 + "], but was [" + input.shape + "]");
  4330. }
  4331. if (node.params['dtype'] && node.params['dtype'].value) {
  4332. tfjs_core_1.util.assert(input.dtype === node.params['dtype'].value, "The dtype of dict['" + node.name + "'] provided in model.execute(dict) must be " + node.params['dtype'].value + ", but was " + input.dtype);
  4333. }
  4334. });
  4335. };
  4336. GraphExecutor.prototype.checkInput = function (inputs) {
  4337. var _this = this;
  4338. var inputKeys = Object.keys(inputs);
  4339. var missing = [];
  4340. var extra = [];
  4341. this.inputNodes.forEach(function (name) {
  4342. if (inputKeys.indexOf(name) === -1)
  4343. missing.push(name);
  4344. });
  4345. inputKeys.forEach(function (name) {
  4346. if (_this.inputNodes.indexOf(name) === -1)
  4347. extra.push(name);
  4348. });
  4349. if (missing.length > 0) {
  4350. throw new Error("The dict provided in model.execute(dict) has the keys " +
  4351. ("[" + inputKeys + "], but is missing the required keys: [" + missing + "]."));
  4352. }
  4353. if (extra.length > 0) {
  4354. throw new Error("The dict provided in model.execute(dict) has " +
  4355. ("unused keys: [" + extra + "]. Please provide only the following keys: ") +
  4356. ("[" + this.inputNodes + "]."));
  4357. }
  4358. };
  4359. return GraphExecutor;
  4360. }());
  4361. exports.GraphExecutor = GraphExecutor;
  4362. },{"../operations/executors/utils":30,"../operations/operation_executor":44,"./execution_context":13,"@tensorflow/tfjs-core":54}],16:[function(require,module,exports){
  4363. "use strict";
  4364. Object.defineProperty(exports, "__esModule", { value: true });
  4365. var frozen_model_1 = require("./executor/frozen_model");
  4366. exports.FrozenModel = frozen_model_1.FrozenModel;
  4367. exports.loadFrozenModel = frozen_model_1.loadFrozenModel;
  4368. var version_1 = require("./version");
  4369. exports.version_converter = version_1.version;
  4370. },{"./executor/frozen_model":14,"./version":46}],17:[function(require,module,exports){
  4371. "use strict";
  4372. Object.defineProperty(exports, "__esModule", { value: true });
  4373. var tfc = require("@tensorflow/tfjs-core");
  4374. var utils_1 = require("./utils");
  4375. exports.executeOp = function (node, tensorMap, context) {
  4376. switch (node.op) {
  4377. case 'add': {
  4378. return [tfc.add(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4379. }
  4380. case 'mod':
  4381. return [tfc.mod(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4382. case 'mul':
  4383. return [tfc.mul(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4384. case 'div': {
  4385. return [tfc.div(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4386. }
  4387. case 'floorDiv': {
  4388. return [tfc.floorDiv(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4389. }
  4390. case 'sub': {
  4391. return [tfc.sub(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4392. }
  4393. case 'minimum': {
  4394. return [tfc.minimum(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4395. }
  4396. case 'maximum': {
  4397. return [tfc.maximum(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4398. }
  4399. case 'pow': {
  4400. return [tfc.pow(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4401. }
  4402. case 'squaredDifference': {
  4403. return [tfc.squaredDifference(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4404. }
  4405. default:
  4406. throw TypeError("Node type " + node.op + " is not implemented");
  4407. }
  4408. };
  4409. exports.CATEGORY = 'arithmetic';
  4410. },{"./utils":30,"@tensorflow/tfjs-core":54}],18:[function(require,module,exports){
  4411. "use strict";
  4412. Object.defineProperty(exports, "__esModule", { value: true });
  4413. var tfc = require("@tensorflow/tfjs-core");
  4414. var utils_1 = require("./utils");
  4415. exports.executeOp = function (node, tensorMap, context) {
  4416. switch (node.op) {
  4417. case 'abs':
  4418. return [tfc.abs(utils_1.getParamValue('x', node, tensorMap, context))];
  4419. case 'acos':
  4420. return [tfc.acos(utils_1.getParamValue('x', node, tensorMap, context))];
  4421. case 'acosh':
  4422. return [tfc.acosh(utils_1.getParamValue('x', node, tensorMap, context))];
  4423. case 'asin':
  4424. return [tfc.asin(utils_1.getParamValue('x', node, tensorMap, context))];
  4425. case 'asinh':
  4426. return [tfc.asinh(utils_1.getParamValue('x', node, tensorMap, context))];
  4427. case 'atan':
  4428. return [tfc.atan(utils_1.getParamValue('x', node, tensorMap, context))];
  4429. case 'atanh':
  4430. return [tfc.atanh(utils_1.getParamValue('x', node, tensorMap, context))];
  4431. case 'ceil':
  4432. return [tfc.ceil(utils_1.getParamValue('x', node, tensorMap, context))];
  4433. case 'cos':
  4434. return [tfc.cos(utils_1.getParamValue('x', node, tensorMap, context))];
  4435. case 'cosh':
  4436. return [tfc.cosh(utils_1.getParamValue('x', node, tensorMap, context))];
  4437. case 'elu':
  4438. return [tfc.elu(utils_1.getParamValue('x', node, tensorMap, context))];
  4439. case 'erf':
  4440. return [tfc.erf(utils_1.getParamValue('x', node, tensorMap, context))];
  4441. case 'exp':
  4442. return [tfc.exp(utils_1.getParamValue('x', node, tensorMap, context))];
  4443. case 'expm1': {
  4444. return [tfc.expm1(utils_1.getParamValue('x', node, tensorMap, context))];
  4445. }
  4446. case 'floor':
  4447. return [tfc.floor(utils_1.getParamValue('x', node, tensorMap, context))];
  4448. case 'log':
  4449. return [tfc.log(utils_1.getParamValue('x', node, tensorMap, context))];
  4450. case 'log1p': {
  4451. return [tfc.log1p(utils_1.getParamValue('x', node, tensorMap, context))];
  4452. }
  4453. case 'neg':
  4454. return [tfc.neg(utils_1.getParamValue('x', node, tensorMap, context))];
  4455. case 'reciprocal': {
  4456. return [tfc.reciprocal(utils_1.getParamValue('x', node, tensorMap, context))];
  4457. }
  4458. case 'relu':
  4459. return [tfc.relu(utils_1.getParamValue('x', node, tensorMap, context))];
  4460. case 'round': {
  4461. return [tfc.round(utils_1.getParamValue('x', node, tensorMap, context))];
  4462. }
  4463. case 'selu':
  4464. return [tfc.selu(utils_1.getParamValue('x', node, tensorMap, context))];
  4465. case 'sigmoid':
  4466. return [tfc.sigmoid(utils_1.getParamValue('x', node, tensorMap, context))];
  4467. case 'sin':
  4468. return [tfc.sin(utils_1.getParamValue('x', node, tensorMap, context))];
  4469. case 'sign': {
  4470. return [tfc.sign(utils_1.getParamValue('x', node, tensorMap, context))];
  4471. }
  4472. case 'sinh': {
  4473. return [tfc.sinh(utils_1.getParamValue('x', node, tensorMap, context))];
  4474. }
  4475. case 'softplus': {
  4476. return [tfc.softplus(utils_1.getParamValue('x', node, tensorMap, context))];
  4477. }
  4478. case 'sqrt': {
  4479. return [tfc.sqrt(utils_1.getParamValue('x', node, tensorMap, context))];
  4480. }
  4481. case 'square': {
  4482. return [tfc.square(utils_1.getParamValue('x', node, tensorMap, context))];
  4483. }
  4484. case 'tanh': {
  4485. return [tfc.tanh(utils_1.getParamValue('x', node, tensorMap, context))];
  4486. }
  4487. case 'tan':
  4488. return [tfc.tan(utils_1.getParamValue('x', node, tensorMap, context))];
  4489. case 'clipByValue':
  4490. return [tfc.clipByValue(utils_1.getParamValue('x', node, tensorMap, context), utils_1.getParamValue('clipValueMin', node, tensorMap, context), utils_1.getParamValue('clipValueMax', node, tensorMap, context))];
  4491. case 'rsqrt':
  4492. return [tfc.div(tfc.scalar(1.0, 'float32'), tfc.sqrt(utils_1.getTensor(node.inputNames[0], tensorMap, context)))];
  4493. default:
  4494. throw TypeError("Node type " + node.op + " is not implemented");
  4495. }
  4496. };
  4497. exports.CATEGORY = 'basic_math';
  4498. },{"./utils":30,"@tensorflow/tfjs-core":54}],19:[function(require,module,exports){
  4499. "use strict";
  4500. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  4501. return new (P || (P = Promise))(function (resolve, reject) {
  4502. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4503. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  4504. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  4505. step((generator = generator.apply(thisArg, _arguments || [])).next());
  4506. });
  4507. };
  4508. var __generator = (this && this.__generator) || function (thisArg, body) {
  4509. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  4510. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  4511. function verb(n) { return function (v) { return step([n, v]); }; }
  4512. function step(op) {
  4513. if (f) throw new TypeError("Generator is already executing.");
  4514. while (_) try {
  4515. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  4516. if (y = 0, t) op = [0, t.value];
  4517. switch (op[0]) {
  4518. case 0: case 1: t = op; break;
  4519. case 4: _.label++; return { value: op[1], done: false };
  4520. case 5: _.label++; y = op[1]; op = [0]; continue;
  4521. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  4522. default:
  4523. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  4524. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  4525. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  4526. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  4527. if (t[2]) _.ops.pop();
  4528. _.trys.pop(); continue;
  4529. }
  4530. op = body.call(thisArg, _);
  4531. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  4532. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  4533. }
  4534. };
  4535. Object.defineProperty(exports, "__esModule", { value: true });
  4536. var utils_1 = require("./utils");
  4537. function executeOp(node, tensorMap, context) {
  4538. return __awaiter(this, void 0, void 0, function () {
  4539. var _a, pred, data_1, inputName, frameId, data, tensor, input;
  4540. return __generator(this, function (_b) {
  4541. switch (_b.label) {
  4542. case 0:
  4543. _a = node.op;
  4544. switch (_a) {
  4545. case 'loopCond': return [3, 1];
  4546. case 'switch': return [3, 2];
  4547. case 'merge': return [3, 4];
  4548. case 'enter': return [3, 5];
  4549. case 'exit': return [3, 6];
  4550. case 'nextIteration': return [3, 7];
  4551. }
  4552. return [3, 8];
  4553. case 1: return [2, [utils_1.getParamValue('pred', node, tensorMap, context)]];
  4554. case 2:
  4555. pred = utils_1.getParamValue('pred', node, tensorMap, context);
  4556. data_1 = utils_1.getParamValue('data', node, tensorMap, context);
  4557. return [4, pred.data()];
  4558. case 3: return [2, (_b.sent())[0] ? [undefined, data_1] : [data_1, undefined]];
  4559. case 4:
  4560. inputName = node.inputNames.find(function (name) { return utils_1.getTensor(name, tensorMap, context) !== undefined; });
  4561. return [2, inputName ? [utils_1.getTensor(inputName, tensorMap, context)] : undefined];
  4562. case 5:
  4563. frameId = utils_1.getParamValue('frameName', node, tensorMap, context);
  4564. data = utils_1.getParamValue('tensor', node, tensorMap, context);
  4565. context.enterFrame(frameId);
  4566. return [2, [data]];
  4567. case 6:
  4568. tensor = utils_1.getParamValue('tensor', node, tensorMap, context);
  4569. context.exitFrame();
  4570. return [2, [tensor]];
  4571. case 7:
  4572. input = utils_1.getParamValue('tensor', node, tensorMap, context);
  4573. context.nextIteration();
  4574. return [2, [input]];
  4575. case 8: throw TypeError("Node type " + node.op + " is not implemented");
  4576. }
  4577. });
  4578. });
  4579. }
  4580. exports.executeOp = executeOp;
  4581. exports.CATEGORY = 'control';
  4582. },{"./utils":30}],20:[function(require,module,exports){
  4583. "use strict";
  4584. Object.defineProperty(exports, "__esModule", { value: true });
  4585. var tfc = require("@tensorflow/tfjs-core");
  4586. var utils_1 = require("./utils");
  4587. exports.executeOp = function (node, tensorMap, context) {
  4588. switch (node.op) {
  4589. case 'conv1d': {
  4590. var stride = utils_1.getParamValue('stride', node, tensorMap, context);
  4591. var pad = utils_1.getParamValue('pad', node, tensorMap, context);
  4592. var dataFormat = utils_1.getParamValue('dataFormat', node, tensorMap, context)
  4593. .toUpperCase();
  4594. var dilation = utils_1.getParamValue('dilation', node, tensorMap, context);
  4595. return [tfc.conv1d(utils_1.getParamValue('x', node, tensorMap, context), utils_1.getParamValue('filter', node, tensorMap, context), stride, pad, dataFormat, dilation)];
  4596. }
  4597. case 'conv2d': {
  4598. var stride = utils_1.getParamValue('strides', node, tensorMap, context);
  4599. var pad = utils_1.getParamValue('pad', node, tensorMap, context);
  4600. var dataFormat = utils_1.getParamValue('dataFormat', node, tensorMap, context)
  4601. .toUpperCase();
  4602. var dilations = utils_1.getParamValue('dilations', node, tensorMap, context);
  4603. return [tfc.conv2d(utils_1.getParamValue('x', node, tensorMap, context), utils_1.getParamValue('filter', node, tensorMap, context), [stride[1], stride[2]], pad, dataFormat, [dilations[0], dilations[1]])];
  4604. }
  4605. case 'conv2dTranspose': {
  4606. var shape = utils_1.getParamValue('outputShape', node, tensorMap, context);
  4607. var stride = utils_1.getParamValue('strides', node, tensorMap, context);
  4608. var pad = utils_1.getParamValue('pad', node, tensorMap, context);
  4609. return [tfc.conv2dTranspose(utils_1.getParamValue('x', node, tensorMap, context), utils_1.getParamValue('filter', node, tensorMap, context), shape, [stride[1], stride[2]], pad)];
  4610. }
  4611. case 'depthwiseConv2d': {
  4612. var stride = utils_1.getParamValue('strides', node, tensorMap, context);
  4613. var pad = utils_1.getParamValue('pad', node, tensorMap, context);
  4614. var dilations = utils_1.getParamValue('dilations', node, tensorMap, context);
  4615. var dataFormat = utils_1.getParamValue('dataFormat', node, tensorMap, context)
  4616. .toUpperCase();
  4617. return [tfc.depthwiseConv2d(utils_1.getParamValue('input', node, tensorMap, context), utils_1.getParamValue('filter', node, tensorMap, context), [stride[1], stride[2]], pad, dataFormat, [dilations[0], dilations[1]])];
  4618. }
  4619. case 'avgPool': {
  4620. var stride = utils_1.getParamValue('strides', node, tensorMap, context);
  4621. var pad = utils_1.getParamValue('pad', node, tensorMap, context);
  4622. var kernelSize = utils_1.getParamValue('kernelSize', node, tensorMap, context);
  4623. return [tfc.avgPool(utils_1.getParamValue('x', node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad)];
  4624. }
  4625. case 'maxPool': {
  4626. var stride = utils_1.getParamValue('strides', node, tensorMap, context);
  4627. var pad = utils_1.getParamValue('pad', node, tensorMap, context);
  4628. var kernelSize = utils_1.getParamValue('kernelSize', node, tensorMap, context);
  4629. return [tfc.maxPool(utils_1.getParamValue('x', node, tensorMap, context), [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad)];
  4630. }
  4631. default:
  4632. throw TypeError("Node type " + node.op + " is not implemented");
  4633. }
  4634. };
  4635. exports.CATEGORY = 'convolution';
  4636. },{"./utils":30,"@tensorflow/tfjs-core":54}],21:[function(require,module,exports){
  4637. "use strict";
  4638. Object.defineProperty(exports, "__esModule", { value: true });
  4639. var tfc = require("@tensorflow/tfjs-core");
  4640. var utils_1 = require("./utils");
  4641. exports.executeOp = function (node, tensorMap, context) {
  4642. switch (node.op) {
  4643. case 'fill': {
  4644. var shape = utils_1.getParamValue('shape', node, tensorMap, context);
  4645. var value = utils_1.getParamValue('value', node, tensorMap, context);
  4646. return [tfc.fill(shape, value)];
  4647. }
  4648. case 'linspace': {
  4649. var start = utils_1.getParamValue('start', node, tensorMap, context);
  4650. var stop_1 = utils_1.getParamValue('stop', node, tensorMap, context);
  4651. var num = utils_1.getParamValue('num', node, tensorMap, context);
  4652. return [tfc.linspace(start, stop_1, num)];
  4653. }
  4654. case 'oneHot': {
  4655. var indices = utils_1.getParamValue('indices', node, tensorMap, context);
  4656. var depth = utils_1.getParamValue('depth', node, tensorMap, context);
  4657. var onValue = utils_1.getParamValue('onValue', node, tensorMap, context);
  4658. var offValue = utils_1.getParamValue('offValue', node, tensorMap, context);
  4659. return [tfc.oneHot(indices, depth, onValue, offValue)];
  4660. }
  4661. case 'ones': {
  4662. return [tfc.ones(utils_1.getParamValue('shape', node, tensorMap, context), utils_1.getParamValue('dtype', node, tensorMap, context))];
  4663. }
  4664. case 'onesLike': {
  4665. return [tfc.onesLike(utils_1.getParamValue('x', node, tensorMap, context))];
  4666. }
  4667. case 'randomUniform': {
  4668. return [tfc.randomUniform(utils_1.getParamValue('shape', node, tensorMap, context), utils_1.getParamValue('minval', node, tensorMap, context), utils_1.getParamValue('maxval', node, tensorMap, context), utils_1.getParamValue('dtype', node, tensorMap, context))];
  4669. }
  4670. case 'range': {
  4671. var start = utils_1.getParamValue('start', node, tensorMap, context);
  4672. var stop_2 = utils_1.getParamValue('stop', node, tensorMap, context);
  4673. var step = utils_1.getParamValue('step', node, tensorMap, context);
  4674. return [tfc.range(start, stop_2, step, utils_1.getParamValue('dtype', node, tensorMap, context))];
  4675. }
  4676. case 'truncatedNormal': {
  4677. var shape = utils_1.getParamValue('shape', node, tensorMap, context);
  4678. var mean = utils_1.getParamValue('mean', node, tensorMap, context);
  4679. var stdDev = utils_1.getParamValue('stdDev', node, tensorMap, context);
  4680. var seed = utils_1.getParamValue('seed', node, tensorMap, context);
  4681. return [tfc.truncatedNormal(shape, mean, stdDev, utils_1.getParamValue('dtype', node, tensorMap, context), seed)];
  4682. }
  4683. case 'zeros': {
  4684. return [tfc.zeros(utils_1.getParamValue('shape', node, tensorMap, context), utils_1.getParamValue('dtype', node, tensorMap, context))];
  4685. }
  4686. case 'zerosLike': {
  4687. return [tfc.zerosLike(utils_1.getParamValue('x', node, tensorMap, context))];
  4688. }
  4689. default:
  4690. throw TypeError("Node type " + node.op + " is not implemented");
  4691. }
  4692. };
  4693. exports.CATEGORY = 'creation';
  4694. },{"./utils":30,"@tensorflow/tfjs-core":54}],22:[function(require,module,exports){
  4695. "use strict";
  4696. Object.defineProperty(exports, "__esModule", { value: true });
  4697. var tfc = require("@tensorflow/tfjs-core");
  4698. var utils_1 = require("./utils");
  4699. exports.executeOp = function (node, tensorMap, context) {
  4700. switch (node.op) {
  4701. case 'const': {
  4702. return tensorMap[node.name];
  4703. }
  4704. case 'placeholder':
  4705. var def = utils_1.getParamValue('default', node, tensorMap, context);
  4706. return [utils_1.getTensor(node.name, tensorMap, context) || def];
  4707. case 'identity':
  4708. case 'stopGradient':
  4709. case 'fakeQuantWithMinMaxVars':
  4710. return [utils_1.getParamValue('x', node, tensorMap, context)];
  4711. case 'snapshot':
  4712. var snapshot = utils_1.getParamValue('x', node, tensorMap, context);
  4713. return [snapshot.clone()];
  4714. case 'shape':
  4715. return [tfc.tensor1d(utils_1.getParamValue('x', node, tensorMap, context).shape, 'int32')];
  4716. case 'size':
  4717. return [tfc.scalar(utils_1.getParamValue('x', node, tensorMap, context).size, 'int32')];
  4718. case 'rank':
  4719. return [tfc.scalar(utils_1.getParamValue('x', node, tensorMap, context).rank, 'int32')];
  4720. case 'noop':
  4721. return [];
  4722. case 'print':
  4723. var input = utils_1.getParamValue('x', node, tensorMap, context);
  4724. var data = utils_1.getParamValue('data', node, tensorMap, context);
  4725. var message = utils_1.getParamValue('message', node, tensorMap, context);
  4726. var summarize = utils_1.getParamValue('summarize', node, tensorMap, context);
  4727. console.warn('The graph has a tf.print() operation,' +
  4728. 'usually used for debugging, which slows down performance.');
  4729. console.log(message);
  4730. for (var i = 0; i < data.length; i++) {
  4731. console.log(Array.prototype.slice.call(data[0].dataSync()).slice(0, summarize));
  4732. }
  4733. return [input];
  4734. default:
  4735. throw TypeError("Node type " + node.op + " is not implemented");
  4736. }
  4737. };
  4738. exports.CATEGORY = 'graph';
  4739. },{"./utils":30,"@tensorflow/tfjs-core":54}],23:[function(require,module,exports){
  4740. "use strict";
  4741. Object.defineProperty(exports, "__esModule", { value: true });
  4742. var tfc = require("@tensorflow/tfjs-core");
  4743. var utils_1 = require("./utils");
  4744. exports.executeOp = function (node, tensorMap, context) {
  4745. switch (node.op) {
  4746. case 'resizeBilinear': {
  4747. var images = utils_1.getParamValue('images', node, tensorMap, context);
  4748. var size = utils_1.getParamValue('size', node, tensorMap, context);
  4749. var alignCorners = utils_1.getParamValue('alignCorners', node, tensorMap, context);
  4750. return [tfc.image.resizeBilinear(images, [size[0], size[1]], alignCorners)];
  4751. }
  4752. case 'resizeNearestNeighbor': {
  4753. var images = utils_1.getParamValue('images', node, tensorMap, context);
  4754. var size = utils_1.getParamValue('size', node, tensorMap, context);
  4755. var alignCorners = utils_1.getParamValue('alignCorners', node, tensorMap, context);
  4756. return [tfc.image.resizeNearestNeighbor(images, [size[0], size[1]], alignCorners)];
  4757. }
  4758. default:
  4759. throw TypeError("Node type " + node.op + " is not implemented");
  4760. }
  4761. };
  4762. exports.CATEGORY = 'image';
  4763. },{"./utils":30,"@tensorflow/tfjs-core":54}],24:[function(require,module,exports){
  4764. "use strict";
  4765. Object.defineProperty(exports, "__esModule", { value: true });
  4766. var tfc = require("@tensorflow/tfjs-core");
  4767. var utils_1 = require("./utils");
  4768. exports.executeOp = function (node, tensorMap, context) {
  4769. switch (node.op) {
  4770. case 'equal': {
  4771. return [tfc.equal(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4772. }
  4773. case 'notEqual': {
  4774. return [tfc.notEqual(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4775. }
  4776. case 'greater': {
  4777. return [tfc.greater(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4778. }
  4779. case 'greaterEqual': {
  4780. return [tfc.greaterEqual(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4781. }
  4782. case 'less': {
  4783. return [tfc.less(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4784. }
  4785. case 'lessEqual': {
  4786. return [tfc.lessEqual(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4787. }
  4788. case 'logicalAnd': {
  4789. return [tfc.logicalAnd(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4790. }
  4791. case 'logicalNot': {
  4792. return [tfc.logicalNot(utils_1.getParamValue('a', node, tensorMap, context))];
  4793. }
  4794. case 'logicalOr': {
  4795. return [tfc.logicalOr(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4796. }
  4797. case 'where': {
  4798. return [tfc.where(utils_1.getParamValue('condition', node, tensorMap, context), utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context))];
  4799. }
  4800. default:
  4801. throw TypeError("Node type " + node.op + " is not implemented");
  4802. }
  4803. };
  4804. exports.CATEGORY = 'logical';
  4805. },{"./utils":30,"@tensorflow/tfjs-core":54}],25:[function(require,module,exports){
  4806. "use strict";
  4807. Object.defineProperty(exports, "__esModule", { value: true });
  4808. var tfc = require("@tensorflow/tfjs-core");
  4809. var utils_1 = require("./utils");
  4810. exports.executeOp = function (node, tensorMap, context) {
  4811. switch (node.op) {
  4812. case 'matMul':
  4813. return [tfc.matMul(utils_1.getParamValue('a', node, tensorMap, context), utils_1.getParamValue('b', node, tensorMap, context), utils_1.getParamValue('transposeA', node, tensorMap, context), utils_1.getParamValue('transposeB', node, tensorMap, context))];
  4814. case 'transpose':
  4815. return [tfc.transpose(utils_1.getParamValue('x', node, tensorMap, context), utils_1.getParamValue('perm', node, tensorMap, context))];
  4816. default:
  4817. throw TypeError("Node type " + node.op + " is not implemented");
  4818. }
  4819. };
  4820. exports.CATEGORY = 'matrices';
  4821. },{"./utils":30,"@tensorflow/tfjs-core":54}],26:[function(require,module,exports){
  4822. "use strict";
  4823. Object.defineProperty(exports, "__esModule", { value: true });
  4824. var tfc = require("@tensorflow/tfjs-core");
  4825. var utils_1 = require("./utils");
  4826. exports.executeOp = function (node, tensorMap, context) {
  4827. switch (node.op) {
  4828. case 'batchNormalization': {
  4829. return [tfc.batchNormalization(utils_1.getParamValue('x', node, tensorMap, context), utils_1.getParamValue('mean', node, tensorMap, context), utils_1.getParamValue('variance', node, tensorMap, context), utils_1.getParamValue('epsilon', node, tensorMap, context), utils_1.getParamValue('scale', node, tensorMap, context), utils_1.getParamValue('offset', node, tensorMap, context))];
  4830. }
  4831. case 'localResponseNormalization': {
  4832. return [tfc.localResponseNormalization(utils_1.getParamValue('x', node, tensorMap, context), utils_1.getParamValue('radius', node, tensorMap, context), utils_1.getParamValue('bias', node, tensorMap, context), utils_1.getParamValue('alpha', node, tensorMap, context), utils_1.getParamValue('beta', node, tensorMap, context))];
  4833. }
  4834. case 'softmax': {
  4835. return [tfc.softmax(utils_1.getParamValue('x', node, tensorMap, context))];
  4836. }
  4837. default:
  4838. throw TypeError("Node type " + node.op + " is not implemented");
  4839. }
  4840. };
  4841. exports.CATEGORY = 'normalization';
  4842. },{"./utils":30,"@tensorflow/tfjs-core":54}],27:[function(require,module,exports){
  4843. "use strict";
  4844. Object.defineProperty(exports, "__esModule", { value: true });
  4845. var tfc = require("@tensorflow/tfjs-core");
  4846. var utils_1 = require("./utils");
  4847. exports.executeOp = function (node, tensorMap, context) {
  4848. switch (node.op) {
  4849. case 'max': {
  4850. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4851. var keepDims = utils_1.getParamValue('keepDims', node, tensorMap, context);
  4852. return [tfc.max(utils_1.getParamValue('x', node, tensorMap, context), axis, keepDims)];
  4853. }
  4854. case 'mean': {
  4855. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4856. var keepDims = utils_1.getParamValue('keepDims', node, tensorMap, context);
  4857. return [tfc.mean(utils_1.getParamValue('x', node, tensorMap, context), axis, keepDims)];
  4858. }
  4859. case 'min': {
  4860. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4861. var keepDims = utils_1.getParamValue('keepDims', node, tensorMap, context);
  4862. return [tfc.min(utils_1.getParamValue('x', node, tensorMap, context), axis, keepDims)];
  4863. }
  4864. case 'sum': {
  4865. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4866. var keepDims = utils_1.getParamValue('keepDims', node, tensorMap, context);
  4867. return [tfc.sum(utils_1.getParamValue('x', node, tensorMap, context), axis, keepDims)];
  4868. }
  4869. case 'argMax': {
  4870. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4871. return [tfc.argMax(utils_1.getParamValue('x', node, tensorMap, context), axis)];
  4872. }
  4873. case 'argMin': {
  4874. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4875. return [tfc.argMin(utils_1.getParamValue('x', node, tensorMap, context), axis)];
  4876. }
  4877. default:
  4878. throw TypeError("Node type " + node.op + " is not implemented");
  4879. }
  4880. };
  4881. exports.CATEGORY = 'reduction';
  4882. },{"./utils":30,"@tensorflow/tfjs-core":54}],28:[function(require,module,exports){
  4883. "use strict";
  4884. Object.defineProperty(exports, "__esModule", { value: true });
  4885. var tfc = require("@tensorflow/tfjs-core");
  4886. var utils_1 = require("./utils");
  4887. exports.executeOp = function (node, tensorMap, context) {
  4888. switch (node.op) {
  4889. case 'concat': {
  4890. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4891. var inputs = utils_1.getParamValue('tensors', node, tensorMap, context);
  4892. return [tfc.concat(inputs, axis)];
  4893. }
  4894. case 'gather': {
  4895. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4896. var input = utils_1.getParamValue('x', node, tensorMap, context);
  4897. var indices = utils_1.getParamValue('indices', node, tensorMap, context);
  4898. return [tfc.gather(input, indices, axis)];
  4899. }
  4900. case 'reverse': {
  4901. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4902. var input = utils_1.getParamValue('x', node, tensorMap, context);
  4903. return [tfc.reverse(input, axis)];
  4904. }
  4905. case 'slice': {
  4906. var begin = utils_1.getParamValue('begin', node, tensorMap, context);
  4907. var size = utils_1.getParamValue('size', node, tensorMap, context);
  4908. return [tfc.slice(utils_1.getParamValue('x', node, tensorMap, context), begin, size)];
  4909. }
  4910. case 'stridedSlice': {
  4911. var begin = utils_1.getParamValue('begin', node, tensorMap, context);
  4912. var end = utils_1.getParamValue('end', node, tensorMap, context);
  4913. var strides = utils_1.getParamValue('strides', node, tensorMap, context);
  4914. var beginMask = utils_1.getParamValue('beginMask', node, tensorMap, context);
  4915. var endMask = utils_1.getParamValue('endMask', node, tensorMap, context);
  4916. return [tfc.stridedSlice(utils_1.getParamValue('x', node, tensorMap, context), begin, end, strides, beginMask, endMask)];
  4917. }
  4918. case 'stack': {
  4919. return tfc.tidy(function () {
  4920. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4921. var tensors = utils_1.getParamValue('tensors', node, tensorMap, context);
  4922. var shape = tensors[0].shape;
  4923. var squeezedShape = tensors[0].squeeze().shape;
  4924. var mapped = tensors.map(function (tensor) {
  4925. var sameShape = tfc.util.arraysEqual(tensor.shape, shape);
  4926. if (!sameShape &&
  4927. !tfc.util.arraysEqual(tensor.squeeze().shape, squeezedShape)) {
  4928. throw new Error('the input tensors shape does not match');
  4929. }
  4930. return sameShape ? tensor : tensor.reshape(shape);
  4931. });
  4932. return [tfc.stack(mapped, axis)];
  4933. });
  4934. }
  4935. case 'unstack': {
  4936. return tfc.tidy(function () {
  4937. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4938. var tensor = utils_1.getParamValue('tensor', node, tensorMap, context);
  4939. return tfc.unstack(tensor, axis);
  4940. });
  4941. }
  4942. case 'tile': {
  4943. var reps = utils_1.getParamValue('reps', node, tensorMap, context);
  4944. return [tfc.tile(utils_1.getParamValue('x', node, tensorMap, context), reps)];
  4945. }
  4946. case 'split': {
  4947. var axis = utils_1.getParamValue('axis', node, tensorMap, context);
  4948. var numOrSizeSplits = utils_1.getParamValue('numOrSizeSplits', node, tensorMap, context);
  4949. return tfc.split(utils_1.getParamValue('x', node, tensorMap, context), numOrSizeSplits, axis);
  4950. }
  4951. default:
  4952. throw TypeError("Node type " + node.op + " is not implemented");
  4953. }
  4954. };
  4955. exports.CATEGORY = 'slice_join';
  4956. },{"./utils":30,"@tensorflow/tfjs-core":54}],29:[function(require,module,exports){
  4957. "use strict";
  4958. Object.defineProperty(exports, "__esModule", { value: true });
  4959. var tfc = require("@tensorflow/tfjs-core");
  4960. var utils_1 = require("./utils");
  4961. exports.executeOp = function (node, tensorMap, context) {
  4962. switch (node.op) {
  4963. case 'cast': {
  4964. return [tfc.cast(utils_1.getParamValue('x', node, tensorMap, context), utils_1.getParamValue('dtype', node, tensorMap, context))];
  4965. }
  4966. case 'expandDims': {
  4967. var axis = node.params['axis'].value;
  4968. return [tfc.expandDims(utils_1.getParamValue('x', node, tensorMap, context), axis)];
  4969. }
  4970. case 'squeeze': {
  4971. var axis = node.params['axis'].value;
  4972. return [tfc.squeeze(utils_1.getParamValue('x', node, tensorMap, context), axis)];
  4973. }
  4974. case 'reshape': {
  4975. return [tfc.reshape(utils_1.getParamValue('x', node, tensorMap, context), utils_1.getParamValue('shape', node, tensorMap, context))];
  4976. }
  4977. case 'pad': {
  4978. return [tfc.pad(utils_1.getParamValue('x', node, tensorMap, context), utils_1.split(utils_1.getParamValue('padding', node, tensorMap, context), 2), utils_1.getParamValue('constantValue', node, tensorMap, context))];
  4979. }
  4980. default:
  4981. throw TypeError("Node type " + node.op + " is not implemented");
  4982. }
  4983. };
  4984. exports.CATEGORY = 'transformation';
  4985. },{"./utils":30,"@tensorflow/tfjs-core":54}],30:[function(require,module,exports){
  4986. "use strict";
  4987. Object.defineProperty(exports, "__esModule", { value: true });
  4988. function getParamValue(paramName, node, tensorMap, context) {
  4989. var param = node.params[paramName];
  4990. if (param && param.inputIndex !== undefined) {
  4991. if (param.type === 'tensor') {
  4992. return getTensor(node.inputNames[param.inputIndex], tensorMap, context);
  4993. }
  4994. if (param.type === 'tensors') {
  4995. var inputs = param.inputIndex === 0 ?
  4996. (param.inputParamLength === 0 ?
  4997. node.inputNames :
  4998. node.inputNames.slice(param.inputIndex, -param.inputParamLength)) :
  4999. node.inputNames.splice(param.inputIndex);
  5000. return inputs.map(function (name) { return getTensor(name, tensorMap, context); });
  5001. }
  5002. var data = Array.prototype.slice.call(getTensor(node.inputNames.slice(param.inputIndex)[0], tensorMap, context)
  5003. .dataSync());
  5004. return param.type === 'number' ? data[0] : data;
  5005. }
  5006. return param && param.value;
  5007. }
  5008. exports.getParamValue = getParamValue;
  5009. function getTensor(name, tensorsMap, context) {
  5010. var _a = parseNodeName(name), nodeName = _a[0], index = _a[1];
  5011. var contextId = context.currentContextIds.find(function (contextId) {
  5012. return !!tensorsMap[getNodeNameWithContextId(nodeName, contextId)];
  5013. });
  5014. return contextId !== undefined ?
  5015. tensorsMap[getNodeNameWithContextId(nodeName, contextId)][index] :
  5016. undefined;
  5017. }
  5018. exports.getTensor = getTensor;
  5019. function getNodeNameAndIndex(inputName, context) {
  5020. var _a = parseNodeName(inputName), nodeName = _a[0], index = _a[1];
  5021. return [
  5022. getNodeNameWithContextId(nodeName, context && context.currentContextId),
  5023. index
  5024. ];
  5025. }
  5026. exports.getNodeNameAndIndex = getNodeNameAndIndex;
  5027. function getNodeNameWithContextId(name, contextId) {
  5028. return !!contextId ? name + "-" + contextId : name;
  5029. }
  5030. function parseNodeName(name) {
  5031. var index = name.lastIndexOf(':');
  5032. if (index === -1)
  5033. return [name, 0];
  5034. var nodeName = name.substring(0, index);
  5035. return [nodeName, Number(name.substring(index + 1))];
  5036. }
  5037. exports.parseNodeName = parseNodeName;
  5038. function split(arr, size) {
  5039. var res = [];
  5040. for (var i = 0; i < arr.length; i += size) {
  5041. res.push(arr.slice(i, i + size));
  5042. }
  5043. return res;
  5044. }
  5045. exports.split = split;
  5046. },{}],31:[function(require,module,exports){
  5047. module.exports=[
  5048. {
  5049. "tfOpName": "Add",
  5050. "dlOpName": "add",
  5051. "category": "arithmetic",
  5052. "params": [
  5053. {
  5054. "tfInputIndex": 0,
  5055. "dlParamName": "a",
  5056. "type": "tensor"
  5057. },
  5058. {
  5059. "tfInputIndex": 1,
  5060. "dlParamName": "b",
  5061. "type": "tensor"
  5062. },
  5063. {
  5064. "tfParamName": "T",
  5065. "dlParamName": "dtype",
  5066. "type": "dtype",
  5067. "notSupported": true
  5068. }
  5069. ]
  5070. },
  5071. {
  5072. "tfOpName": "BiasAdd",
  5073. "dlOpName": "add",
  5074. "category": "arithmetic",
  5075. "params": [
  5076. {
  5077. "tfInputIndex": 0,
  5078. "dlParamName": "a",
  5079. "type": "tensor"
  5080. },
  5081. {
  5082. "tfInputIndex": 1,
  5083. "dlParamName": "b",
  5084. "type": "tensor"
  5085. },
  5086. {
  5087. "tfParamName": "T",
  5088. "dlParamName": "dtype",
  5089. "type": "dtype",
  5090. "notSupported": true
  5091. }
  5092. ]
  5093. },
  5094. {
  5095. "tfOpName": "Sub",
  5096. "dlOpName": "sub",
  5097. "category": "arithmetic",
  5098. "params": [
  5099. {
  5100. "tfInputIndex": 0,
  5101. "dlParamName": "a",
  5102. "type": "tensor"
  5103. },
  5104. {
  5105. "tfInputIndex": 1,
  5106. "dlParamName": "b",
  5107. "type": "tensor"
  5108. },
  5109. {
  5110. "tfParamName": "T",
  5111. "dlParamName": "dtype",
  5112. "type": "dtype",
  5113. "notSupported": true
  5114. }
  5115. ]
  5116. },
  5117. {
  5118. "tfOpName": "RealDiv",
  5119. "dlOpName": "div",
  5120. "category": "arithmetic",
  5121. "params": [
  5122. {
  5123. "tfInputIndex": 0,
  5124. "dlParamName": "a",
  5125. "type": "tensor"
  5126. },
  5127. {
  5128. "tfInputIndex": 1,
  5129. "dlParamName": "b",
  5130. "type": "tensor"
  5131. },
  5132. {
  5133. "tfParamName": "T",
  5134. "dlParamName": "dtype",
  5135. "type": "dtype",
  5136. "notSupported": true
  5137. }
  5138. ]
  5139. },
  5140. {
  5141. "tfOpName": "Div",
  5142. "dlOpName": "div",
  5143. "category": "arithmetic",
  5144. "params": [
  5145. {
  5146. "tfInputIndex": 0,
  5147. "dlParamName": "a",
  5148. "type": "tensor"
  5149. },
  5150. {
  5151. "tfInputIndex": 1,
  5152. "dlParamName": "b",
  5153. "type": "tensor"
  5154. },
  5155. {
  5156. "tfParamName": "T",
  5157. "dlParamName": "dtype",
  5158. "type": "dtype",
  5159. "notSupported": true
  5160. }
  5161. ]
  5162. },
  5163. {
  5164. "tfOpName": "FloorDiv",
  5165. "dlOpName": "floorDiv",
  5166. "category": "arithmetic",
  5167. "params": [
  5168. {
  5169. "tfInputIndex": 0,
  5170. "dlParamName": "a",
  5171. "type": "tensor"
  5172. },
  5173. {
  5174. "tfInputIndex": 1,
  5175. "dlParamName": "b",
  5176. "type": "tensor"
  5177. },
  5178. {
  5179. "tfParamName": "T",
  5180. "dlParamName": "dtype",
  5181. "type": "dtype",
  5182. "notSupported": true
  5183. }
  5184. ]
  5185. },
  5186. {
  5187. "tfOpName": "Mul",
  5188. "dlOpName": "mul",
  5189. "category": "arithmetic",
  5190. "params": [
  5191. {
  5192. "tfInputIndex": 0,
  5193. "dlParamName": "a",
  5194. "type": "tensor"
  5195. },
  5196. {
  5197. "tfInputIndex": 1,
  5198. "dlParamName": "b",
  5199. "type": "tensor"
  5200. },
  5201. {
  5202. "tfParamName": "T",
  5203. "dlParamName": "dtype",
  5204. "type": "dtype",
  5205. "notSupported": true
  5206. }
  5207. ]
  5208. },
  5209. {
  5210. "tfOpName": "Maximum",
  5211. "dlOpName": "maximum",
  5212. "category": "arithmetic",
  5213. "params": [
  5214. {
  5215. "tfInputIndex": 0,
  5216. "dlParamName": "a",
  5217. "type": "tensor"
  5218. },
  5219. {
  5220. "tfInputIndex": 1,
  5221. "dlParamName": "b",
  5222. "type": "tensor"
  5223. }
  5224. ]
  5225. },
  5226. {
  5227. "tfOpName": "Minimum",
  5228. "dlOpName": "minimum",
  5229. "category": "arithmetic",
  5230. "params": [
  5231. {
  5232. "tfInputIndex": 0,
  5233. "dlParamName": "a",
  5234. "type": "tensor"
  5235. },
  5236. {
  5237. "tfInputIndex": 1,
  5238. "dlParamName": "b",
  5239. "type": "tensor"
  5240. }
  5241. ]
  5242. },
  5243. {
  5244. "tfOpName": "Pow",
  5245. "dlOpName": "pow",
  5246. "category": "arithmetic",
  5247. "params": [
  5248. {
  5249. "tfInputIndex": 0,
  5250. "dlParamName": "a",
  5251. "type": "tensor"
  5252. },
  5253. {
  5254. "tfInputIndex": 1,
  5255. "dlParamName": "b",
  5256. "type": "tensor"
  5257. },
  5258. {
  5259. "tfParamName": "T",
  5260. "dlParamName": "dtype",
  5261. "type": "dtype",
  5262. "notSupported": true
  5263. }
  5264. ]
  5265. },
  5266. {
  5267. "tfOpName": "SquaredDifference",
  5268. "dlOpName": "squaredDifference",
  5269. "category": "arithmetic",
  5270. "params": [
  5271. {
  5272. "tfInputIndex": 0,
  5273. "dlParamName": "a",
  5274. "type": "tensor"
  5275. },
  5276. {
  5277. "tfInputIndex": 1,
  5278. "dlParamName": "b",
  5279. "type": "tensor"
  5280. },
  5281. {
  5282. "tfParamName": "T",
  5283. "dlParamName": "dtype",
  5284. "type": "dtype",
  5285. "notSupported": true
  5286. }
  5287. ]
  5288. },
  5289. {
  5290. "tfOpName": "Mod",
  5291. "dlOpName": "mod",
  5292. "category": "arithmetic",
  5293. "params": [
  5294. {
  5295. "tfInputIndex": 0,
  5296. "dlParamName": "a",
  5297. "type": "tensor"
  5298. },
  5299. {
  5300. "tfInputIndex": 1,
  5301. "dlParamName": "b",
  5302. "type": "tensor"
  5303. },
  5304. {
  5305. "tfParamName": "T",
  5306. "dlParamName": "dtype",
  5307. "type": "dtype",
  5308. "notSupported": true
  5309. }
  5310. ]
  5311. }
  5312. ]
  5313. },{}],32:[function(require,module,exports){
  5314. module.exports=[
  5315. {
  5316. "tfOpName": "Abs",
  5317. "dlOpName": "abs",
  5318. "category": "basic_math",
  5319. "params": [
  5320. {
  5321. "tfInputIndex": 0,
  5322. "dlParamName": "x",
  5323. "type": "tensor"
  5324. },
  5325. {
  5326. "tfParamName": "T",
  5327. "dlParamName": "dtype",
  5328. "type": "dtype",
  5329. "notSupported": true
  5330. }
  5331. ]
  5332. },
  5333. {
  5334. "tfOpName": "Acos",
  5335. "dlOpName": "acos",
  5336. "category": "basic_math",
  5337. "params": [
  5338. {
  5339. "tfInputIndex": 0,
  5340. "dlParamName": "x",
  5341. "type": "tensor"
  5342. },
  5343. {
  5344. "tfParamName": "T",
  5345. "dlParamName": "dtype",
  5346. "type": "dtype",
  5347. "notSupported": true
  5348. }
  5349. ]
  5350. },
  5351. {
  5352. "tfOpName": "Asin",
  5353. "dlOpName": "asin",
  5354. "category": "basic_math",
  5355. "params": [
  5356. {
  5357. "tfInputIndex": 0,
  5358. "dlParamName": "x",
  5359. "type": "tensor"
  5360. },
  5361. {
  5362. "tfParamName": "T",
  5363. "dlParamName": "dtype",
  5364. "type": "dtype",
  5365. "notSupported": true
  5366. }
  5367. ]
  5368. },
  5369. {
  5370. "tfOpName": "atan",
  5371. "dlOpName": "atan",
  5372. "category": "basic_math",
  5373. "params": [
  5374. {
  5375. "tfInputIndex": 0,
  5376. "dlParamName": "x",
  5377. "type": "tensor"
  5378. },
  5379. {
  5380. "tfParamName": "T",
  5381. "dlParamName": "dtype",
  5382. "type": "dtype",
  5383. "notSupported": true
  5384. }
  5385. ]
  5386. },
  5387. {
  5388. "tfOpName": "Ceil",
  5389. "dlOpName": "ceil",
  5390. "category": "basic_math",
  5391. "params": [
  5392. {
  5393. "tfInputIndex": 0,
  5394. "dlParamName": "x",
  5395. "type": "tensor"
  5396. },
  5397. {
  5398. "tfParamName": "T",
  5399. "dlParamName": "dtype",
  5400. "type": "dtype",
  5401. "notSupported": true
  5402. }
  5403. ]
  5404. },
  5405. {
  5406. "tfOpName": "ClipByValue",
  5407. "dlOpName": "clipByValue",
  5408. "category": "basic_math",
  5409. "params": [
  5410. {
  5411. "tfInputIndex": 0,
  5412. "dlParamName": "x",
  5413. "type": "tensor"
  5414. },
  5415. {
  5416. "tfParamName": "clip_value_min",
  5417. "dlParamName": "clipValueMin",
  5418. "type": "number"
  5419. },
  5420. {
  5421. "tfParamName": "clip_value_max",
  5422. "dlParamName": "clipValueMax",
  5423. "type": "number"
  5424. }
  5425. ]
  5426. },
  5427. {
  5428. "tfOpName": "Cos",
  5429. "dlOpName": "cos",
  5430. "category": "basic_math",
  5431. "params": [
  5432. {
  5433. "tfInputIndex": 0,
  5434. "dlParamName": "x",
  5435. "type": "tensor"
  5436. },
  5437. {
  5438. "tfParamName": "T",
  5439. "dlParamName": "dtype",
  5440. "type": "dtype",
  5441. "notSupported": true
  5442. }
  5443. ]
  5444. },
  5445. {
  5446. "tfOpName": "Cosh",
  5447. "dlOpName": "cosh",
  5448. "category": "basic_math",
  5449. "params": [
  5450. {
  5451. "tfInputIndex": 0,
  5452. "dlParamName": "x",
  5453. "type": "tensor"
  5454. },
  5455. {
  5456. "tfParamName": "T",
  5457. "dlParamName": "dtype",
  5458. "type": "dtype",
  5459. "notSupported": true
  5460. }
  5461. ]
  5462. },
  5463. {
  5464. "tfOpName": "Elu",
  5465. "dlOpName": "elu",
  5466. "category": "basic_math",
  5467. "params": [
  5468. {
  5469. "tfInputIndex": 0,
  5470. "dlParamName": "x",
  5471. "type": "tensor"
  5472. },
  5473. {
  5474. "tfParamName": "T",
  5475. "dlParamName": "dtype",
  5476. "type": "dtype",
  5477. "notSupported": true
  5478. }
  5479. ]
  5480. },
  5481. {
  5482. "tfOpName": "Exp",
  5483. "dlOpName": "exp",
  5484. "category": "basic_math",
  5485. "params": [
  5486. {
  5487. "tfInputIndex": 0,
  5488. "dlParamName": "x",
  5489. "type": "tensor"
  5490. },
  5491. {
  5492. "tfParamName": "T",
  5493. "dlParamName": "dtype",
  5494. "type": "dtype",
  5495. "notSupported": true
  5496. }
  5497. ]
  5498. },
  5499. {
  5500. "tfOpName": "Floor",
  5501. "dlOpName": "floor",
  5502. "category": "basic_math",
  5503. "params": [
  5504. {
  5505. "tfInputIndex": 0,
  5506. "dlParamName": "x",
  5507. "type": "tensor"
  5508. },
  5509. {
  5510. "tfParamName": "T",
  5511. "dlParamName": "dtype",
  5512. "type": "dtype",
  5513. "notSupported": true
  5514. }
  5515. ]
  5516. },
  5517. {
  5518. "tfOpName": "Log",
  5519. "dlOpName": "log",
  5520. "category": "basic_math",
  5521. "params": [
  5522. {
  5523. "tfInputIndex": 0,
  5524. "dlParamName": "x",
  5525. "type": "tensor"
  5526. },
  5527. {
  5528. "tfParamName": "T",
  5529. "dlParamName": "dtype",
  5530. "type": "dtype",
  5531. "notSupported": true
  5532. }
  5533. ]
  5534. },
  5535. {
  5536. "tfOpName": "Neg",
  5537. "dlOpName": "neg",
  5538. "category": "basic_math",
  5539. "params": [
  5540. {
  5541. "tfInputIndex": 0,
  5542. "dlParamName": "x",
  5543. "type": "tensor"
  5544. },
  5545. {
  5546. "tfParamName": "T",
  5547. "dlParamName": "dtype",
  5548. "type": "dtype",
  5549. "notSupported": true
  5550. }
  5551. ]
  5552. },
  5553. {
  5554. "tfOpName": "Relu",
  5555. "dlOpName": "relu",
  5556. "category": "basic_math",
  5557. "params": [
  5558. {
  5559. "tfInputIndex": 0,
  5560. "dlParamName": "x",
  5561. "type": "tensor"
  5562. },
  5563. {
  5564. "tfParamName": "T",
  5565. "dlParamName": "dtype",
  5566. "type": "dtype",
  5567. "notSupported": true
  5568. }
  5569. ]
  5570. },
  5571. {
  5572. "tfOpName": "Relu6",
  5573. "dlOpName": "clipByValue",
  5574. "category": "basic_math",
  5575. "params": [
  5576. {
  5577. "tfInputIndex": 0,
  5578. "dlParamName": "x",
  5579. "type": "tensor"
  5580. },
  5581. {
  5582. "tfParamName": "T",
  5583. "dlParamName": "dtype",
  5584. "type": "dtype",
  5585. "notSupported": true
  5586. },
  5587. {
  5588. "dlParamName": "clipValueMin",
  5589. "type": "number",
  5590. "defaultValue": 0
  5591. },
  5592. {
  5593. "dlParamName": "clipValueMax",
  5594. "type": "number",
  5595. "defaultValue": 6
  5596. }
  5597. ]
  5598. },
  5599. {
  5600. "tfOpName": "Selu",
  5601. "dlOpName": "selu",
  5602. "category": "basic_math",
  5603. "params": [
  5604. {
  5605. "tfInputIndex": 0,
  5606. "dlParamName": "x",
  5607. "type": "tensor"
  5608. },
  5609. {
  5610. "tfParamName": "T",
  5611. "dlParamName": "dtype",
  5612. "type": "dtype",
  5613. "notSupported": true
  5614. }
  5615. ]
  5616. },
  5617. {
  5618. "tfOpName": "Sigmoid",
  5619. "dlOpName": "sigmoid",
  5620. "category": "basic_math",
  5621. "params": [
  5622. {
  5623. "tfInputIndex": 0,
  5624. "dlParamName": "x",
  5625. "type": "tensor"
  5626. },
  5627. {
  5628. "tfParamName": "T",
  5629. "dlParamName": "dtype",
  5630. "type": "dtype",
  5631. "notSupported": true
  5632. }
  5633. ]
  5634. },
  5635. {
  5636. "tfOpName": "Sin",
  5637. "dlOpName": "sin",
  5638. "category": "basic_math",
  5639. "params": [
  5640. {
  5641. "tfInputIndex": 0,
  5642. "dlParamName": "x",
  5643. "type": "tensor"
  5644. },
  5645. {
  5646. "tfParamName": "T",
  5647. "dlParamName": "dtype",
  5648. "type": "dtype",
  5649. "notSupported": true
  5650. }
  5651. ]
  5652. },
  5653. {
  5654. "tfOpName": "Sinh",
  5655. "dlOpName": "sinh",
  5656. "category": "basic_math",
  5657. "params": [
  5658. {
  5659. "tfInputIndex": 0,
  5660. "dlParamName": "x",
  5661. "type": "tensor"
  5662. },
  5663. {
  5664. "tfParamName": "T",
  5665. "dlParamName": "dtype",
  5666. "type": "dtype",
  5667. "notSupported": true
  5668. }
  5669. ]
  5670. },
  5671. {
  5672. "tfOpName": "Sqrt",
  5673. "dlOpName": "sqrt",
  5674. "category": "basic_math",
  5675. "params": [
  5676. {
  5677. "tfInputIndex": 0,
  5678. "dlParamName": "x",
  5679. "type": "tensor"
  5680. },
  5681. {
  5682. "tfParamName": "T",
  5683. "dlParamName": "dtype",
  5684. "type": "dtype",
  5685. "notSupported": true
  5686. }
  5687. ]
  5688. },
  5689. {
  5690. "tfOpName": "Rsqrt",
  5691. "dlOpName": "rsqrt",
  5692. "category": "basic_math",
  5693. "params": [
  5694. {
  5695. "tfInputIndex": 0,
  5696. "dlParamName": "x",
  5697. "type": "tensor"
  5698. },
  5699. {
  5700. "tfParamName": "T",
  5701. "dlParamName": "dtype",
  5702. "type": "dtype",
  5703. "notSupported": true
  5704. }
  5705. ]
  5706. },
  5707. {
  5708. "tfOpName": "Square",
  5709. "dlOpName": "square",
  5710. "category": "basic_math",
  5711. "params": [
  5712. {
  5713. "tfInputIndex": 0,
  5714. "dlParamName": "x",
  5715. "type": "tensor"
  5716. },
  5717. {
  5718. "tfParamName": "T",
  5719. "dlParamName": "dtype",
  5720. "type": "dtype",
  5721. "notSupported": true
  5722. }
  5723. ]
  5724. },
  5725. {
  5726. "tfOpName": "Tan",
  5727. "dlOpName": "tan",
  5728. "category": "basic_math",
  5729. "params": [
  5730. {
  5731. "tfInputIndex": 0,
  5732. "dlParamName": "x",
  5733. "type": "tensor"
  5734. },
  5735. {
  5736. "tfParamName": "T",
  5737. "dlParamName": "dtype",
  5738. "type": "dtype",
  5739. "notSupported": true
  5740. }
  5741. ]
  5742. },
  5743. {
  5744. "tfOpName": "Tanh",
  5745. "dlOpName": "tanh",
  5746. "category": "basic_math",
  5747. "params": [
  5748. {
  5749. "tfInputIndex": 0,
  5750. "dlParamName": "x",
  5751. "type": "tensor"
  5752. },
  5753. {
  5754. "tfParamName": "T",
  5755. "dlParamName": "dtype",
  5756. "type": "dtype",
  5757. "notSupported": true
  5758. }
  5759. ]
  5760. },
  5761. {
  5762. "tfOpName": "Sign",
  5763. "dlOpName": "sign",
  5764. "category": "basic_math",
  5765. "params": [
  5766. {
  5767. "tfInputIndex": 0,
  5768. "dlParamName": "x",
  5769. "type": "tensor"
  5770. },
  5771. {
  5772. "tfParamName": "T",
  5773. "dlParamName": "dtype",
  5774. "type": "dtype",
  5775. "notSupported": true
  5776. }
  5777. ]
  5778. },
  5779. {
  5780. "tfOpName": "Round",
  5781. "dlOpName": "round",
  5782. "category": "basic_math",
  5783. "params": [
  5784. {
  5785. "tfInputIndex": 0,
  5786. "dlParamName": "x",
  5787. "type": "tensor"
  5788. },
  5789. {
  5790. "tfParamName": "T",
  5791. "dlParamName": "dtype",
  5792. "type": "dtype",
  5793. "notSupported": true
  5794. }
  5795. ]
  5796. },
  5797. {
  5798. "tfOpName": "Expm1",
  5799. "dlOpName": "expm1",
  5800. "category": "basic_math",
  5801. "params": [
  5802. {
  5803. "tfInputIndex": 0,
  5804. "dlParamName": "x",
  5805. "type": "tensor"
  5806. },
  5807. {
  5808. "tfParamName": "T",
  5809. "dlParamName": "dtype",
  5810. "type": "dtype",
  5811. "notSupported": true
  5812. }
  5813. ]
  5814. },
  5815. {
  5816. "tfOpName": "Log1p",
  5817. "dlOpName": "log1p",
  5818. "category": "basic_math",
  5819. "params": [
  5820. {
  5821. "tfInputIndex": 0,
  5822. "dlParamName": "x",
  5823. "type": "tensor"
  5824. },
  5825. {
  5826. "tfParamName": "T",
  5827. "dlParamName": "dtype",
  5828. "type": "dtype",
  5829. "notSupported": true
  5830. }
  5831. ]
  5832. },
  5833. {
  5834. "tfOpName": "Reciprocal",
  5835. "dlOpName": "reciprocal",
  5836. "category": "basic_math",
  5837. "params": [
  5838. {
  5839. "tfInputIndex": 0,
  5840. "dlParamName": "x",
  5841. "type": "tensor"
  5842. },
  5843. {
  5844. "tfParamName": "T",
  5845. "dlParamName": "dtype",
  5846. "type": "dtype",
  5847. "notSupported": true
  5848. }
  5849. ]
  5850. },
  5851. {
  5852. "tfOpName": "Reciprocal",
  5853. "dlOpName": "reciprocal",
  5854. "category": "basic_math",
  5855. "params": [
  5856. {
  5857. "tfInputIndex": 0,
  5858. "dlParamName": "x",
  5859. "type": "tensor"
  5860. },
  5861. {
  5862. "tfParamName": "T",
  5863. "dlParamName": "dtype",
  5864. "type": "dtype",
  5865. "notSupported": true
  5866. }
  5867. ]
  5868. },
  5869. {
  5870. "tfOpName": "Softplus",
  5871. "dlOpName": "softplus",
  5872. "category": "basic_math",
  5873. "params": [
  5874. {
  5875. "tfInputIndex": 0,
  5876. "dlParamName": "x",
  5877. "type": "tensor"
  5878. },
  5879. {
  5880. "tfParamName": "T",
  5881. "dlParamName": "dtype",
  5882. "type": "dtype",
  5883. "notSupported": true
  5884. }
  5885. ]
  5886. },
  5887. {
  5888. "tfOpName": "Asinh",
  5889. "dlOpName": "asinh",
  5890. "category": "basic_math",
  5891. "params": [
  5892. {
  5893. "tfInputIndex": 0,
  5894. "dlParamName": "x",
  5895. "type": "tensor"
  5896. },
  5897. {
  5898. "tfParamName": "T",
  5899. "dlParamName": "dtype",
  5900. "type": "dtype",
  5901. "notSupported": true
  5902. }
  5903. ]
  5904. },
  5905. {
  5906. "tfOpName": "Acosh",
  5907. "dlOpName": "acosh",
  5908. "category": "basic_math",
  5909. "params": [
  5910. {
  5911. "tfInputIndex": 0,
  5912. "dlParamName": "x",
  5913. "type": "tensor"
  5914. },
  5915. {
  5916. "tfParamName": "T",
  5917. "dlParamName": "dtype",
  5918. "type": "dtype",
  5919. "notSupported": true
  5920. }
  5921. ]
  5922. },
  5923. {
  5924. "tfOpName": "Atanh",
  5925. "dlOpName": "atanh",
  5926. "category": "basic_math",
  5927. "params": [
  5928. {
  5929. "tfInputIndex": 0,
  5930. "dlParamName": "x",
  5931. "type": "tensor"
  5932. },
  5933. {
  5934. "tfParamName": "T",
  5935. "dlParamName": "dtype",
  5936. "type": "dtype",
  5937. "notSupported": true
  5938. }
  5939. ]
  5940. },
  5941. {
  5942. "tfOpName": "Erf",
  5943. "dlOpName": "erf",
  5944. "category": "basic_math",
  5945. "params": [
  5946. {
  5947. "tfInputIndex": 0,
  5948. "dlParamName": "x",
  5949. "type": "tensor"
  5950. },
  5951. {
  5952. "tfParamName": "T",
  5953. "dlParamName": "dtype",
  5954. "type": "dtype",
  5955. "notSupported": true
  5956. }
  5957. ]
  5958. }
  5959. ]
  5960. },{}],33:[function(require,module,exports){
  5961. module.exports=[
  5962. {
  5963. "tfOpName": "LoopCond",
  5964. "dlOpName": "loopCond",
  5965. "category": "control",
  5966. "params": [
  5967. {
  5968. "tfInputIndex": 0,
  5969. "dlParamName": "pred",
  5970. "type": "tensor"
  5971. }
  5972. ]
  5973. },
  5974. {
  5975. "tfOpName": "Switch",
  5976. "dlOpName": "switch",
  5977. "category": "control",
  5978. "params": [
  5979. {
  5980. "tfInputIndex": 0,
  5981. "dlParamName": "data",
  5982. "type": "tensor"
  5983. },
  5984. {
  5985. "tfInputIndex": 1,
  5986. "dlParamName": "pred",
  5987. "type": "tensor"
  5988. }
  5989. ]
  5990. },
  5991. {
  5992. "tfOpName": "Merge",
  5993. "dlOpName": "merge",
  5994. "category": "control",
  5995. "params": [
  5996. {
  5997. "tfInputIndex": 0,
  5998. "tfInputParamLength": 0,
  5999. "dlParamName": "tensors",
  6000. "type": "tensors"
  6001. }
  6002. ]
  6003. },
  6004. {
  6005. "tfOpName": "Enter",
  6006. "dlOpName": "enter",
  6007. "category": "control",
  6008. "params": [
  6009. {
  6010. "tfInputIndex": 0,
  6011. "dlParamName": "tensor",
  6012. "type": "tensor"
  6013. },
  6014. {
  6015. "tfParamName": "T",
  6016. "dlParamName": "dtype",
  6017. "type": "dtype",
  6018. "notSupported": true
  6019. },
  6020. {
  6021. "tfParamName": "frame_name",
  6022. "dlParamName": "frameName",
  6023. "type": "string"
  6024. },
  6025. {
  6026. "tfParamName": "is_constant",
  6027. "dlParamName": "isConstant",
  6028. "type": "bool"
  6029. }
  6030. ]
  6031. },
  6032. {
  6033. "tfOpName": "Exit",
  6034. "dlOpName": "exit",
  6035. "category": "control",
  6036. "params": [
  6037. {
  6038. "tfInputIndex": 0,
  6039. "dlParamName": "tensor",
  6040. "type": "tensor"
  6041. },
  6042. {
  6043. "tfParamName": "T",
  6044. "dlParamName": "dtype",
  6045. "type": "dtype",
  6046. "notSupported": true
  6047. }
  6048. ]
  6049. },
  6050. {
  6051. "tfOpName": "NextIteration",
  6052. "dlOpName": "nextIteration",
  6053. "category": "control",
  6054. "params": [
  6055. {
  6056. "tfInputIndex": 0,
  6057. "dlParamName": "tensor",
  6058. "type": "tensor"
  6059. },
  6060. {
  6061. "tfParamName": "T",
  6062. "dlParamName": "dtype",
  6063. "type": "dtype",
  6064. "notSupported": true
  6065. }
  6066. ]
  6067. }
  6068. ]
  6069. },{}],34:[function(require,module,exports){
  6070. module.exports=[
  6071. {
  6072. "tfOpName": "AvgPool",
  6073. "dlOpName": "avgPool",
  6074. "category": "convolution",
  6075. "params": [
  6076. {
  6077. "tfInputIndex": 0,
  6078. "dlParamName": "x",
  6079. "type": "tensor"
  6080. },
  6081. {
  6082. "tfParamName": "strides",
  6083. "dlParamName": "strides",
  6084. "type": "number[]"
  6085. },
  6086. {
  6087. "tfParamName": "padding",
  6088. "dlParamName": "pad",
  6089. "type": "string"
  6090. },
  6091. {
  6092. "tfParamName": "data_format",
  6093. "dlParamName": "dataFormat",
  6094. "type": "string",
  6095. "notSupported": true
  6096. },
  6097. {
  6098. "tfParamName": "ksize",
  6099. "dlParamName": "kernelSize",
  6100. "type": "number[]"
  6101. },
  6102. {
  6103. "tfParamName": "T",
  6104. "dlParamName": "dtype",
  6105. "type": "dtype",
  6106. "notSupported": true
  6107. }
  6108. ]
  6109. },
  6110. {
  6111. "tfOpName": "MaxPool",
  6112. "dlOpName": "maxPool",
  6113. "category": "convolution",
  6114. "params": [
  6115. {
  6116. "tfInputIndex": 0,
  6117. "dlParamName": "x",
  6118. "type": "tensor"
  6119. },
  6120. {
  6121. "tfParamName": "strides",
  6122. "dlParamName": "strides",
  6123. "type": "number[]"
  6124. },
  6125. {
  6126. "tfParamName": "padding",
  6127. "dlParamName": "pad",
  6128. "type": "string"
  6129. },
  6130. {
  6131. "tfParamName": "data_format",
  6132. "dlParamName": "dataFormat",
  6133. "type": "string",
  6134. "notSupported": true
  6135. },
  6136. {
  6137. "tfParamName": "ksize",
  6138. "dlParamName": "kernelSize",
  6139. "type": "number[]"
  6140. },
  6141. {
  6142. "tfParamName": "T",
  6143. "dlParamName": "dtype",
  6144. "type": "dtype",
  6145. "notSupported": true
  6146. }
  6147. ]
  6148. },
  6149. {
  6150. "tfOpName": "Conv1D",
  6151. "dlOpName": "conv1d",
  6152. "category": "convolution",
  6153. "params": [
  6154. {
  6155. "tfInputIndex": 0,
  6156. "dlParamName": "x",
  6157. "type": "tensor"
  6158. },
  6159. {
  6160. "tfInputIndex": 1,
  6161. "dlParamName": "filter",
  6162. "type": "tensor"
  6163. },
  6164. {
  6165. "tfParamName": "stride",
  6166. "dlParamName": "stride",
  6167. "type": "number"
  6168. },
  6169. {
  6170. "tfParamName": "padding",
  6171. "dlParamName": "pad",
  6172. "type": "string"
  6173. },
  6174. {
  6175. "tfParamName": "data_format",
  6176. "dlParamName": "dataFormat",
  6177. "type": "string",
  6178. "defaultValue": "NWC"
  6179. },
  6180. {
  6181. "tfParamName": "T",
  6182. "dlParamName": "dtype",
  6183. "type": "dtype",
  6184. "notSupported": true
  6185. },
  6186. {
  6187. "tfParamName": "dilation",
  6188. "dlParamName": "dilation",
  6189. "type": "number",
  6190. "defaultValue": 1
  6191. }
  6192. ]
  6193. },
  6194. {
  6195. "tfOpName": "Conv2D",
  6196. "dlOpName": "conv2d",
  6197. "category": "convolution",
  6198. "params": [
  6199. {
  6200. "tfInputIndex": 0,
  6201. "dlParamName": "x",
  6202. "type": "tensor"
  6203. },
  6204. {
  6205. "tfInputIndex": 1,
  6206. "dlParamName": "filter",
  6207. "type": "tensor"
  6208. },
  6209. {
  6210. "tfParamName": "T",
  6211. "dlParamName": "dtype",
  6212. "type": "dtype",
  6213. "notSupported": true
  6214. },
  6215. {
  6216. "tfParamName": "strides",
  6217. "dlParamName": "strides",
  6218. "type": "number[]"
  6219. },
  6220. {
  6221. "tfParamName": "padding",
  6222. "dlParamName": "pad",
  6223. "type": "string"
  6224. },
  6225. {
  6226. "tfParamName": "useCudnnOnGpu",
  6227. "dlParamName": "useCudnnOnGpu",
  6228. "type": "bool"
  6229. },
  6230. {
  6231. "tfParamName": "data_format",
  6232. "dlParamName": "dataFormat",
  6233. "type": "string",
  6234. "defaultValue": "NHWC"
  6235. },
  6236. {
  6237. "tfParamName": "dilations",
  6238. "dlParamName": "dilations",
  6239. "type": "number[]"
  6240. }
  6241. ]
  6242. },
  6243. {
  6244. "tfOpName": "Conv2DBackpropInput",
  6245. "dlOpName": "conv2dTranspose",
  6246. "category": "convolution",
  6247. "params": [
  6248. {
  6249. "tfInputIndex": 2,
  6250. "dlParamName": "x",
  6251. "type": "tensor"
  6252. },
  6253. {
  6254. "tfInputIndex": 1,
  6255. "dlParamName": "filter",
  6256. "type": "tensor"
  6257. },
  6258. {
  6259. "tfInputIndex": 0,
  6260. "dlParamName": "outputShape",
  6261. "type": "number[]"
  6262. },
  6263. {
  6264. "tfParamName": "strides",
  6265. "dlParamName": "strides",
  6266. "type": "number[]"
  6267. },
  6268. {
  6269. "tfParamName": "padding",
  6270. "dlParamName": "pad",
  6271. "type": "string"
  6272. },
  6273. {
  6274. "tfParamName": "data_format",
  6275. "dlParamName": "dataFormat",
  6276. "type": "string",
  6277. "notSupported": true
  6278. }
  6279. ]
  6280. },
  6281. {
  6282. "tfOpName": "DepthwiseConv2d",
  6283. "dlOpName": "depthwiseConv2d",
  6284. "category": "convolution",
  6285. "params": [
  6286. {
  6287. "tfInputIndex": 0,
  6288. "dlParamName": "input",
  6289. "type": "tensor"
  6290. },
  6291. {
  6292. "tfInputIndex": 1,
  6293. "dlParamName": "filter",
  6294. "type": "tensor"
  6295. },
  6296. {
  6297. "tfParamName": "strides",
  6298. "dlParamName": "strides",
  6299. "type": "number[]"
  6300. },
  6301. {
  6302. "tfParamName": "padding",
  6303. "dlParamName": "pad",
  6304. "type": "string"
  6305. },
  6306. {
  6307. "tfParamName": "data_format",
  6308. "dlParamName": "dataFormat",
  6309. "type": "string",
  6310. "defaultValue": "NHWC"
  6311. },
  6312. {
  6313. "tfParamName": "dilations",
  6314. "dlParamName": "dilations",
  6315. "type": "number[]"
  6316. }
  6317. ]
  6318. },
  6319. {
  6320. "tfOpName": "DepthwiseConv2dNative",
  6321. "dlOpName": "depthwiseConv2d",
  6322. "category": "convolution",
  6323. "params": [
  6324. {
  6325. "tfInputIndex": 0,
  6326. "dlParamName": "input",
  6327. "type": "tensor"
  6328. },
  6329. {
  6330. "tfInputIndex": 1,
  6331. "dlParamName": "filter",
  6332. "type": "tensor"
  6333. },
  6334. {
  6335. "tfParamName": "strides",
  6336. "dlParamName": "strides",
  6337. "type": "number[]"
  6338. },
  6339. {
  6340. "tfParamName": "padding",
  6341. "dlParamName": "pad",
  6342. "type": "string"
  6343. },
  6344. {
  6345. "tfParamName": "data_format",
  6346. "dlParamName": "dataFormat",
  6347. "type": "string",
  6348. "defaultValue": "NHWC"
  6349. },
  6350. {
  6351. "tfParamName": "dilations",
  6352. "dlParamName": "dilations",
  6353. "type": "number[]"
  6354. }
  6355. ]
  6356. }
  6357. ]
  6358. },{}],35:[function(require,module,exports){
  6359. module.exports=[
  6360. {
  6361. "tfOpName": "Fill",
  6362. "dlOpName": "fill",
  6363. "category": "creation",
  6364. "params": [
  6365. {
  6366. "tfInputIndex": 0,
  6367. "dlParamName": "shape",
  6368. "type": "number[]"
  6369. },
  6370. {
  6371. "tfInputIndex": 1,
  6372. "dlParamName": "value",
  6373. "type": "number"
  6374. },
  6375. {
  6376. "tfParamName": "T",
  6377. "dlParamName": "dtype",
  6378. "type": "dtype",
  6379. "notSupported": true
  6380. }
  6381. ]
  6382. },
  6383. {
  6384. "tfOpName": "LinSpace",
  6385. "dlOpName": "linspace",
  6386. "category": "creation",
  6387. "params": [
  6388. {
  6389. "tfInputIndex": 0,
  6390. "dlParamName": "start",
  6391. "type": "number"
  6392. },
  6393. {
  6394. "tfInputIndex": 1,
  6395. "dlParamName": "stop",
  6396. "type": "number"
  6397. },
  6398. {
  6399. "tfInputIndex": 2,
  6400. "dlParamName": "num",
  6401. "type": "number"
  6402. },
  6403. {
  6404. "tfParamName": "T",
  6405. "dlParamName": "dtype",
  6406. "type": "dtype",
  6407. "notSupported": true
  6408. }
  6409. ]
  6410. },
  6411. {
  6412. "tfOpName": "OneHot",
  6413. "dlOpName": "oneHot",
  6414. "category": "creation",
  6415. "params": [
  6416. {
  6417. "tfInputIndex": 0,
  6418. "dlParamName": "indices",
  6419. "type": "tensor"
  6420. },
  6421. {
  6422. "tfInputIndex": 1,
  6423. "dlParamName": "depth",
  6424. "type": "number"
  6425. },
  6426. {
  6427. "tfInputIndex": 2,
  6428. "dlParamName": "onValue",
  6429. "type": "number",
  6430. "defaultValue": 1
  6431. },
  6432. {
  6433. "tfInputIndex": 3,
  6434. "dlParamName": "offValue",
  6435. "type": "number",
  6436. "defaultValue": 0
  6437. },
  6438. {
  6439. "tfParamName": "axis",
  6440. "dlParamName": "axis",
  6441. "type": "number",
  6442. "notSupported": true
  6443. },
  6444. {
  6445. "tfParamName": "T",
  6446. "dlParamName": "dtype",
  6447. "type": "dtype",
  6448. "notSupported": true
  6449. }
  6450. ]
  6451. },
  6452. {
  6453. "tfOpName": "Ones",
  6454. "dlOpName": "ones",
  6455. "category": "creation",
  6456. "params": [
  6457. {
  6458. "tfInputIndex": 0,
  6459. "dlParamName": "shape",
  6460. "type": "number[]"
  6461. },
  6462. {
  6463. "tfParamName": "T",
  6464. "dlParamName": "dtype",
  6465. "type": "dtype"
  6466. }
  6467. ]
  6468. },
  6469. {
  6470. "tfOpName": "OnesLike",
  6471. "dlOpName": "onesLike",
  6472. "category": "creation",
  6473. "params": [
  6474. {
  6475. "tfInputIndex": 0,
  6476. "dlParamName": "x",
  6477. "type": "tensor"
  6478. },
  6479. {
  6480. "tfParamName": "dtype",
  6481. "dlParamName": "dtype",
  6482. "type": "dtype"
  6483. }
  6484. ]
  6485. },
  6486. {
  6487. "tfOpName": "RandomUniform",
  6488. "dlOpName": "randomUniform",
  6489. "category": "creation",
  6490. "params": [
  6491. {
  6492. "tfInputIndex": 0,
  6493. "dlParamName": "shape",
  6494. "type": "number[]"
  6495. },
  6496. {
  6497. "tfParamName": "minval",
  6498. "dlParamName": "minval",
  6499. "type": "number",
  6500. "defaultValue": 0
  6501. },
  6502. {
  6503. "tfParamName": "maxval",
  6504. "dlParamName": "maxval",
  6505. "type": "number",
  6506. "defaultValue": 1
  6507. },
  6508. {
  6509. "tfParamName": "dtype",
  6510. "dlParamName": "dtype",
  6511. "type": "dtype"
  6512. },
  6513. {
  6514. "tfParamName": "seed",
  6515. "dlParamName": "seed",
  6516. "type": "number",
  6517. "defaultValue": 0
  6518. },
  6519. {
  6520. "tfParamName": "seed2",
  6521. "dlParamName": "seed2",
  6522. "type": "number",
  6523. "defaultValue": 0,
  6524. "notSupported": true
  6525. },
  6526. {
  6527. "tfParamName": "T",
  6528. "dlParamName": "T",
  6529. "type": "number",
  6530. "notSupported": true
  6531. }
  6532. ]
  6533. },
  6534. {
  6535. "tfOpName": "Range",
  6536. "dlOpName": "range",
  6537. "category": "creation",
  6538. "params": [
  6539. {
  6540. "tfInputIndex": 0,
  6541. "dlParamName": "start",
  6542. "type": "number"
  6543. },
  6544. {
  6545. "tfInputIndex": 1,
  6546. "dlParamName": "stop",
  6547. "type": "number"
  6548. },
  6549. {
  6550. "tfInputIndex": 2,
  6551. "dlParamName": "step",
  6552. "type": "number",
  6553. "defaultValue": 0
  6554. },
  6555. {
  6556. "tfParamName": "Tidx",
  6557. "dlParamName": "dtype",
  6558. "type": "dtype"
  6559. }
  6560. ]
  6561. },
  6562. {
  6563. "tfOpName": "truncatedNormal",
  6564. "dlOpName": "truncatedNormal",
  6565. "category": "creation",
  6566. "params": [
  6567. {
  6568. "tfInputIndex": 0,
  6569. "dlParamName": "shape",
  6570. "type": "number[]"
  6571. },
  6572. {
  6573. "tfParamName": "means",
  6574. "dlParamName": "mean",
  6575. "type": "number",
  6576. "defaultValue": 0.0
  6577. },
  6578. {
  6579. "tfParamName": "stddev",
  6580. "dlParamName": "stdDev",
  6581. "type": "number",
  6582. "defaultValue": 1.0
  6583. },
  6584. {
  6585. "tfParamName": "seed",
  6586. "dlParamName": "seed",
  6587. "type": "number"
  6588. },
  6589. {
  6590. "tfParamName": "seed2",
  6591. "dlParamName": "seed2",
  6592. "type": "number",
  6593. "defaultValue": 0,
  6594. "notSupported": true
  6595. },
  6596. {
  6597. "tfParamName": "dtype",
  6598. "dlParamName": "dtype",
  6599. "type": "dtype"
  6600. },
  6601. {
  6602. "tfParamName": "T",
  6603. "dlParamName": "T",
  6604. "type": "number",
  6605. "notSupported": true
  6606. }
  6607. ]
  6608. },
  6609. {
  6610. "tfOpName": "Zeros",
  6611. "dlOpName": "zeros",
  6612. "category": "creation",
  6613. "params": [
  6614. {
  6615. "tfInputIndex": 0,
  6616. "dlParamName": "shape",
  6617. "type": "number[]"
  6618. },
  6619. {
  6620. "tfParamName": "T",
  6621. "dlParamName": "dtype",
  6622. "type": "dtype"
  6623. }
  6624. ]
  6625. },
  6626. {
  6627. "tfOpName": "ZerosLike",
  6628. "dlOpName": "zerosLike",
  6629. "category": "creation",
  6630. "params": [
  6631. {
  6632. "tfInputIndex": 0,
  6633. "dlParamName": "x",
  6634. "type": "tensor"
  6635. },
  6636. {
  6637. "tfParamName": "T",
  6638. "dlParamName": "dtype",
  6639. "type": "dtype"
  6640. }
  6641. ]
  6642. }
  6643. ]
  6644. },{}],36:[function(require,module,exports){
  6645. module.exports=[
  6646. {
  6647. "tfOpName": "PlaceholderWithDefault",
  6648. "dlOpName": "placeholder",
  6649. "category": "graph",
  6650. "params": [
  6651. {
  6652. "tfInputIndex": 0,
  6653. "dlParamName": "default",
  6654. "type": "tensor"
  6655. },
  6656. {
  6657. "tfParamName": "shape",
  6658. "dlParamName": "shape",
  6659. "type": "shape"
  6660. },
  6661. {
  6662. "tfParamName": "dtype",
  6663. "dlParamName": "dtype",
  6664. "type": "dtype"
  6665. }
  6666. ]
  6667. },
  6668. {
  6669. "tfOpName": "Placeholder",
  6670. "dlOpName": "placeholder",
  6671. "category": "graph",
  6672. "params": [
  6673. {
  6674. "tfParamName": "shape",
  6675. "dlParamName": "shape",
  6676. "type": "shape"
  6677. },
  6678. {
  6679. "tfParamName": "dtype",
  6680. "dlParamName": "dtype",
  6681. "type": "dtype"
  6682. }
  6683. ]
  6684. },
  6685. {
  6686. "tfOpName": "Const",
  6687. "dlOpName": "const",
  6688. "category": "graph"
  6689. },
  6690. {
  6691. "tfOpName": "Identity",
  6692. "dlOpName": "identity",
  6693. "category": "graph",
  6694. "params": [
  6695. {
  6696. "tfInputIndex": 0,
  6697. "dlParamName": "x",
  6698. "type": "tensor"
  6699. }
  6700. ]
  6701. },
  6702. {
  6703. "tfOpName": "Snapshot",
  6704. "dlOpName": "snapshot",
  6705. "category": "graph",
  6706. "params": [
  6707. {
  6708. "tfInputIndex": 0,
  6709. "dlParamName": "x",
  6710. "type": "tensor"
  6711. }
  6712. ]
  6713. },
  6714. {
  6715. "tfOpName": "Rank",
  6716. "dlOpName": "rank",
  6717. "category": "graph",
  6718. "params": [
  6719. {
  6720. "tfInputIndex": 0,
  6721. "dlParamName": "x",
  6722. "type": "tensor"
  6723. }
  6724. ]
  6725. },
  6726. {
  6727. "tfOpName": "Size",
  6728. "dlOpName": "size",
  6729. "category": "graph",
  6730. "params": [
  6731. {
  6732. "tfInputIndex": 0,
  6733. "dlParamName": "x",
  6734. "type": "tensor"
  6735. }
  6736. ]
  6737. },
  6738. {
  6739. "tfOpName": "Shape",
  6740. "dlOpName": "shape",
  6741. "category": "graph",
  6742. "params": [
  6743. {
  6744. "tfInputIndex": 0,
  6745. "dlParamName": "x",
  6746. "type": "tensor"
  6747. }
  6748. ]
  6749. },
  6750. {
  6751. "tfOpName": "Print",
  6752. "dlOpName": "print",
  6753. "category": "graph",
  6754. "params": [
  6755. {
  6756. "tfInputIndex": 0,
  6757. "dlParamName": "x",
  6758. "type": "tensor"
  6759. },
  6760. {
  6761. "tfInputIndex": 1,
  6762. "tfInputParamLength": 1,
  6763. "dlParamName": "data",
  6764. "type": "tensors"
  6765. },
  6766. {
  6767. "tfParamName": "message",
  6768. "dlParamName": "message",
  6769. "type": "string"
  6770. },
  6771. {
  6772. "tfParamName": "first_n",
  6773. "dlParamName": "firstN",
  6774. "type": "number",
  6775. "notSupprted": true
  6776. },
  6777. {
  6778. "tfParamName": "summarize",
  6779. "dlParamName": "summarize",
  6780. "type": "number",
  6781. "defaultValue": 3
  6782. }
  6783. ]
  6784. },
  6785. {
  6786. "tfOpName": "NoOp",
  6787. "dlOpName": "noop",
  6788. "category": "graph",
  6789. "params": []
  6790. },
  6791. {
  6792. "tfOpName": "StopGradient",
  6793. "dlOpName": "stopGradient",
  6794. "category": "graph",
  6795. "params": [
  6796. {
  6797. "tfInputIndex": 0,
  6798. "dlParamName": "x",
  6799. "type": "tensor"
  6800. }
  6801. ]
  6802. },
  6803. {
  6804. "tfOpName": "FakeQuantWithMinMaxVars",
  6805. "dlOpName": "fakeQuantWithMinMaxVars",
  6806. "category": "graph",
  6807. "params": [
  6808. {
  6809. "tfInputIndex": 0,
  6810. "dlParamName": "x",
  6811. "type": "tensor"
  6812. },
  6813. {
  6814. "tfParamName": "min",
  6815. "dlParamName": "min",
  6816. "type": "number"
  6817. },
  6818. {
  6819. "tfParamName": "max",
  6820. "dlParamName": "max",
  6821. "type": "number"
  6822. }
  6823. ]
  6824. }
  6825. ]
  6826. },{}],37:[function(require,module,exports){
  6827. module.exports=[
  6828. {
  6829. "tfOpName": "ResizeBilinear",
  6830. "dlOpName": "resizeBilinear",
  6831. "category": "image",
  6832. "params": [
  6833. {
  6834. "tfInputIndex": 0,
  6835. "dlParamName": "images",
  6836. "type": "tensor"
  6837. },
  6838. {
  6839. "tfInputIndex": 1,
  6840. "dlParamName": "size",
  6841. "type": "number[]"
  6842. },
  6843. {
  6844. "tfParamName": "align_corners",
  6845. "dlParamName": "alignCorners",
  6846. "type": "bool"
  6847. },
  6848. {
  6849. "tfParamName": "T",
  6850. "dlParamName": "dtype",
  6851. "type": "dtype",
  6852. "notSupported": true
  6853. }
  6854. ]
  6855. },
  6856. {
  6857. "tfOpName": "ResizeNearestNeighbor",
  6858. "dlOpName": "resizeNearestNeighbor",
  6859. "category": "image",
  6860. "params": [
  6861. {
  6862. "tfInputIndex": 0,
  6863. "dlParamName": "images",
  6864. "type": "tensor"
  6865. },
  6866. {
  6867. "tfInputIndex": 1,
  6868. "dlParamName": "size",
  6869. "type": "number[]"
  6870. },
  6871. {
  6872. "tfParamName": "align_corners",
  6873. "dlParamName": "alignCorners",
  6874. "type": "bool"
  6875. },
  6876. {
  6877. "tfParamName": "T",
  6878. "dlParamName": "dtype",
  6879. "type": "dtype",
  6880. "notSupported": true
  6881. }
  6882. ]
  6883. }
  6884. ]
  6885. },{}],38:[function(require,module,exports){
  6886. module.exports=[
  6887. {
  6888. "tfOpName": "Equal",
  6889. "dlOpName": "equal",
  6890. "category": "logical",
  6891. "params": [
  6892. {
  6893. "tfInputIndex": 0,
  6894. "dlParamName": "a",
  6895. "type": "tensor"
  6896. },
  6897. {
  6898. "tfInputIndex": 1,
  6899. "dlParamName": "b",
  6900. "type": "tensor"
  6901. },
  6902. {
  6903. "tfParamName": "T",
  6904. "dlParamName": "dtype",
  6905. "type": "dtype",
  6906. "notSupported": true
  6907. }
  6908. ]
  6909. },
  6910. {
  6911. "tfOpName": "NotEqual",
  6912. "dlOpName": "notEqual",
  6913. "category": "logical",
  6914. "params": [
  6915. {
  6916. "tfInputIndex": 0,
  6917. "dlParamName": "a",
  6918. "type": "tensor"
  6919. },
  6920. {
  6921. "tfInputIndex": 1,
  6922. "dlParamName": "b",
  6923. "type": "tensor"
  6924. },
  6925. {
  6926. "tfParamName": "T",
  6927. "dlParamName": "dtype",
  6928. "type": "dtype",
  6929. "notSupported": true
  6930. }
  6931. ]
  6932. },
  6933. {
  6934. "tfOpName": "Greater",
  6935. "dlOpName": "greater",
  6936. "category": "logical",
  6937. "params": [
  6938. {
  6939. "tfInputIndex": 0,
  6940. "dlParamName": "a",
  6941. "type": "tensor"
  6942. },
  6943. {
  6944. "tfInputIndex": 1,
  6945. "dlParamName": "b",
  6946. "type": "tensor"
  6947. },
  6948. {
  6949. "tfParamName": "T",
  6950. "dlParamName": "dtype",
  6951. "type": "dtype",
  6952. "notSupported": true
  6953. }
  6954. ]
  6955. },
  6956. {
  6957. "tfOpName": "GreaterEqual",
  6958. "dlOpName": "greaterEqual",
  6959. "category": "logical",
  6960. "params": [
  6961. {
  6962. "tfInputIndex": 0,
  6963. "dlParamName": "a",
  6964. "type": "tensor"
  6965. },
  6966. {
  6967. "tfInputIndex": 1,
  6968. "dlParamName": "b",
  6969. "type": "tensor"
  6970. },
  6971. {
  6972. "tfParamName": "T",
  6973. "dlParamName": "dtype",
  6974. "type": "dtype",
  6975. "notSupported": true
  6976. }
  6977. ]
  6978. },
  6979. {
  6980. "tfOpName": "Less",
  6981. "dlOpName": "less",
  6982. "category": "logical",
  6983. "params": [
  6984. {
  6985. "tfInputIndex": 0,
  6986. "dlParamName": "a",
  6987. "type": "tensor"
  6988. },
  6989. {
  6990. "tfInputIndex": 1,
  6991. "dlParamName": "b",
  6992. "type": "tensor"
  6993. },
  6994. {
  6995. "tfParamName": "T",
  6996. "dlParamName": "dtype",
  6997. "type": "dtype",
  6998. "notSupported": true
  6999. }
  7000. ]
  7001. },
  7002. {
  7003. "tfOpName": "LessEqual",
  7004. "dlOpName": "lessEqual",
  7005. "category": "logical",
  7006. "params": [
  7007. {
  7008. "tfInputIndex": 0,
  7009. "dlParamName": "a",
  7010. "type": "tensor"
  7011. },
  7012. {
  7013. "tfInputIndex": 1,
  7014. "dlParamName": "b",
  7015. "type": "tensor"
  7016. },
  7017. {
  7018. "tfParamName": "T",
  7019. "dlParamName": "dtype",
  7020. "type": "dtype",
  7021. "notSupported": true
  7022. }
  7023. ]
  7024. },
  7025. {
  7026. "tfOpName": "LogicalAnd",
  7027. "dlOpName": "logicalAnd",
  7028. "category": "logical",
  7029. "params": [
  7030. {
  7031. "tfInputIndex": 0,
  7032. "dlParamName": "a",
  7033. "type": "tensor"
  7034. },
  7035. {
  7036. "tfInputIndex": 1,
  7037. "dlParamName": "b",
  7038. "type": "tensor"
  7039. },
  7040. {
  7041. "tfParamName": "T",
  7042. "dlParamName": "dtype",
  7043. "type": "dtype",
  7044. "notSupported": true
  7045. }
  7046. ]
  7047. },
  7048. {
  7049. "tfOpName": "LogicalNot",
  7050. "dlOpName": "logicalNot",
  7051. "category": "logical",
  7052. "params": [
  7053. {
  7054. "tfInputIndex": 0,
  7055. "dlParamName": "a",
  7056. "type": "tensor"
  7057. },
  7058. {
  7059. "tfParamName": "T",
  7060. "dlParamName": "dtype",
  7061. "type": "dtype",
  7062. "notSupported": true
  7063. }
  7064. ]
  7065. },
  7066. {
  7067. "tfOpName": "LogicalOr",
  7068. "dlOpName": "logicalOr",
  7069. "category": "logical",
  7070. "params": [
  7071. {
  7072. "tfInputIndex": 0,
  7073. "dlParamName": "a",
  7074. "type": "tensor"
  7075. },
  7076. {
  7077. "tfInputIndex": 1,
  7078. "dlParamName": "b",
  7079. "type": "tensor"
  7080. },
  7081. {
  7082. "tfParamName": "T",
  7083. "dlParamName": "dtype",
  7084. "type": "dtype",
  7085. "notSupported": true
  7086. }
  7087. ]
  7088. },
  7089. {
  7090. "tfOpName": "Select",
  7091. "dlOpName": "where",
  7092. "category": "logical",
  7093. "params": [
  7094. {
  7095. "tfInputIndex": 0,
  7096. "dlParamName": "condition",
  7097. "type": "tensor"
  7098. },
  7099. {
  7100. "tfInputIndex": 1,
  7101. "dlParamName": "a",
  7102. "type": "tensor"
  7103. },
  7104. {
  7105. "tfInputIndex": 2,
  7106. "dlParamName": "b",
  7107. "type": "tensor"
  7108. },
  7109. {
  7110. "tfParamName": "T",
  7111. "dlParamName": "dtype",
  7112. "type": "dtype",
  7113. "notSupported": true
  7114. }
  7115. ]
  7116. }
  7117. ]
  7118. },{}],39:[function(require,module,exports){
  7119. module.exports=[
  7120. {
  7121. "tfOpName": "MatMul",
  7122. "dlOpName": "matMul",
  7123. "category": "matrices",
  7124. "params": [
  7125. {
  7126. "tfInputIndex": 0,
  7127. "dlParamName": "a",
  7128. "type": "tensor"
  7129. },
  7130. {
  7131. "tfInputIndex": 1,
  7132. "dlParamName": "b",
  7133. "type": "tensor"
  7134. },
  7135. {
  7136. "tfParamName": "transpose_a",
  7137. "dlParamName": "transposeA",
  7138. "type": "bool",
  7139. "defaultValue": false
  7140. },
  7141. {
  7142. "tfParamName": "transpose_b",
  7143. "dlParamName": "transposeB",
  7144. "type": "bool",
  7145. "defaultValue": false
  7146. },
  7147. {
  7148. "tfParamName": "T",
  7149. "dlParamName": "dtype",
  7150. "type": "dtype",
  7151. "notSupported": true
  7152. }
  7153. ]
  7154. },
  7155. {
  7156. "tfOpName": "Transpose",
  7157. "dlOpName": "transpose",
  7158. "category": "matrices",
  7159. "params": [
  7160. {
  7161. "tfInputIndex": 0,
  7162. "dlParamName": "x",
  7163. "type": "tensor"
  7164. },
  7165. {
  7166. "tfParamName": "perm",
  7167. "dlParamName": "perm",
  7168. "type": "number[]"
  7169. },
  7170. {
  7171. "tfParamName": "T",
  7172. "dlParamName": "dtype",
  7173. "type": "dtype",
  7174. "notSupported": true
  7175. }
  7176. ]
  7177. }
  7178. ]
  7179. },{}],40:[function(require,module,exports){
  7180. module.exports=[
  7181. {
  7182. "tfOpName": "FusedBatchNorm",
  7183. "dlOpName": "batchNormalization",
  7184. "category": "normalization",
  7185. "params": [
  7186. {
  7187. "tfInputIndex": 0,
  7188. "dlParamName": "x",
  7189. "type": "tensor"
  7190. },
  7191. {
  7192. "tfInputIndex": 1,
  7193. "dlParamName": "scale",
  7194. "type": "tensor"
  7195. },
  7196. {
  7197. "tfInputIndex": 2,
  7198. "dlParamName": "offset",
  7199. "type": "tensor"
  7200. },
  7201. {
  7202. "tfInputIndex": 3,
  7203. "dlParamName": "mean",
  7204. "type": "tensor"
  7205. },
  7206. {
  7207. "tfInputIndex": 4,
  7208. "dlParamName": "variance",
  7209. "type": "tensor"
  7210. },
  7211. {
  7212. "tfParamName": "epsilon",
  7213. "dlParamName": "epsilon",
  7214. "type": "number",
  7215. "defaultValue": 0.001
  7216. },
  7217. {
  7218. "tfParamName": "data_format",
  7219. "dlParamName": "dataFormat",
  7220. "type": "string",
  7221. "notSupported": true
  7222. }
  7223. ]
  7224. },
  7225. {
  7226. "tfOpName": "FusedBatchNormV2",
  7227. "dlOpName": "batchNormalization",
  7228. "category": "normalization",
  7229. "params": [
  7230. {
  7231. "tfInputIndex": 0,
  7232. "dlParamName": "x",
  7233. "type": "tensor"
  7234. },
  7235. {
  7236. "tfInputIndex": 1,
  7237. "dlParamName": "scale",
  7238. "type": "tensor"
  7239. },
  7240. {
  7241. "tfInputIndex": 2,
  7242. "dlParamName": "offset",
  7243. "type": "tensor"
  7244. },
  7245. {
  7246. "tfInputIndex": 3,
  7247. "dlParamName": "mean",
  7248. "type": "tensor"
  7249. },
  7250. {
  7251. "tfInputIndex": 4,
  7252. "dlParamName": "variance",
  7253. "type": "tensor"
  7254. },
  7255. {
  7256. "tfParamName": "epsilon",
  7257. "dlParamName": "epsilon",
  7258. "type": "number",
  7259. "defaultValue": 0.001
  7260. },
  7261. {
  7262. "tfParamName": "data_format",
  7263. "dlParamName": "dataFormat",
  7264. "type": "string",
  7265. "notSupported": true
  7266. }
  7267. ]
  7268. },
  7269. {
  7270. "tfOpName": "LRN",
  7271. "dlOpName": "localResponseNormalization",
  7272. "category": "normalization",
  7273. "params": [
  7274. {
  7275. "tfInputIndex": 0,
  7276. "dlParamName": "x",
  7277. "type": "tensor"
  7278. },
  7279. {
  7280. "tfParamName": "depth_radius",
  7281. "dlParamName": "radius",
  7282. "type": "number",
  7283. "defaultValue": 5
  7284. },
  7285. {
  7286. "tfParamName": "bias",
  7287. "dlParamName": "bias",
  7288. "type": "number",
  7289. "defaultValue": 1.0
  7290. },
  7291. {
  7292. "tfParamName": "alpha",
  7293. "dlParamName": "alpha",
  7294. "type": "number",
  7295. "defaultValue": 1.0
  7296. },
  7297. {
  7298. "tfParamName": "beta",
  7299. "dlParamName": "beta",
  7300. "type": "number",
  7301. "defaultValue": 0.5
  7302. }
  7303. ]
  7304. }, {
  7305. "tfOpName": "Softmax",
  7306. "dlOpName": "softmax",
  7307. "category": "normalization",
  7308. "params": [
  7309. {
  7310. "tfInputIndex": 0,
  7311. "dlParamName": "x",
  7312. "type": "tensor"
  7313. }
  7314. ]
  7315. }
  7316. ]
  7317. },{}],41:[function(require,module,exports){
  7318. module.exports=[
  7319. {
  7320. "tfOpName": "Max",
  7321. "dlOpName": "max",
  7322. "category": "reduction",
  7323. "params": [
  7324. {
  7325. "tfInputIndex": 0,
  7326. "dlParamName": "x",
  7327. "type": "tensor"
  7328. },
  7329. {
  7330. "tfInputIndex": 1,
  7331. "dlParamName": "axis",
  7332. "type": "number[]"
  7333. },
  7334. {
  7335. "tfParamName": "keep_dims",
  7336. "dlParamName": "keepDims",
  7337. "type": "bool"
  7338. }
  7339. ]
  7340. },
  7341. {
  7342. "tfOpName": "Mean",
  7343. "dlOpName": "mean",
  7344. "category": "reduction",
  7345. "params": [
  7346. {
  7347. "tfInputIndex": 0,
  7348. "dlParamName": "x",
  7349. "type": "tensor"
  7350. },
  7351. {
  7352. "tfInputIndex": 1,
  7353. "dlParamName": "axis",
  7354. "type": "number[]"
  7355. },
  7356. {
  7357. "tfParamName": "keep_dims",
  7358. "dlParamName": "keepDims",
  7359. "type": "bool"
  7360. }
  7361. ]
  7362. },
  7363. {
  7364. "tfOpName": "Min",
  7365. "dlOpName": "min",
  7366. "category": "reduction",
  7367. "params": [
  7368. {
  7369. "tfInputIndex": 0,
  7370. "dlParamName": "x",
  7371. "type": "tensor"
  7372. },
  7373. {
  7374. "tfInputIndex": 1,
  7375. "dlParamName": "axis",
  7376. "type": "number[]"
  7377. },
  7378. {
  7379. "tfParamName": "keep_dims",
  7380. "dlParamName": "keepDims",
  7381. "type": "bool"
  7382. }
  7383. ]
  7384. },
  7385. {
  7386. "tfOpName": "Sum",
  7387. "dlOpName": "sum",
  7388. "category": "reduction",
  7389. "params": [
  7390. {
  7391. "tfInputIndex": 0,
  7392. "dlParamName": "x",
  7393. "type": "tensor"
  7394. },
  7395. {
  7396. "tfInputIndex": 1,
  7397. "dlParamName": "axis",
  7398. "type": "number[]"
  7399. },
  7400. {
  7401. "tfParamName": "keep_dims",
  7402. "dlParamName": "keepDims",
  7403. "type": "bool"
  7404. }
  7405. ]
  7406. },
  7407. {
  7408. "tfOpName": "ArgMax",
  7409. "dlOpName": "argMax",
  7410. "category": "reduction",
  7411. "params": [
  7412. {
  7413. "tfInputIndex": 0,
  7414. "dlParamName": "x",
  7415. "type": "tensor"
  7416. },
  7417. {
  7418. "tfInputIndex": 1,
  7419. "dlParamName": "axis",
  7420. "type": "number"
  7421. }
  7422. ]
  7423. },
  7424. {
  7425. "tfOpName": "ArgMin",
  7426. "dlOpName": "argMin",
  7427. "category": "reduction",
  7428. "params": [
  7429. {
  7430. "tfInputIndex": 0,
  7431. "dlParamName": "x",
  7432. "type": "tensor"
  7433. },
  7434. {
  7435. "tfInputIndex": 1,
  7436. "dlParamName": "axis",
  7437. "type": "number"
  7438. }
  7439. ]
  7440. }
  7441. ]
  7442. },{}],42:[function(require,module,exports){
  7443. module.exports=[
  7444. {
  7445. "tfOpName": "ConcatV2",
  7446. "dlOpName": "concat",
  7447. "category": "slice_join",
  7448. "params": [
  7449. {
  7450. "tfInputIndex": 0,
  7451. "tfInputParamLength": 1,
  7452. "dlParamName": "tensors",
  7453. "type": "tensors"
  7454. },
  7455. {
  7456. "tfInputIndex": -1,
  7457. "dlParamName": "axis",
  7458. "type": "number"
  7459. }
  7460. ]
  7461. },
  7462. {
  7463. "tfOpName": "Concat",
  7464. "dlOpName": "concat",
  7465. "category": "slice_join",
  7466. "params": [
  7467. {
  7468. "tfInputIndex": 1,
  7469. "tfInputParamLength": 1,
  7470. "dlParamName": "tensors",
  7471. "type": "tensors"
  7472. },
  7473. {
  7474. "tfInputIndex": 0,
  7475. "dlParamName": "axis",
  7476. "type": "number"
  7477. }
  7478. ]
  7479. },
  7480. {
  7481. "tfOpName": "GatherV2",
  7482. "dlOpName": "gather",
  7483. "category": "slice_join",
  7484. "params": [
  7485. {
  7486. "tfInputIndex": 0,
  7487. "dlParamName": "x",
  7488. "type": "tensor"
  7489. },
  7490. {
  7491. "tfInputIndex": 1,
  7492. "dlParamName": "indices",
  7493. "type": "tensor"
  7494. },
  7495. {
  7496. "tfParamName": "axis",
  7497. "dlParamName": "axis",
  7498. "type": "number",
  7499. "defaultValue": 0
  7500. }
  7501. ]
  7502. },
  7503. {
  7504. "tfOpName": "Gather",
  7505. "dlOpName": "gather",
  7506. "category": "slice_join",
  7507. "params": [
  7508. {
  7509. "tfInputIndex": 0,
  7510. "dlParamName": "x",
  7511. "type": "tensor"
  7512. },
  7513. {
  7514. "tfInputIndex": 1,
  7515. "dlParamName": "indices",
  7516. "type": "tensor"
  7517. },
  7518. {
  7519. "tfParamName": "axis",
  7520. "dlParamName": "axis",
  7521. "type": "number",
  7522. "defaultValue": 0
  7523. },
  7524. {
  7525. "tfParamName": "validate_indices",
  7526. "dlParamName": "validateIndices",
  7527. "type": "bool",
  7528. "notSupported": true
  7529. }
  7530. ]
  7531. },
  7532. {
  7533. "tfOpName": "Reverse",
  7534. "dlOpName": "reverse",
  7535. "category": "slice_join",
  7536. "params": [{
  7537. "tfInputIndex": 0,
  7538. "dlParamName": "x",
  7539. "type": "tensor"
  7540. },
  7541. {
  7542. "tfInputIndex": 1,
  7543. "dlParamName": "axis",
  7544. "type": "number"
  7545. }
  7546. ]
  7547. },
  7548. {
  7549. "tfOpName": "ReverseV2",
  7550. "dlOpName": "reverse",
  7551. "category": "slice_join",
  7552. "params": [{
  7553. "tfInputIndex": 0,
  7554. "dlParamName": "x",
  7555. "type": "tensor"
  7556. },
  7557. {
  7558. "tfInputIndex": 1,
  7559. "dlParamName": "axis",
  7560. "type": "number"
  7561. }
  7562. ]
  7563. },
  7564. {
  7565. "tfOpName": "Slice",
  7566. "dlOpName": "slice",
  7567. "category": "slice_join",
  7568. "params": [{
  7569. "tfInputIndex": 0,
  7570. "dlParamName": "x",
  7571. "type": "tensor"
  7572. },
  7573. {
  7574. "tfInputIndex": 1,
  7575. "dlParamName": "begin",
  7576. "type": "number[]"
  7577. },
  7578. {
  7579. "tfInputIndex": 2,
  7580. "dlParamName": "size",
  7581. "type": "number[]"
  7582. }
  7583. ]
  7584. },
  7585. {
  7586. "tfOpName": "StridedSlice",
  7587. "dlOpName": "stridedSlice",
  7588. "category": "slice_join",
  7589. "params": [{
  7590. "tfInputIndex": 0,
  7591. "dlParamName": "x",
  7592. "type": "tensor"
  7593. },
  7594. {
  7595. "tfInputIndex": 1,
  7596. "dlParamName": "begin",
  7597. "type": "number[]"
  7598. },
  7599. {
  7600. "tfInputIndex": 2,
  7601. "dlParamName": "end",
  7602. "type": "number[]"
  7603. },
  7604. {
  7605. "tfInputIndex": 3,
  7606. "dlParamName": "strides",
  7607. "type": "number[]"
  7608. },
  7609. {
  7610. "tfParamName": "begin_mask",
  7611. "dlParamName": "beginMask",
  7612. "type": "number",
  7613. "defaultValue": 0
  7614. },
  7615. {
  7616. "tfParamName": "end_mask",
  7617. "dlParamName": "endMask",
  7618. "type": "number",
  7619. "defaultValue": 0
  7620. }
  7621. ]
  7622. },
  7623. {
  7624. "tfOpName": "Pack",
  7625. "dlOpName": "stack",
  7626. "category": "slice_join",
  7627. "params": [{
  7628. "tfInputIndex": 0,
  7629. "tfInputParamLength": 0,
  7630. "dlParamName": "tensors",
  7631. "type": "tensors"
  7632. },
  7633. {
  7634. "tfParamName": "axis",
  7635. "dlParamName": "axis",
  7636. "type": "number",
  7637. "defaultValue": 0
  7638. }
  7639. ]
  7640. },
  7641. {
  7642. "tfOpName": "Unpack",
  7643. "dlOpName": "unstack",
  7644. "category": "slice_join",
  7645. "params": [{
  7646. "tfInputIndex": 0,
  7647. "tfInputParamLength": 0,
  7648. "dlParamName": "tensor",
  7649. "type": "tensor"
  7650. },
  7651. {
  7652. "tfParamName": "axis",
  7653. "dlParamName": "axis",
  7654. "type": "number",
  7655. "defaultValue": 0
  7656. },
  7657. {
  7658. "tfParamName": "num",
  7659. "dlParamName": "num",
  7660. "type": "number",
  7661. "defaultValue": 0,
  7662. "notSupported": true
  7663. }
  7664. ]
  7665. },
  7666. {
  7667. "tfOpName": "Tile",
  7668. "dlOpName": "tile",
  7669. "category": "slice_join",
  7670. "params": [{
  7671. "tfInputIndex": 0,
  7672. "dlParamName": "x",
  7673. "type": "tensor"
  7674. },
  7675. {
  7676. "tfInputIndex": 1,
  7677. "dlParamName": "reps",
  7678. "type": "number[]"
  7679. }
  7680. ]
  7681. },
  7682. {
  7683. "tfOpName": "Split",
  7684. "dlOpName": "split",
  7685. "category": "slice_join",
  7686. "params": [{
  7687. "tfInputIndex": 0,
  7688. "dlParamName": "axis",
  7689. "type": "number",
  7690. "defaultValue": 0
  7691. },
  7692. {
  7693. "tfInputIndex": 1,
  7694. "dlParamName": "x",
  7695. "type": "tensor"
  7696. },
  7697. {
  7698. "tfParamName": "num_split",
  7699. "dlParamName": "numOrSizeSplits",
  7700. "type": "number",
  7701. "defaultValue": 1
  7702. }
  7703. ]
  7704. }
  7705. ]
  7706. },{}],43:[function(require,module,exports){
  7707. module.exports=[
  7708. {
  7709. "tfOpName": "Cast",
  7710. "dlOpName": "cast",
  7711. "category": "transformation",
  7712. "params": [
  7713. {
  7714. "tfInputIndex": 0,
  7715. "dlParamName": "x",
  7716. "type": "tensor"
  7717. },
  7718. {
  7719. "tfParamName": "SrcT",
  7720. "dlParamName": "sdtype",
  7721. "type": "dtype",
  7722. "notSupported": true
  7723. },
  7724. {
  7725. "tfParamName": "DstT",
  7726. "dlParamName": "dtype",
  7727. "type": "dtype"
  7728. }
  7729. ]
  7730. },
  7731. {
  7732. "tfOpName": "ExpandDims",
  7733. "dlOpName": "expandDims",
  7734. "category": "transformation",
  7735. "params": [{
  7736. "tfInputIndex": 0,
  7737. "dlParamName": "x",
  7738. "type": "tensor"
  7739. },
  7740. {
  7741. "tfInputIndex": 1,
  7742. "tfParamNameDeprecated": "dim",
  7743. "dlParamName": "axis",
  7744. "type": "number"
  7745. }
  7746. ]
  7747. },
  7748. {
  7749. "tfOpName": "Pad",
  7750. "dlOpName": "pad",
  7751. "category": "transformation",
  7752. "params": [{
  7753. "tfInputIndex": 0,
  7754. "dlParamName": "x",
  7755. "type": "tensor"
  7756. },
  7757. {
  7758. "tfInputIndex": 1,
  7759. "dlParamName": "padding",
  7760. "type": "number[]"
  7761. },
  7762. {
  7763. "tfParamName": "constant_value",
  7764. "dlParamName": "constantValue",
  7765. "type": "number",
  7766. "defaultValue": 0
  7767. }
  7768. ]
  7769. },
  7770. {
  7771. "tfOpName": "PadV2",
  7772. "dlOpName": "pad",
  7773. "category": "transformation",
  7774. "params": [{
  7775. "tfInputIndex": 0,
  7776. "dlParamName": "x",
  7777. "type": "tensor"
  7778. },
  7779. {
  7780. "tfInputIndex": 1,
  7781. "dlParamName": "padding",
  7782. "type": "number[]"
  7783. },
  7784. {
  7785. "tfInputIndex": 2,
  7786. "dlParamName": "constantValue",
  7787. "type": "number",
  7788. "defaultValue": 0
  7789. }
  7790. ]
  7791. },
  7792. {
  7793. "tfOpName": "Reshape",
  7794. "dlOpName": "reshape",
  7795. "category": "transformation",
  7796. "params": [{
  7797. "tfInputIndex": 0,
  7798. "dlParamName": "x",
  7799. "type": "tensor"
  7800. },
  7801. {
  7802. "tfInputIndex": 1,
  7803. "dlParamName": "shape",
  7804. "type": "number[]"
  7805. }
  7806. ]
  7807. },
  7808. {
  7809. "tfOpName": "Squeeze",
  7810. "dlOpName": "squeeze",
  7811. "category": "transformation",
  7812. "params": [{
  7813. "tfInputIndex": 0,
  7814. "dlParamName": "x",
  7815. "type": "tensor"
  7816. },
  7817. {
  7818. "tfParamName": "axis",
  7819. "tfParamNameDeprecated": "squeeze_dims",
  7820. "dlParamName": "axis",
  7821. "type": "number[]"
  7822. }
  7823. ]
  7824. }
  7825. ]
  7826. },{}],44:[function(require,module,exports){
  7827. "use strict";
  7828. Object.defineProperty(exports, "__esModule", { value: true });
  7829. var arithmetic = require("./executors/arithmetic_executor");
  7830. var basicMath = require("./executors/basic_math_executor");
  7831. var control = require("./executors/control_executor");
  7832. var convolution = require("./executors/convolution_executor");
  7833. var creation = require("./executors/creation_executor");
  7834. var graph = require("./executors/graph_executor");
  7835. var image = require("./executors/image_executor");
  7836. var logical = require("./executors/logical_executor");
  7837. var matrices = require("./executors/matrices_executor");
  7838. var normalization = require("./executors/normalization_executor");
  7839. var reduction = require("./executors/reduction_executor");
  7840. var sliceJoin = require("./executors/slice_join_executor");
  7841. var transformation = require("./executors/transformation_executor");
  7842. function executeOp(node, tensorMap, context) {
  7843. switch (node.category) {
  7844. case 'arithmetic':
  7845. return arithmetic.executeOp(node, tensorMap, context);
  7846. case 'basic_math':
  7847. return basicMath.executeOp(node, tensorMap, context);
  7848. case 'control':
  7849. return control.executeOp(node, tensorMap, context);
  7850. case 'convolution':
  7851. return convolution.executeOp(node, tensorMap, context);
  7852. case 'creation':
  7853. return creation.executeOp(node, tensorMap, context);
  7854. case 'image':
  7855. return image.executeOp(node, tensorMap, context);
  7856. case 'graph':
  7857. return graph.executeOp(node, tensorMap, context);
  7858. case 'logical':
  7859. return logical.executeOp(node, tensorMap, context);
  7860. case 'matrices':
  7861. return matrices.executeOp(node, tensorMap, context);
  7862. case 'normalization':
  7863. return normalization.executeOp(node, tensorMap, context);
  7864. case 'reduction':
  7865. return reduction.executeOp(node, tensorMap, context);
  7866. case 'slice_join':
  7867. return sliceJoin.executeOp(node, tensorMap, context);
  7868. case 'transformation':
  7869. return transformation.executeOp(node, tensorMap, context);
  7870. default:
  7871. throw TypeError("Node type " + node.op + " is not implemented");
  7872. }
  7873. }
  7874. exports.executeOp = executeOp;
  7875. },{"./executors/arithmetic_executor":17,"./executors/basic_math_executor":18,"./executors/control_executor":19,"./executors/convolution_executor":20,"./executors/creation_executor":21,"./executors/graph_executor":22,"./executors/image_executor":23,"./executors/logical_executor":24,"./executors/matrices_executor":25,"./executors/normalization_executor":26,"./executors/reduction_executor":27,"./executors/slice_join_executor":28,"./executors/transformation_executor":29}],45:[function(require,module,exports){
  7876. "use strict";
  7877. Object.defineProperty(exports, "__esModule", { value: true });
  7878. var compiled_api_1 = require("../data/compiled_api");
  7879. var utils_1 = require("./executors/utils");
  7880. var arithmetic = require("./op_list/arithmetic.json");
  7881. var basicMath = require("./op_list/basic_math.json");
  7882. var control = require("./op_list/control.json");
  7883. var convolution = require("./op_list/convolution.json");
  7884. var creation = require("./op_list/creation.json");
  7885. var graph = require("./op_list/graph.json");
  7886. var image = require("./op_list/image.json");
  7887. var logical = require("./op_list/logical.json");
  7888. var matrices = require("./op_list/matrices.json");
  7889. var normalization = require("./op_list/normalization.json");
  7890. var reduction = require("./op_list/reduction.json");
  7891. var sliceJoin = require("./op_list/slice_join.json");
  7892. var transformation = require("./op_list/transformation.json");
  7893. var CONTROL_FLOW_OPS = ['Switch', 'Merge', 'Enter', 'Exit', 'NextIteration'];
  7894. var OperationMapper = (function () {
  7895. function OperationMapper() {
  7896. var ops = [
  7897. arithmetic, basicMath, control, convolution, creation, logical, image,
  7898. graph, matrices, normalization, reduction, sliceJoin, transformation
  7899. ];
  7900. var mappersJson = [].concat.apply([], ops.map(function (op) { return op.default ? op.default : op; }));
  7901. this.opMappers = mappersJson.reduce(function (map, mapper) {
  7902. map[mapper.tfOpName] = mapper;
  7903. return map;
  7904. }, {});
  7905. }
  7906. Object.defineProperty(OperationMapper, "Instance", {
  7907. get: function () {
  7908. return this._instance || (this._instance = new this());
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. OperationMapper.prototype.isControlFlow = function (node) {
  7914. return CONTROL_FLOW_OPS.some(function (op) { return op === node.op; });
  7915. };
  7916. OperationMapper.prototype.transformGraph = function (graph) {
  7917. var _this = this;
  7918. var tfNodes = graph.node;
  7919. var withControlFlow = false;
  7920. var placeholders = [];
  7921. var nodes = tfNodes.reduce(function (map, node) {
  7922. map[node.name] = _this.mapNode(node);
  7923. if (_this.isControlFlow(node))
  7924. withControlFlow = true;
  7925. if (node.op === 'Placeholder')
  7926. placeholders.push(map[node.name]);
  7927. return map;
  7928. }, {});
  7929. var inputs = [];
  7930. var outputs = [];
  7931. Object.keys(nodes).forEach(function (key) {
  7932. var node = nodes[key];
  7933. node.inputNames.forEach(function (name) {
  7934. var nodeName = utils_1.getNodeNameAndIndex(name)[0];
  7935. node.inputs.push(nodes[nodeName]);
  7936. nodes[nodeName].children.push(node);
  7937. });
  7938. if (node.inputs.length === 0)
  7939. inputs.push(node);
  7940. });
  7941. Object.keys(nodes).forEach(function (key) {
  7942. var node = nodes[key];
  7943. if (node.children.length === 0)
  7944. outputs.push(node);
  7945. });
  7946. return { nodes: nodes, inputs: inputs, outputs: outputs, placeholders: placeholders, withControlFlow: withControlFlow };
  7947. };
  7948. OperationMapper.prototype.mapNode = function (node) {
  7949. var _this = this;
  7950. var mapper = this.opMappers[node.op];
  7951. if (mapper === undefined) {
  7952. throw new Error('Tensorflow Op is not supported: ' + node.op);
  7953. }
  7954. var newNode = {
  7955. name: node.name,
  7956. op: mapper.dlOpName,
  7957. category: mapper.category,
  7958. inputNames: (node.input ||
  7959. []).map(function (input) { return input.startsWith('^') ? input.substr(1) : input; }),
  7960. inputs: [],
  7961. children: [],
  7962. params: {}
  7963. };
  7964. if (!!mapper.params) {
  7965. newNode.params = mapper.params.reduce(function (map, param) {
  7966. var inputIndex = param.tfInputIndex;
  7967. var inputParamLength = param.tfInputParamLength;
  7968. var type = param.type;
  7969. var value = undefined;
  7970. if (inputIndex === undefined) {
  7971. switch (param.type) {
  7972. case 'string':
  7973. value = _this.getStringParam(node.attr, param.tfParamName, param.defaultValue);
  7974. if (value === undefined && !!param.tfParamNameDeprecated) {
  7975. value = _this.getStringParam(node.attr, param.tfParamNameDeprecated, param.defaultValue);
  7976. }
  7977. break;
  7978. case 'number':
  7979. value = _this.getNumberParam(node.attr, param.tfParamName, param.defaultValue);
  7980. if (value === undefined && !!param.tfParamNameDeprecated) {
  7981. value = _this.getNumberParam(node.attr, param.tfParamNameDeprecated, param.defaultValue);
  7982. }
  7983. break;
  7984. case 'number[]':
  7985. value = _this.getNumericArrayParam(node.attr, param.tfParamName, param.defaultValue);
  7986. if (value === undefined && !!param.tfParamNameDeprecated) {
  7987. value = _this.getNumericArrayParam(node.attr, param.tfParamNameDeprecated, param.defaultValue);
  7988. }
  7989. break;
  7990. case 'bool':
  7991. value = _this.getBoolParam(node.attr, param.tfParamName, param.defaultValue);
  7992. if (value === undefined && !!param.tfParamNameDeprecated) {
  7993. value = _this.getBoolParam(node.attr, param.tfParamNameDeprecated, param.defaultValue);
  7994. }
  7995. break;
  7996. case 'shape':
  7997. value = _this.getTensorShapeParam(node.attr, param.tfParamName, param.defaultValue);
  7998. if (value === undefined && !!param.tfParamNameDeprecated) {
  7999. value = _this.getTensorShapeParam(node.attr, param.tfParamNameDeprecated, param.defaultValue);
  8000. }
  8001. break;
  8002. case 'dtype':
  8003. value = _this.getDtypeParam(node.attr, param.tfParamName, param.defaultValue);
  8004. if (value === undefined && !!param.tfParamNameDeprecated) {
  8005. value = _this.getDtypeParam(node.attr, param.tfParamNameDeprecated, param.defaultValue);
  8006. }
  8007. break;
  8008. case 'tensor':
  8009. case 'tensors':
  8010. break;
  8011. default:
  8012. throw new Error("Unsupported param type: " + param.type + " for op: " + node.op);
  8013. }
  8014. }
  8015. map[param.dlParamName] = { value: value, inputIndex: inputIndex, type: type, inputParamLength: inputParamLength };
  8016. return map;
  8017. }, {});
  8018. }
  8019. return newNode;
  8020. };
  8021. OperationMapper.prototype.getStringParam = function (attrs, name, def, keepCase) {
  8022. if (keepCase === void 0) { keepCase = false; }
  8023. var param = attrs[name];
  8024. if (param !== undefined) {
  8025. var value = String.fromCharCode.apply(null, param.s);
  8026. return keepCase ? value : value.toLowerCase();
  8027. }
  8028. return def;
  8029. };
  8030. OperationMapper.prototype.getBoolParam = function (attrs, name, def) {
  8031. var param = attrs[name];
  8032. return param ? param.b : def;
  8033. };
  8034. OperationMapper.prototype.getNumberParam = function (attrs, name, def) {
  8035. var param = attrs[name];
  8036. var value = (param ? ((param.f !== undefined) ? param.f : param.i) : def);
  8037. return (typeof value === 'number') ? value : value['toInt']();
  8038. };
  8039. OperationMapper.prototype.getDtypeParam = function (attrs, name, def) {
  8040. var param = attrs[name];
  8041. if (param && param.type) {
  8042. switch (param.type) {
  8043. case compiled_api_1.tensorflow.DataType.DT_FLOAT:
  8044. return 'float32';
  8045. case compiled_api_1.tensorflow.DataType.DT_INT32:
  8046. return 'int32';
  8047. case compiled_api_1.tensorflow.DataType.DT_BOOL:
  8048. return 'bool';
  8049. default:
  8050. return def;
  8051. }
  8052. }
  8053. return def;
  8054. };
  8055. OperationMapper.prototype.getTensorShapeParam = function (attrs, name, def) {
  8056. var param = attrs[name];
  8057. if (param && param.shape) {
  8058. return param.shape.dim.map(function (dim) { return dim.size; });
  8059. }
  8060. return def;
  8061. };
  8062. OperationMapper.prototype.getNumericArrayParam = function (attrs, name, def) {
  8063. var param = attrs[name];
  8064. if (param) {
  8065. return ((param.list.f && param.list.f.length ? param.list.f :
  8066. param.list.i))
  8067. .map(function (v) { return (typeof v === 'number') ? v : v['toInt'](); });
  8068. }
  8069. return def;
  8070. };
  8071. return OperationMapper;
  8072. }());
  8073. exports.OperationMapper = OperationMapper;
  8074. },{"../data/compiled_api":12,"./executors/utils":30,"./op_list/arithmetic.json":31,"./op_list/basic_math.json":32,"./op_list/control.json":33,"./op_list/convolution.json":34,"./op_list/creation.json":35,"./op_list/graph.json":36,"./op_list/image.json":37,"./op_list/logical.json":38,"./op_list/matrices.json":39,"./op_list/normalization.json":40,"./op_list/reduction.json":41,"./op_list/slice_join.json":42,"./op_list/transformation.json":43}],46:[function(require,module,exports){
  8075. "use strict";
  8076. Object.defineProperty(exports, "__esModule", { value: true });
  8077. var version = '0.4.3';
  8078. exports.version = version;
  8079. },{}],47:[function(require,module,exports){
  8080. "use strict";
  8081. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  8082. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  8083. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8084. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  8085. return c > 3 && r && Object.defineProperty(target, key, r), r;
  8086. };
  8087. Object.defineProperty(exports, "__esModule", { value: true });
  8088. var doc_1 = require("./doc");
  8089. var BrowserUtil = (function () {
  8090. function BrowserUtil() {
  8091. }
  8092. BrowserUtil.nextFrame = function () {
  8093. return new Promise(function (resolve) { return requestAnimationFrame(function () { return resolve(); }); });
  8094. };
  8095. __decorate([
  8096. doc_1.doc({ heading: 'Performance', subheading: 'Timing' })
  8097. ], BrowserUtil, "nextFrame", null);
  8098. return BrowserUtil;
  8099. }());
  8100. exports.BrowserUtil = BrowserUtil;
  8101. },{"./doc":49}],48:[function(require,module,exports){
  8102. "use strict";
  8103. Object.defineProperty(exports, "__esModule", { value: true });
  8104. function isMobile() {
  8105. var a = navigator.userAgent || navigator.vendor || window.opera;
  8106. return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i
  8107. .test(a) ||
  8108. /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i
  8109. .test(a.substr(0, 4));
  8110. }
  8111. exports.isMobile = isMobile;
  8112. },{}],49:[function(require,module,exports){
  8113. "use strict";
  8114. Object.defineProperty(exports, "__esModule", { value: true });
  8115. function doc(info) {
  8116. return function () {
  8117. var args = [];
  8118. for (var _i = 0; _i < arguments.length; _i++) {
  8119. args[_i] = arguments[_i];
  8120. }
  8121. };
  8122. }
  8123. exports.doc = doc;
  8124. },{}],50:[function(require,module,exports){
  8125. "use strict";
  8126. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  8127. return new (P || (P = Promise))(function (resolve, reject) {
  8128. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  8129. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  8130. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  8131. step((generator = generator.apply(thisArg, _arguments || [])).next());
  8132. });
  8133. };
  8134. var __generator = (this && this.__generator) || function (thisArg, body) {
  8135. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  8136. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  8137. function verb(n) { return function (v) { return step([n, v]); }; }
  8138. function step(op) {
  8139. if (f) throw new TypeError("Generator is already executing.");
  8140. while (_) try {
  8141. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  8142. if (y = 0, t) op = [0, t.value];
  8143. switch (op[0]) {
  8144. case 0: case 1: t = op; break;
  8145. case 4: _.label++; return { value: op[1], done: false };
  8146. case 5: _.label++; y = op[1]; op = [0]; continue;
  8147. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  8148. default:
  8149. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  8150. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  8151. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  8152. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  8153. if (t[2]) _.ops.pop();
  8154. _.trys.pop(); continue;
  8155. }
  8156. op = body.call(thisArg, _);
  8157. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  8158. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  8159. }
  8160. };
  8161. Object.defineProperty(exports, "__esModule", { value: true });
  8162. var environment_1 = require("./environment");
  8163. var globals_1 = require("./globals");
  8164. var ops = require("./ops/ops");
  8165. var profiler_1 = require("./profiler");
  8166. var tape_1 = require("./tape");
  8167. var tensor_1 = require("./tensor");
  8168. var util = require("./util");
  8169. var Engine = (function () {
  8170. function Engine(backend, safeMode) {
  8171. this.backend = backend;
  8172. this.safeMode = safeMode;
  8173. this.registeredVariables = {};
  8174. this.refCounter = new WeakMap();
  8175. this.nextTapeNodeId = 0;
  8176. this.numBytes = 0;
  8177. this.numTensors = 0;
  8178. this.numDataBuffers = 0;
  8179. this.gradientScopeCount = 0;
  8180. this.customGradientDepth = 0;
  8181. this.keepTensors = new Set();
  8182. this.activeScope = { track: [] };
  8183. this.scopeStack = [this.activeScope];
  8184. this.profiler = new profiler_1.Profiler(backend);
  8185. }
  8186. Engine.prototype.runKernel = function (forwardFunc, inputs, backwardsFunc) {
  8187. var _this = this;
  8188. var result;
  8189. var saved = [];
  8190. var saveFunc = function (x) {
  8191. saved.push(x);
  8192. return x;
  8193. };
  8194. var scopeName = this.activeScope.name;
  8195. this.customGradientDepth++;
  8196. if (!environment_1.ENV.get('DEBUG')) {
  8197. result = forwardFunc(this.backend, saveFunc);
  8198. }
  8199. else {
  8200. result = this.profiler.profileKernel(scopeName, function () { return forwardFunc(_this.backend, saveFunc); });
  8201. }
  8202. this.customGradientDepth--;
  8203. if (this.shouldRecord()) {
  8204. var tapeNode = {
  8205. id: this.nextTapeNodeId++,
  8206. name: scopeName,
  8207. inputs: inputs,
  8208. output: result,
  8209. };
  8210. if (backwardsFunc != null) {
  8211. tapeNode.gradient = function (dy) { return backwardsFunc(dy, saved); };
  8212. }
  8213. this.activeTape.push(tapeNode);
  8214. }
  8215. return result;
  8216. };
  8217. Engine.prototype.registerTensor = function (a) {
  8218. var refCount = this.refCounter.has(a.dataId) ? this.refCounter.get(a.dataId) : 0;
  8219. this.numTensors++;
  8220. if (refCount === 0) {
  8221. this.numDataBuffers++;
  8222. this.numBytes +=
  8223. util.sizeFromShape(a.shape) * util.bytesPerElement(a.dtype);
  8224. this.backend.register(a.dataId, a.shape, a.dtype);
  8225. }
  8226. this.refCounter.set(a.dataId, refCount + 1);
  8227. if (!(a instanceof tensor_1.Variable)) {
  8228. this.track(a);
  8229. }
  8230. };
  8231. Engine.prototype.registerVariable = function (v) {
  8232. if (this.registeredVariables[v.name] != null) {
  8233. throw new Error("Variable with name " + v.name + " was already registered");
  8234. }
  8235. this.registeredVariables[v.name] = v;
  8236. };
  8237. Engine.prototype.disposeTensor = function (a) {
  8238. if (!this.refCounter.has(a.dataId)) {
  8239. return;
  8240. }
  8241. if (this.keepTensors.has(a.id)) {
  8242. this.keepTensors.delete(a.id);
  8243. }
  8244. this.numTensors--;
  8245. var refCount = this.refCounter.get(a.dataId);
  8246. if (refCount <= 1) {
  8247. this.refCounter.delete(a.dataId);
  8248. this.backend.disposeData(a.dataId);
  8249. this.numDataBuffers--;
  8250. this.numBytes -=
  8251. util.sizeFromShape(a.shape) * util.bytesPerElement(a.dtype);
  8252. }
  8253. else {
  8254. this.refCounter.set(a.dataId, refCount - 1);
  8255. }
  8256. };
  8257. Engine.prototype.disposeVariables = function () {
  8258. for (var varName in this.registeredVariables) {
  8259. var v = this.registeredVariables[varName];
  8260. this.disposeTensor(v);
  8261. delete this.registeredVariables[varName];
  8262. }
  8263. };
  8264. Engine.prototype.memory = function () {
  8265. var info = this.backend.memory();
  8266. info.numTensors = this.numTensors;
  8267. info.numDataBuffers = this.numDataBuffers;
  8268. info.numBytes = this.numBytes;
  8269. return info;
  8270. };
  8271. Engine.prototype.shouldRecord = function () {
  8272. return this.activeTape != null && this.customGradientDepth === 0;
  8273. };
  8274. Engine.prototype.addTapeNode = function (inputs, result, gradientsFunc) {
  8275. var inputsMap = {};
  8276. inputs.forEach(function (input, idx) {
  8277. inputsMap[idx] = input;
  8278. });
  8279. var gradient = function (dy) {
  8280. var res = gradientsFunc(dy);
  8281. var resMap = {};
  8282. res.forEach(function (r, idx) {
  8283. resMap[idx] = function () { return r; };
  8284. });
  8285. return resMap;
  8286. };
  8287. var tapeNode = {
  8288. id: this.nextTapeNodeId++,
  8289. name: this.activeScope.name,
  8290. inputs: inputsMap,
  8291. output: result,
  8292. gradient: gradient
  8293. };
  8294. this.activeTape.push(tapeNode);
  8295. };
  8296. Engine.prototype.keep = function (result) {
  8297. if (this.scopeStack.length === 1 && environment_1.ENV.engine.safeMode) {
  8298. throw new Error('Safe mode is ON. Enclose all tensor operations inside tf.tidy(): ' +
  8299. 'tf.tidy(() => {...}) to avoid memory leaks.');
  8300. }
  8301. this.keepTensors.add(result.id);
  8302. return result;
  8303. };
  8304. Engine.prototype.startScope = function (name, gradientsMode) {
  8305. if (gradientsMode === void 0) { gradientsMode = false; }
  8306. if (gradientsMode && this.gradientScopeCount === 0) {
  8307. this.activeTape = [];
  8308. }
  8309. if (gradientsMode) {
  8310. this.gradientScopeCount++;
  8311. }
  8312. var scopeInfo = { track: [] };
  8313. if (name) {
  8314. scopeInfo.name = name;
  8315. }
  8316. this.scopeStack.push(scopeInfo);
  8317. this.activeScope = scopeInfo;
  8318. };
  8319. Engine.prototype.endScope = function (result, gradientsMode) {
  8320. var _this = this;
  8321. if (gradientsMode === void 0) { gradientsMode = false; }
  8322. if (gradientsMode) {
  8323. this.gradientScopeCount--;
  8324. if (this.gradientScopeCount === 0) {
  8325. this.activeTape = null;
  8326. }
  8327. }
  8328. var tensorsToKeep = new Set(this.keepTensors);
  8329. var tensorsToTrackInParent = util.getTensorsInContainer(result);
  8330. tensorsToTrackInParent.forEach(function (tensor) { return tensorsToKeep.add(tensor.id); });
  8331. for (var i = 0; i < this.activeScope.track.length; i++) {
  8332. var tensor = this.activeScope.track[i];
  8333. if (tensorsToKeep.has(tensor.id)) {
  8334. continue;
  8335. }
  8336. if (this.activeTape != null) {
  8337. tensorsToTrackInParent.push(tensor);
  8338. }
  8339. else {
  8340. tensor.dispose();
  8341. }
  8342. }
  8343. var oldScope = this.scopeStack.pop();
  8344. this.activeScope = this.scopeStack.length === 0 ?
  8345. { track: [] } :
  8346. this.scopeStack[this.scopeStack.length - 1];
  8347. tensorsToTrackInParent.forEach(function (tensor) {
  8348. if (!_this.keepTensors.has(tensor.id) &&
  8349. util.isTensorInList(tensor, oldScope.track)) {
  8350. _this.track(tensor);
  8351. }
  8352. });
  8353. };
  8354. Engine.prototype.gradients = function (f, xs, dy, allowNoGradients) {
  8355. var _this = this;
  8356. if (allowNoGradients === void 0) { allowNoGradients = false; }
  8357. util.assert(xs.length > 0, 'gradients() received an empty list of xs.');
  8358. return globals_1.tidy('gradients', function () {
  8359. var y = f();
  8360. util.assert(y instanceof tensor_1.Tensor, 'The result y returned by f() must be a tensor.');
  8361. var filteredTape = tape_1.getFilteredNodesXToY(_this.activeTape, xs, y);
  8362. if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {
  8363. throw new Error('Cannot compute gradient of y=f(x) with respect to x. Make sure ' +
  8364. 'that the f you passed encloses all operations that lead from x ' +
  8365. 'to y.');
  8366. }
  8367. var accumulatedGradientMap = {};
  8368. accumulatedGradientMap[y.id] = (dy == null) ? ops.ones(y.shape) : dy;
  8369. tape_1.backpropagateGradients(accumulatedGradientMap, filteredTape);
  8370. var grads = xs.map(function (x) { return accumulatedGradientMap[x.id]; });
  8371. return { value: y, grads: grads };
  8372. }, true);
  8373. };
  8374. Engine.prototype.customGrad = function (f) {
  8375. var _this = this;
  8376. util.assert(util.isFunction(f), 'The f passed in customGrad(f) must be a function.');
  8377. return function () {
  8378. var inputs = [];
  8379. for (var _i = 0; _i < arguments.length; _i++) {
  8380. inputs[_i] = arguments[_i];
  8381. }
  8382. util.assert(inputs.every(function (t) { return t instanceof tensor_1.Tensor; }), 'The args passed in customGrad(f)(x1, x2,...) must all be tensors');
  8383. _this.customGradientDepth++;
  8384. var gradientsFunc;
  8385. var gradientsMode = true;
  8386. var result = globals_1.tidy(f.name, function () {
  8387. var _a = f.apply(void 0, inputs), value = _a.value, gradFunc = _a.gradFunc;
  8388. util.assert(value instanceof tensor_1.Tensor, 'The function f passed in customGrad(f) must return an object ' +
  8389. 'where `obj.value` is a tensor');
  8390. util.assert(util.isFunction(gradFunc), 'The function f passed in customGrad(f) must return an object ' +
  8391. 'where `obj.gradFunc` is a function.');
  8392. gradientsFunc = gradFunc;
  8393. return value;
  8394. }, gradientsMode);
  8395. _this.customGradientDepth--;
  8396. if (_this.shouldRecord()) {
  8397. var gradFunc = function (dy) {
  8398. var res = gradientsFunc(dy);
  8399. var grads = Array.isArray(res) ? res : [res];
  8400. util.assert(grads.length === inputs.length, 'The function f passed in customGrad(f) must return an object ' +
  8401. 'where `obj.gradFunc` is a function that returns the same ' +
  8402. 'number of tensors as inputs passed to f(...).');
  8403. util.assert(grads.every(function (t) { return t instanceof tensor_1.Tensor; }), 'The function f passed in customGrad(f) must return an object ' +
  8404. 'where `obj.gradFunc` is a function that returns a list of ' +
  8405. 'only tensors.');
  8406. return grads;
  8407. };
  8408. _this.addTapeNode(inputs, result, gradFunc);
  8409. }
  8410. return result;
  8411. };
  8412. };
  8413. Engine.prototype.write = function (dataId, values) {
  8414. this.backend.write(dataId, values);
  8415. };
  8416. Engine.prototype.readSync = function (dataId) {
  8417. return this.backend.readSync(dataId);
  8418. };
  8419. Engine.prototype.read = function (dataId) {
  8420. return this.backend.read(dataId);
  8421. };
  8422. Engine.prototype.fromPixels = function (pixels, numChannels) {
  8423. return this.backend.fromPixels(pixels, numChannels);
  8424. };
  8425. Engine.prototype.time = function (query) {
  8426. return __awaiter(this, void 0, void 0, function () {
  8427. var start, timingInfo;
  8428. return __generator(this, function (_a) {
  8429. switch (_a.label) {
  8430. case 0:
  8431. start = performance.now();
  8432. return [4, this.backend.time(query)];
  8433. case 1:
  8434. timingInfo = _a.sent();
  8435. timingInfo.wallMs = performance.now() - start;
  8436. return [2, timingInfo];
  8437. }
  8438. });
  8439. });
  8440. };
  8441. Engine.prototype.track = function (result) {
  8442. if (this.scopeStack.length === 1 && this.safeMode) {
  8443. throw new Error('Safe mode is ON. Enclose all tensor operations inside tf.tidy(): ' +
  8444. 'tf.tidy(() => {op();...}); to avoid memory leaks.');
  8445. }
  8446. this.activeScope.track.push(result);
  8447. return result;
  8448. };
  8449. return Engine;
  8450. }());
  8451. exports.Engine = Engine;
  8452. },{"./environment":51,"./globals":52,"./ops/ops":129,"./profiler":155,"./tape":157,"./tensor":158,"./util":164}],51:[function(require,module,exports){
  8453. (function (process,global){
  8454. "use strict";
  8455. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  8456. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  8457. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8458. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  8459. return c > 3 && r && Object.defineProperty(target, key, r), r;
  8460. };
  8461. Object.defineProperty(exports, "__esModule", { value: true });
  8462. var device_util = require("./device_util");
  8463. var doc_1 = require("./doc");
  8464. var engine_1 = require("./engine");
  8465. var util = require("./util");
  8466. var Type;
  8467. (function (Type) {
  8468. Type[Type["NUMBER"] = 0] = "NUMBER";
  8469. Type[Type["BOOLEAN"] = 1] = "BOOLEAN";
  8470. Type[Type["STRING"] = 2] = "STRING";
  8471. })(Type = exports.Type || (exports.Type = {}));
  8472. exports.URL_PROPERTIES = [
  8473. { name: 'DEBUG', type: Type.BOOLEAN }, { name: 'IS_BROWSER', type: Type.BOOLEAN },
  8474. { name: 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION', type: Type.NUMBER },
  8475. { name: 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE', type: Type.BOOLEAN },
  8476. { name: 'WEBGL_VERSION', type: Type.NUMBER },
  8477. { name: 'WEBGL_RENDER_FLOAT32_ENABLED', type: Type.BOOLEAN },
  8478. { name: 'WEBGL_DOWNLOAD_FLOAT_ENABLED', type: Type.BOOLEAN }, {
  8479. name: 'WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED',
  8480. type: Type.BOOLEAN
  8481. },
  8482. { name: 'BACKEND', type: Type.STRING }
  8483. ];
  8484. var TEST_EPSILON_FLOAT32_ENABLED = 1e-3;
  8485. var TEST_EPSILON_FLOAT32_DISABLED = 1e-1;
  8486. function hasExtension(gl, extensionName) {
  8487. var ext = gl.getExtension(extensionName);
  8488. return ext != null;
  8489. }
  8490. function getWebGLRenderingContext(webGLVersion) {
  8491. if (webGLVersion === 0 || !exports.ENV.get('IS_BROWSER')) {
  8492. throw new Error('Cannot get WebGL rendering context, WebGL is disabled.');
  8493. }
  8494. var tempCanvas = document.createElement('canvas');
  8495. if (webGLVersion === 1) {
  8496. return (tempCanvas.getContext('webgl') ||
  8497. tempCanvas.getContext('experimental-webgl'));
  8498. }
  8499. return tempCanvas.getContext('webgl2');
  8500. }
  8501. function loseContext(gl) {
  8502. if (gl != null) {
  8503. var loseContextExtension = gl.getExtension('WEBGL_lose_context');
  8504. if (loseContextExtension == null) {
  8505. throw new Error('Extension WEBGL_lose_context not supported on this browser.');
  8506. }
  8507. loseContextExtension.loseContext();
  8508. }
  8509. }
  8510. function isWebGLVersionEnabled(webGLVersion) {
  8511. var gl;
  8512. try {
  8513. gl = getWebGLRenderingContext(webGLVersion);
  8514. }
  8515. catch (e) {
  8516. return false;
  8517. }
  8518. if (gl != null) {
  8519. loseContext(gl);
  8520. return true;
  8521. }
  8522. return false;
  8523. }
  8524. function getWebGLDisjointQueryTimerVersion(webGLVersion) {
  8525. if (webGLVersion === 0) {
  8526. return 0;
  8527. }
  8528. var queryTimerVersion;
  8529. var gl = getWebGLRenderingContext(webGLVersion);
  8530. if (hasExtension(gl, 'EXT_disjoint_timer_query_webgl2') &&
  8531. webGLVersion === 2) {
  8532. queryTimerVersion = 2;
  8533. }
  8534. else if (hasExtension(gl, 'EXT_disjoint_timer_query')) {
  8535. queryTimerVersion = 1;
  8536. }
  8537. else {
  8538. queryTimerVersion = 0;
  8539. }
  8540. if (gl != null) {
  8541. loseContext(gl);
  8542. }
  8543. return queryTimerVersion;
  8544. }
  8545. function createFloatTextureAndBindToFramebuffer(gl, webGLVersion) {
  8546. var frameBuffer = gl.createFramebuffer();
  8547. var texture = gl.createTexture();
  8548. gl.bindTexture(gl.TEXTURE_2D, texture);
  8549. var internalFormat = webGLVersion === 2 ? gl.RGBA32F : gl.RGBA;
  8550. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 1, 1, 0, gl.RGBA, gl.FLOAT, null);
  8551. gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
  8552. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8553. }
  8554. function isRenderToFloatTextureEnabled(webGLVersion) {
  8555. if (webGLVersion === 0) {
  8556. return false;
  8557. }
  8558. var gl = getWebGLRenderingContext(webGLVersion);
  8559. if (webGLVersion === 1) {
  8560. if (!hasExtension(gl, 'OES_texture_float')) {
  8561. return false;
  8562. }
  8563. }
  8564. else {
  8565. if (!hasExtension(gl, 'EXT_color_buffer_float')) {
  8566. return false;
  8567. }
  8568. }
  8569. createFloatTextureAndBindToFramebuffer(gl, webGLVersion);
  8570. var isFrameBufferComplete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
  8571. loseContext(gl);
  8572. return isFrameBufferComplete;
  8573. }
  8574. function isDownloadFloatTextureEnabled(webGLVersion) {
  8575. if (webGLVersion === 0) {
  8576. return false;
  8577. }
  8578. var gl = getWebGLRenderingContext(webGLVersion);
  8579. if (webGLVersion === 1) {
  8580. if (!hasExtension(gl, 'OES_texture_float')) {
  8581. return false;
  8582. }
  8583. }
  8584. else {
  8585. if (!hasExtension(gl, 'EXT_color_buffer_float')) {
  8586. return false;
  8587. }
  8588. }
  8589. createFloatTextureAndBindToFramebuffer(gl, webGLVersion);
  8590. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.FLOAT, new Float32Array(4));
  8591. var readPixelsNoError = gl.getError() === gl.NO_ERROR;
  8592. loseContext(gl);
  8593. return readPixelsNoError;
  8594. }
  8595. function isWebGLGetBufferSubDataAsyncExtensionEnabled(webGLVersion) {
  8596. if (webGLVersion > 0) {
  8597. return false;
  8598. }
  8599. if (webGLVersion !== 2) {
  8600. return false;
  8601. }
  8602. var gl = getWebGLRenderingContext(webGLVersion);
  8603. var isEnabled = hasExtension(gl, 'WEBGL_get_buffer_sub_data_async');
  8604. loseContext(gl);
  8605. return isEnabled;
  8606. }
  8607. function isChrome() {
  8608. return navigator != null && navigator.userAgent != null &&
  8609. /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
  8610. }
  8611. var Environment = (function () {
  8612. function Environment(features) {
  8613. this.features = {};
  8614. this.registry = {};
  8615. if (features != null) {
  8616. this.features = features;
  8617. }
  8618. if (this.get('DEBUG')) {
  8619. console.warn('Debugging mode is ON. The output of every math call will ' +
  8620. 'be downloaded to CPU and checked for NaNs. ' +
  8621. 'This significantly impacts performance.');
  8622. }
  8623. }
  8624. Environment.setBackend = function (backendType, safeMode) {
  8625. if (safeMode === void 0) { safeMode = false; }
  8626. if (!(backendType in exports.ENV.registry)) {
  8627. throw new Error("Backend type '" + backendType + "' not found in registry");
  8628. }
  8629. exports.ENV.initBackend(backendType, safeMode);
  8630. };
  8631. Environment.getBackend = function () {
  8632. exports.ENV.initDefaultBackend();
  8633. return exports.ENV.currentBackend;
  8634. };
  8635. Environment.disposeVariables = function () {
  8636. exports.ENV.engine.disposeVariables();
  8637. };
  8638. Environment.memory = function () {
  8639. return exports.ENV.engine.memory();
  8640. };
  8641. Environment.prototype.get = function (feature) {
  8642. if (feature in this.features) {
  8643. return this.features[feature];
  8644. }
  8645. this.features[feature] = this.evaluateFeature(feature);
  8646. return this.features[feature];
  8647. };
  8648. Environment.prototype.getFeatures = function () {
  8649. return this.features;
  8650. };
  8651. Environment.prototype.set = function (feature, value) {
  8652. this.features[feature] = value;
  8653. };
  8654. Environment.prototype.getBestBackendType = function () {
  8655. var _this = this;
  8656. if (Object.keys(this.registry).length === 0) {
  8657. throw new Error('No backend found in registry.');
  8658. }
  8659. var sortedBackends = Object.keys(this.registry)
  8660. .map(function (name) {
  8661. return { name: name, entry: _this.registry[name] };
  8662. })
  8663. .sort(function (a, b) {
  8664. return b.entry.priority - a.entry.priority;
  8665. });
  8666. return sortedBackends[0].name;
  8667. };
  8668. Environment.prototype.evaluateFeature = function (feature) {
  8669. if (feature === 'DEBUG') {
  8670. return false;
  8671. }
  8672. else if (feature === 'IS_BROWSER') {
  8673. return typeof window !== 'undefined';
  8674. }
  8675. else if (feature === 'IS_NODE') {
  8676. return (typeof process !== 'undefined') &&
  8677. (typeof process.versions.node !== 'undefined');
  8678. }
  8679. else if (feature === 'IS_CHROME') {
  8680. return isChrome();
  8681. }
  8682. else if (feature === 'BACKEND') {
  8683. return this.getBestBackendType();
  8684. }
  8685. else if (feature === 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') {
  8686. var webGLVersion = this.get('WEBGL_VERSION');
  8687. if (webGLVersion === 0) {
  8688. return 0;
  8689. }
  8690. return getWebGLDisjointQueryTimerVersion(webGLVersion);
  8691. }
  8692. else if (feature === 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') {
  8693. return this.get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0 &&
  8694. !device_util.isMobile();
  8695. }
  8696. else if (feature === 'WEBGL_VERSION') {
  8697. if (isWebGLVersionEnabled(2)) {
  8698. return 2;
  8699. }
  8700. else if (isWebGLVersionEnabled(1)) {
  8701. return 1;
  8702. }
  8703. return 0;
  8704. }
  8705. else if (feature === 'WEBGL_RENDER_FLOAT32_ENABLED') {
  8706. return isRenderToFloatTextureEnabled(this.get('WEBGL_VERSION'));
  8707. }
  8708. else if (feature === 'WEBGL_DOWNLOAD_FLOAT_ENABLED') {
  8709. return isDownloadFloatTextureEnabled(this.get('WEBGL_VERSION'));
  8710. }
  8711. else if (feature === 'WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED') {
  8712. return isWebGLGetBufferSubDataAsyncExtensionEnabled(this.get('WEBGL_VERSION'));
  8713. }
  8714. else if (feature === 'TEST_EPSILON') {
  8715. if (this.get('WEBGL_RENDER_FLOAT32_ENABLED')) {
  8716. return TEST_EPSILON_FLOAT32_ENABLED;
  8717. }
  8718. return TEST_EPSILON_FLOAT32_DISABLED;
  8719. }
  8720. throw new Error("Unknown feature " + feature + ".");
  8721. };
  8722. Environment.prototype.setFeatures = function (features) {
  8723. this.features = features;
  8724. };
  8725. Environment.prototype.reset = function () {
  8726. this.features = getFeaturesFromURL();
  8727. if (this.globalEngine != null) {
  8728. this.globalEngine = null;
  8729. }
  8730. };
  8731. Environment.prototype.initBackend = function (backendType, safeMode) {
  8732. if (safeMode === void 0) { safeMode = false; }
  8733. this.currentBackend = backendType;
  8734. var backend = exports.ENV.findBackend(backendType);
  8735. this.globalEngine = new engine_1.Engine(backend, safeMode);
  8736. };
  8737. Environment.prototype.findBackend = function (name) {
  8738. if (!(name in this.registry)) {
  8739. return null;
  8740. }
  8741. return this.registry[name].backend;
  8742. };
  8743. Environment.prototype.registerBackend = function (name, factory, priority) {
  8744. if (priority === void 0) { priority = 1; }
  8745. if (name in this.registry) {
  8746. console.warn(name + " backend was already registered");
  8747. }
  8748. try {
  8749. var backend = factory();
  8750. this.registry[name] = { backend: backend, priority: priority };
  8751. return true;
  8752. }
  8753. catch (err) {
  8754. console.warn("Registration of backend " + name + " failed");
  8755. console.warn(err.stack || err.message);
  8756. return false;
  8757. }
  8758. };
  8759. Environment.prototype.removeBackend = function (name) {
  8760. if (!(name in this.registry)) {
  8761. throw new Error(name + " backend not found in registry");
  8762. }
  8763. this.registry[name].backend.dispose();
  8764. delete this.registry[name];
  8765. };
  8766. Object.defineProperty(Environment.prototype, "engine", {
  8767. get: function () {
  8768. this.initDefaultBackend();
  8769. return this.globalEngine;
  8770. },
  8771. enumerable: true,
  8772. configurable: true
  8773. });
  8774. Environment.prototype.initDefaultBackend = function () {
  8775. if (this.globalEngine == null) {
  8776. this.initBackend(exports.ENV.get('BACKEND'), false);
  8777. }
  8778. };
  8779. __decorate([
  8780. doc_1.doc({ heading: 'Environment' })
  8781. ], Environment, "setBackend", null);
  8782. __decorate([
  8783. doc_1.doc({ heading: 'Environment' })
  8784. ], Environment, "getBackend", null);
  8785. __decorate([
  8786. doc_1.doc({ heading: 'Environment' })
  8787. ], Environment, "disposeVariables", null);
  8788. __decorate([
  8789. doc_1.doc({ heading: 'Performance', subheading: 'Memory' })
  8790. ], Environment, "memory", null);
  8791. return Environment;
  8792. }());
  8793. exports.Environment = Environment;
  8794. var TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';
  8795. function getFeaturesFromURL() {
  8796. var features = {};
  8797. if (typeof window === 'undefined' || typeof window.location === 'undefined') {
  8798. return features;
  8799. }
  8800. var urlParams = util.getQueryParams(window.location.search);
  8801. if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {
  8802. var urlFlags_1 = {};
  8803. var keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');
  8804. keyValues.forEach(function (keyValue) {
  8805. var _a = keyValue.split(':'), key = _a[0], value = _a[1];
  8806. urlFlags_1[key] = value;
  8807. });
  8808. exports.URL_PROPERTIES.forEach(function (urlProperty) {
  8809. if (urlProperty.name in urlFlags_1) {
  8810. console.log("Setting feature override from URL " + urlProperty.name + ": " +
  8811. ("" + urlFlags_1[urlProperty.name]));
  8812. if (urlProperty.type === Type.NUMBER) {
  8813. features[urlProperty.name] = +urlFlags_1[urlProperty.name];
  8814. }
  8815. else if (urlProperty.type === Type.BOOLEAN) {
  8816. features[urlProperty.name] = urlFlags_1[urlProperty.name] === 'true';
  8817. }
  8818. else if (urlProperty.type === Type.STRING) {
  8819. features[urlProperty.name] = urlFlags_1[urlProperty.name];
  8820. }
  8821. else {
  8822. console.warn("Unknown URL param: " + urlProperty.name + ".");
  8823. }
  8824. }
  8825. });
  8826. }
  8827. return features;
  8828. }
  8829. function getGlobalNamespace() {
  8830. var ns;
  8831. if (typeof (window) !== 'undefined') {
  8832. ns = window;
  8833. }
  8834. else if (typeof (global) !== 'undefined') {
  8835. ns = global;
  8836. }
  8837. else {
  8838. throw new Error('Could not find a global object');
  8839. }
  8840. return ns;
  8841. }
  8842. function getOrMakeEnvironment() {
  8843. var ns = getGlobalNamespace();
  8844. ns.ENV = ns.ENV || new Environment(getFeaturesFromURL());
  8845. return ns.ENV;
  8846. }
  8847. exports.ENV = getOrMakeEnvironment();
  8848. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8849. },{"./device_util":48,"./doc":49,"./engine":50,"./util":164,"_process":215}],52:[function(require,module,exports){
  8850. "use strict";
  8851. Object.defineProperty(exports, "__esModule", { value: true });
  8852. var gradients_1 = require("./gradients");
  8853. var tracking_1 = require("./tracking");
  8854. exports.tidy = tracking_1.Tracking.tidy;
  8855. exports.keep = tracking_1.Tracking.keep;
  8856. exports.dispose = tracking_1.Tracking.dispose;
  8857. exports.time = tracking_1.Tracking.time;
  8858. exports.grad = gradients_1.Gradients.grad;
  8859. exports.valueAndGrad = gradients_1.Gradients.valueAndGrad;
  8860. exports.grads = gradients_1.Gradients.grads;
  8861. exports.valueAndGrads = gradients_1.Gradients.valueAndGrads;
  8862. exports.variableGrads = gradients_1.Gradients.variableGrads;
  8863. exports.customGrad = gradients_1.Gradients.customGrad;
  8864. },{"./gradients":53,"./tracking":161}],53:[function(require,module,exports){
  8865. "use strict";
  8866. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  8867. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  8868. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8869. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  8870. return c > 3 && r && Object.defineProperty(target, key, r), r;
  8871. };
  8872. Object.defineProperty(exports, "__esModule", { value: true });
  8873. var doc_1 = require("./doc");
  8874. var environment_1 = require("./environment");
  8875. var globals_1 = require("./globals");
  8876. var tensor_1 = require("./tensor");
  8877. var util = require("./util");
  8878. var Gradients = (function () {
  8879. function Gradients() {
  8880. }
  8881. Gradients.gradScope = function (nameOrScopeFn, scopeFn) {
  8882. return globals_1.tidy(nameOrScopeFn, scopeFn, true);
  8883. };
  8884. Gradients.grad = function (f) {
  8885. util.assert(util.isFunction(f), 'The f passed in grad(f) must be a function');
  8886. return function (x, dy) {
  8887. util.assert(x instanceof tensor_1.Tensor, 'The x passed in grad(f)(x) must be a tensor');
  8888. util.assert(dy == null || dy instanceof tensor_1.Tensor, 'The dy passed in grad(f)(x, dy) must be a tensor');
  8889. return globals_1.tidy(function () {
  8890. var _a = environment_1.ENV.engine.gradients(function () { return f(x); }, [x], dy), value = _a.value, grads = _a.grads;
  8891. if (dy != null) {
  8892. util.assertShapesMatch(value.shape, dy.shape, 'The shape of dy passed in grad(f)(x, dy) must match the shape ' +
  8893. 'returned by f(x)');
  8894. }
  8895. checkGrads(grads);
  8896. return grads[0];
  8897. });
  8898. };
  8899. };
  8900. Gradients.grads = function (f) {
  8901. util.assert(util.isFunction(f), 'The f passed in grads(f) must be a function');
  8902. return function (args, dy) {
  8903. util.assert(Array.isArray(args) && args.every(function (arg) { return arg instanceof tensor_1.Tensor; }), 'The args passed in grads(f)(args) must be an array of tensors');
  8904. util.assert(dy == null || dy instanceof tensor_1.Tensor, 'The dy passed in grads(f)(args, dy) must be a tensor');
  8905. return globals_1.tidy(function () {
  8906. var _a = environment_1.ENV.engine.gradients(function () { return f.apply(void 0, args); }, args, dy), value = _a.value, grads = _a.grads;
  8907. if (dy != null) {
  8908. util.assertShapesMatch(value.shape, dy.shape, 'The shape of dy passed in grads(f)([x1,...], dy) must ' +
  8909. 'match the shape returned by f([x1,...])');
  8910. }
  8911. checkGrads(grads);
  8912. return grads;
  8913. });
  8914. };
  8915. };
  8916. Gradients.valueAndGrad = function (f) {
  8917. util.assert(util.isFunction(f), 'The f passed in valueAndGrad(f) must be a function');
  8918. return function (x, dy) {
  8919. util.assert(x instanceof tensor_1.Tensor, 'The x passed in valueAndGrad(f)(x) must be a tensor');
  8920. util.assert(dy == null || dy instanceof tensor_1.Tensor, 'The dy passed in valueAndGrad(f)(x, dy) must be a tensor');
  8921. var _a = environment_1.ENV.engine.gradients(function () { return f(x); }, [x], dy), grads = _a.grads, value = _a.value;
  8922. checkGrads(grads);
  8923. return { grad: grads[0], value: value };
  8924. };
  8925. };
  8926. Gradients.valueAndGrads = function (f) {
  8927. util.assert(util.isFunction(f), 'The f passed in valueAndGrads(f) must be a function');
  8928. return function (args, dy) {
  8929. util.assert(Array.isArray(args) && args.every(function (arg) { return arg instanceof tensor_1.Tensor; }), 'The args passed in valueAndGrads(f)(args) must be array of tensors');
  8930. util.assert(dy == null || dy instanceof tensor_1.Tensor, 'The dy passed in valueAndGrads(f)(args, dy) must be a tensor');
  8931. var res = environment_1.ENV.engine.gradients(function () { return f.apply(void 0, args); }, args, dy);
  8932. if (dy != null) {
  8933. util.assertShapesMatch(res.value.shape, dy.shape, 'The shape of dy passed in valueAndGrads(f)([x1,...], dy) must ' +
  8934. 'match the shape returned by f([x1,...])');
  8935. }
  8936. checkGrads(res.grads);
  8937. return res;
  8938. };
  8939. };
  8940. Gradients.variableGrads = function (f, varList) {
  8941. util.assert(util.isFunction(f), 'The f passed in variableGrads(f) must be a function');
  8942. util.assert(varList == null ||
  8943. Array.isArray(varList) && varList.every(function (v) { return v instanceof tensor_1.Variable; }), 'The varList passed in variableGrads(f, varList) must be an array ' +
  8944. 'of variables');
  8945. if (varList == null) {
  8946. varList = [];
  8947. for (var varName in environment_1.ENV.engine.registeredVariables) {
  8948. varList.push(environment_1.ENV.engine.registeredVariables[varName]);
  8949. }
  8950. }
  8951. var originalVarCount = varList.length;
  8952. varList = varList.filter(function (variable) { return variable.trainable; });
  8953. util.assert(varList.length > 0, "variableGrads() expects at least one of the input variables to be " +
  8954. ("trainable, but none of the " + originalVarCount + " variables is ") +
  8955. "trainable.");
  8956. var allowNoGradients = true;
  8957. var _a = environment_1.ENV.engine.gradients(f, varList, null, allowNoGradients), value = _a.value, grads = _a.grads;
  8958. util.assert(grads.some(function (g) { return g != null; }), 'Cannot find a connection between any variable and the result of the ' +
  8959. 'loss function y=f(x). Please make sure the operations that use ' +
  8960. 'variables are inside the function f passed to minimize().');
  8961. util.assert(value.rank === 0, "The f passed in variableGrads(f) must return a scalar, but it " +
  8962. ("returned a rank-" + value.rank + " tensor"));
  8963. var namedGrads = {};
  8964. varList.forEach(function (v, i) {
  8965. if (grads[i] != null) {
  8966. namedGrads[v.name] = grads[i];
  8967. }
  8968. });
  8969. return { value: value, grads: namedGrads };
  8970. };
  8971. Gradients.customGrad = function (f) {
  8972. return environment_1.ENV.engine.customGrad(f);
  8973. };
  8974. __decorate([
  8975. doc_1.doc({ heading: 'Training', subheading: 'Gradients' })
  8976. ], Gradients, "grad", null);
  8977. __decorate([
  8978. doc_1.doc({ heading: 'Training', subheading: 'Gradients' })
  8979. ], Gradients, "grads", null);
  8980. __decorate([
  8981. doc_1.doc({ heading: 'Training', subheading: 'Gradients' })
  8982. ], Gradients, "valueAndGrad", null);
  8983. __decorate([
  8984. doc_1.doc({ heading: 'Training', subheading: 'Gradients' })
  8985. ], Gradients, "valueAndGrads", null);
  8986. __decorate([
  8987. doc_1.doc({ heading: 'Training', subheading: 'Gradients' })
  8988. ], Gradients, "variableGrads", null);
  8989. __decorate([
  8990. doc_1.doc({ heading: 'Training', subheading: 'Gradients' })
  8991. ], Gradients, "customGrad", null);
  8992. return Gradients;
  8993. }());
  8994. exports.Gradients = Gradients;
  8995. function checkGrads(grads) {
  8996. var numNullGradients = grads.filter(function (g) { return g == null; }).length;
  8997. if (numNullGradients > 0) {
  8998. throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.");
  8999. }
  9000. }
  9001. },{"./doc":49,"./environment":51,"./globals":52,"./tensor":158,"./util":164}],54:[function(require,module,exports){
  9002. "use strict";
  9003. function __export(m) {
  9004. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  9005. }
  9006. Object.defineProperty(exports, "__esModule", { value: true });
  9007. require("./kernels/backend_webgl");
  9008. require("./kernels/backend_cpu");
  9009. var browser_util_1 = require("./browser_util");
  9010. var environment = require("./environment");
  9011. exports.environment = environment;
  9012. var environment_1 = require("./environment");
  9013. var io = require("./io/io");
  9014. exports.io = io;
  9015. var serialization = require("./serialization");
  9016. exports.serialization = serialization;
  9017. var test_util = require("./test_util");
  9018. exports.test_util = test_util;
  9019. var util = require("./util");
  9020. exports.util = util;
  9021. var version_1 = require("./version");
  9022. exports.version_core = version_1.version;
  9023. var webgl = require("./webgl");
  9024. exports.webgl = webgl;
  9025. var adadelta_optimizer_1 = require("./optimizers/adadelta_optimizer");
  9026. exports.AdadeltaOptimizer = adadelta_optimizer_1.AdadeltaOptimizer;
  9027. var adagrad_optimizer_1 = require("./optimizers/adagrad_optimizer");
  9028. exports.AdagradOptimizer = adagrad_optimizer_1.AdagradOptimizer;
  9029. var adam_optimizer_1 = require("./optimizers/adam_optimizer");
  9030. exports.AdamOptimizer = adam_optimizer_1.AdamOptimizer;
  9031. var adamax_optimizer_1 = require("./optimizers/adamax_optimizer");
  9032. exports.AdamaxOptimizer = adamax_optimizer_1.AdamaxOptimizer;
  9033. var momentum_optimizer_1 = require("./optimizers/momentum_optimizer");
  9034. exports.MomentumOptimizer = momentum_optimizer_1.MomentumOptimizer;
  9035. var optimizer_1 = require("./optimizers/optimizer");
  9036. exports.Optimizer = optimizer_1.Optimizer;
  9037. var rmsprop_optimizer_1 = require("./optimizers/rmsprop_optimizer");
  9038. exports.RMSPropOptimizer = rmsprop_optimizer_1.RMSPropOptimizer;
  9039. var sgd_optimizer_1 = require("./optimizers/sgd_optimizer");
  9040. exports.SGDOptimizer = sgd_optimizer_1.SGDOptimizer;
  9041. var tensor_1 = require("./tensor");
  9042. exports.Tensor = tensor_1.Tensor;
  9043. exports.TensorBuffer = tensor_1.TensorBuffer;
  9044. exports.variable = tensor_1.variable;
  9045. exports.Variable = tensor_1.Variable;
  9046. var types_1 = require("./types");
  9047. exports.Rank = types_1.Rank;
  9048. __export(require("./ops/ops"));
  9049. var loss_ops_1 = require("./ops/loss_ops");
  9050. exports.Reduction = loss_ops_1.Reduction;
  9051. __export(require("./train"));
  9052. __export(require("./globals"));
  9053. var environment_2 = require("./environment");
  9054. exports.ENV = environment_2.ENV;
  9055. exports.Environment = environment_2.Environment;
  9056. exports.setBackend = environment_1.Environment.setBackend;
  9057. exports.getBackend = environment_1.Environment.getBackend;
  9058. exports.disposeVariables = environment_1.Environment.disposeVariables;
  9059. exports.memory = environment_1.Environment.memory;
  9060. var doc_1 = require("./doc");
  9061. exports.doc = doc_1.doc;
  9062. exports.nextFrame = browser_util_1.BrowserUtil.nextFrame;
  9063. },{"./browser_util":47,"./doc":49,"./environment":51,"./globals":52,"./io/io":58,"./kernels/backend_cpu":65,"./kernels/backend_webgl":67,"./ops/loss_ops":122,"./ops/ops":129,"./optimizers/adadelta_optimizer":145,"./optimizers/adagrad_optimizer":146,"./optimizers/adam_optimizer":147,"./optimizers/adamax_optimizer":148,"./optimizers/momentum_optimizer":149,"./optimizers/optimizer":150,"./optimizers/rmsprop_optimizer":153,"./optimizers/sgd_optimizer":154,"./serialization":156,"./tensor":158,"./test_util":160,"./train":162,"./types":163,"./util":164,"./version":165,"./webgl":166}],55:[function(require,module,exports){
  9064. "use strict";
  9065. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9066. return new (P || (P = Promise))(function (resolve, reject) {
  9067. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9068. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9069. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  9070. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9071. });
  9072. };
  9073. var __generator = (this && this.__generator) || function (thisArg, body) {
  9074. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  9075. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  9076. function verb(n) { return function (v) { return step([n, v]); }; }
  9077. function step(op) {
  9078. if (f) throw new TypeError("Generator is already executing.");
  9079. while (_) try {
  9080. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  9081. if (y = 0, t) op = [0, t.value];
  9082. switch (op[0]) {
  9083. case 0: case 1: t = op; break;
  9084. case 4: _.label++; return { value: op[1], done: false };
  9085. case 5: _.label++; y = op[1]; op = [0]; continue;
  9086. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  9087. default:
  9088. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  9089. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  9090. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  9091. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  9092. if (t[2]) _.ops.pop();
  9093. _.trys.pop(); continue;
  9094. }
  9095. op = body.call(thisArg, _);
  9096. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  9097. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  9098. }
  9099. };
  9100. Object.defineProperty(exports, "__esModule", { value: true });
  9101. var environment_1 = require("../environment");
  9102. var io_utils_1 = require("./io_utils");
  9103. var router_registry_1 = require("./router_registry");
  9104. var DEFAULT_FILE_NAME_PREFIX = 'model';
  9105. var DEFAULT_JSON_EXTENSION_NAME = '.json';
  9106. var DEFAULT_WEIGHT_DATA_EXTENSION_NAME = '.weights.bin';
  9107. var BrowserDownloads = (function () {
  9108. function BrowserDownloads(fileNamePrefix) {
  9109. if (!environment_1.ENV.get('IS_BROWSER')) {
  9110. throw new Error('triggerDownloads() cannot proceed because the current environment ' +
  9111. 'is not a browser.');
  9112. }
  9113. if (fileNamePrefix.startsWith(BrowserDownloads.URL_SCHEME)) {
  9114. fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length);
  9115. }
  9116. if (fileNamePrefix == null || fileNamePrefix.length === 0) {
  9117. fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;
  9118. }
  9119. this.modelTopologyFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;
  9120. this.weightDataFileName =
  9121. fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;
  9122. }
  9123. BrowserDownloads.prototype.save = function (modelArtifacts) {
  9124. return __awaiter(this, void 0, void 0, function () {
  9125. var weightsURL, weightsManifest, modelTopologyAndWeightManifest, modelTopologyAndWeightManifestURL, jsonAnchor, weightDataAnchor;
  9126. return __generator(this, function (_a) {
  9127. weightsURL = window.URL.createObjectURL(new Blob([modelArtifacts.weightData], { type: 'application/octet-stream' }));
  9128. if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
  9129. throw new Error('DownloadTrigger.save() does not support saving model topology ' +
  9130. 'in binary formats yet.');
  9131. }
  9132. else {
  9133. weightsManifest = [{
  9134. paths: ['./' + this.weightDataFileName],
  9135. weights: modelArtifacts.weightSpecs
  9136. }];
  9137. modelTopologyAndWeightManifest = {
  9138. modelTopology: modelArtifacts.modelTopology,
  9139. weightsManifest: weightsManifest
  9140. };
  9141. modelTopologyAndWeightManifestURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: 'application/json' }));
  9142. jsonAnchor = this.jsonAnchor == null ? document.createElement('a') :
  9143. this.jsonAnchor;
  9144. jsonAnchor.download = this.modelTopologyFileName;
  9145. jsonAnchor.href = modelTopologyAndWeightManifestURL;
  9146. jsonAnchor.click();
  9147. if (modelArtifacts.weightData != null) {
  9148. weightDataAnchor = this.weightDataAnchor == null ?
  9149. document.createElement('a') :
  9150. this.weightDataAnchor;
  9151. weightDataAnchor.download = this.weightDataFileName;
  9152. weightDataAnchor.href = weightsURL;
  9153. weightDataAnchor.click();
  9154. }
  9155. return [2, { modelArtifactsInfo: io_utils_1.getModelArtifactsInfoForJSON(modelArtifacts) }];
  9156. }
  9157. return [2];
  9158. });
  9159. });
  9160. };
  9161. BrowserDownloads.URL_SCHEME = 'downloads://';
  9162. return BrowserDownloads;
  9163. }());
  9164. exports.BrowserDownloads = BrowserDownloads;
  9165. var BrowserFiles = (function () {
  9166. function BrowserFiles(files) {
  9167. if (files == null || files.length < 1) {
  9168. throw new Error("When calling browserFiles, at least 1 file is required, " +
  9169. ("but received " + files));
  9170. }
  9171. this.files = files;
  9172. }
  9173. BrowserFiles.prototype.load = function () {
  9174. return __awaiter(this, void 0, void 0, function () {
  9175. var _this = this;
  9176. var jsonFile, weightFiles;
  9177. return __generator(this, function (_a) {
  9178. jsonFile = this.files[0];
  9179. weightFiles = this.files.slice(1);
  9180. return [2, new Promise(function (resolve, reject) {
  9181. var jsonReader = new FileReader();
  9182. jsonReader.onload = function (event) {
  9183. var modelJSON = JSON.parse(event.target.result);
  9184. var modelTopology = modelJSON.modelTopology;
  9185. if (modelTopology == null) {
  9186. reject(new Error("modelTopology field is missing from file " + jsonFile.name));
  9187. return;
  9188. }
  9189. if (weightFiles.length === 0) {
  9190. resolve({ modelTopology: modelTopology });
  9191. }
  9192. var weightsManifest = modelJSON.weightsManifest;
  9193. if (weightsManifest == null) {
  9194. reject(new Error("weightManifest field is missing from file " + jsonFile.name));
  9195. return;
  9196. }
  9197. var pathToFile;
  9198. try {
  9199. pathToFile =
  9200. _this.checkManifestAndWeightFiles(weightsManifest, weightFiles);
  9201. }
  9202. catch (err) {
  9203. reject(err);
  9204. return;
  9205. }
  9206. var weightSpecs = [];
  9207. var paths = [];
  9208. var perFileBuffers = [];
  9209. weightsManifest.forEach(function (weightsGroup) {
  9210. weightsGroup.paths.forEach(function (path) {
  9211. paths.push(path);
  9212. perFileBuffers.push(null);
  9213. });
  9214. weightSpecs.push.apply(weightSpecs, weightsGroup.weights);
  9215. });
  9216. weightsManifest.forEach(function (weightsGroup) {
  9217. weightsGroup.paths.forEach(function (path) {
  9218. var weightFileReader = new FileReader();
  9219. weightFileReader.onload = function (event) {
  9220. var weightData = event.target.result;
  9221. var index = paths.indexOf(path);
  9222. perFileBuffers[index] = weightData;
  9223. if (perFileBuffers.indexOf(null) === -1) {
  9224. resolve({
  9225. modelTopology: modelTopology,
  9226. weightSpecs: weightSpecs,
  9227. weightData: io_utils_1.concatenateArrayBuffers(perFileBuffers),
  9228. });
  9229. }
  9230. };
  9231. weightFileReader.onerror = function (error) {
  9232. reject("Failed to weights data from file of path '" + path + "'.");
  9233. return;
  9234. };
  9235. weightFileReader.readAsArrayBuffer(pathToFile[path]);
  9236. });
  9237. });
  9238. };
  9239. jsonReader.onerror = function (error) {
  9240. reject("Failed to read model topology and weights manifest JSON " +
  9241. ("from file '" + jsonFile.name + "'. BrowserFiles supports loading ") +
  9242. "Keras-style tf.Model artifacts only.");
  9243. return;
  9244. };
  9245. jsonReader.readAsText(jsonFile);
  9246. })];
  9247. });
  9248. });
  9249. };
  9250. BrowserFiles.prototype.checkManifestAndWeightFiles = function (manifest, files) {
  9251. var basenames = [];
  9252. var fileNames = files.map(function (file) { return io_utils_1.basename(file.name); });
  9253. var pathToFile = {};
  9254. for (var _i = 0, manifest_1 = manifest; _i < manifest_1.length; _i++) {
  9255. var group = manifest_1[_i];
  9256. group.paths.forEach(function (path) {
  9257. var pathBasename = io_utils_1.basename(path);
  9258. if (basenames.indexOf(pathBasename) !== -1) {
  9259. throw new Error("Duplicate file basename found in weights manifest: " +
  9260. ("'" + pathBasename + "'"));
  9261. }
  9262. basenames.push(pathBasename);
  9263. if (fileNames.indexOf(pathBasename) === -1) {
  9264. throw new Error("Weight file with basename '" + pathBasename + "' is not provided.");
  9265. }
  9266. else {
  9267. pathToFile[path] = files[fileNames.indexOf(pathBasename)];
  9268. }
  9269. });
  9270. }
  9271. if (basenames.length !== files.length) {
  9272. throw new Error("Mismatch in the number of files in weights manifest " +
  9273. ("(" + basenames.length + ") and the number of weight files provided ") +
  9274. ("(" + files.length + ")."));
  9275. }
  9276. return pathToFile;
  9277. };
  9278. return BrowserFiles;
  9279. }());
  9280. exports.browserDownloadsRouter = function (url) {
  9281. if (!environment_1.ENV.get('IS_BROWSER')) {
  9282. return null;
  9283. }
  9284. else {
  9285. if (url.startsWith(BrowserDownloads.URL_SCHEME)) {
  9286. return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));
  9287. }
  9288. else {
  9289. return null;
  9290. }
  9291. }
  9292. };
  9293. router_registry_1.IORouterRegistry.registerSaveRouter(exports.browserDownloadsRouter);
  9294. function browserDownloads(fileNamePrefix) {
  9295. if (fileNamePrefix === void 0) { fileNamePrefix = 'model'; }
  9296. return new BrowserDownloads(fileNamePrefix);
  9297. }
  9298. exports.browserDownloads = browserDownloads;
  9299. function browserFiles(files) {
  9300. return new BrowserFiles(files);
  9301. }
  9302. exports.browserFiles = browserFiles;
  9303. },{"../environment":51,"./io_utils":59,"./router_registry":62}],56:[function(require,module,exports){
  9304. "use strict";
  9305. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9306. return new (P || (P = Promise))(function (resolve, reject) {
  9307. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9308. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9309. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  9310. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9311. });
  9312. };
  9313. var __generator = (this && this.__generator) || function (thisArg, body) {
  9314. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  9315. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  9316. function verb(n) { return function (v) { return step([n, v]); }; }
  9317. function step(op) {
  9318. if (f) throw new TypeError("Generator is already executing.");
  9319. while (_) try {
  9320. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  9321. if (y = 0, t) op = [0, t.value];
  9322. switch (op[0]) {
  9323. case 0: case 1: t = op; break;
  9324. case 4: _.label++; return { value: op[1], done: false };
  9325. case 5: _.label++; y = op[1]; op = [0]; continue;
  9326. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  9327. default:
  9328. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  9329. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  9330. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  9331. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  9332. if (t[2]) _.ops.pop();
  9333. _.trys.pop(); continue;
  9334. }
  9335. op = body.call(thisArg, _);
  9336. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  9337. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  9338. }
  9339. };
  9340. Object.defineProperty(exports, "__esModule", { value: true });
  9341. var environment_1 = require("../environment");
  9342. var util_1 = require("../util");
  9343. var io_utils_1 = require("./io_utils");
  9344. var router_registry_1 = require("./router_registry");
  9345. var weights_loader_1 = require("./weights_loader");
  9346. var BrowserHTTPRequest = (function () {
  9347. function BrowserHTTPRequest(path, requestInit) {
  9348. this.DEFAULT_METHOD = 'POST';
  9349. if (!environment_1.ENV.get('IS_BROWSER')) {
  9350. throw new Error('browserHTTPRequest is not supported outside the web browser.');
  9351. }
  9352. util_1.assert(path != null && path.length > 0, 'URL path for browserHTTPRequest must not be null, undefined or ' +
  9353. 'empty.');
  9354. this.path = path;
  9355. if (requestInit != null && requestInit.body != null) {
  9356. throw new Error('requestInit is expected to have no pre-existing body, but has one.');
  9357. }
  9358. this.requestInit = requestInit || {};
  9359. }
  9360. BrowserHTTPRequest.prototype.save = function (modelArtifacts) {
  9361. return __awaiter(this, void 0, void 0, function () {
  9362. var init, weightsManifest, modelTopologyAndWeightManifest, response;
  9363. return __generator(this, function (_a) {
  9364. switch (_a.label) {
  9365. case 0:
  9366. if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
  9367. throw new Error('BrowserHTTPRequest.save() does not support saving model topology ' +
  9368. 'in binary formats yet.');
  9369. }
  9370. init = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);
  9371. init.body = new FormData();
  9372. weightsManifest = [{
  9373. paths: ['./model.weights.bin'],
  9374. weights: modelArtifacts.weightSpecs,
  9375. }];
  9376. modelTopologyAndWeightManifest = {
  9377. modelTopology: modelArtifacts.modelTopology,
  9378. weightsManifest: weightsManifest
  9379. };
  9380. init.body.append('model.json', new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: 'application/json' }), 'model.json');
  9381. if (modelArtifacts.weightData != null) {
  9382. init.body.append('model.weights.bin', new Blob([modelArtifacts.weightData], { type: 'application/octet-stream' }), 'model.weights.bin');
  9383. }
  9384. return [4, fetch(this.path, init)];
  9385. case 1:
  9386. response = _a.sent();
  9387. if (response.status === 200) {
  9388. return [2, {
  9389. modelArtifactsInfo: io_utils_1.getModelArtifactsInfoForJSON(modelArtifacts),
  9390. responses: [response],
  9391. }];
  9392. }
  9393. else {
  9394. throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status " +
  9395. (response.status + "."));
  9396. }
  9397. return [2];
  9398. }
  9399. });
  9400. });
  9401. };
  9402. BrowserHTTPRequest.prototype.load = function () {
  9403. return __awaiter(this, void 0, void 0, function () {
  9404. var modelConfigRequest, modelConfig, modelTopology, weightsManifest, weightSpecs, weightData, weightsManifest_1, _i, weightsManifest_2, entry, pathPrefix_1, fetchURLs_1, _a;
  9405. return __generator(this, function (_b) {
  9406. switch (_b.label) {
  9407. case 0: return [4, fetch(this.path, this.requestInit)];
  9408. case 1:
  9409. modelConfigRequest = _b.sent();
  9410. return [4, modelConfigRequest.json()];
  9411. case 2:
  9412. modelConfig = _b.sent();
  9413. modelTopology = modelConfig['modelTopology'];
  9414. weightsManifest = modelConfig['weightsManifest'];
  9415. if (modelTopology == null && weightsManifest == null) {
  9416. throw new Error("The JSON from HTTP path " + this.path + " contains neither model " +
  9417. "topology or manifest for weights.");
  9418. }
  9419. if (!(weightsManifest != null)) return [3, 4];
  9420. weightsManifest_1 = modelConfig['weightsManifest'];
  9421. weightSpecs = [];
  9422. for (_i = 0, weightsManifest_2 = weightsManifest_1; _i < weightsManifest_2.length; _i++) {
  9423. entry = weightsManifest_2[_i];
  9424. weightSpecs.push.apply(weightSpecs, entry.weights);
  9425. }
  9426. pathPrefix_1 = this.path.substring(0, this.path.lastIndexOf('/'));
  9427. if (!pathPrefix_1.endsWith('/')) {
  9428. pathPrefix_1 = pathPrefix_1 + '/';
  9429. }
  9430. fetchURLs_1 = [];
  9431. weightsManifest_1.forEach(function (weightsGroup) {
  9432. weightsGroup.paths.forEach(function (path) {
  9433. fetchURLs_1.push(pathPrefix_1 + path);
  9434. });
  9435. });
  9436. _a = io_utils_1.concatenateArrayBuffers;
  9437. return [4, weights_loader_1.loadWeightsAsArrayBuffer(fetchURLs_1, this.requestInit)];
  9438. case 3:
  9439. weightData = _a.apply(void 0, [_b.sent()]);
  9440. _b.label = 4;
  9441. case 4: return [2, { modelTopology: modelTopology, weightSpecs: weightSpecs, weightData: weightData }];
  9442. }
  9443. });
  9444. });
  9445. };
  9446. BrowserHTTPRequest.URL_SCHEMES = ['http://', 'https://'];
  9447. return BrowserHTTPRequest;
  9448. }());
  9449. exports.BrowserHTTPRequest = BrowserHTTPRequest;
  9450. exports.httpRequestRouter = function (url) {
  9451. if (!environment_1.ENV.get('IS_BROWSER')) {
  9452. return null;
  9453. }
  9454. else {
  9455. for (var _i = 0, _a = BrowserHTTPRequest.URL_SCHEMES; _i < _a.length; _i++) {
  9456. var scheme = _a[_i];
  9457. if (url.startsWith(scheme)) {
  9458. return browserHTTPRequest(url);
  9459. }
  9460. }
  9461. return null;
  9462. }
  9463. };
  9464. router_registry_1.IORouterRegistry.registerSaveRouter(exports.httpRequestRouter);
  9465. router_registry_1.IORouterRegistry.registerLoadRouter(exports.httpRequestRouter);
  9466. function browserHTTPRequest(path, requestInit) {
  9467. return new BrowserHTTPRequest(path, requestInit);
  9468. }
  9469. exports.browserHTTPRequest = browserHTTPRequest;
  9470. },{"../environment":51,"../util":164,"./io_utils":59,"./router_registry":62,"./weights_loader":64}],57:[function(require,module,exports){
  9471. "use strict";
  9472. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9473. return new (P || (P = Promise))(function (resolve, reject) {
  9474. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9475. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9476. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  9477. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9478. });
  9479. };
  9480. var __generator = (this && this.__generator) || function (thisArg, body) {
  9481. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  9482. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  9483. function verb(n) { return function (v) { return step([n, v]); }; }
  9484. function step(op) {
  9485. if (f) throw new TypeError("Generator is already executing.");
  9486. while (_) try {
  9487. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  9488. if (y = 0, t) op = [0, t.value];
  9489. switch (op[0]) {
  9490. case 0: case 1: t = op; break;
  9491. case 4: _.label++; return { value: op[1], done: false };
  9492. case 5: _.label++; y = op[1]; op = [0]; continue;
  9493. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  9494. default:
  9495. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  9496. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  9497. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  9498. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  9499. if (t[2]) _.ops.pop();
  9500. _.trys.pop(); continue;
  9501. }
  9502. op = body.call(thisArg, _);
  9503. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  9504. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  9505. }
  9506. };
  9507. Object.defineProperty(exports, "__esModule", { value: true });
  9508. var environment_1 = require("../environment");
  9509. var io_utils_1 = require("./io_utils");
  9510. var model_management_1 = require("./model_management");
  9511. var router_registry_1 = require("./router_registry");
  9512. var DATABASE_NAME = 'tensorflowjs';
  9513. var DATABASE_VERSION = 1;
  9514. var MODEL_STORE_NAME = 'models_store';
  9515. var INFO_STORE_NAME = 'model_info_store';
  9516. function deleteDatabase() {
  9517. return __awaiter(this, void 0, void 0, function () {
  9518. var idbFactory;
  9519. return __generator(this, function (_a) {
  9520. idbFactory = getIndexedDBFactory();
  9521. return [2, new Promise(function (resolve, reject) {
  9522. var deleteRequest = idbFactory.deleteDatabase(DATABASE_NAME);
  9523. deleteRequest.onsuccess = function () { return resolve(); };
  9524. deleteRequest.onerror = function (error) { return reject(error); };
  9525. })];
  9526. });
  9527. });
  9528. }
  9529. exports.deleteDatabase = deleteDatabase;
  9530. function getIndexedDBFactory() {
  9531. if (!environment_1.ENV.get('IS_BROWSER')) {
  9532. throw new Error('Failed to obtain IndexedDB factory because the current environment' +
  9533. 'is not a web browser.');
  9534. }
  9535. var theWindow = window;
  9536. var factory = theWindow.indexedDB || theWindow.mozIndexedDB ||
  9537. theWindow.webkitIndexedDB || theWindow.msIndexedDB ||
  9538. theWindow.shimIndexedDB;
  9539. if (factory == null) {
  9540. throw new Error('The current browser does not appear to support IndexedDB.');
  9541. }
  9542. return factory;
  9543. }
  9544. function setUpDatabase(openRequest) {
  9545. var db = openRequest.result;
  9546. db.createObjectStore(MODEL_STORE_NAME, { keyPath: 'modelPath' });
  9547. db.createObjectStore(INFO_STORE_NAME, { keyPath: 'modelPath' });
  9548. }
  9549. var BrowserIndexedDB = (function () {
  9550. function BrowserIndexedDB(modelPath) {
  9551. this.indexedDB = getIndexedDBFactory();
  9552. if (modelPath == null || !modelPath) {
  9553. throw new Error('For IndexedDB, modelPath must not be null, undefined or empty.');
  9554. }
  9555. this.modelPath = modelPath;
  9556. }
  9557. BrowserIndexedDB.prototype.save = function (modelArtifacts) {
  9558. return __awaiter(this, void 0, void 0, function () {
  9559. return __generator(this, function (_a) {
  9560. if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
  9561. throw new Error('BrowserLocalStorage.save() does not support saving model topology ' +
  9562. 'in binary formats yet.');
  9563. }
  9564. return [2, this.databaseAction(this.modelPath, modelArtifacts)];
  9565. });
  9566. });
  9567. };
  9568. BrowserIndexedDB.prototype.load = function () {
  9569. return __awaiter(this, void 0, void 0, function () {
  9570. return __generator(this, function (_a) {
  9571. return [2, this.databaseAction(this.modelPath)];
  9572. });
  9573. });
  9574. };
  9575. BrowserIndexedDB.prototype.databaseAction = function (modelPath, modelArtifacts) {
  9576. var _this = this;
  9577. return new Promise(function (resolve, reject) {
  9578. var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
  9579. openRequest.onupgradeneeded = function () { return setUpDatabase(openRequest); };
  9580. openRequest.onsuccess = function () {
  9581. var db = openRequest.result;
  9582. if (modelArtifacts == null) {
  9583. var modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');
  9584. var modelStore = modelTx.objectStore(MODEL_STORE_NAME);
  9585. var getRequest_1 = modelStore.get(_this.modelPath);
  9586. getRequest_1.onsuccess = function () {
  9587. if (getRequest_1.result == null) {
  9588. db.close();
  9589. return reject(new Error("Cannot find model with path '" + _this.modelPath + "' " +
  9590. "in IndexedDB."));
  9591. }
  9592. else {
  9593. resolve(getRequest_1.result.modelArtifacts);
  9594. }
  9595. };
  9596. getRequest_1.onerror = function (error) {
  9597. db.close();
  9598. return reject(getRequest_1.error);
  9599. };
  9600. modelTx.oncomplete = function () { return db.close(); };
  9601. }
  9602. else {
  9603. var modelArtifactsInfo_1 = io_utils_1.getModelArtifactsInfoForJSON(modelArtifacts);
  9604. var infoTx_1 = db.transaction(INFO_STORE_NAME, 'readwrite');
  9605. var infoStore_1 = infoTx_1.objectStore(INFO_STORE_NAME);
  9606. var putInfoRequest_1 = infoStore_1.put({ modelPath: _this.modelPath, modelArtifactsInfo: modelArtifactsInfo_1 });
  9607. var modelTx_1;
  9608. putInfoRequest_1.onsuccess = function () {
  9609. modelTx_1 = db.transaction(MODEL_STORE_NAME, 'readwrite');
  9610. var modelStore = modelTx_1.objectStore(MODEL_STORE_NAME);
  9611. var putModelRequest = modelStore.put({
  9612. modelPath: _this.modelPath,
  9613. modelArtifacts: modelArtifacts,
  9614. modelArtifactsInfo: modelArtifactsInfo_1
  9615. });
  9616. putModelRequest.onsuccess = function () { return resolve({ modelArtifactsInfo: modelArtifactsInfo_1 }); };
  9617. putModelRequest.onerror = function (error) {
  9618. infoStore_1 = infoTx_1.objectStore(INFO_STORE_NAME);
  9619. var deleteInfoRequest = infoStore_1.delete(_this.modelPath);
  9620. deleteInfoRequest.onsuccess = function () {
  9621. db.close();
  9622. return reject(putModelRequest.error);
  9623. };
  9624. deleteInfoRequest.onerror = function (error) {
  9625. db.close();
  9626. return reject(putModelRequest.error);
  9627. };
  9628. };
  9629. };
  9630. putInfoRequest_1.onerror = function (error) {
  9631. db.close();
  9632. return reject(putInfoRequest_1.error);
  9633. };
  9634. infoTx_1.oncomplete = function () {
  9635. if (modelTx_1 == null) {
  9636. db.close();
  9637. }
  9638. else {
  9639. modelTx_1.oncomplete = function () { return db.close(); };
  9640. }
  9641. };
  9642. }
  9643. };
  9644. openRequest.onerror = function (error) { return reject(openRequest.error); };
  9645. });
  9646. };
  9647. BrowserIndexedDB.URL_SCHEME = 'indexeddb://';
  9648. return BrowserIndexedDB;
  9649. }());
  9650. exports.BrowserIndexedDB = BrowserIndexedDB;
  9651. exports.indexedDBRouter = function (url) {
  9652. if (!environment_1.ENV.get('IS_BROWSER')) {
  9653. return null;
  9654. }
  9655. else {
  9656. if (url.startsWith(BrowserIndexedDB.URL_SCHEME)) {
  9657. return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));
  9658. }
  9659. else {
  9660. return null;
  9661. }
  9662. }
  9663. };
  9664. router_registry_1.IORouterRegistry.registerSaveRouter(exports.indexedDBRouter);
  9665. router_registry_1.IORouterRegistry.registerLoadRouter(exports.indexedDBRouter);
  9666. function browserIndexedDB(modelPath) {
  9667. return new BrowserIndexedDB(modelPath);
  9668. }
  9669. exports.browserIndexedDB = browserIndexedDB;
  9670. function maybeStripScheme(key) {
  9671. return key.startsWith(BrowserIndexedDB.URL_SCHEME) ?
  9672. key.slice(BrowserIndexedDB.URL_SCHEME.length) :
  9673. key;
  9674. }
  9675. var BrowserIndexedDBManager = (function () {
  9676. function BrowserIndexedDBManager() {
  9677. this.indexedDB = getIndexedDBFactory();
  9678. }
  9679. BrowserIndexedDBManager.prototype.listModels = function () {
  9680. return __awaiter(this, void 0, void 0, function () {
  9681. var _this = this;
  9682. return __generator(this, function (_a) {
  9683. return [2, new Promise(function (resolve, reject) {
  9684. var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
  9685. openRequest.onupgradeneeded = function () { return setUpDatabase(openRequest); };
  9686. openRequest.onsuccess = function () {
  9687. var db = openRequest.result;
  9688. var tx = db.transaction(INFO_STORE_NAME, 'readonly');
  9689. var store = tx.objectStore(INFO_STORE_NAME);
  9690. var getAllInfoRequest = store.getAll();
  9691. getAllInfoRequest.onsuccess = function () {
  9692. var out = {};
  9693. for (var _i = 0, _a = getAllInfoRequest.result; _i < _a.length; _i++) {
  9694. var item = _a[_i];
  9695. out[item.modelPath] = item.modelArtifactsInfo;
  9696. }
  9697. resolve(out);
  9698. };
  9699. getAllInfoRequest.onerror = function (error) {
  9700. db.close();
  9701. return reject(getAllInfoRequest.error);
  9702. };
  9703. tx.oncomplete = function () { return db.close(); };
  9704. };
  9705. openRequest.onerror = function (error) { return reject(openRequest.error); };
  9706. })];
  9707. });
  9708. });
  9709. };
  9710. BrowserIndexedDBManager.prototype.removeModel = function (path) {
  9711. return __awaiter(this, void 0, void 0, function () {
  9712. var _this = this;
  9713. return __generator(this, function (_a) {
  9714. path = maybeStripScheme(path);
  9715. return [2, new Promise(function (resolve, reject) {
  9716. var openRequest = _this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
  9717. openRequest.onupgradeneeded = function () { return setUpDatabase(openRequest); };
  9718. openRequest.onsuccess = function () {
  9719. var db = openRequest.result;
  9720. var infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');
  9721. var infoStore = infoTx.objectStore(INFO_STORE_NAME);
  9722. var getInfoRequest = infoStore.get(path);
  9723. var modelTx;
  9724. getInfoRequest.onsuccess = function () {
  9725. if (getInfoRequest.result == null) {
  9726. db.close();
  9727. return reject(new Error("Cannot find model with path '" + path + "' " +
  9728. "in IndexedDB."));
  9729. }
  9730. else {
  9731. var deleteInfoRequest = infoStore.delete(path);
  9732. var deleteModelData_1 = function () {
  9733. modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');
  9734. var modelStore = modelTx.objectStore(MODEL_STORE_NAME);
  9735. var deleteModelRequest = modelStore.delete(path);
  9736. deleteModelRequest.onsuccess = function () {
  9737. return resolve(getInfoRequest.result.modelArtifactsInfo);
  9738. };
  9739. deleteModelRequest.onerror = function (error) {
  9740. return reject(getInfoRequest.error);
  9741. };
  9742. };
  9743. deleteInfoRequest.onsuccess = deleteModelData_1;
  9744. deleteInfoRequest.onerror = function (error) {
  9745. deleteModelData_1();
  9746. db.close();
  9747. return reject(getInfoRequest.error);
  9748. };
  9749. }
  9750. };
  9751. getInfoRequest.onerror = function (error) {
  9752. db.close();
  9753. return reject(getInfoRequest.error);
  9754. };
  9755. infoTx.oncomplete = function () {
  9756. if (modelTx == null) {
  9757. db.close();
  9758. }
  9759. else {
  9760. modelTx.oncomplete = function () { return db.close(); };
  9761. }
  9762. };
  9763. };
  9764. openRequest.onerror = function (error) { return reject(openRequest.error); };
  9765. })];
  9766. });
  9767. });
  9768. };
  9769. return BrowserIndexedDBManager;
  9770. }());
  9771. exports.BrowserIndexedDBManager = BrowserIndexedDBManager;
  9772. if (environment_1.ENV.get('IS_BROWSER')) {
  9773. try {
  9774. model_management_1.ModelStoreManagerRegistry.registerManager(BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());
  9775. }
  9776. catch (err) {
  9777. }
  9778. }
  9779. },{"../environment":51,"./io_utils":59,"./model_management":61,"./router_registry":62}],58:[function(require,module,exports){
  9780. "use strict";
  9781. Object.defineProperty(exports, "__esModule", { value: true });
  9782. require("./indexed_db");
  9783. require("./local_storage");
  9784. var browser_files_1 = require("./browser_files");
  9785. exports.browserFiles = browser_files_1.browserFiles;
  9786. var browser_http_1 = require("./browser_http");
  9787. exports.browserHTTPRequest = browser_http_1.browserHTTPRequest;
  9788. var io_utils_1 = require("./io_utils");
  9789. exports.concatenateArrayBuffers = io_utils_1.concatenateArrayBuffers;
  9790. exports.decodeWeights = io_utils_1.decodeWeights;
  9791. exports.encodeWeights = io_utils_1.encodeWeights;
  9792. exports.getModelArtifactsInfoForJSON = io_utils_1.getModelArtifactsInfoForJSON;
  9793. var model_management_1 = require("./model_management");
  9794. var router_registry_1 = require("./router_registry");
  9795. var weights_loader_1 = require("./weights_loader");
  9796. exports.loadWeights = weights_loader_1.loadWeights;
  9797. var registerSaveRouter = router_registry_1.IORouterRegistry.registerSaveRouter;
  9798. exports.registerSaveRouter = registerSaveRouter;
  9799. var registerLoadRouter = router_registry_1.IORouterRegistry.registerLoadRouter;
  9800. exports.registerLoadRouter = registerLoadRouter;
  9801. var getSaveHandlers = router_registry_1.IORouterRegistry.getSaveHandlers;
  9802. exports.getSaveHandlers = getSaveHandlers;
  9803. var getLoadHandlers = router_registry_1.IORouterRegistry.getLoadHandlers;
  9804. exports.getLoadHandlers = getLoadHandlers;
  9805. var copyModel = model_management_1.ModelManagement.copyModel;
  9806. exports.copyModel = copyModel;
  9807. var listModels = model_management_1.ModelManagement.listModels;
  9808. exports.listModels = listModels;
  9809. var moveModel = model_management_1.ModelManagement.moveModel;
  9810. exports.moveModel = moveModel;
  9811. var removeModel = model_management_1.ModelManagement.removeModel;
  9812. exports.removeModel = removeModel;
  9813. },{"./browser_files":55,"./browser_http":56,"./indexed_db":57,"./io_utils":59,"./local_storage":60,"./model_management":61,"./router_registry":62,"./weights_loader":64}],59:[function(require,module,exports){
  9814. "use strict";
  9815. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  9816. return new (P || (P = Promise))(function (resolve, reject) {
  9817. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  9818. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  9819. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  9820. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9821. });
  9822. };
  9823. var __generator = (this && this.__generator) || function (thisArg, body) {
  9824. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  9825. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  9826. function verb(n) { return function (v) { return step([n, v]); }; }
  9827. function step(op) {
  9828. if (f) throw new TypeError("Generator is already executing.");
  9829. while (_) try {
  9830. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  9831. if (y = 0, t) op = [0, t.value];
  9832. switch (op[0]) {
  9833. case 0: case 1: t = op; break;
  9834. case 4: _.label++; return { value: op[1], done: false };
  9835. case 5: _.label++; y = op[1]; op = [0]; continue;
  9836. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  9837. default:
  9838. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  9839. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  9840. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  9841. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  9842. if (t[2]) _.ops.pop();
  9843. _.trys.pop(); continue;
  9844. }
  9845. op = body.call(thisArg, _);
  9846. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  9847. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  9848. }
  9849. };
  9850. Object.defineProperty(exports, "__esModule", { value: true });
  9851. var array_ops_1 = require("../ops/array_ops");
  9852. var util_1 = require("../util");
  9853. var types_1 = require("./types");
  9854. function encodeWeights(tensors) {
  9855. return __awaiter(this, void 0, void 0, function () {
  9856. var specs, dataPromises, name_1, t, tensorValues;
  9857. return __generator(this, function (_a) {
  9858. switch (_a.label) {
  9859. case 0:
  9860. specs = [];
  9861. dataPromises = [];
  9862. for (name_1 in tensors) {
  9863. t = tensors[name_1];
  9864. if (t.dtype !== 'float32' && t.dtype !== 'int32' && t.dtype !== 'bool') {
  9865. throw new Error("Unsupported dtype in weight '" + name_1 + "': " + t.dtype);
  9866. }
  9867. specs.push({ name: name_1, shape: t.shape, dtype: t.dtype });
  9868. dataPromises.push(t.data());
  9869. }
  9870. return [4, Promise.all(dataPromises)];
  9871. case 1:
  9872. tensorValues = _a.sent();
  9873. return [2, { data: concatenateTypedArrays(tensorValues), specs: specs }];
  9874. }
  9875. });
  9876. });
  9877. }
  9878. exports.encodeWeights = encodeWeights;
  9879. function decodeWeights(buffer, specs) {
  9880. var out = {};
  9881. var offset = 0;
  9882. for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) {
  9883. var spec = specs_1[_i];
  9884. var name_2 = spec.name;
  9885. var dtype = spec.dtype;
  9886. var shape = spec.shape;
  9887. if (spec.quantization != null) {
  9888. throw new Error("decodeWeights does not support quantization yet, but encountered " +
  9889. ("weight '" + name_2 + " with quantization.'"));
  9890. }
  9891. var size = util_1.sizeFromShape(shape);
  9892. var value = void 0;
  9893. if (dtype === 'float32') {
  9894. value = array_ops_1.ArrayOps.tensor(new Float32Array(buffer, offset, size), shape, 'float32');
  9895. }
  9896. else if (dtype === 'int32') {
  9897. value =
  9898. array_ops_1.ArrayOps.tensor(new Int32Array(buffer, offset, size), shape, 'int32');
  9899. }
  9900. else if (dtype === 'bool') {
  9901. value =
  9902. array_ops_1.ArrayOps.tensor(new Uint8Array(buffer, offset, size), shape, 'bool');
  9903. }
  9904. else {
  9905. throw new Error("Unsupported dtype in weight '" + name_2 + "': " + dtype);
  9906. }
  9907. out[name_2] = value;
  9908. offset += size * types_1.DTYPE_VALUE_SIZE_MAP[dtype];
  9909. }
  9910. return out;
  9911. }
  9912. exports.decodeWeights = decodeWeights;
  9913. function concatenateTypedArrays(xs) {
  9914. if (xs === null) {
  9915. throw new Error("Invalid input value: " + JSON.stringify(xs));
  9916. }
  9917. var totalByteLength = 0;
  9918. xs.forEach(function (x) {
  9919. if (x instanceof Float32Array || x instanceof Int32Array) {
  9920. totalByteLength += x.buffer.byteLength;
  9921. }
  9922. else if (x instanceof Uint8Array) {
  9923. totalByteLength += x.buffer.byteLength;
  9924. }
  9925. else {
  9926. throw new Error("Unsupported TypedArray subtype: " + x.constructor.name);
  9927. }
  9928. });
  9929. var y = new Uint8Array(totalByteLength);
  9930. var offset = 0;
  9931. xs.forEach(function (x) {
  9932. y.set(new Uint8Array(x.buffer), offset);
  9933. offset += x.buffer.byteLength;
  9934. });
  9935. return y.buffer;
  9936. }
  9937. exports.concatenateTypedArrays = concatenateTypedArrays;
  9938. function stringByteLength(str) {
  9939. return new Blob([str]).size;
  9940. }
  9941. exports.stringByteLength = stringByteLength;
  9942. function arrayBufferToBase64String(buffer) {
  9943. return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
  9944. }
  9945. exports.arrayBufferToBase64String = arrayBufferToBase64String;
  9946. function base64StringToArrayBuffer(str) {
  9947. var s = atob(str);
  9948. var buffer = new Uint8Array(s.length);
  9949. for (var i = 0; i < s.length; ++i) {
  9950. buffer.set([s.charCodeAt(i)], i);
  9951. }
  9952. return buffer.buffer;
  9953. }
  9954. exports.base64StringToArrayBuffer = base64StringToArrayBuffer;
  9955. function concatenateArrayBuffers(buffers) {
  9956. var totalByteLength = 0;
  9957. buffers.forEach(function (buffer) {
  9958. totalByteLength += buffer.byteLength;
  9959. });
  9960. var temp = new Uint8Array(totalByteLength);
  9961. var offset = 0;
  9962. buffers.forEach(function (buffer) {
  9963. temp.set(new Uint8Array(buffer), offset);
  9964. offset += buffer.byteLength;
  9965. });
  9966. return temp.buffer;
  9967. }
  9968. exports.concatenateArrayBuffers = concatenateArrayBuffers;
  9969. function basename(path) {
  9970. var SEPARATOR = '/';
  9971. path = path.trim();
  9972. while (path.endsWith(SEPARATOR)) {
  9973. path = path.slice(0, path.length - 1);
  9974. }
  9975. var items = path.split(SEPARATOR);
  9976. return items[items.length - 1];
  9977. }
  9978. exports.basename = basename;
  9979. function getModelArtifactsInfoForJSON(modelArtifacts) {
  9980. if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
  9981. throw new Error('Expected JSON model topology, received ArrayBuffer.');
  9982. }
  9983. return {
  9984. dateSaved: new Date(),
  9985. modelTopologyType: 'JSON',
  9986. modelTopologyBytes: modelArtifacts.modelTopology == null ?
  9987. 0 :
  9988. stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),
  9989. weightSpecsBytes: modelArtifacts.weightSpecs == null ?
  9990. 0 :
  9991. stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),
  9992. weightDataBytes: modelArtifacts.weightData == null ?
  9993. 0 :
  9994. modelArtifacts.weightData.byteLength,
  9995. };
  9996. }
  9997. exports.getModelArtifactsInfoForJSON = getModelArtifactsInfoForJSON;
  9998. },{"../ops/array_ops":108,"../util":164,"./types":63}],60:[function(require,module,exports){
  9999. "use strict";
  10000. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10001. return new (P || (P = Promise))(function (resolve, reject) {
  10002. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10003. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10004. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  10005. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10006. });
  10007. };
  10008. var __generator = (this && this.__generator) || function (thisArg, body) {
  10009. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  10010. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  10011. function verb(n) { return function (v) { return step([n, v]); }; }
  10012. function step(op) {
  10013. if (f) throw new TypeError("Generator is already executing.");
  10014. while (_) try {
  10015. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  10016. if (y = 0, t) op = [0, t.value];
  10017. switch (op[0]) {
  10018. case 0: case 1: t = op; break;
  10019. case 4: _.label++; return { value: op[1], done: false };
  10020. case 5: _.label++; y = op[1]; op = [0]; continue;
  10021. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  10022. default:
  10023. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  10024. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  10025. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  10026. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  10027. if (t[2]) _.ops.pop();
  10028. _.trys.pop(); continue;
  10029. }
  10030. op = body.call(thisArg, _);
  10031. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  10032. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  10033. }
  10034. };
  10035. Object.defineProperty(exports, "__esModule", { value: true });
  10036. var environment_1 = require("../environment");
  10037. var util_1 = require("../util");
  10038. var io_utils_1 = require("./io_utils");
  10039. var model_management_1 = require("./model_management");
  10040. var router_registry_1 = require("./router_registry");
  10041. var PATH_SEPARATOR = '/';
  10042. var PATH_PREFIX = 'tensorflowjs_models';
  10043. var INFO_SUFFIX = 'info';
  10044. var MODEL_TOPOLOGY_SUFFIX = 'model_topology';
  10045. var WEIGHT_SPECS_SUFFIX = 'weight_specs';
  10046. var WEIGHT_DATA_SUFFIX = 'weight_data';
  10047. function purgeLocalStorageArtifacts() {
  10048. if (!environment_1.ENV.get('IS_BROWSER') || typeof window.localStorage === 'undefined') {
  10049. throw new Error('purgeLocalStorageModels() cannot proceed because local storage is ' +
  10050. 'unavailable in the current environment.');
  10051. }
  10052. var LS = window.localStorage;
  10053. var purgedModelPaths = [];
  10054. for (var i = 0; i < LS.length; ++i) {
  10055. var key = LS.key(i);
  10056. var prefix = PATH_PREFIX + PATH_SEPARATOR;
  10057. if (key.startsWith(prefix) && key.length > prefix.length) {
  10058. LS.removeItem(key);
  10059. var modelName = getModelPathFromKey(key);
  10060. if (purgedModelPaths.indexOf(modelName) === -1) {
  10061. purgedModelPaths.push(modelName);
  10062. }
  10063. }
  10064. }
  10065. return purgedModelPaths;
  10066. }
  10067. exports.purgeLocalStorageArtifacts = purgeLocalStorageArtifacts;
  10068. function getModelKeys(path) {
  10069. return {
  10070. info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),
  10071. topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),
  10072. weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),
  10073. weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR)
  10074. };
  10075. }
  10076. function getModelPathFromKey(key) {
  10077. var items = key.split(PATH_SEPARATOR);
  10078. if (items.length < 3) {
  10079. throw new Error("Invalid key format: " + key);
  10080. }
  10081. return items.slice(1, items.length - 1).join(PATH_SEPARATOR);
  10082. }
  10083. function maybeStripScheme(key) {
  10084. return key.startsWith(BrowserLocalStorage.URL_SCHEME) ?
  10085. key.slice(BrowserLocalStorage.URL_SCHEME.length) :
  10086. key;
  10087. }
  10088. var BrowserLocalStorage = (function () {
  10089. function BrowserLocalStorage(modelPath) {
  10090. if (!environment_1.ENV.get('IS_BROWSER') || typeof window.localStorage === 'undefined') {
  10091. throw new Error('The current environment does not support local storage.');
  10092. }
  10093. this.LS = window.localStorage;
  10094. if (modelPath == null || !modelPath) {
  10095. throw new Error('For local storage, modelPath must not be null, undefined or empty.');
  10096. }
  10097. this.modelPath = modelPath;
  10098. this.keys = getModelKeys(this.modelPath);
  10099. }
  10100. BrowserLocalStorage.prototype.save = function (modelArtifacts) {
  10101. return __awaiter(this, void 0, void 0, function () {
  10102. var topology, weightSpecs, modelArtifactsInfo, key;
  10103. return __generator(this, function (_a) {
  10104. if (modelArtifacts.modelTopology instanceof ArrayBuffer) {
  10105. throw new Error('BrowserLocalStorage.save() does not support saving model topology ' +
  10106. 'in binary formats yet.');
  10107. }
  10108. else {
  10109. topology = JSON.stringify(modelArtifacts.modelTopology);
  10110. weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);
  10111. modelArtifactsInfo = io_utils_1.getModelArtifactsInfoForJSON(modelArtifacts);
  10112. try {
  10113. this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));
  10114. this.LS.setItem(this.keys.topology, topology);
  10115. this.LS.setItem(this.keys.weightSpecs, weightSpecs);
  10116. this.LS.setItem(this.keys.weightData, io_utils_1.arrayBufferToBase64String(modelArtifacts.weightData));
  10117. return [2, { modelArtifactsInfo: modelArtifactsInfo }];
  10118. }
  10119. catch (err) {
  10120. for (key in this.keys) {
  10121. this.LS.removeItem(this.keys[key]);
  10122. }
  10123. throw new Error("Failed to save model '" + this.modelPath + "' to local storage: " +
  10124. "size quota being exceeded is a possible cause of this failure: " +
  10125. ("modelTopologyBytes=" + modelArtifactsInfo.modelTopologyBytes + ", ") +
  10126. ("weightSpecsBytes=" + modelArtifactsInfo.weightSpecsBytes + ", ") +
  10127. ("weightDataBytes=" + modelArtifactsInfo.weightDataBytes + "."));
  10128. }
  10129. }
  10130. return [2];
  10131. });
  10132. });
  10133. };
  10134. BrowserLocalStorage.prototype.load = function () {
  10135. return __awaiter(this, void 0, void 0, function () {
  10136. var info, out, topology, weightSpecs, weightDataBase64;
  10137. return __generator(this, function (_a) {
  10138. info = JSON.parse(this.LS.getItem(this.keys.info));
  10139. if (info == null) {
  10140. throw new Error("In local storage, there is no model with name '" + this.modelPath + "'");
  10141. }
  10142. if (info.modelTopologyType !== 'JSON') {
  10143. throw new Error('BrowserLocalStorage does not support loading non-JSON model ' +
  10144. 'topology yet.');
  10145. }
  10146. out = {};
  10147. topology = JSON.parse(this.LS.getItem(this.keys.topology));
  10148. if (topology == null) {
  10149. throw new Error("In local storage, the topology of model '" + this.modelPath + "' " +
  10150. "is missing.");
  10151. }
  10152. out.modelTopology = topology;
  10153. weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
  10154. if (weightSpecs == null) {
  10155. throw new Error("In local storage, the weight specs of model '" + this.modelPath + "' " +
  10156. "are missing.");
  10157. }
  10158. out.weightSpecs = weightSpecs;
  10159. weightDataBase64 = this.LS.getItem(this.keys.weightData);
  10160. if (weightDataBase64 == null) {
  10161. throw new Error("In local storage, the binary weight values of model " +
  10162. ("'" + this.modelPath + "' are missing."));
  10163. }
  10164. out.weightData = io_utils_1.base64StringToArrayBuffer(weightDataBase64);
  10165. return [2, out];
  10166. });
  10167. });
  10168. };
  10169. BrowserLocalStorage.URL_SCHEME = 'localstorage://';
  10170. return BrowserLocalStorage;
  10171. }());
  10172. exports.BrowserLocalStorage = BrowserLocalStorage;
  10173. exports.localStorageRouter = function (url) {
  10174. if (!environment_1.ENV.get('IS_BROWSER')) {
  10175. return null;
  10176. }
  10177. else {
  10178. if (url.startsWith(BrowserLocalStorage.URL_SCHEME)) {
  10179. return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length));
  10180. }
  10181. else {
  10182. return null;
  10183. }
  10184. }
  10185. };
  10186. router_registry_1.IORouterRegistry.registerSaveRouter(exports.localStorageRouter);
  10187. router_registry_1.IORouterRegistry.registerLoadRouter(exports.localStorageRouter);
  10188. function browserLocalStorage(modelPath) {
  10189. return new BrowserLocalStorage(modelPath);
  10190. }
  10191. exports.browserLocalStorage = browserLocalStorage;
  10192. var BrowserLocalStorageManager = (function () {
  10193. function BrowserLocalStorageManager() {
  10194. util_1.assert(environment_1.ENV.get('IS_BROWSER'), 'Current environment is not a web browser');
  10195. util_1.assert(typeof window.localStorage !== 'undefined', 'Current browser does not appear to support localStorage');
  10196. this.LS = window.localStorage;
  10197. }
  10198. BrowserLocalStorageManager.prototype.listModels = function () {
  10199. return __awaiter(this, void 0, void 0, function () {
  10200. var out, prefix, suffix, i, key, modelPath;
  10201. return __generator(this, function (_a) {
  10202. out = {};
  10203. prefix = PATH_PREFIX + PATH_SEPARATOR;
  10204. suffix = PATH_SEPARATOR + INFO_SUFFIX;
  10205. for (i = 0; i < this.LS.length; ++i) {
  10206. key = this.LS.key(i);
  10207. if (key.startsWith(prefix) && key.endsWith(suffix)) {
  10208. modelPath = getModelPathFromKey(key);
  10209. out[modelPath] = JSON.parse(this.LS.getItem(key));
  10210. }
  10211. }
  10212. return [2, out];
  10213. });
  10214. });
  10215. };
  10216. BrowserLocalStorageManager.prototype.removeModel = function (path) {
  10217. return __awaiter(this, void 0, void 0, function () {
  10218. var keys, info;
  10219. return __generator(this, function (_a) {
  10220. path = maybeStripScheme(path);
  10221. keys = getModelKeys(path);
  10222. if (this.LS.getItem(keys.info) == null) {
  10223. throw new Error("Cannot find model at path '" + path + "'");
  10224. }
  10225. info = JSON.parse(this.LS.getItem(keys.info));
  10226. this.LS.removeItem(keys.info);
  10227. this.LS.removeItem(keys.topology);
  10228. this.LS.removeItem(keys.weightSpecs);
  10229. this.LS.removeItem(keys.weightData);
  10230. return [2, info];
  10231. });
  10232. });
  10233. };
  10234. return BrowserLocalStorageManager;
  10235. }());
  10236. exports.BrowserLocalStorageManager = BrowserLocalStorageManager;
  10237. if (environment_1.ENV.get('IS_BROWSER')) {
  10238. try {
  10239. model_management_1.ModelStoreManagerRegistry.registerManager(BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());
  10240. }
  10241. catch (err) {
  10242. }
  10243. }
  10244. },{"../environment":51,"../util":164,"./io_utils":59,"./model_management":61,"./router_registry":62}],61:[function(require,module,exports){
  10245. "use strict";
  10246. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  10247. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  10248. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  10249. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  10250. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10251. };
  10252. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10253. return new (P || (P = Promise))(function (resolve, reject) {
  10254. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10255. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10256. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  10257. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10258. });
  10259. };
  10260. var __generator = (this && this.__generator) || function (thisArg, body) {
  10261. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  10262. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  10263. function verb(n) { return function (v) { return step([n, v]); }; }
  10264. function step(op) {
  10265. if (f) throw new TypeError("Generator is already executing.");
  10266. while (_) try {
  10267. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  10268. if (y = 0, t) op = [0, t.value];
  10269. switch (op[0]) {
  10270. case 0: case 1: t = op; break;
  10271. case 4: _.label++; return { value: op[1], done: false };
  10272. case 5: _.label++; y = op[1]; op = [0]; continue;
  10273. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  10274. default:
  10275. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  10276. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  10277. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  10278. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  10279. if (t[2]) _.ops.pop();
  10280. _.trys.pop(); continue;
  10281. }
  10282. op = body.call(thisArg, _);
  10283. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  10284. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  10285. }
  10286. };
  10287. Object.defineProperty(exports, "__esModule", { value: true });
  10288. var doc_1 = require("../doc");
  10289. var util_1 = require("../util");
  10290. var router_registry_1 = require("./router_registry");
  10291. var URL_SCHEME_SUFFIX = '://';
  10292. var ModelStoreManagerRegistry = (function () {
  10293. function ModelStoreManagerRegistry() {
  10294. this.managers = {};
  10295. }
  10296. ModelStoreManagerRegistry.getInstance = function () {
  10297. if (ModelStoreManagerRegistry.instance == null) {
  10298. ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();
  10299. }
  10300. return ModelStoreManagerRegistry.instance;
  10301. };
  10302. ModelStoreManagerRegistry.registerManager = function (scheme, manager) {
  10303. util_1.assert(scheme != null, 'scheme must not be undefined or null.');
  10304. if (scheme.endsWith(URL_SCHEME_SUFFIX)) {
  10305. scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));
  10306. }
  10307. util_1.assert(scheme.length > 0, 'scheme must not be an empty string.');
  10308. var registry = ModelStoreManagerRegistry.getInstance();
  10309. util_1.assert(registry.managers[scheme] == null, "A model store manager is already registered for scheme '" + scheme + "'.");
  10310. registry.managers[scheme] = manager;
  10311. };
  10312. ModelStoreManagerRegistry.getManager = function (scheme) {
  10313. var manager = this.getInstance().managers[scheme];
  10314. if (manager == null) {
  10315. throw new Error("Cannot find model manager for scheme '" + scheme + "'");
  10316. }
  10317. return manager;
  10318. };
  10319. ModelStoreManagerRegistry.getSchemes = function () {
  10320. return Object.keys(this.getInstance().managers);
  10321. };
  10322. return ModelStoreManagerRegistry;
  10323. }());
  10324. exports.ModelStoreManagerRegistry = ModelStoreManagerRegistry;
  10325. function parseURL(url) {
  10326. if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {
  10327. throw new Error("The url string provided does not contain a scheme. " +
  10328. "Supported schemes are: " +
  10329. ("" + ModelStoreManagerRegistry.getSchemes().join(',')));
  10330. }
  10331. return {
  10332. scheme: url.split(URL_SCHEME_SUFFIX)[0],
  10333. path: url.split(URL_SCHEME_SUFFIX)[1],
  10334. };
  10335. }
  10336. function cloneModelInternal(sourceURL, destURL, deleteSource) {
  10337. if (deleteSource === void 0) { deleteSource = false; }
  10338. return __awaiter(this, void 0, void 0, function () {
  10339. var loadHandlers, loadHandler, saveHandlers, saveHandler, sourceScheme, sourcePath, sameMedium, modelArtifacts, saveResult;
  10340. return __generator(this, function (_a) {
  10341. switch (_a.label) {
  10342. case 0:
  10343. util_1.assert(sourceURL !== destURL, "Old path and new path are the same: '" + sourceURL + "'");
  10344. loadHandlers = router_registry_1.IORouterRegistry.getLoadHandlers(sourceURL);
  10345. util_1.assert(loadHandlers.length > 0, "Copying failed because no load handler is found for source URL " + sourceURL + ".");
  10346. util_1.assert(loadHandlers.length < 2, "Copying failed because more than one (" + loadHandlers.length + ") " +
  10347. ("load handlers for source URL " + sourceURL + "."));
  10348. loadHandler = loadHandlers[0];
  10349. saveHandlers = router_registry_1.IORouterRegistry.getSaveHandlers(destURL);
  10350. util_1.assert(saveHandlers.length > 0, "Copying failed because no save handler is found for destination URL " +
  10351. (destURL + "."));
  10352. util_1.assert(saveHandlers.length < 2, "Copying failed because more than one (" + loadHandlers.length + ") " +
  10353. ("save handlers for destination URL " + destURL + "."));
  10354. saveHandler = saveHandlers[0];
  10355. sourceScheme = parseURL(sourceURL).scheme;
  10356. sourcePath = parseURL(sourceURL).path;
  10357. sameMedium = sourceScheme === parseURL(sourceURL).scheme;
  10358. return [4, loadHandler.load()];
  10359. case 1:
  10360. modelArtifacts = _a.sent();
  10361. if (!(deleteSource && sameMedium)) return [3, 3];
  10362. return [4, ModelStoreManagerRegistry.getManager(sourceScheme)
  10363. .removeModel(sourcePath)];
  10364. case 2:
  10365. _a.sent();
  10366. _a.label = 3;
  10367. case 3: return [4, saveHandler.save(modelArtifacts)];
  10368. case 4:
  10369. saveResult = _a.sent();
  10370. if (!(deleteSource && !sameMedium)) return [3, 6];
  10371. return [4, ModelStoreManagerRegistry.getManager(sourceScheme)
  10372. .removeModel(sourcePath)];
  10373. case 5:
  10374. _a.sent();
  10375. _a.label = 6;
  10376. case 6: return [2, saveResult.modelArtifactsInfo];
  10377. }
  10378. });
  10379. });
  10380. }
  10381. var ModelManagement = (function () {
  10382. function ModelManagement() {
  10383. }
  10384. ModelManagement.listModels = function () {
  10385. return __awaiter(this, void 0, void 0, function () {
  10386. var schemes, out, _i, schemes_1, scheme, schemeOut, path, url;
  10387. return __generator(this, function (_a) {
  10388. switch (_a.label) {
  10389. case 0:
  10390. schemes = ModelStoreManagerRegistry.getSchemes();
  10391. out = {};
  10392. _i = 0, schemes_1 = schemes;
  10393. _a.label = 1;
  10394. case 1:
  10395. if (!(_i < schemes_1.length)) return [3, 4];
  10396. scheme = schemes_1[_i];
  10397. return [4, ModelStoreManagerRegistry.getManager(scheme).listModels()];
  10398. case 2:
  10399. schemeOut = _a.sent();
  10400. for (path in schemeOut) {
  10401. url = scheme + URL_SCHEME_SUFFIX + path;
  10402. out[url] = schemeOut[path];
  10403. }
  10404. _a.label = 3;
  10405. case 3:
  10406. _i++;
  10407. return [3, 1];
  10408. case 4: return [2, out];
  10409. }
  10410. });
  10411. });
  10412. };
  10413. ModelManagement.removeModel = function (url) {
  10414. return __awaiter(this, void 0, void 0, function () {
  10415. var schemeAndPath, manager;
  10416. return __generator(this, function (_a) {
  10417. switch (_a.label) {
  10418. case 0:
  10419. schemeAndPath = parseURL(url);
  10420. manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);
  10421. return [4, manager.removeModel(schemeAndPath.path)];
  10422. case 1: return [2, _a.sent()];
  10423. }
  10424. });
  10425. });
  10426. };
  10427. ModelManagement.copyModel = function (sourceURL, destURL) {
  10428. return __awaiter(this, void 0, void 0, function () {
  10429. var deleteSource;
  10430. return __generator(this, function (_a) {
  10431. switch (_a.label) {
  10432. case 0:
  10433. deleteSource = false;
  10434. return [4, cloneModelInternal(sourceURL, destURL, deleteSource)];
  10435. case 1: return [2, _a.sent()];
  10436. }
  10437. });
  10438. });
  10439. };
  10440. ModelManagement.moveModel = function (sourceURL, destURL) {
  10441. return __awaiter(this, void 0, void 0, function () {
  10442. var deleteSource;
  10443. return __generator(this, function (_a) {
  10444. switch (_a.label) {
  10445. case 0:
  10446. deleteSource = true;
  10447. return [4, cloneModelInternal(sourceURL, destURL, deleteSource)];
  10448. case 1: return [2, _a.sent()];
  10449. }
  10450. });
  10451. });
  10452. };
  10453. __decorate([
  10454. doc_1.doc({ heading: 'Models', subheading: 'Management', namespace: 'io' })
  10455. ], ModelManagement, "listModels", null);
  10456. __decorate([
  10457. doc_1.doc({ heading: 'Models', subheading: 'Management', namespace: 'io' })
  10458. ], ModelManagement, "removeModel", null);
  10459. __decorate([
  10460. doc_1.doc({ heading: 'Models', subheading: 'Management', namespace: 'io' })
  10461. ], ModelManagement, "copyModel", null);
  10462. __decorate([
  10463. doc_1.doc({ heading: 'Models', subheading: 'Management', namespace: 'io' })
  10464. ], ModelManagement, "moveModel", null);
  10465. return ModelManagement;
  10466. }());
  10467. exports.ModelManagement = ModelManagement;
  10468. },{"../doc":49,"../util":164,"./router_registry":62}],62:[function(require,module,exports){
  10469. "use strict";
  10470. Object.defineProperty(exports, "__esModule", { value: true });
  10471. var IORouterRegistry = (function () {
  10472. function IORouterRegistry() {
  10473. this.saveRouters = [];
  10474. this.loadRouters = [];
  10475. }
  10476. IORouterRegistry.getInstance = function () {
  10477. if (IORouterRegistry.instance == null) {
  10478. IORouterRegistry.instance = new IORouterRegistry();
  10479. }
  10480. return IORouterRegistry.instance;
  10481. };
  10482. IORouterRegistry.registerSaveRouter = function (saveRouter) {
  10483. IORouterRegistry.getInstance().saveRouters.push(saveRouter);
  10484. };
  10485. IORouterRegistry.registerLoadRouter = function (loadRouter) {
  10486. IORouterRegistry.getInstance().loadRouters.push(loadRouter);
  10487. };
  10488. IORouterRegistry.getSaveHandlers = function (url) {
  10489. return IORouterRegistry.getHandlers(url, 'save');
  10490. };
  10491. IORouterRegistry.getLoadHandlers = function (url) {
  10492. return IORouterRegistry.getHandlers(url, 'load');
  10493. };
  10494. IORouterRegistry.getHandlers = function (url, handlerType) {
  10495. var validHandlers = [];
  10496. var routers = handlerType === 'load' ? this.getInstance().loadRouters :
  10497. this.getInstance().saveRouters;
  10498. routers.forEach(function (router) {
  10499. var handler = router(url);
  10500. if (handler !== null) {
  10501. validHandlers.push(handler);
  10502. }
  10503. });
  10504. return validHandlers;
  10505. };
  10506. return IORouterRegistry;
  10507. }());
  10508. exports.IORouterRegistry = IORouterRegistry;
  10509. },{}],63:[function(require,module,exports){
  10510. "use strict";
  10511. Object.defineProperty(exports, "__esModule", { value: true });
  10512. exports.DTYPE_VALUE_SIZE_MAP = {
  10513. 'float32': 4,
  10514. 'int32': 4,
  10515. 'uint16': 2,
  10516. 'uint8': 1,
  10517. 'bool': 1,
  10518. };
  10519. },{}],64:[function(require,module,exports){
  10520. "use strict";
  10521. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10522. return new (P || (P = Promise))(function (resolve, reject) {
  10523. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10524. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10525. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  10526. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10527. });
  10528. };
  10529. var __generator = (this && this.__generator) || function (thisArg, body) {
  10530. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  10531. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  10532. function verb(n) { return function (v) { return step([n, v]); }; }
  10533. function step(op) {
  10534. if (f) throw new TypeError("Generator is already executing.");
  10535. while (_) try {
  10536. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  10537. if (y = 0, t) op = [0, t.value];
  10538. switch (op[0]) {
  10539. case 0: case 1: t = op; break;
  10540. case 4: _.label++; return { value: op[1], done: false };
  10541. case 5: _.label++; y = op[1]; op = [0]; continue;
  10542. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  10543. default:
  10544. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  10545. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  10546. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  10547. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  10548. if (t[2]) _.ops.pop();
  10549. _.trys.pop(); continue;
  10550. }
  10551. op = body.call(thisArg, _);
  10552. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  10553. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  10554. }
  10555. };
  10556. Object.defineProperty(exports, "__esModule", { value: true });
  10557. var ops_1 = require("../ops/ops");
  10558. var util = require("../util");
  10559. var types_1 = require("./types");
  10560. function loadWeightsAsArrayBuffer(fetchURLs, requestOptions) {
  10561. return __awaiter(this, void 0, void 0, function () {
  10562. var requests, responses, buffers;
  10563. return __generator(this, function (_a) {
  10564. switch (_a.label) {
  10565. case 0:
  10566. requests = fetchURLs.map(function (fetchURL) { return fetch(fetchURL, requestOptions); });
  10567. return [4, Promise.all(requests)];
  10568. case 1:
  10569. responses = _a.sent();
  10570. return [4, Promise.all(responses.map(function (response) { return response.arrayBuffer(); }))];
  10571. case 2:
  10572. buffers = _a.sent();
  10573. return [2, buffers];
  10574. }
  10575. });
  10576. });
  10577. }
  10578. exports.loadWeightsAsArrayBuffer = loadWeightsAsArrayBuffer;
  10579. function loadWeights(manifest, filePathPrefix, weightNames, requestOptions) {
  10580. if (filePathPrefix === void 0) { filePathPrefix = ''; }
  10581. return __awaiter(this, void 0, void 0, function () {
  10582. var groupIndicesToFetchMap, groupWeightsToFetch, weightsFound, allManifestWeightNames, weightsNotFound, groupIndicesToFetch, fetchUrls, buffers, weightsTensorMap, bufferIndexOffset;
  10583. return __generator(this, function (_a) {
  10584. switch (_a.label) {
  10585. case 0:
  10586. groupIndicesToFetchMap = manifest.map(function () { return false; });
  10587. groupWeightsToFetch = {};
  10588. weightsFound = weightNames != null ? weightNames.map(function () { return false; }) : [];
  10589. allManifestWeightNames = [];
  10590. manifest.forEach(function (manifestGroupConfig, groupIndex) {
  10591. var groupOffset = 0;
  10592. manifestGroupConfig.weights.forEach(function (weightsEntry) {
  10593. var rawDtype = ('quantization' in weightsEntry) ?
  10594. weightsEntry.quantization.dtype :
  10595. weightsEntry.dtype;
  10596. var weightsBytes = types_1.DTYPE_VALUE_SIZE_MAP[rawDtype] *
  10597. util.sizeFromShape(weightsEntry.shape);
  10598. var enqueueWeightsForFetchingFn = function () {
  10599. groupIndicesToFetchMap[groupIndex] = true;
  10600. if (groupWeightsToFetch[groupIndex] == null) {
  10601. groupWeightsToFetch[groupIndex] = [];
  10602. }
  10603. groupWeightsToFetch[groupIndex].push({
  10604. manifestEntry: weightsEntry,
  10605. groupOffset: groupOffset,
  10606. sizeBytes: weightsBytes
  10607. });
  10608. };
  10609. if (weightNames != null) {
  10610. weightNames.forEach(function (weightName, weightIndex) {
  10611. if (weightName === weightsEntry.name) {
  10612. enqueueWeightsForFetchingFn();
  10613. weightsFound[weightIndex] = true;
  10614. }
  10615. });
  10616. }
  10617. else {
  10618. enqueueWeightsForFetchingFn();
  10619. }
  10620. allManifestWeightNames.push(weightsEntry.name);
  10621. groupOffset += weightsBytes;
  10622. });
  10623. });
  10624. if (!weightsFound.every(function (found) { return found; })) {
  10625. weightsNotFound = weightNames.filter(function (weight, i) { return !weightsFound[i]; });
  10626. throw new Error("Could not find weights in manifest with names: " +
  10627. (weightsNotFound.join(', ') + ". \n") +
  10628. "Manifest JSON has weights with names: " +
  10629. (allManifestWeightNames.join(', ') + "."));
  10630. }
  10631. groupIndicesToFetch = groupIndicesToFetchMap.reduce(function (accumulator, shouldFetch, i) {
  10632. if (shouldFetch) {
  10633. accumulator.push(i);
  10634. }
  10635. return accumulator;
  10636. }, []);
  10637. fetchUrls = [];
  10638. groupIndicesToFetch.forEach(function (i) {
  10639. manifest[i].paths.forEach(function (filepath) {
  10640. var fetchUrl = filePathPrefix +
  10641. (!filePathPrefix.endsWith('/') ? '/' : '') + filepath;
  10642. fetchUrls.push(fetchUrl);
  10643. });
  10644. });
  10645. return [4, loadWeightsAsArrayBuffer(fetchUrls, requestOptions)];
  10646. case 1:
  10647. buffers = _a.sent();
  10648. weightsTensorMap = {};
  10649. bufferIndexOffset = 0;
  10650. groupIndicesToFetch.forEach(function (i) {
  10651. var numBuffers = manifest[i].paths.length;
  10652. var groupBytes = 0;
  10653. for (var i_1 = 0; i_1 < numBuffers; i_1++) {
  10654. groupBytes += buffers[bufferIndexOffset + i_1].byteLength;
  10655. }
  10656. var groupBuffer = new ArrayBuffer(groupBytes);
  10657. var groupByteBuffer = new Uint8Array(groupBuffer);
  10658. var groupBufferOffset = 0;
  10659. for (var i_2 = 0; i_2 < numBuffers; i_2++) {
  10660. var buffer = new Uint8Array(buffers[bufferIndexOffset + i_2]);
  10661. groupByteBuffer.set(buffer, groupBufferOffset);
  10662. groupBufferOffset += buffer.byteLength;
  10663. }
  10664. var weightsEntries = groupWeightsToFetch[i];
  10665. weightsEntries.forEach(function (weightsEntry) {
  10666. var byteBuffer = groupBuffer.slice(weightsEntry.groupOffset, weightsEntry.groupOffset + weightsEntry.sizeBytes);
  10667. var typedArray;
  10668. var dtype = weightsEntry.manifestEntry.dtype;
  10669. if ('quantization' in weightsEntry.manifestEntry) {
  10670. var quantization_1 = weightsEntry.manifestEntry.quantization;
  10671. if (quantization_1.dtype !== 'uint8' && quantization_1.dtype !== 'uint16') {
  10672. throw new Error("Weight " + weightsEntry.manifestEntry.name + " has unknown " +
  10673. ("quantization dtype " + quantization_1.dtype + "."));
  10674. }
  10675. var quantizedArray = (quantization_1.dtype === 'uint8') ?
  10676. new Uint8Array(byteBuffer) :
  10677. new Uint16Array(byteBuffer);
  10678. if (dtype === 'float32') {
  10679. typedArray = Float32Array.from(quantizedArray, function (v) { return v * quantization_1.scale + quantization_1.min; });
  10680. }
  10681. else if (dtype === 'int32') {
  10682. typedArray = Int32Array.from(quantizedArray, function (v) { return Math.round(v * quantization_1.scale + quantization_1.min); });
  10683. }
  10684. else {
  10685. throw new Error("Weight " + weightsEntry.manifestEntry.name + " has a dtype not " +
  10686. ("supported by quantization: " + dtype));
  10687. }
  10688. }
  10689. else {
  10690. if (dtype === 'float32') {
  10691. typedArray = new Float32Array(byteBuffer);
  10692. }
  10693. else if (dtype === 'int32') {
  10694. typedArray = new Int32Array(byteBuffer);
  10695. }
  10696. else {
  10697. throw new Error("Weight " + weightsEntry.manifestEntry.name + " has unknown dtype " +
  10698. (dtype + "."));
  10699. }
  10700. }
  10701. var weightName = weightsEntry.manifestEntry.name;
  10702. if (weightsTensorMap[weightName] != null) {
  10703. throw new Error("Duplicate weight with name " + weightName + ". " +
  10704. "Please make sure weights names are unique in the manifest JSON.");
  10705. }
  10706. weightsTensorMap[weightName] = ops_1.tensor(typedArray, weightsEntry.manifestEntry.shape, weightsEntry.manifestEntry.dtype);
  10707. });
  10708. bufferIndexOffset += numBuffers;
  10709. });
  10710. return [2, weightsTensorMap];
  10711. }
  10712. });
  10713. });
  10714. }
  10715. exports.loadWeights = loadWeights;
  10716. },{"../ops/ops":129,"../util":164,"./types":63}],65:[function(require,module,exports){
  10717. "use strict";
  10718. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  10719. return new (P || (P = Promise))(function (resolve, reject) {
  10720. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10721. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  10722. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  10723. step((generator = generator.apply(thisArg, _arguments || [])).next());
  10724. });
  10725. };
  10726. var __generator = (this && this.__generator) || function (thisArg, body) {
  10727. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  10728. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  10729. function verb(n) { return function (v) { return step([n, v]); }; }
  10730. function step(op) {
  10731. if (f) throw new TypeError("Generator is already executing.");
  10732. while (_) try {
  10733. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  10734. if (y = 0, t) op = [0, t.value];
  10735. switch (op[0]) {
  10736. case 0: case 1: t = op; break;
  10737. case 4: _.label++; return { value: op[1], done: false };
  10738. case 5: _.label++; y = op[1]; op = [0]; continue;
  10739. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  10740. default:
  10741. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  10742. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  10743. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  10744. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  10745. if (t[2]) _.ops.pop();
  10746. _.trys.pop(); continue;
  10747. }
  10748. op = body.call(thisArg, _);
  10749. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  10750. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  10751. }
  10752. };
  10753. Object.defineProperty(exports, "__esModule", { value: true });
  10754. var seedrandom = require("seedrandom");
  10755. var environment_1 = require("../environment");
  10756. var axis_util = require("../ops/axis_util");
  10757. var broadcast_util = require("../ops/broadcast_util");
  10758. var concat_util = require("../ops/concat_util");
  10759. var erf_util = require("../ops/erf_util");
  10760. var ops = require("../ops/ops");
  10761. var ops_1 = require("../ops/ops");
  10762. var selu_util = require("../ops/selu_util");
  10763. var slice_util_1 = require("../ops/slice_util");
  10764. var tensor_1 = require("../tensor");
  10765. var types = require("../types");
  10766. var util = require("../util");
  10767. var backend_util = require("./backend_util");
  10768. var MathBackendCPU = (function () {
  10769. function MathBackendCPU() {
  10770. this.data = new WeakMap();
  10771. this.firstUse = true;
  10772. if (environment_1.ENV.get('IS_BROWSER')) {
  10773. this.canvas = document.createElement('canvas');
  10774. }
  10775. }
  10776. MathBackendCPU.prototype.register = function (dataId, shape, dtype) {
  10777. if (this.firstUse) {
  10778. this.firstUse = false;
  10779. if (environment_1.ENV.get('IS_NODE')) {
  10780. console.warn('\n============================\n' +
  10781. 'Hi there 👋. Looks like you are running TensorFlow.js in ' +
  10782. 'Node.js. To speed things up dramatically, install our node ' +
  10783. 'backend, which binds to TensorFlow C++, by running ' +
  10784. 'npm i @tensorflow/tfjs-node, ' +
  10785. 'or npm i @tensorflow/tfjs-node-gpu if you have CUDA. ' +
  10786. 'Then call require(\'tensorflow/tfjs-node\'); (-gpu ' +
  10787. 'suffix for CUDA) at the start of your program. ' +
  10788. 'Visit https://github.com/tensorflow/tfjs-node for more details.' +
  10789. '\n============================\n');
  10790. }
  10791. }
  10792. if (this.data.has(dataId)) {
  10793. throw new Error("Data buffer is already registered");
  10794. }
  10795. this.data.set(dataId, null);
  10796. };
  10797. MathBackendCPU.prototype.write = function (dataId, values) {
  10798. if (values == null) {
  10799. throw new Error('MathBackendCPU.write(): values can not be null');
  10800. }
  10801. this.throwIfNoData(dataId);
  10802. this.data.set(dataId, values);
  10803. };
  10804. MathBackendCPU.prototype.fromPixels = function (pixels, numChannels) {
  10805. if (pixels == null) {
  10806. throw new Error('MathBackendCPU.writePixels(): pixels can not be null');
  10807. }
  10808. var vals;
  10809. if (pixels instanceof ImageData) {
  10810. vals = pixels.data;
  10811. }
  10812. else if (pixels instanceof HTMLCanvasElement) {
  10813. vals = pixels.getContext('2d')
  10814. .getImageData(0, 0, pixels.width, pixels.height)
  10815. .data;
  10816. }
  10817. else if (pixels instanceof HTMLImageElement ||
  10818. pixels instanceof HTMLVideoElement) {
  10819. if (this.canvas == null) {
  10820. throw new Error('Can\'t read pixels from HTMLImageElement outside ' +
  10821. 'the browser.');
  10822. }
  10823. this.canvas.width = pixels.width;
  10824. this.canvas.height = pixels.height;
  10825. this.canvas.getContext('2d').drawImage(pixels, 0, 0, pixels.width, pixels.height);
  10826. vals = this.canvas.getContext('2d')
  10827. .getImageData(0, 0, pixels.width, pixels.height)
  10828. .data;
  10829. }
  10830. else {
  10831. throw new Error("pixels is of unknown type: " + pixels.constructor.name);
  10832. }
  10833. var values;
  10834. if (numChannels === 4) {
  10835. values = new Int32Array(vals);
  10836. }
  10837. else {
  10838. var numPixels = pixels.width * pixels.height;
  10839. values = new Int32Array(numPixels * numChannels);
  10840. for (var i = 0; i < numPixels; i++) {
  10841. for (var channel = 0; channel < numChannels; ++channel) {
  10842. values[i * numChannels + channel] = vals[i * 4 + channel];
  10843. }
  10844. }
  10845. }
  10846. var outShape = [pixels.height, pixels.width, numChannels];
  10847. return ops_1.tensor3d(values, outShape, 'int32');
  10848. };
  10849. MathBackendCPU.prototype.read = function (dataId) {
  10850. return __awaiter(this, void 0, void 0, function () {
  10851. return __generator(this, function (_a) {
  10852. return [2, this.readSync(dataId)];
  10853. });
  10854. });
  10855. };
  10856. MathBackendCPU.prototype.readSync = function (dataId) {
  10857. this.throwIfNoData(dataId);
  10858. return this.data.get(dataId);
  10859. };
  10860. MathBackendCPU.prototype.disposeData = function (dataId) {
  10861. if (this.data.has(dataId)) {
  10862. this.data.delete(dataId);
  10863. }
  10864. };
  10865. MathBackendCPU.prototype.time = function (f) {
  10866. return __awaiter(this, void 0, void 0, function () {
  10867. var start, kernelMs;
  10868. return __generator(this, function (_a) {
  10869. start = performance.now();
  10870. f();
  10871. kernelMs = performance.now() - start;
  10872. return [2, { kernelMs: kernelMs }];
  10873. });
  10874. });
  10875. };
  10876. MathBackendCPU.prototype.memory = function () {
  10877. return {
  10878. unreliable: true
  10879. };
  10880. };
  10881. MathBackendCPU.prototype.throwIfNoData = function (dataId) {
  10882. if (!this.data.has(dataId)) {
  10883. throw new Error("CPU backend: No data found for this tensor. " +
  10884. "Did you change your backend in the middle of the program? " +
  10885. "New backends can't use Tensors created with previous backends");
  10886. }
  10887. };
  10888. MathBackendCPU.prototype.slice = function (x, begin, size) {
  10889. var buffer = ops.buffer(size, x.dtype);
  10890. for (var i = 0; i < buffer.size; ++i) {
  10891. var loc = buffer.indexToLoc(i);
  10892. var xLoc = loc.map(function (idx, j) { return idx + begin[j]; });
  10893. buffer.set.apply(buffer, [x.get.apply(x, xLoc)].concat(loc));
  10894. }
  10895. return buffer.toTensor();
  10896. };
  10897. MathBackendCPU.prototype.stridedSlice = function (x, begin, end, strides, beginMask, endMask) {
  10898. var _a = slice_util_1.getStridedSlicedInfo(x.shape, begin, end, strides, beginMask, endMask), beginIndex = _a[0], size = _a[1];
  10899. if (size.some(function (axis) { return axis === 0; })) {
  10900. return ops.tensor([], size);
  10901. }
  10902. var buffer = ops.buffer(size, x.dtype);
  10903. for (var i = 0; i < buffer.size; i++) {
  10904. var loc = buffer.indexToLoc(i);
  10905. var newLoc = new Array(loc.length);
  10906. for (var j = 0; j < newLoc.length; j++) {
  10907. newLoc[j] = loc[j] * strides[j] + beginIndex[j];
  10908. }
  10909. buffer.set.apply(buffer, [x.get.apply(x, newLoc)].concat(loc));
  10910. }
  10911. return buffer.toTensor();
  10912. };
  10913. MathBackendCPU.prototype.reverse = function (x, axis) {
  10914. var buffer = ops.buffer(x.shape, x.dtype);
  10915. var xBuffer = x.buffer();
  10916. var _loop_1 = function (i) {
  10917. var outLoc = buffer.indexToLoc(i);
  10918. var inLoc = outLoc.slice();
  10919. axis.forEach(function (ax) { return inLoc[ax] = x.shape[ax] - 1 - inLoc[ax]; });
  10920. buffer.set.apply(buffer, [xBuffer.get.apply(xBuffer, inLoc)].concat(outLoc));
  10921. };
  10922. for (var i = 0; i < buffer.size; i++) {
  10923. _loop_1(i);
  10924. }
  10925. return buffer.toTensor();
  10926. };
  10927. MathBackendCPU.prototype.concat = function (a, b) {
  10928. var outShape = concat_util.computeOutShape(a.shape, b.shape, 1);
  10929. var buffer = ops.buffer(outShape, a.dtype);
  10930. if (a.shape[0] === 1 && b.shape[0] === 1) {
  10931. var aVals = a.dataSync();
  10932. var bVals = b.dataSync();
  10933. var vals = buffer.values;
  10934. vals.set(aVals, 0);
  10935. vals.set(bVals, a.size);
  10936. return buffer.toTensor();
  10937. }
  10938. for (var i = 0; i < outShape[0]; ++i) {
  10939. for (var j = 0; j < a.shape[1]; ++j) {
  10940. buffer.set(a.get(i, j), i, j);
  10941. }
  10942. for (var j = 0; j < b.shape[1]; ++j) {
  10943. buffer.set(b.get(i, j), i, j + a.shape[1]);
  10944. }
  10945. }
  10946. return buffer.toTensor();
  10947. };
  10948. MathBackendCPU.prototype.neg = function (x) {
  10949. return this.multiply(ops.scalar(-1), x);
  10950. };
  10951. MathBackendCPU.prototype.add = function (a, b) {
  10952. return this.broadcastedBinaryOp(a, b, types.upcastType(a.dtype, b.dtype), function (aValue, bValue) { return aValue + bValue; });
  10953. };
  10954. MathBackendCPU.prototype.subtract = function (a, b) {
  10955. return this.broadcastedBinaryOp(a, b, types.upcastType(a.dtype, b.dtype), function (aValue, bValue) { return aValue - bValue; });
  10956. };
  10957. MathBackendCPU.prototype.pow = function (a, b) {
  10958. return this.broadcastedBinaryOp(a, b, a.dtype, function (aValue, bValue) { return Math.pow(aValue, bValue); });
  10959. };
  10960. MathBackendCPU.prototype.matMul = function (a, b, transposeA, transposeB) {
  10961. var sharedDim = transposeA ? a.shape[0] : a.shape[1];
  10962. var leftDim = transposeA ? a.shape[1] : a.shape[0];
  10963. var rightDim = transposeB ? b.shape[0] : b.shape[1];
  10964. var aValues = a.dataSync();
  10965. var bValues = b.dataSync();
  10966. var _a = transposeA ? [1, a.strides[0]] : [a.strides[0], 1], aOuterStep = _a[0], aInnerStep = _a[1];
  10967. var _b = transposeB ? [b.strides[0], 1] : [1, b.strides[0]], bOuterStep = _b[0], bInnerStep = _b[1];
  10968. var aOuterEnd = leftDim * aOuterStep;
  10969. var bOuterEnd = rightDim * bOuterStep;
  10970. var result = new Float32Array(leftDim * rightDim);
  10971. var resultIndex = 0;
  10972. for (var aOuter = 0; aOuter < aOuterEnd; aOuter += aOuterStep) {
  10973. for (var bOuter = 0; bOuter < bOuterEnd; bOuter += bOuterStep) {
  10974. var aInner = aOuter;
  10975. var bInner = bOuter;
  10976. var sum = 0;
  10977. for (var k = 0; k < sharedDim; ++k) {
  10978. sum += aValues[aInner] * bValues[bInner];
  10979. aInner += aInnerStep;
  10980. bInner += bInnerStep;
  10981. }
  10982. result[resultIndex++] = sum;
  10983. }
  10984. }
  10985. return ops.tensor2d(result, [leftDim, rightDim]);
  10986. };
  10987. MathBackendCPU.prototype.multiply = function (a, b) {
  10988. return this.broadcastedBinaryOp(a, b, types.upcastType(a.dtype, b.dtype), function (aValue, bValue) { return aValue * bValue; });
  10989. };
  10990. MathBackendCPU.prototype.realDivide = function (a, b) {
  10991. var op = function (a, b) { return a / b; };
  10992. var outputDtype = 'float32';
  10993. return this.broadcastedBinaryOp(a, b, outputDtype, op);
  10994. };
  10995. MathBackendCPU.prototype.floorDiv = function (a, b) {
  10996. var op = function (a, b) { return Math.floor(a / b); };
  10997. var outputDtype = 'int32';
  10998. return this.broadcastedBinaryOp(a, b, outputDtype, op);
  10999. };
  11000. MathBackendCPU.prototype.sum = function (x, axes) {
  11001. axis_util.assertAxesAreInnerMostDims('sum', axes, x.rank);
  11002. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  11003. var resultDtype = types.upcastType(x.dtype, 'int32');
  11004. var result = ops.zeros(outShape, resultDtype);
  11005. var reduceSize = util.sizeFromShape(reduceShape);
  11006. var vals = result.dataSync();
  11007. var aVals = x.dataSync();
  11008. for (var i = 0; i < vals.length; ++i) {
  11009. var offset = i * reduceSize;
  11010. var sum = 0;
  11011. for (var j = 0; j < reduceSize; ++j) {
  11012. sum += aVals[offset + j];
  11013. }
  11014. vals[i] = sum;
  11015. }
  11016. return result;
  11017. };
  11018. MathBackendCPU.prototype.unsortedSegmentSum = function (x, segmentIds, numSegments) {
  11019. var res = [];
  11020. var numIters = x.rank - segmentIds.rank;
  11021. for (var i = 0; i < numIters; ++i) {
  11022. segmentIds = segmentIds.expandDims(i + 1);
  11023. }
  11024. for (var i = 0; i < numSegments; ++i) {
  11025. var segmentId = ops.scalar(i, 'int32');
  11026. var mask = ops.equal(segmentId, segmentIds).asType('float32');
  11027. var sum = mask.mul(x).sum(0);
  11028. res.push(sum);
  11029. }
  11030. return ops.stack(res);
  11031. };
  11032. MathBackendCPU.prototype.argMin = function (x, axis) {
  11033. var axes = [axis];
  11034. axis_util.assertAxesAreInnerMostDims('argMin', axes, x.rank);
  11035. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  11036. var result = ops.zeros(outShape, 'int32');
  11037. var reduceSize = util.sizeFromShape(reduceShape);
  11038. var vals = result.dataSync();
  11039. var aVals = x.dataSync();
  11040. for (var i = 0; i < vals.length; ++i) {
  11041. var offset = i * reduceSize;
  11042. var min = aVals[offset];
  11043. var minIndex = 0;
  11044. for (var j = 0; j < reduceSize; ++j) {
  11045. var value = aVals[offset + j];
  11046. if (value < min) {
  11047. min = value;
  11048. minIndex = j;
  11049. }
  11050. }
  11051. vals[i] = minIndex;
  11052. }
  11053. return result;
  11054. };
  11055. MathBackendCPU.prototype.argMax = function (x, axis) {
  11056. var axes = [axis];
  11057. axis_util.assertAxesAreInnerMostDims('argMax', axes, x.rank);
  11058. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  11059. var result = ops.zeros(outShape, 'int32');
  11060. var reduceSize = util.sizeFromShape(reduceShape);
  11061. var vals = result.dataSync();
  11062. var aVals = x.dataSync();
  11063. for (var i = 0; i < vals.length; ++i) {
  11064. var offset = i * reduceSize;
  11065. var max = aVals[offset];
  11066. var maxIndex = 0;
  11067. for (var j = 0; j < reduceSize; ++j) {
  11068. var value = aVals[offset + j];
  11069. if (value > max) {
  11070. max = value;
  11071. maxIndex = j;
  11072. }
  11073. }
  11074. vals[i] = maxIndex;
  11075. }
  11076. return result;
  11077. };
  11078. MathBackendCPU.prototype.cumsum = function (x, axis, exclusive, reverse) {
  11079. if (axis !== x.rank - 1) {
  11080. throw new Error("backend.cumsum in CPU expects an inner-most axis=" + (x.rank - 1) + " " +
  11081. ("but got axis=" + axis));
  11082. }
  11083. var resultDtype = types.upcastType(x.dtype, 'int32');
  11084. var result = ops.zeros(x.shape, resultDtype);
  11085. var vals = result.dataSync();
  11086. var aVals = x.dataSync();
  11087. var finalDim = x.shape[x.rank - 1];
  11088. var indexAdjuster = reverse ?
  11089. function (i, j) { return i + finalDim - j - 1; } :
  11090. function (i, j) { return i + j; };
  11091. for (var i = 0; i < aVals.length; i += finalDim) {
  11092. for (var j = 0; j < finalDim; j++) {
  11093. var idx = indexAdjuster(i, j);
  11094. if (j === 0) {
  11095. vals[idx] = exclusive ? 0 : aVals[idx];
  11096. }
  11097. else {
  11098. var prevIdx = indexAdjuster(i, j - 1);
  11099. vals[idx] = exclusive ? aVals[prevIdx] + vals[prevIdx] :
  11100. aVals[idx] + vals[prevIdx];
  11101. }
  11102. }
  11103. }
  11104. return result;
  11105. };
  11106. MathBackendCPU.prototype.equal = function (a, b) {
  11107. return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
  11108. return (aVal === bVal) ? 1 : 0;
  11109. });
  11110. };
  11111. MathBackendCPU.prototype.notEqual = function (a, b) {
  11112. return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
  11113. return (aVal !== bVal) ? 1 : 0;
  11114. });
  11115. };
  11116. MathBackendCPU.prototype.less = function (a, b) {
  11117. return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
  11118. return (aVal < bVal) ? 1 : 0;
  11119. });
  11120. };
  11121. MathBackendCPU.prototype.lessEqual = function (a, b) {
  11122. return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
  11123. return (aVal <= bVal) ? 1 : 0;
  11124. });
  11125. };
  11126. MathBackendCPU.prototype.greater = function (a, b) {
  11127. return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
  11128. return (aVal > bVal) ? 1 : 0;
  11129. });
  11130. };
  11131. MathBackendCPU.prototype.greaterEqual = function (a, b) {
  11132. return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
  11133. return (aVal >= bVal) ? 1 : 0;
  11134. });
  11135. };
  11136. MathBackendCPU.prototype.logicalNot = function (x) {
  11137. var values = x.dataSync();
  11138. var newValues = new Int32Array(values.length);
  11139. for (var i = 0; i < values.length; ++i) {
  11140. newValues[i] = values[i] ? 0 : 1;
  11141. }
  11142. return tensor_1.Tensor.make(x.shape, { values: newValues }, 'bool');
  11143. };
  11144. MathBackendCPU.prototype.logicalAnd = function (a, b) {
  11145. return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
  11146. return aVal && bVal;
  11147. });
  11148. };
  11149. MathBackendCPU.prototype.logicalOr = function (a, b) {
  11150. return this.broadcastedBinaryOp(a, b, 'bool', function (aVal, bVal) {
  11151. return aVal || bVal;
  11152. });
  11153. };
  11154. MathBackendCPU.prototype.where = function (condition, a, b, dtype) {
  11155. var values = condition.dataSync();
  11156. var aValues = a.dataSync();
  11157. var bValues = b.dataSync();
  11158. var result = ops.zeros(a.shape, dtype);
  11159. var newValues = result.dataSync();
  11160. var index = 0;
  11161. var offset = condition.rank === 0 || condition.rank > 1 || a.rank === 1 ?
  11162. 1 :
  11163. a.shape[1];
  11164. for (var i = 0; i < values.length; i++) {
  11165. for (var j = 0; j < offset; j++) {
  11166. if (values[i] === 1) {
  11167. newValues[index++] = aValues[i];
  11168. }
  11169. else {
  11170. newValues[index++] = bValues[i];
  11171. }
  11172. }
  11173. }
  11174. return result;
  11175. };
  11176. MathBackendCPU.prototype.topKValues = function (x, k) {
  11177. return this.topK(x, k).values;
  11178. };
  11179. MathBackendCPU.prototype.topKIndices = function (x, k) {
  11180. return this.topK(x, k).indices;
  11181. };
  11182. MathBackendCPU.prototype.topK = function (x, k) {
  11183. var values = x.dataSync();
  11184. var valuesAndIndices = [];
  11185. for (var i = 0; i < values.length; i++) {
  11186. valuesAndIndices.push({ value: values[i], index: i });
  11187. }
  11188. valuesAndIndices.sort(function (a, b) {
  11189. return b.value - a.value;
  11190. });
  11191. var topkValues = util.getTypedArrayFromDType(x.dtype, k);
  11192. var topkIndices = new Int32Array(k);
  11193. for (var i = 0; i < k; i++) {
  11194. topkValues[i] = valuesAndIndices[i].value;
  11195. topkIndices[i] = valuesAndIndices[i].index;
  11196. }
  11197. return {
  11198. values: ops.tensor1d(topkValues, x.dtype),
  11199. indices: ops.tensor1d(topkIndices, 'int32')
  11200. };
  11201. };
  11202. MathBackendCPU.prototype.min = function (x, axes) {
  11203. axis_util.assertAxesAreInnerMostDims('min', axes, x.rank);
  11204. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  11205. var result = ops.zeros(outShape, x.dtype);
  11206. var reduceSize = util.sizeFromShape(reduceShape);
  11207. var vals = result.dataSync();
  11208. var aVals = x.dataSync();
  11209. for (var i = 0; i < vals.length; ++i) {
  11210. var offset = i * reduceSize;
  11211. var min = aVals[offset];
  11212. for (var j = 0; j < reduceSize; ++j) {
  11213. var value = aVals[offset + j];
  11214. if (value < min) {
  11215. min = value;
  11216. }
  11217. }
  11218. vals[i] = min;
  11219. }
  11220. return result;
  11221. };
  11222. MathBackendCPU.prototype.minimum = function (a, b) {
  11223. return this.broadcastedBinaryOp(a, b, a.dtype, function (aVal, bVal) { return Math.min(aVal, bVal); });
  11224. };
  11225. MathBackendCPU.prototype.mod = function (a, b) {
  11226. return this.broadcastedBinaryOp(a, b, a.dtype, function (aVal, bVal) {
  11227. var rem = aVal % bVal;
  11228. if ((aVal < 0 && bVal < 0) || (aVal >= 0 && bVal >= 0)) {
  11229. return rem;
  11230. }
  11231. else {
  11232. return (rem + bVal) % bVal;
  11233. }
  11234. });
  11235. };
  11236. MathBackendCPU.prototype.max = function (x, axes) {
  11237. axis_util.assertAxesAreInnerMostDims('max', axes, x.rank);
  11238. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  11239. var result = ops.zeros(outShape, x.dtype);
  11240. var reduceSize = util.sizeFromShape(reduceShape);
  11241. var vals = result.dataSync();
  11242. var aVals = x.dataSync();
  11243. for (var i = 0; i < vals.length; ++i) {
  11244. var offset = i * reduceSize;
  11245. var max = aVals[offset];
  11246. for (var j = 0; j < reduceSize; ++j) {
  11247. var value = aVals[offset + j];
  11248. if (value > max) {
  11249. max = value;
  11250. }
  11251. }
  11252. vals[i] = max;
  11253. }
  11254. return result;
  11255. };
  11256. MathBackendCPU.prototype.maximum = function (a, b) {
  11257. return this.broadcastedBinaryOp(a, b, a.dtype, function (aVal, bVal) { return Math.max(aVal, bVal); });
  11258. };
  11259. MathBackendCPU.prototype.all = function (x, axes) {
  11260. axis_util.assertAxesAreInnerMostDims('all', axes, x.rank);
  11261. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  11262. var result = ops.zeros(outShape, x.dtype);
  11263. var reduceSize = util.sizeFromShape(reduceShape);
  11264. var vals = result.dataSync();
  11265. var aVals = x.dataSync();
  11266. for (var i = 0; i < vals.length; ++i) {
  11267. var offset = i * reduceSize;
  11268. var all = aVals[offset];
  11269. for (var j = 0; j < reduceSize; ++j) {
  11270. var value = aVals[offset + j];
  11271. all = all && value;
  11272. }
  11273. vals[i] = all;
  11274. }
  11275. return result;
  11276. };
  11277. MathBackendCPU.prototype.squaredDifference = function (a, b) {
  11278. return this.broadcastedBinaryOp(a, b, a.dtype, function (aVal, bVal) {
  11279. var diff = aVal - bVal;
  11280. return diff * diff;
  11281. });
  11282. };
  11283. MathBackendCPU.prototype.ceil = function (x) {
  11284. var values = x.dataSync();
  11285. var newValues = new Float32Array(values.length);
  11286. for (var i = 0; i < values.length; ++i) {
  11287. newValues[i] = Math.ceil(values[i]);
  11288. }
  11289. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11290. };
  11291. MathBackendCPU.prototype.floor = function (x) {
  11292. var values = x.dataSync();
  11293. var newValues = new Float32Array(values.length);
  11294. for (var i = 0; i < values.length; ++i) {
  11295. newValues[i] = Math.floor(values[i]);
  11296. }
  11297. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11298. };
  11299. MathBackendCPU.prototype.sign = function (x) {
  11300. var values = x.dataSync();
  11301. var newValues = new Float32Array(values.length);
  11302. for (var i = 0; i < values.length; ++i) {
  11303. if (values[i] < 0) {
  11304. newValues[i] = -1;
  11305. }
  11306. else if (values[i] > 0) {
  11307. newValues[i] = 1;
  11308. }
  11309. else {
  11310. newValues[i] = 0;
  11311. }
  11312. }
  11313. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11314. };
  11315. MathBackendCPU.prototype.round = function (x) {
  11316. var values = x.dataSync();
  11317. var newValues = new Float32Array(values.length);
  11318. for (var i = 0; i < values.length; ++i) {
  11319. var base = Math.floor(values[i]);
  11320. if (values[i] - base < 0.5) {
  11321. newValues[i] = Math.floor(values[i]);
  11322. }
  11323. else if (values[i] - base > 0.5) {
  11324. newValues[i] = Math.ceil(values[i]);
  11325. }
  11326. else {
  11327. if (base % 2.0 === 0.0) {
  11328. newValues[i] = base;
  11329. }
  11330. else {
  11331. newValues[i] = base + 1.0;
  11332. }
  11333. }
  11334. }
  11335. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11336. };
  11337. MathBackendCPU.prototype.exp = function (x) {
  11338. var values = x.dataSync();
  11339. var newValues = new Float32Array(values.length);
  11340. for (var i = 0; i < values.length; ++i) {
  11341. newValues[i] = Math.exp(values[i]);
  11342. }
  11343. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11344. };
  11345. MathBackendCPU.prototype.expm1 = function (x) {
  11346. var values = x.dataSync();
  11347. var newValues = new Float32Array(values.length);
  11348. for (var i = 0; i < values.length; ++i) {
  11349. newValues[i] = Math.expm1(values[i]);
  11350. }
  11351. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11352. };
  11353. MathBackendCPU.prototype.log = function (x) {
  11354. var values = x.dataSync();
  11355. var newValues = new Float32Array(values.length);
  11356. for (var i = 0; i < values.length; ++i) {
  11357. var value = values[i];
  11358. newValues[i] = Math.log(value);
  11359. }
  11360. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11361. };
  11362. MathBackendCPU.prototype.log1p = function (x) {
  11363. var values = x.dataSync();
  11364. var newValues = new Float32Array(values.length);
  11365. for (var i = 0; i < values.length; ++i) {
  11366. var value = values[i];
  11367. newValues[i] = Math.log1p(value);
  11368. }
  11369. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11370. };
  11371. MathBackendCPU.prototype.sqrt = function (x) {
  11372. var values = x.dataSync();
  11373. var newValues = new Float32Array(values.length);
  11374. for (var i = 0; i < values.length; ++i) {
  11375. var value = values[i];
  11376. newValues[i] = Math.sqrt(value);
  11377. }
  11378. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11379. };
  11380. MathBackendCPU.prototype.rsqrt = function (x) {
  11381. var values = x.dataSync();
  11382. var newValues = new Float32Array(values.length);
  11383. for (var i = 0; i < values.length; ++i) {
  11384. var value = values[i];
  11385. newValues[i] = 1 / Math.sqrt(value);
  11386. }
  11387. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11388. };
  11389. MathBackendCPU.prototype.square = function (x) {
  11390. var values = x.dataSync();
  11391. var newValues = new Float32Array(values.length);
  11392. for (var i = 0; i < values.length; ++i) {
  11393. var value = values[i];
  11394. newValues[i] = value * value;
  11395. }
  11396. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11397. };
  11398. MathBackendCPU.prototype.reciprocal = function (x) {
  11399. var values = x.dataSync();
  11400. var newValues = new Float32Array(values.length);
  11401. for (var i = 0; i < values.length; ++i) {
  11402. newValues[i] = 1 / values[i];
  11403. }
  11404. return tensor_1.Tensor.make(x.shape, { values: newValues });
  11405. };
  11406. MathBackendCPU.prototype.relu = function (x) {
  11407. var res = ops.zeros(x.shape, x.dtype);
  11408. var resVals = res.dataSync();
  11409. var inVals = x.dataSync();
  11410. for (var i = 0; i < inVals.length; ++i) {
  11411. resVals[i] = Math.max(0, inVals[i]);
  11412. }
  11413. return res;
  11414. };
  11415. MathBackendCPU.prototype.elu = function (x) {
  11416. var resultValues = new Float32Array(x.size);
  11417. var values = x.dataSync();
  11418. for (var i = 0; i < values.length; ++i) {
  11419. var v = values[i];
  11420. if (v >= 0) {
  11421. resultValues[i] = v;
  11422. }
  11423. else {
  11424. resultValues[i] = (Math.exp(v) - 1);
  11425. }
  11426. }
  11427. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11428. };
  11429. MathBackendCPU.prototype.eluDer = function (dy, y) {
  11430. var resultValues = new Float32Array(y.size);
  11431. var values = y.dataSync();
  11432. var dyValues = dy.dataSync();
  11433. for (var i = 0; i < values.length; ++i) {
  11434. var v = values[i];
  11435. if (v >= 1) {
  11436. resultValues[i] = dyValues[i];
  11437. }
  11438. else {
  11439. resultValues[i] = dyValues[i] * (v + 1);
  11440. }
  11441. }
  11442. return tensor_1.Tensor.make(y.shape, { values: resultValues });
  11443. };
  11444. MathBackendCPU.prototype.selu = function (x) {
  11445. var scaleAlpha = selu_util.SELU_SCALEALPHA;
  11446. var scale = selu_util.SELU_SCALE;
  11447. var resultValues = new Float32Array(x.size);
  11448. var values = x.dataSync();
  11449. for (var i = 0; i < values.length; ++i) {
  11450. var v = values[i];
  11451. if (v >= 0) {
  11452. resultValues[i] = scale * v;
  11453. }
  11454. else {
  11455. resultValues[i] = scaleAlpha * (Math.exp(v) - 1);
  11456. }
  11457. }
  11458. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11459. };
  11460. MathBackendCPU.prototype.clip = function (x, min, max) {
  11461. var resultValues = new Float32Array(x.size);
  11462. var values = x.dataSync();
  11463. for (var i = 0; i < values.length; ++i) {
  11464. resultValues[i] = Math.min(max, Math.max(min, values[i]));
  11465. }
  11466. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11467. };
  11468. MathBackendCPU.prototype.abs = function (x) {
  11469. var resultValues = new Float32Array(x.size);
  11470. var values = x.dataSync();
  11471. for (var i = 0; i < values.length; ++i) {
  11472. resultValues[i] = Math.abs(values[i]);
  11473. }
  11474. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11475. };
  11476. MathBackendCPU.prototype.int = function (x) {
  11477. var resultValues = new Int32Array(x.size);
  11478. var values = x.dataSync();
  11479. for (var i = 0; i < values.length; ++i) {
  11480. resultValues[i] = values[i];
  11481. }
  11482. return tensor_1.Tensor.make(x.shape, { values: resultValues }, 'int32');
  11483. };
  11484. MathBackendCPU.prototype.sigmoid = function (x) {
  11485. var resultValues = new Float32Array(x.size);
  11486. var values = x.dataSync();
  11487. for (var i = 0; i < values.length; ++i) {
  11488. resultValues[i] = 1 / (1 + Math.exp(-values[i]));
  11489. }
  11490. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11491. };
  11492. MathBackendCPU.prototype.softplus = function (x) {
  11493. var epsilon = 1.1920928955078125e-7;
  11494. var threshold = Math.log(epsilon) + 2.0;
  11495. var resultValues = new Float32Array(x.size);
  11496. var values = x.dataSync();
  11497. for (var i = 0; i < values.length; ++i) {
  11498. var tooLarge = values[i] > -threshold;
  11499. var tooSmall = values[i] < threshold;
  11500. var expX = Math.exp(values[i]);
  11501. var result = void 0;
  11502. if (tooSmall) {
  11503. result = expX;
  11504. }
  11505. else if (tooLarge) {
  11506. result = values[i];
  11507. }
  11508. else {
  11509. result = Math.log(1.0 + expX);
  11510. }
  11511. resultValues[i] = result;
  11512. }
  11513. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11514. };
  11515. MathBackendCPU.prototype.sin = function (x) {
  11516. var resultValues = new Float32Array(x.size);
  11517. var values = x.dataSync();
  11518. for (var i = 0; i < values.length; ++i) {
  11519. resultValues[i] = Math.sin(values[i]);
  11520. }
  11521. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11522. };
  11523. MathBackendCPU.prototype.cos = function (x) {
  11524. var resultValues = new Float32Array(x.size);
  11525. var values = x.dataSync();
  11526. for (var i = 0; i < values.length; ++i) {
  11527. resultValues[i] = Math.cos(values[i]);
  11528. }
  11529. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11530. };
  11531. MathBackendCPU.prototype.tan = function (x) {
  11532. var resultValues = new Float32Array(x.size);
  11533. var values = x.dataSync();
  11534. for (var i = 0; i < values.length; ++i) {
  11535. resultValues[i] = Math.tan(values[i]);
  11536. }
  11537. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11538. };
  11539. MathBackendCPU.prototype.asin = function (x) {
  11540. var resultValues = new Float32Array(x.size);
  11541. var values = x.dataSync();
  11542. for (var i = 0; i < values.length; ++i) {
  11543. resultValues[i] = Math.asin(values[i]);
  11544. }
  11545. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11546. };
  11547. MathBackendCPU.prototype.acos = function (x) {
  11548. var resultValues = new Float32Array(x.size);
  11549. var values = x.dataSync();
  11550. for (var i = 0; i < values.length; ++i) {
  11551. resultValues[i] = Math.acos(values[i]);
  11552. }
  11553. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11554. };
  11555. MathBackendCPU.prototype.atan = function (x) {
  11556. var resultValues = new Float32Array(x.size);
  11557. var values = x.dataSync();
  11558. for (var i = 0; i < values.length; ++i) {
  11559. resultValues[i] = Math.atan(values[i]);
  11560. }
  11561. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11562. };
  11563. MathBackendCPU.prototype.atan2 = function (a, b) {
  11564. return this.broadcastedBinaryOp(a, b, a.dtype, function (aValue, bValue) { return Math.atan2(aValue, bValue); });
  11565. };
  11566. MathBackendCPU.prototype.sinh = function (x) {
  11567. var resultValues = new Float32Array(x.size);
  11568. var values = x.dataSync();
  11569. for (var i = 0; i < values.length; ++i) {
  11570. resultValues[i] = Math.sinh(values[i]);
  11571. }
  11572. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11573. };
  11574. MathBackendCPU.prototype.cosh = function (x) {
  11575. var resultValues = new Float32Array(x.size);
  11576. var values = x.dataSync();
  11577. for (var i = 0; i < values.length; ++i) {
  11578. resultValues[i] = Math.cosh(values[i]);
  11579. }
  11580. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11581. };
  11582. MathBackendCPU.prototype.tanh = function (x) {
  11583. var resultValues = new Float32Array(x.size);
  11584. var values = x.dataSync();
  11585. for (var i = 0; i < values.length; ++i) {
  11586. resultValues[i] = util.tanh(values[i]);
  11587. }
  11588. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11589. };
  11590. MathBackendCPU.prototype.asinh = function (x) {
  11591. var resultValues = new Float32Array(x.size);
  11592. var values = x.dataSync();
  11593. for (var i = 0; i < values.length; ++i) {
  11594. resultValues[i] = Math.asinh(values[i]);
  11595. }
  11596. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11597. };
  11598. MathBackendCPU.prototype.acosh = function (x) {
  11599. var resultValues = new Float32Array(x.size);
  11600. var values = x.dataSync();
  11601. for (var i = 0; i < values.length; ++i) {
  11602. resultValues[i] = Math.acosh(values[i]);
  11603. }
  11604. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11605. };
  11606. MathBackendCPU.prototype.atanh = function (x) {
  11607. var resultValues = new Float32Array(x.size);
  11608. var values = x.dataSync();
  11609. for (var i = 0; i < values.length; ++i) {
  11610. resultValues[i] = Math.atanh(values[i]);
  11611. }
  11612. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11613. };
  11614. MathBackendCPU.prototype.erf = function (x) {
  11615. var resultValues = new Float32Array(x.size);
  11616. var values = x.dataSync();
  11617. var p = erf_util.ERF_P;
  11618. var a1 = erf_util.ERF_A1;
  11619. var a2 = erf_util.ERF_A2;
  11620. var a3 = erf_util.ERF_A3;
  11621. var a4 = erf_util.ERF_A4;
  11622. var a5 = erf_util.ERF_A5;
  11623. for (var i = 0; i < values.length; ++i) {
  11624. var v = values[i];
  11625. var t = 1.0 / (1.0 + p * v);
  11626. resultValues[i] = 1.0 -
  11627. (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t *
  11628. Math.exp(-v * v);
  11629. }
  11630. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11631. };
  11632. MathBackendCPU.prototype.step = function (x, alpha) {
  11633. if (alpha === void 0) { alpha = 0; }
  11634. var resultValues = new Float32Array(x.size);
  11635. var values = x.dataSync();
  11636. for (var i = 0; i < values.length; ++i) {
  11637. var value = values[i];
  11638. if (isNaN(value)) {
  11639. resultValues[i] = NaN;
  11640. }
  11641. else {
  11642. resultValues[i] = value > 0 ? 1 : alpha;
  11643. }
  11644. }
  11645. return tensor_1.Tensor.make(x.shape, { values: resultValues });
  11646. };
  11647. MathBackendCPU.prototype.conv2d = function (x, filter, convInfo) {
  11648. var filterHeight = convInfo.filterHeight;
  11649. var filterWidth = convInfo.filterWidth;
  11650. var dilationHeight = convInfo.dilationHeight;
  11651. var dilationWidth = convInfo.dilationWidth;
  11652. var padLeft = convInfo.padInfo.left;
  11653. var padTop = convInfo.padInfo.top;
  11654. var y = ops.buffer(convInfo.outShape, x.dtype);
  11655. for (var b = 0; b < convInfo.batchSize; ++b) {
  11656. for (var d2 = 0; d2 < convInfo.outChannels; ++d2) {
  11657. for (var yR = 0; yR < convInfo.outHeight; ++yR) {
  11658. var xRCorner = yR * convInfo.strideHeight - padLeft;
  11659. for (var yC = 0; yC < convInfo.outWidth; ++yC) {
  11660. var xCCorner = yC * convInfo.strideWidth - padTop;
  11661. var dotProd = 0;
  11662. for (var wR = 0; wR < filterHeight; wR++) {
  11663. var xR = xRCorner + wR * dilationHeight;
  11664. if (xR < 0 || xR >= convInfo.inHeight) {
  11665. continue;
  11666. }
  11667. for (var wC = 0; wC < filterWidth; wC++) {
  11668. var xC = xCCorner + wC * dilationWidth;
  11669. if (xC < 0 || xC >= convInfo.inWidth) {
  11670. continue;
  11671. }
  11672. for (var d1 = 0; d1 < convInfo.inChannels; ++d1) {
  11673. var pixel = x.get(b, xR, xC, d1);
  11674. var weight = filter.get(wR, wC, d1, d2);
  11675. dotProd += pixel * weight;
  11676. }
  11677. }
  11678. }
  11679. y.set(dotProd, b, yR, yC, d2);
  11680. }
  11681. }
  11682. }
  11683. }
  11684. return y.toTensor();
  11685. };
  11686. MathBackendCPU.prototype.conv2dDerInput = function (dy, filter, convInfo) {
  11687. var dx = ops.buffer(convInfo.inShape, 'float32');
  11688. var dxValues = dx.values;
  11689. var _a = dx.strides, dxS0 = _a[0], dxS1 = _a[1], dxS2 = _a[2];
  11690. var dyValues = dy.dataSync();
  11691. var _b = dy.strides, dyS0 = _b[0], dyS1 = _b[1], dyS2 = _b[2];
  11692. var fltValues = filter.dataSync();
  11693. var _c = filter.strides, fltS0 = _c[0], fltS1 = _c[1], fltS2 = _c[2];
  11694. var batchSize = convInfo.batchSize, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth, inChannels = convInfo.inChannels, inHeight = convInfo.inHeight, inWidth = convInfo.inWidth, outChannels = convInfo.outChannels, outHeight = convInfo.outHeight, outWidth = convInfo.outWidth, strideHeight = convInfo.strideHeight, strideWidth = convInfo.strideWidth;
  11695. var topPad = filterHeight - 1 - convInfo.padInfo.top;
  11696. var leftPad = filterWidth - 1 - convInfo.padInfo.left;
  11697. for (var b = 0; b < batchSize; ++b) {
  11698. for (var d1 = 0; d1 < inChannels; ++d1) {
  11699. for (var xR = 0; xR < inHeight; ++xR) {
  11700. var xRCorner = xR - topPad;
  11701. var xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));
  11702. var yRMax = Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);
  11703. for (var xC = 0; xC < inWidth; ++xC) {
  11704. var xCCorner = xC - leftPad;
  11705. var xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));
  11706. var yCMax = Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);
  11707. var dotProd = 0;
  11708. for (var yR = xRMin; yR < yRMax; ++yR) {
  11709. var wR = yR * strideHeight - xRCorner;
  11710. for (var yC = xCMin; yC < yCMax; ++yC) {
  11711. var wC = yC * strideWidth - xCCorner;
  11712. var dyOffset = dyS0 * b + dyS1 * yR + dyS2 * yC;
  11713. var fltOffset = fltS0 * (filterHeight - 1 - wR) +
  11714. fltS1 * (filterWidth - 1 - wC) + fltS2 * d1;
  11715. for (var d2 = 0; d2 < outChannels; ++d2) {
  11716. var pixel = dyValues[dyOffset + d2];
  11717. var weight = fltValues[fltOffset + d2];
  11718. dotProd += pixel * weight;
  11719. }
  11720. }
  11721. }
  11722. dxValues[dxS0 * b + dxS1 * xR + dxS2 * xC + d1] = dotProd;
  11723. }
  11724. }
  11725. }
  11726. }
  11727. return dx.toTensor();
  11728. };
  11729. MathBackendCPU.prototype.conv2dDerFilter = function (x, dy, convInfo) {
  11730. var strideHeight = convInfo.strideHeight;
  11731. var strideWidth = convInfo.strideWidth;
  11732. var filterHeight = convInfo.filterHeight;
  11733. var filterWidth = convInfo.filterWidth;
  11734. var dW = ops.buffer(convInfo.filterShape, 'float32');
  11735. var leftPad = convInfo.padInfo.left;
  11736. var topPad = convInfo.padInfo.top;
  11737. for (var wR = 0; wR < filterHeight; ++wR) {
  11738. var yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));
  11739. var yRMax = Math.min(convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);
  11740. for (var wC = 0; wC < filterWidth; ++wC) {
  11741. var yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));
  11742. var yCMax = Math.min(convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);
  11743. for (var d1 = 0; d1 < convInfo.inChannels; ++d1) {
  11744. for (var d2 = 0; d2 < convInfo.outChannels; ++d2) {
  11745. var dotProd = 0;
  11746. for (var b = 0; b < convInfo.batchSize; ++b) {
  11747. for (var yR = yRMin; yR < yRMax; ++yR) {
  11748. var xR = wR + yR * strideHeight - topPad;
  11749. for (var yC = yCMin; yC < yCMax; ++yC) {
  11750. var xC = wC + yC * strideWidth - leftPad;
  11751. dotProd += x.get(b, xR, xC, d1) * dy.get(b, yR, yC, d2);
  11752. }
  11753. }
  11754. }
  11755. dW.set(dotProd, wR, wC, d1, d2);
  11756. }
  11757. }
  11758. }
  11759. }
  11760. return dW.toTensor();
  11761. };
  11762. MathBackendCPU.prototype.depthwiseConv2D = function (x, filter, convInfo) {
  11763. var filterHeight = convInfo.filterHeight;
  11764. var filterWidth = convInfo.filterWidth;
  11765. var dilationHeight = convInfo.dilationHeight;
  11766. var dilationWidth = convInfo.dilationWidth;
  11767. var padLeft = convInfo.padInfo.left;
  11768. var padTop = convInfo.padInfo.top;
  11769. var chMul = convInfo.outChannels / convInfo.inChannels;
  11770. var y = ops.buffer(convInfo.outShape, x.dtype);
  11771. for (var b = 0; b < convInfo.batchSize; ++b) {
  11772. for (var d1 = 0; d1 < convInfo.inChannels; ++d1) {
  11773. for (var yR = 0; yR < convInfo.outHeight; ++yR) {
  11774. var xRCorner = yR * convInfo.strideHeight - padLeft;
  11775. for (var yC = 0; yC < convInfo.outWidth; ++yC) {
  11776. var xCCorner = yC * convInfo.strideWidth - padTop;
  11777. for (var q = 0; q < chMul; ++q) {
  11778. var dotProd = 0;
  11779. for (var wR = 0; wR < filterHeight; ++wR) {
  11780. var xR = xRCorner + wR * dilationHeight;
  11781. if (xR < 0 || xR >= convInfo.inHeight) {
  11782. continue;
  11783. }
  11784. for (var wC = 0; wC < filterWidth; ++wC) {
  11785. var xC = xCCorner + wC * dilationWidth;
  11786. if (xC < 0 || xC >= convInfo.inWidth) {
  11787. continue;
  11788. }
  11789. var pixel = x.get(b, xR, xC, d1);
  11790. var weight = filter.get(wR, wC, d1, q);
  11791. dotProd += pixel * weight;
  11792. }
  11793. }
  11794. y.set(dotProd, b, yR, yC, d1 * chMul + q);
  11795. }
  11796. }
  11797. }
  11798. }
  11799. }
  11800. return y.toTensor();
  11801. };
  11802. MathBackendCPU.prototype.depthwiseConv2DDerInput = function (dy, filter, convInfo) {
  11803. var dx = ops.buffer(convInfo.inShape, 'float32');
  11804. var dxValues = dx.values;
  11805. var _a = dx.strides, dxS0 = _a[0], dxS1 = _a[1], dxS2 = _a[2];
  11806. var dyValues = dy.dataSync();
  11807. var _b = dy.strides, dyS0 = _b[0], dyS1 = _b[1], dyS2 = _b[2];
  11808. var fltValues = filter.dataSync();
  11809. var _c = filter.strides, fltS0 = _c[0], fltS1 = _c[1], fltS2 = _c[2];
  11810. var batchSize = convInfo.batchSize, filterHeight = convInfo.filterHeight, filterWidth = convInfo.filterWidth, inChannels = convInfo.inChannels, inHeight = convInfo.inHeight, inWidth = convInfo.inWidth, outChannels = convInfo.outChannels, outHeight = convInfo.outHeight, outWidth = convInfo.outWidth, strideHeight = convInfo.strideHeight, strideWidth = convInfo.strideWidth;
  11811. var topPad = filterHeight - 1 - convInfo.padInfo.top;
  11812. var leftPad = filterWidth - 1 - convInfo.padInfo.left;
  11813. var chMul = outChannels / inChannels;
  11814. for (var b = 0; b < batchSize; ++b) {
  11815. for (var d1 = 0; d1 < inChannels; ++d1) {
  11816. for (var xR = 0; xR < inHeight; ++xR) {
  11817. var xRCorner = xR - topPad;
  11818. var xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));
  11819. var yRMax = Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);
  11820. for (var xC = 0; xC < inWidth; ++xC) {
  11821. var xCCorner = xC - leftPad;
  11822. var xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));
  11823. var yCMax = Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);
  11824. var dotProd = 0;
  11825. for (var yR = xRMin; yR < yRMax; ++yR) {
  11826. var wR = yR * strideHeight - xRCorner;
  11827. for (var yC = xCMin; yC < yCMax; ++yC) {
  11828. var wC = yC * strideWidth - xCCorner;
  11829. var dyOffset = dyS0 * b + dyS1 * yR + dyS2 * yC;
  11830. var fltOffset = fltS0 * (filterHeight - 1 - wR) +
  11831. fltS1 * (filterWidth - 1 - wC) + fltS2 * d1;
  11832. for (var dm = 0; dm < chMul; ++dm) {
  11833. var d2 = d1 * chMul + dm;
  11834. var pixel = dyValues[dyOffset + d2];
  11835. var weight = fltValues[fltOffset + dm];
  11836. dotProd += pixel * weight;
  11837. }
  11838. }
  11839. }
  11840. dxValues[dxS0 * b + dxS1 * xR + dxS2 * xC + d1] = dotProd;
  11841. }
  11842. }
  11843. }
  11844. }
  11845. return dx.toTensor();
  11846. };
  11847. MathBackendCPU.prototype.depthwiseConv2DDerFilter = function (x, dy, convInfo) {
  11848. var strideHeight = convInfo.strideHeight;
  11849. var strideWidth = convInfo.strideWidth;
  11850. var filterHeight = convInfo.filterHeight;
  11851. var filterWidth = convInfo.filterWidth;
  11852. var dW = ops.buffer(convInfo.filterShape, 'float32');
  11853. var leftPad = convInfo.padInfo.left;
  11854. var topPad = convInfo.padInfo.top;
  11855. var chMul = convInfo.outChannels / convInfo.inChannels;
  11856. for (var wR = 0; wR < filterHeight; ++wR) {
  11857. var yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));
  11858. var yRMax = Math.min(convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);
  11859. for (var wC = 0; wC < filterWidth; ++wC) {
  11860. var yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));
  11861. var yCMax = Math.min(convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);
  11862. for (var d2 = 0; d2 < convInfo.outChannels; ++d2) {
  11863. var d1 = Math.trunc(d2 / chMul);
  11864. var dm = d2 % chMul;
  11865. var dotProd = 0;
  11866. for (var b = 0; b < convInfo.batchSize; ++b) {
  11867. for (var yR = yRMin; yR < yRMax; ++yR) {
  11868. var xR = wR + yR * strideHeight - topPad;
  11869. for (var yC = yCMin; yC < yCMax; ++yC) {
  11870. var xC = wC + yC * strideWidth - leftPad;
  11871. dotProd += x.get(b, xR, xC, d1) * dy.get(b, yR, yC, d2);
  11872. }
  11873. }
  11874. }
  11875. dW.set(dotProd, wR, wC, d1, dm);
  11876. }
  11877. }
  11878. }
  11879. return dW.toTensor();
  11880. };
  11881. MathBackendCPU.prototype.tile = function (x, reps) {
  11882. var newShape = new Array(x.rank);
  11883. for (var i = 0; i < newShape.length; i++) {
  11884. newShape[i] = x.shape[i] * reps[i];
  11885. }
  11886. var result = ops.buffer(newShape, x.dtype);
  11887. var xBuf = x.buffer();
  11888. for (var i = 0; i < result.values.length; ++i) {
  11889. var newLoc = result.indexToLoc(i);
  11890. var originalLoc = new Array(x.rank);
  11891. for (var i_1 = 0; i_1 < originalLoc.length; i_1++) {
  11892. originalLoc[i_1] = newLoc[i_1] % x.shape[i_1];
  11893. }
  11894. var originalIndex = xBuf.locToIndex(originalLoc);
  11895. result.values[i] = xBuf.values[originalIndex];
  11896. }
  11897. return result.toTensor();
  11898. };
  11899. MathBackendCPU.prototype.pad = function (x, paddings, constantValue) {
  11900. var outShape = paddings.map(function (p, i) { return p[0] + x.shape[i] + p[1]; });
  11901. var start = paddings.map(function (p) { return p[0]; });
  11902. var xBuffer = x.buffer();
  11903. var buffer = ops.buffer(outShape, x.dtype);
  11904. if (constantValue !== 0) {
  11905. buffer.values.fill(constantValue);
  11906. }
  11907. for (var i = 0; i < x.size; i++) {
  11908. var coords = xBuffer.indexToLoc(i);
  11909. var outCoords = coords.map(function (c, i) { return c + start[i]; });
  11910. buffer.set.apply(buffer, [x.get.apply(x, coords)].concat(outCoords));
  11911. }
  11912. return buffer.toTensor();
  11913. };
  11914. MathBackendCPU.prototype.transpose = function (x, perm) {
  11915. var newShape = new Array(x.rank);
  11916. for (var i = 0; i < newShape.length; i++) {
  11917. newShape[i] = x.shape[perm[i]];
  11918. }
  11919. var values = x.dataSync();
  11920. var result = ops_1.buffer(newShape, x.dtype);
  11921. var xBuf = x.buffer();
  11922. for (var i = 0; i < x.size; ++i) {
  11923. var loc = xBuf.indexToLoc(i);
  11924. var newLoc = new Array(loc.length);
  11925. for (var i_2 = 0; i_2 < newLoc.length; i_2++) {
  11926. newLoc[i_2] = loc[perm[i_2]];
  11927. }
  11928. var newIndex = result.locToIndex(newLoc);
  11929. result.values[newIndex] = values[i];
  11930. }
  11931. return result.toTensor();
  11932. };
  11933. MathBackendCPU.prototype.gather = function (x, indices, axis) {
  11934. var newShape = x.shape.slice();
  11935. var indicesValues = indices.dataSync();
  11936. newShape[axis] = indicesValues.length;
  11937. var result = ops_1.buffer(newShape, x.dtype);
  11938. var xBuf = x.buffer();
  11939. for (var i = 0; i < result.size; ++i) {
  11940. var newLoc = result.indexToLoc(i);
  11941. var originalLoc = newLoc.slice();
  11942. originalLoc[axis] = indicesValues[newLoc[axis]];
  11943. var originalIndex = xBuf.locToIndex(originalLoc);
  11944. result.values[i] = xBuf.values[originalIndex];
  11945. }
  11946. return result.toTensor();
  11947. };
  11948. MathBackendCPU.prototype.pool = function (x, convInfo, poolType) {
  11949. var strideHeight = convInfo.strideHeight;
  11950. var strideWidth = convInfo.strideWidth;
  11951. var filterHeight = convInfo.filterHeight;
  11952. var filterWidth = convInfo.filterWidth;
  11953. var y = ops.buffer(convInfo.outShape, 'float32');
  11954. var padTop = convInfo.padInfo.top;
  11955. var padLeft = convInfo.padInfo.left;
  11956. for (var b = 0; b < convInfo.batchSize; ++b) {
  11957. for (var d = 0; d < convInfo.inChannels; ++d) {
  11958. for (var yR = 0; yR < convInfo.outHeight; ++yR) {
  11959. var xRCorner = yR * strideHeight - padTop;
  11960. var xRMin = Math.max(0, xRCorner);
  11961. var xRMax = Math.min(convInfo.inHeight, filterHeight + xRCorner);
  11962. for (var yC = 0; yC < convInfo.outWidth; ++yC) {
  11963. var xCCorner = yC * strideWidth - padLeft;
  11964. var xCMin = Math.max(0, xCCorner);
  11965. var xCMax = Math.min(convInfo.inWidth, filterWidth + xCCorner);
  11966. var minMaxValue = (poolType === 'max' ? Number.NEGATIVE_INFINITY :
  11967. Number.POSITIVE_INFINITY);
  11968. var avgValue = 0;
  11969. var count = 0;
  11970. for (var xR = xRMin; xR < xRMax; ++xR) {
  11971. for (var xC = xCMin; xC < xCMax; ++xC) {
  11972. var pixel = x.get(b, xR, xC, d);
  11973. if ((poolType === 'max' && pixel > minMaxValue)) {
  11974. minMaxValue = pixel;
  11975. }
  11976. else if (poolType === 'avg') {
  11977. avgValue += pixel;
  11978. count++;
  11979. }
  11980. }
  11981. if (isNaN(minMaxValue)) {
  11982. break;
  11983. }
  11984. }
  11985. y.set(poolType === 'avg' ? avgValue / count : minMaxValue, b, yR, yC, d);
  11986. }
  11987. }
  11988. }
  11989. }
  11990. return y.toTensor();
  11991. };
  11992. MathBackendCPU.prototype.maxPool = function (x, convInfo) {
  11993. return this.pool(x, convInfo, 'max');
  11994. };
  11995. MathBackendCPU.prototype.maxPoolPositions = function (x, convInfo) {
  11996. var maxPositions = ops.buffer(convInfo.outShape, 'int32');
  11997. var strideHeight = convInfo.strideHeight;
  11998. var strideWidth = convInfo.strideWidth;
  11999. var filterHeight = convInfo.filterHeight;
  12000. var filterWidth = convInfo.filterWidth;
  12001. var padTop = convInfo.padInfo.top;
  12002. var padLeft = convInfo.padInfo.left;
  12003. for (var b = 0; b < convInfo.batchSize; ++b) {
  12004. for (var d = 0; d < convInfo.inChannels; ++d) {
  12005. for (var yR = 0; yR < convInfo.outHeight; ++yR) {
  12006. var xRCorner = yR * strideHeight - padTop;
  12007. var xRMin = Math.max(0, xRCorner);
  12008. var xRMax = Math.min(convInfo.inHeight, filterHeight + xRCorner);
  12009. for (var yC = 0; yC < convInfo.outWidth; ++yC) {
  12010. var xCCorner = yC * strideWidth - padLeft;
  12011. var xCMin = Math.max(0, xCCorner);
  12012. var xCMax = Math.min(convInfo.inWidth, filterWidth + xCCorner);
  12013. var maxValue = Number.NEGATIVE_INFINITY;
  12014. var maxPosition = -1;
  12015. for (var xR = xRMin; xR < xRMax; ++xR) {
  12016. var wR = xR - xRCorner;
  12017. for (var xC = xCMin; xC < xCMax; ++xC) {
  12018. var wC = xC - xCCorner;
  12019. var pixel = x.get(b, xR, xC, d);
  12020. if (pixel > maxValue) {
  12021. maxValue = pixel;
  12022. maxPosition = wR * filterWidth + wC;
  12023. }
  12024. }
  12025. }
  12026. maxPositions.set(maxPosition, b, yR, yC, d);
  12027. }
  12028. }
  12029. }
  12030. }
  12031. return maxPositions.toTensor();
  12032. };
  12033. MathBackendCPU.prototype.maxPoolBackprop = function (dy, x, y, convInfo) {
  12034. var maxPositions = this.maxPoolPositions(x, convInfo);
  12035. var strideHeight = convInfo.strideHeight;
  12036. var strideWidth = convInfo.strideWidth;
  12037. var filterHeight = convInfo.filterHeight;
  12038. var filterWidth = convInfo.filterWidth;
  12039. var padLeft = filterWidth - 1 - convInfo.padInfo.left;
  12040. var padTop = filterHeight - 1 - convInfo.padInfo.top;
  12041. var dx = ops.buffer(x.shape, 'float32');
  12042. for (var b = 0; b < convInfo.batchSize; ++b) {
  12043. for (var d = 0; d < convInfo.inChannels; ++d) {
  12044. for (var dxR = 0; dxR < convInfo.inHeight; ++dxR) {
  12045. for (var dxC = 0; dxC < convInfo.inWidth; ++dxC) {
  12046. var dyRCorner = dxR - padTop;
  12047. var dyCCorner = dxC - padLeft;
  12048. var dotProd = 0;
  12049. for (var wR = 0; wR < filterHeight; ++wR) {
  12050. var dyR = (dyRCorner + wR) / strideHeight;
  12051. if (dyR < 0 || dyR >= convInfo.outHeight ||
  12052. Math.floor(dyR) !== dyR) {
  12053. continue;
  12054. }
  12055. for (var wC = 0; wC < filterWidth; ++wC) {
  12056. var dyC = (dyCCorner + wC) / strideWidth;
  12057. if (dyC < 0 || dyC >= convInfo.outWidth ||
  12058. Math.floor(dyC) !== dyC) {
  12059. continue;
  12060. }
  12061. var maxPos = filterHeight * filterWidth - 1 -
  12062. maxPositions.get(b, dyR, dyC, d);
  12063. var curPos = wR * filterWidth + wC;
  12064. var mask = maxPos === curPos ? 1 : 0;
  12065. if (mask === 0) {
  12066. continue;
  12067. }
  12068. var pixel = dy.get(b, dyR, dyC, d);
  12069. dotProd += pixel * mask;
  12070. }
  12071. }
  12072. dx.set(dotProd, b, dxR, dxC, d);
  12073. }
  12074. }
  12075. }
  12076. }
  12077. return dx.toTensor();
  12078. };
  12079. MathBackendCPU.prototype.avgPoolBackprop = function (dy, x, convInfo) {
  12080. var strideHeight = convInfo.strideHeight;
  12081. var strideWidth = convInfo.strideWidth;
  12082. var filterHeight = convInfo.filterHeight;
  12083. var filterWidth = convInfo.filterWidth;
  12084. var padLeft = filterWidth - 1 - convInfo.padInfo.left;
  12085. var padTop = filterHeight - 1 - convInfo.padInfo.top;
  12086. var dx = ops.buffer(x.shape, 'float32');
  12087. var avgMultiplier = 1 / (filterHeight * filterWidth);
  12088. for (var b = 0; b < convInfo.batchSize; ++b) {
  12089. for (var d = 0; d < convInfo.inChannels; ++d) {
  12090. for (var dxR = 0; dxR < convInfo.inHeight; ++dxR) {
  12091. for (var dxC = 0; dxC < convInfo.inWidth; ++dxC) {
  12092. var dyRCorner = dxR - padTop;
  12093. var dyCCorner = dxC - padLeft;
  12094. var dotProd = 0;
  12095. for (var wR = 0; wR < filterHeight; ++wR) {
  12096. var dyR = (dyRCorner + wR) / strideHeight;
  12097. if (dyR < 0 || dyR >= convInfo.outHeight ||
  12098. Math.floor(dyR) !== dyR) {
  12099. continue;
  12100. }
  12101. for (var wC = 0; wC < filterWidth; ++wC) {
  12102. var dyC = (dyCCorner + wC) / strideWidth;
  12103. if (dyC < 0 || dyC >= convInfo.outWidth ||
  12104. Math.floor(dyC) !== dyC) {
  12105. continue;
  12106. }
  12107. var pixel = dy.get(b, dyR, dyC, d);
  12108. dotProd += pixel;
  12109. }
  12110. }
  12111. dx.set(dotProd * avgMultiplier, b, dxR, dxC, d);
  12112. }
  12113. }
  12114. }
  12115. }
  12116. return dx.toTensor();
  12117. };
  12118. MathBackendCPU.prototype.cast = function (x, dtype) {
  12119. return backend_util.castTensor(x, dtype, this);
  12120. };
  12121. MathBackendCPU.prototype.reshape = function (x, shape) {
  12122. return backend_util.reshapeTensor(x, shape);
  12123. };
  12124. MathBackendCPU.prototype.avgPool = function (x, convInfo) {
  12125. return this.pool(x, convInfo, 'avg').toFloat();
  12126. };
  12127. MathBackendCPU.prototype.resizeBilinear = function (x, newHeight, newWidth, alignCorners) {
  12128. var _a = x.shape, batch = _a[0], oldHeight = _a[1], oldWidth = _a[2], numChannels = _a[3];
  12129. var output = ops.buffer([batch, newHeight, newWidth, numChannels], x.dtype);
  12130. var effectiveInputSize = [
  12131. (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,
  12132. (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth
  12133. ];
  12134. var effectiveOutputSize = [
  12135. (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,
  12136. (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth
  12137. ];
  12138. for (var b = 0; b < batch; b++) {
  12139. for (var r = 0; r < newHeight; r++) {
  12140. for (var c = 0; c < newWidth; c++) {
  12141. for (var d = 0; d < numChannels; d++) {
  12142. var sourceFracRow = (effectiveInputSize[0]) * r / (effectiveOutputSize[0]);
  12143. var sourceFracCol = (effectiveInputSize[1]) * c / (effectiveOutputSize[1]);
  12144. var sourceRowFloor = Math.floor(sourceFracRow);
  12145. var sourceRowCeil = Math.min(oldHeight - 1, Math.ceil(sourceFracRow));
  12146. var sourceColFloor = Math.floor(sourceFracCol);
  12147. var sourceColCeil = Math.min(oldWidth - 1, Math.ceil(sourceFracCol));
  12148. var topLeft = x.get(b, sourceRowFloor, sourceColFloor, d);
  12149. var bottomLeft = x.get(b, sourceRowCeil, sourceColFloor, d);
  12150. var topRight = x.get(b, sourceRowFloor, sourceColCeil, d);
  12151. var bottomRight = x.get(b, sourceRowCeil, sourceColCeil, d);
  12152. var rowFrac = sourceFracRow - sourceRowFloor;
  12153. var colFrac = sourceFracCol - sourceColFloor;
  12154. var top_1 = topLeft + (topRight - topLeft) * colFrac;
  12155. var bottom = bottomLeft + (bottomRight - bottomLeft) * colFrac;
  12156. var newValue = top_1 + (bottom - top_1) * rowFrac;
  12157. output.set(newValue, b, r, c, d);
  12158. }
  12159. }
  12160. }
  12161. }
  12162. return output.toTensor();
  12163. };
  12164. MathBackendCPU.prototype.resizeBilinearBackprop = function (dy, x, alignCorners) {
  12165. var _a = x.shape, batch = _a[0], xHeight = _a[1], xWidth = _a[2], depth = _a[3];
  12166. var _b = dy.shape, yHeight = _b[1], yWidth = _b[2];
  12167. var output = ops.buffer([batch, xHeight, xWidth, depth], x.dtype);
  12168. var effectiveXSize = [
  12169. (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,
  12170. (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth
  12171. ];
  12172. var effectiveYSize = [
  12173. (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,
  12174. (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth
  12175. ];
  12176. var heightScale = effectiveXSize[0] / effectiveYSize[0];
  12177. var widthScale = effectiveXSize[1] / effectiveYSize[1];
  12178. for (var b = 0; b < batch; b++) {
  12179. for (var r = 0; r < yHeight; r++) {
  12180. var dxR = r * heightScale;
  12181. var topDxRIndex = Math.floor(dxR);
  12182. var bottomDxRIndex = Math.min(Math.ceil(dxR), xHeight - 1);
  12183. var dxRLerp = dxR - topDxRIndex;
  12184. var inverseDxRLerp = 1.0 - dxRLerp;
  12185. for (var c = 0; c < yWidth; c++) {
  12186. var dxC = c * widthScale;
  12187. var leftDxCIndex = Math.floor(dxC);
  12188. var rightDxCIndex = Math.min(Math.ceil(dxC), xWidth - 1);
  12189. var dxCLerp = dxC - leftDxCIndex;
  12190. var inverseDxCLerp = 1.0 - dxCLerp;
  12191. for (var d = 0; d < depth; d++) {
  12192. var dyVal = dy.get(b, r, c, d);
  12193. var topLeft = output.get(b, topDxRIndex, leftDxCIndex, d);
  12194. topLeft += dyVal * inverseDxRLerp * inverseDxCLerp;
  12195. output.set(topLeft, b, topDxRIndex, leftDxCIndex, d);
  12196. var topRight = output.get(b, topDxRIndex, rightDxCIndex, d);
  12197. topRight += dyVal * inverseDxRLerp * dxCLerp;
  12198. output.set(topRight, b, topDxRIndex, rightDxCIndex, d);
  12199. var bottomLeft = output.get(b, bottomDxRIndex, leftDxCIndex, d);
  12200. bottomLeft += dyVal * dxRLerp * inverseDxCLerp;
  12201. output.set(bottomLeft, b, bottomDxRIndex, leftDxCIndex, d);
  12202. var bottomRight = output.get(b, bottomDxRIndex, rightDxCIndex, d);
  12203. bottomRight += dyVal * dxRLerp * dxCLerp;
  12204. output.set(bottomRight, b, bottomDxRIndex, rightDxCIndex, d);
  12205. }
  12206. }
  12207. }
  12208. }
  12209. return output.toTensor();
  12210. };
  12211. MathBackendCPU.prototype.resizeNearestNeighbor = function (x, newHeight, newWidth, alignCorners) {
  12212. var _a = x.shape, batch = _a[0], oldHeight = _a[1], oldWidth = _a[2], numChannels = _a[3];
  12213. var output = ops.buffer([batch, newHeight, newWidth, numChannels], x.dtype);
  12214. var effectiveInputSize = alignCorners ? [oldHeight - 1, oldWidth - 1] : [oldHeight, oldWidth];
  12215. var effectiveOutputSize = alignCorners ? [newHeight - 1, newWidth - 1] : [newHeight, newWidth];
  12216. for (var b = 0; b < batch; b++) {
  12217. for (var r = 0; r < newHeight; r++) {
  12218. for (var c = 0; c < newWidth; c++) {
  12219. for (var d = 0; d < numChannels; d++) {
  12220. var sourceFracRow = (effectiveInputSize[0]) * r / (effectiveOutputSize[0]);
  12221. var sourceFracCol = (effectiveInputSize[1]) * c / (effectiveOutputSize[1]);
  12222. var sourceNearestRow = Math.min(oldHeight - 1, alignCorners ? Math.round(sourceFracRow) :
  12223. Math.floor(sourceFracRow));
  12224. var sourceNearestCol = Math.min(oldWidth - 1, alignCorners ? Math.round(sourceFracCol) :
  12225. Math.floor(sourceFracCol));
  12226. var newValue = x.get(b, sourceNearestRow, sourceNearestCol, d);
  12227. output.set(newValue, b, r, c, d);
  12228. }
  12229. }
  12230. }
  12231. }
  12232. return output.toTensor();
  12233. };
  12234. MathBackendCPU.prototype.batchNormalization = function (x, mean, variance, varianceEpsilon, scale, offset) {
  12235. var xValues = x.dataSync();
  12236. var meanValues = mean.dataSync();
  12237. var varianceValues = variance.dataSync();
  12238. var scaleValues = scale ? scale.dataSync() : new Float32Array([1]);
  12239. var offsetValues = offset ? offset.dataSync() : new Float32Array([0]);
  12240. var outValues = new Float32Array(xValues.length);
  12241. for (var i = 0; i < xValues.length; i++) {
  12242. outValues[i] = offsetValues[i % offsetValues.length] +
  12243. (xValues[i] - meanValues[i % meanValues.length]) *
  12244. scaleValues[i % scaleValues.length] /
  12245. Math.sqrt(varianceValues[i % varianceValues.length] + varianceEpsilon);
  12246. }
  12247. return ops_1.tensor4d(outValues, x.shape);
  12248. };
  12249. MathBackendCPU.prototype.localResponseNormalization4D = function (x, radius, bias, alpha, beta) {
  12250. var output = ops.buffer(x.shape, 'float32');
  12251. var rad = radius;
  12252. var maxD = output.shape[3] - 1;
  12253. function sumAcrossChannels(b, r, c, d) {
  12254. var sum = 0.0;
  12255. for (var j = Math.max(0, d - rad); j <= Math.min(d + rad, maxD); j++) {
  12256. var z = x.get(b, r, c, j);
  12257. sum += z * z;
  12258. }
  12259. return sum;
  12260. }
  12261. for (var b = 0; b < output.shape[0]; b++) {
  12262. for (var r = 0; r <= output.shape[1]; r++) {
  12263. for (var c = 0; c < output.shape[2]; c++) {
  12264. for (var d = 0; d < output.shape[3]; d++) {
  12265. var sum = sumAcrossChannels(b, r, c, d);
  12266. var val = x.get(b, r, c, d) * Math.pow(bias + alpha * sum, -beta);
  12267. output.set(val, b, r, c, d);
  12268. }
  12269. }
  12270. }
  12271. }
  12272. return output.toTensor();
  12273. };
  12274. MathBackendCPU.prototype.multinomial = function (logits, normalized, numSamples, seed) {
  12275. var probabilities = normalized ? logits : ops.softmax(logits);
  12276. var batchSize = probabilities.shape[0];
  12277. var numEvents = probabilities.shape[1];
  12278. var res = ops.zeros([batchSize, numSamples], 'int32');
  12279. var resVals = res.dataSync();
  12280. var probVals = probabilities.dataSync();
  12281. for (var b = 0; b < batchSize; ++b) {
  12282. var offset = b * numEvents;
  12283. var cdf = new Float32Array(numEvents - 1);
  12284. cdf[0] = probVals[offset];
  12285. for (var event_1 = 1; event_1 < cdf.length; ++event_1) {
  12286. cdf[event_1] = cdf[event_1 - 1] + probVals[offset + event_1];
  12287. }
  12288. var random = seedrandom.alea(seed.toString());
  12289. var outOffset = b * numSamples;
  12290. for (var sampleId = 0; sampleId < numSamples; ++sampleId) {
  12291. var r = random();
  12292. resVals[outOffset + sampleId] = cdf.length;
  12293. for (var event_2 = 0; event_2 < cdf.length; event_2++) {
  12294. if (r < cdf[event_2]) {
  12295. resVals[outOffset + sampleId] = event_2;
  12296. break;
  12297. }
  12298. }
  12299. }
  12300. }
  12301. return res;
  12302. };
  12303. MathBackendCPU.prototype.oneHot = function (indices, depth, onValue, offValue) {
  12304. var res = new Float32Array(indices.size * depth);
  12305. res.fill(offValue);
  12306. for (var event_3 = 0; event_3 < indices.size; ++event_3) {
  12307. if (indices.get(event_3) >= 0 && indices.get(event_3) < depth) {
  12308. res[event_3 * depth + indices.get(event_3)] = onValue;
  12309. }
  12310. }
  12311. return ops.tensor2d(res, [indices.size, depth], 'int32');
  12312. };
  12313. MathBackendCPU.prototype.broadcastedBinaryOp = function (a, b, dtype, op) {
  12314. var newShape = broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  12315. var result = ops.buffer(newShape, dtype);
  12316. var aValues = a.dataSync();
  12317. var bValues = b.dataSync();
  12318. var aBroadcastDims = broadcast_util.getBroadcastDims(a.shape, newShape);
  12319. var bBroadcastDims = broadcast_util.getBroadcastDims(b.shape, newShape);
  12320. var aBuf = a.buffer();
  12321. var bBuf = b.buffer();
  12322. var _loop_2 = function (i) {
  12323. var loc = result.indexToLoc(i);
  12324. var aLoc = loc.slice(-a.rank);
  12325. aBroadcastDims.forEach(function (d) { return aLoc[d] = 0; });
  12326. var aIndex = aBuf.locToIndex(aLoc);
  12327. var bLoc = loc.slice(-b.rank);
  12328. bBroadcastDims.forEach(function (d) { return bLoc[d] = 0; });
  12329. var bIndex = bBuf.locToIndex(bLoc);
  12330. result.values[i] = op(aValues[aIndex], bValues[bIndex]);
  12331. };
  12332. for (var i = 0; i < result.values.length; ++i) {
  12333. _loop_2(i);
  12334. }
  12335. return result.toTensor();
  12336. };
  12337. MathBackendCPU.prototype.dispose = function () { };
  12338. return MathBackendCPU;
  12339. }());
  12340. exports.MathBackendCPU = MathBackendCPU;
  12341. environment_1.ENV.registerBackend('cpu', function () { return new MathBackendCPU(); }, 1);
  12342. },{"../environment":51,"../ops/axis_util":109,"../ops/broadcast_util":112,"../ops/concat_util":115,"../ops/erf_util":118,"../ops/ops":129,"../ops/selu_util":137,"../ops/slice_util":140,"../tensor":158,"../types":163,"../util":164,"./backend_util":66,"seedrandom":231}],66:[function(require,module,exports){
  12343. "use strict";
  12344. Object.defineProperty(exports, "__esModule", { value: true });
  12345. var __1 = require("..");
  12346. var array_ops_1 = require("../ops/array_ops");
  12347. function castTensor(x, dtype, backend) {
  12348. if (!__1.util.hasEncodingLoss(x.dtype, dtype)) {
  12349. return __1.Tensor.make(x.shape, { dataId: x.dataId }, dtype);
  12350. }
  12351. if (dtype === 'int32') {
  12352. return backend.int(x);
  12353. }
  12354. else if (dtype === 'bool') {
  12355. return backend.notEqual(x, array_ops_1.ArrayOps.scalar(0, x.dtype));
  12356. }
  12357. else {
  12358. throw new Error("Error in Cast: unknown dtype argument (" + dtype + ")");
  12359. }
  12360. }
  12361. exports.castTensor = castTensor;
  12362. function reshapeTensor(x, shape) {
  12363. return __1.Tensor.make(shape, { dataId: x.dataId }, x.dtype);
  12364. }
  12365. exports.reshapeTensor = reshapeTensor;
  12366. },{"..":54,"../ops/array_ops":108}],67:[function(require,module,exports){
  12367. "use strict";
  12368. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  12369. return new (P || (P = Promise))(function (resolve, reject) {
  12370. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  12371. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  12372. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  12373. step((generator = generator.apply(thisArg, _arguments || [])).next());
  12374. });
  12375. };
  12376. var __generator = (this && this.__generator) || function (thisArg, body) {
  12377. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  12378. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  12379. function verb(n) { return function (v) { return step([n, v]); }; }
  12380. function step(op) {
  12381. if (f) throw new TypeError("Generator is already executing.");
  12382. while (_) try {
  12383. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  12384. if (y = 0, t) op = [0, t.value];
  12385. switch (op[0]) {
  12386. case 0: case 1: t = op; break;
  12387. case 4: _.label++; return { value: op[1], done: false };
  12388. case 5: _.label++; y = op[1]; op = [0]; continue;
  12389. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  12390. default:
  12391. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  12392. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  12393. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  12394. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  12395. if (t[2]) _.ops.pop();
  12396. _.trys.pop(); continue;
  12397. }
  12398. op = body.call(thisArg, _);
  12399. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  12400. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  12401. }
  12402. };
  12403. Object.defineProperty(exports, "__esModule", { value: true });
  12404. var environment_1 = require("../environment");
  12405. var axis_util = require("../ops/axis_util");
  12406. var ops = require("../ops/ops");
  12407. var reduce_util = require("../ops/reduce_util");
  12408. var segment_util = require("../ops/segment_util");
  12409. var slice_util_1 = require("../ops/slice_util");
  12410. var tensor_1 = require("../tensor");
  12411. var types = require("../types");
  12412. var util = require("../util");
  12413. var backend_util = require("./backend_util");
  12414. var argminmax_gpu_1 = require("./webgl/argminmax_gpu");
  12415. var avg_pool_backprop_gpu_1 = require("./webgl/avg_pool_backprop_gpu");
  12416. var batchnorm_gpu_1 = require("./webgl/batchnorm_gpu");
  12417. var binaryop_gpu = require("./webgl/binaryop_gpu");
  12418. var binaryop_gpu_1 = require("./webgl/binaryop_gpu");
  12419. var clip_gpu_1 = require("./webgl/clip_gpu");
  12420. var concat_gpu_1 = require("./webgl/concat_gpu");
  12421. var conv_backprop_gpu_1 = require("./webgl/conv_backprop_gpu");
  12422. var conv_backprop_gpu_depthwise_1 = require("./webgl/conv_backprop_gpu_depthwise");
  12423. var conv_gpu_1 = require("./webgl/conv_gpu");
  12424. var conv_gpu_depthwise_1 = require("./webgl/conv_gpu_depthwise");
  12425. var cumsum_gpu_1 = require("./webgl/cumsum_gpu");
  12426. var encode_float_gpu_1 = require("./webgl/encode_float_gpu");
  12427. var from_pixels_gpu_1 = require("./webgl/from_pixels_gpu");
  12428. var gather_gpu_1 = require("./webgl/gather_gpu");
  12429. var gpgpu_context_1 = require("./webgl/gpgpu_context");
  12430. var gpgpu_math = require("./webgl/gpgpu_math");
  12431. var gpgpu_util = require("./webgl/gpgpu_util");
  12432. var logical_gpu_1 = require("./webgl/logical_gpu");
  12433. var lrn_gpu_1 = require("./webgl/lrn_gpu");
  12434. var max_pool_backprop_gpu_1 = require("./webgl/max_pool_backprop_gpu");
  12435. var mulmat_gpu_1 = require("./webgl/mulmat_gpu");
  12436. var multinomial_gpu_1 = require("./webgl/multinomial_gpu");
  12437. var onehot_gpu_1 = require("./webgl/onehot_gpu");
  12438. var pad_gpu_1 = require("./webgl/pad_gpu");
  12439. var pool_gpu_1 = require("./webgl/pool_gpu");
  12440. var reduce_gpu_1 = require("./webgl/reduce_gpu");
  12441. var resize_bilinear_backprop_gpu_1 = require("./webgl/resize_bilinear_backprop_gpu");
  12442. var resize_bilinear_gpu_1 = require("./webgl/resize_bilinear_gpu");
  12443. var resize_nearest_neighbor_gpu_1 = require("./webgl/resize_nearest_neighbor_gpu");
  12444. var reverse_gpu_1 = require("./webgl/reverse_gpu");
  12445. var segment_gpu_1 = require("./webgl/segment_gpu");
  12446. var slice_gpu_1 = require("./webgl/slice_gpu");
  12447. var strided_slice_gpu_1 = require("./webgl/strided_slice_gpu");
  12448. var tex_util_1 = require("./webgl/tex_util");
  12449. var texture_manager_1 = require("./webgl/texture_manager");
  12450. var tile_gpu_1 = require("./webgl/tile_gpu");
  12451. var transpose_gpu_1 = require("./webgl/transpose_gpu");
  12452. var unary_op = require("./webgl/unaryop_gpu");
  12453. var unaryop_gpu_1 = require("./webgl/unaryop_gpu");
  12454. var webgl_util = require("./webgl/webgl_util");
  12455. var BEFORE_PAGING_CONSTANT = 300;
  12456. exports.SIZE_UPLOAD_UNIFORM = 32;
  12457. var MathBackendWebGL = (function () {
  12458. function MathBackendWebGL(gpgpu, delayedStorage) {
  12459. if (delayedStorage === void 0) { delayedStorage = true; }
  12460. this.gpgpu = gpgpu;
  12461. this.delayedStorage = delayedStorage;
  12462. this.texData = new WeakMap();
  12463. this.pendingRead = new WeakMap();
  12464. this.pendingDisposal = new WeakSet();
  12465. this.lruDataGPU = [];
  12466. this.numBytesInGPU = 0;
  12467. this.uploadWaitMs = 0;
  12468. this.downloadWaitMs = 0;
  12469. this.binaryCache = {};
  12470. this.disposed = false;
  12471. if (environment_1.ENV.get('WEBGL_VERSION') < 1) {
  12472. throw new Error('WebGL is not supported on this device');
  12473. }
  12474. if (environment_1.ENV.get('IS_BROWSER')) {
  12475. this.canvas = document.createElement('canvas');
  12476. }
  12477. if (gpgpu == null) {
  12478. this.gpgpu = new gpgpu_context_1.GPGPUContext(gpgpu_util.createWebGLContext(this.canvas));
  12479. this.gpgpuCreatedLocally = true;
  12480. }
  12481. else {
  12482. this.gpgpuCreatedLocally = false;
  12483. }
  12484. this.NUM_BYTES_BEFORE_PAGING =
  12485. (window.screen.height * window.screen.width * window.devicePixelRatio) *
  12486. BEFORE_PAGING_CONSTANT;
  12487. this.textureManager = new texture_manager_1.TextureManager(this.gpgpu);
  12488. }
  12489. MathBackendWebGL.prototype.register = function (dataId, shape, dtype) {
  12490. if (this.texData.has(dataId)) {
  12491. throw new Error('Data buffer is already registered');
  12492. }
  12493. this.texData.set(dataId, {
  12494. shape: shape,
  12495. dtype: dtype,
  12496. values: null,
  12497. texture: null,
  12498. texShape: null,
  12499. usage: tex_util_1.TextureUsage.RENDER
  12500. });
  12501. };
  12502. MathBackendWebGL.prototype.fromPixels = function (pixels, numChannels) {
  12503. if (pixels == null) {
  12504. throw new Error('MathBackendWebGL.writePixels(): pixels can not be null');
  12505. }
  12506. var texShape = [pixels.height, pixels.width];
  12507. var outShape = [pixels.height, pixels.width, numChannels];
  12508. if (pixels instanceof HTMLVideoElement) {
  12509. if (this.fromPixelsCanvas == null) {
  12510. if (!environment_1.ENV.get('IS_BROWSER')) {
  12511. throw new Error('Can\'t read pixels from HTMLImageElement outside the browser.');
  12512. }
  12513. if (document.readyState !== 'complete') {
  12514. throw new Error('The DOM is not ready yet. Please call tf.fromPixels() ' +
  12515. 'once the DOM is ready. One way to do that is to add an event ' +
  12516. 'listener for `DOMContentLoaded` on the document object');
  12517. }
  12518. this.fromPixelsCanvas = document.createElement('canvas');
  12519. }
  12520. this.fromPixelsCanvas.width = pixels.width;
  12521. this.fromPixelsCanvas.height = pixels.height;
  12522. this.fromPixelsCanvas.getContext('2d').drawImage(pixels, 0, 0, pixels.width, pixels.height);
  12523. pixels = this.fromPixelsCanvas;
  12524. }
  12525. var tempPixelArray = tensor_1.Tensor.make(texShape, {}, 'int32');
  12526. this.texData.get(tempPixelArray.dataId).usage = tex_util_1.TextureUsage.PIXELS;
  12527. this.gpgpu.uploadPixelDataToTexture(this.getTexture(tempPixelArray.dataId), pixels);
  12528. var program = new from_pixels_gpu_1.FromPixelsProgram(outShape);
  12529. var res = this.compileAndRun(program, [tempPixelArray]);
  12530. tempPixelArray.dispose();
  12531. return res;
  12532. };
  12533. MathBackendWebGL.prototype.write = function (dataId, values) {
  12534. if (values == null) {
  12535. throw new Error('MathBackendWebGL.write(): values can not be null');
  12536. }
  12537. this.throwIfNoData(dataId);
  12538. var texData = this.texData.get(dataId);
  12539. var texture = texData.texture, texShape = texData.texShape, usage = texData.usage;
  12540. if (texture != null) {
  12541. this.releaseTexture(dataId, texture, texShape, usage);
  12542. texData.texture = null;
  12543. texData.texShape = null;
  12544. }
  12545. texData.usage = tex_util_1.TextureUsage.UPLOAD;
  12546. texData.values = values;
  12547. if (!this.delayedStorage) {
  12548. this.uploadToGPU(dataId);
  12549. }
  12550. };
  12551. MathBackendWebGL.prototype.readSync = function (dataId) {
  12552. this.throwIfNoData(dataId);
  12553. var texData = this.texData.get(dataId);
  12554. var shape = texData.shape, texture = texData.texture, values = texData.values, texShape = texData.texShape, dtype = texData.dtype;
  12555. if (values != null) {
  12556. this.cacheOnCPU(dataId);
  12557. return values;
  12558. }
  12559. var shouldTimeProgram = this.activeTimers != null;
  12560. var start;
  12561. if (shouldTimeProgram) {
  12562. start = performance.now();
  12563. }
  12564. var float32Values;
  12565. if (environment_1.ENV.get('WEBGL_DOWNLOAD_FLOAT_ENABLED')) {
  12566. float32Values = this.gpgpu.downloadFloat32MatrixFromOutputTexture(texture, texShape[0], texShape[1]);
  12567. }
  12568. else {
  12569. var tmpTarget = tensor_1.Tensor.make(shape, {});
  12570. this.texData.get(tmpTarget.dataId).usage = tex_util_1.TextureUsage.DOWNLOAD;
  12571. var tmpInput = tensor_1.Tensor.make(shape, { dataId: dataId }, dtype);
  12572. var program = new encode_float_gpu_1.EncodeFloatProgram(shape);
  12573. var res = this.compileAndRun(program, [tmpInput], tmpTarget);
  12574. var tmpData = this.texData.get(tmpTarget.dataId);
  12575. float32Values =
  12576. this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(tmpData.texture, tmpData.texShape[0], tmpData.texShape[1]);
  12577. res.dispose();
  12578. tmpInput.dispose();
  12579. tmpTarget.dispose();
  12580. }
  12581. if (shouldTimeProgram) {
  12582. this.downloadWaitMs += performance.now() - start;
  12583. }
  12584. this.cacheOnCPU(dataId, float32Values);
  12585. return texData.values;
  12586. };
  12587. MathBackendWebGL.prototype.read = function (dataId) {
  12588. return __awaiter(this, void 0, void 0, function () {
  12589. var subscribers_1, texData, texture, values, texShape, float32Values, subscribers, vals;
  12590. return __generator(this, function (_a) {
  12591. switch (_a.label) {
  12592. case 0:
  12593. if (this.pendingRead.has(dataId)) {
  12594. subscribers_1 = this.pendingRead.get(dataId);
  12595. return [2, new Promise(function (resolve) { return subscribers_1.push(resolve); })];
  12596. }
  12597. this.throwIfNoData(dataId);
  12598. texData = this.texData.get(dataId);
  12599. texture = texData.texture, values = texData.values, texShape = texData.texShape;
  12600. if (values != null) {
  12601. this.cacheOnCPU(dataId);
  12602. return [2, values];
  12603. }
  12604. if (!environment_1.ENV.get('WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED')) return [3, 2];
  12605. return [4, this.gpgpu.downloadMatrixFromTextureAsync(texture, texShape[0], texShape[1])];
  12606. case 1:
  12607. float32Values = _a.sent();
  12608. this.cacheOnCPU(dataId, float32Values);
  12609. return [2, texData.values];
  12610. case 2:
  12611. if (environment_1.ENV.get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 0) {
  12612. return [2, this.readSync(dataId)];
  12613. }
  12614. this.pendingRead.set(dataId, []);
  12615. return [4, this.gpgpu.runQuery(function () { })];
  12616. case 3:
  12617. _a.sent();
  12618. subscribers = this.pendingRead.get(dataId);
  12619. this.pendingRead.delete(dataId);
  12620. vals = this.readSync(dataId);
  12621. subscribers.forEach(function (resolve) { return resolve(vals); });
  12622. if (this.pendingDisposal.has(dataId)) {
  12623. this.pendingDisposal.delete(dataId);
  12624. this.disposeData(dataId);
  12625. }
  12626. return [2, vals];
  12627. }
  12628. });
  12629. });
  12630. };
  12631. MathBackendWebGL.prototype.time = function (f) {
  12632. return __awaiter(this, void 0, void 0, function () {
  12633. var oldActiveTimers, newActiveTimers, outerMostTime, flattenedActiveTimers, kernelMs, res;
  12634. return __generator(this, function (_a) {
  12635. switch (_a.label) {
  12636. case 0:
  12637. oldActiveTimers = this.activeTimers;
  12638. newActiveTimers = [];
  12639. outerMostTime = false;
  12640. if (this.programTimersStack == null) {
  12641. this.programTimersStack = newActiveTimers;
  12642. outerMostTime = true;
  12643. }
  12644. else {
  12645. this.activeTimers.push(newActiveTimers);
  12646. }
  12647. this.activeTimers = newActiveTimers;
  12648. f();
  12649. flattenedActiveTimers = util.flatten(this.activeTimers);
  12650. this.activeTimers = oldActiveTimers;
  12651. if (outerMostTime) {
  12652. this.programTimersStack = null;
  12653. }
  12654. return [4, Promise.all(flattenedActiveTimers).then(function (results) {
  12655. var sum = 0;
  12656. results.forEach(function (result) { return sum += result; });
  12657. return sum;
  12658. })];
  12659. case 1:
  12660. kernelMs = _a.sent();
  12661. res = {
  12662. uploadWaitMs: this.uploadWaitMs,
  12663. downloadWaitMs: this.downloadWaitMs,
  12664. kernelMs: kernelMs,
  12665. wallMs: null
  12666. };
  12667. this.uploadWaitMs = 0;
  12668. this.downloadWaitMs = 0;
  12669. return [2, res];
  12670. }
  12671. });
  12672. });
  12673. };
  12674. MathBackendWebGL.prototype.memory = function () {
  12675. return { unreliable: false, numBytesInGPU: this.numBytesInGPU };
  12676. };
  12677. MathBackendWebGL.prototype.startTimer = function () {
  12678. if (environment_1.ENV.get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0) {
  12679. return this.gpgpu.beginQuery();
  12680. }
  12681. return { startMs: performance.now(), endMs: null };
  12682. };
  12683. MathBackendWebGL.prototype.endTimer = function (query) {
  12684. if (environment_1.ENV.get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0) {
  12685. this.gpgpu.endQuery();
  12686. return query;
  12687. }
  12688. query.endMs = performance.now();
  12689. return query;
  12690. };
  12691. MathBackendWebGL.prototype.getQueryTime = function (query) {
  12692. return __awaiter(this, void 0, void 0, function () {
  12693. var timerQuery;
  12694. return __generator(this, function (_a) {
  12695. if (environment_1.ENV.get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0) {
  12696. return [2, this.gpgpu.pollQueryTime(query)];
  12697. }
  12698. timerQuery = query;
  12699. return [2, timerQuery.endMs - timerQuery.startMs];
  12700. });
  12701. });
  12702. };
  12703. MathBackendWebGL.prototype.disposeData = function (dataId) {
  12704. if (this.pendingDisposal.has(dataId)) {
  12705. return;
  12706. }
  12707. if (this.pendingRead.has(dataId)) {
  12708. this.pendingDisposal.add(dataId);
  12709. return;
  12710. }
  12711. if (this.texData.has(dataId)) {
  12712. var _a = this.texData.get(dataId), texture = _a.texture, texShape = _a.texShape, usage = _a.usage;
  12713. if (texture != null) {
  12714. this.releaseTexture(dataId, texture, texShape, usage);
  12715. }
  12716. this.texData.delete(dataId);
  12717. }
  12718. };
  12719. MathBackendWebGL.prototype.getTexture = function (dataId) {
  12720. this.uploadToGPU(dataId);
  12721. return this.texData.get(dataId).texture;
  12722. };
  12723. MathBackendWebGL.prototype.getGPGPUContext = function () {
  12724. return this.gpgpu;
  12725. };
  12726. MathBackendWebGL.prototype.getCanvas = function () {
  12727. return this.canvas;
  12728. };
  12729. MathBackendWebGL.prototype.slice = function (x, begin, size) {
  12730. var program = new slice_gpu_1.SliceProgram(size);
  12731. var customSetup = program.getCustomSetupFunc(begin);
  12732. return this.compileAndRun(program, [x], null, customSetup);
  12733. };
  12734. MathBackendWebGL.prototype.stridedSlice = function (x, begin, end, strides, beginMask, endMask) {
  12735. var _a = slice_util_1.getStridedSlicedInfo(x.shape, begin, end, strides, beginMask, endMask), beginIndex = _a[0], size = _a[1];
  12736. if (size.some(function (axis) { return axis === 0; })) {
  12737. return ops.tensor([], size);
  12738. }
  12739. var program = new strided_slice_gpu_1.StridedSliceProgram(beginIndex, strides, size);
  12740. return this.compileAndRun(program, [x]);
  12741. };
  12742. MathBackendWebGL.prototype.reverse = function (x, axis) {
  12743. var program = new reverse_gpu_1.ReverseProgram(x.shape, axis);
  12744. return this.compileAndRun(program, [x]);
  12745. };
  12746. MathBackendWebGL.prototype.concat = function (a, b) {
  12747. var program = new concat_gpu_1.ConcatProgram(a.shape, b.shape);
  12748. return this.compileAndRun(program, [a, b]);
  12749. };
  12750. MathBackendWebGL.prototype.neg = function (x) {
  12751. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.NEG);
  12752. return this.compileAndRun(program, [x]);
  12753. };
  12754. MathBackendWebGL.prototype.matMul = function (a, b, transposeA, transposeB) {
  12755. var program = new mulmat_gpu_1.MatMulProgram(a.shape, b.shape, transposeA, transposeB);
  12756. return this.compileAndRun(program, [a, b]);
  12757. };
  12758. MathBackendWebGL.prototype.multiply = function (a, b) {
  12759. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.MUL, a.shape, b.shape);
  12760. var output = this.makeOutputArray(program.outputShape, types.upcastType(a.dtype, b.dtype));
  12761. return this.compileAndRun(program, [a, b], output);
  12762. };
  12763. MathBackendWebGL.prototype.batchNormalization = function (x, mean, variance, varianceEpsilon, scale, offset) {
  12764. var inputs = [x, mean, variance];
  12765. var offsetShape = null;
  12766. if (offset != null) {
  12767. offsetShape = offset.shape;
  12768. inputs.push(offset);
  12769. }
  12770. var scaleShape = null;
  12771. if (scale != null) {
  12772. scaleShape = scale.shape;
  12773. inputs.push(scale);
  12774. }
  12775. var program = new batchnorm_gpu_1.BatchNormProgram(x.shape, mean.shape, variance.shape, offsetShape, scaleShape, varianceEpsilon);
  12776. return this.compileAndRun(program, inputs);
  12777. };
  12778. MathBackendWebGL.prototype.localResponseNormalization4D = function (x, radius, bias, alpha, beta) {
  12779. var program = new lrn_gpu_1.LRNProgram(x.shape, radius, bias, alpha, beta);
  12780. return this.compileAndRun(program, [x]);
  12781. };
  12782. MathBackendWebGL.prototype.tile = function (x, reps) {
  12783. var program = new tile_gpu_1.TileProgram(x.shape, reps);
  12784. return this.compileAndRun(program, [x]);
  12785. };
  12786. MathBackendWebGL.prototype.pad = function (x, paddings, constantValue) {
  12787. var program = new pad_gpu_1.PadProgram(x.shape, paddings, constantValue);
  12788. return this.compileAndRun(program, [x]);
  12789. };
  12790. MathBackendWebGL.prototype.transpose = function (x, perm) {
  12791. var program = new transpose_gpu_1.TransposeProgram(x.shape, perm);
  12792. return this.compileAndRun(program, [x]);
  12793. };
  12794. MathBackendWebGL.prototype.gather = function (x, indices, axis) {
  12795. var program = new gather_gpu_1.GatherProgram(x.shape, indices.size, axis);
  12796. return this.compileAndRun(program, [x, indices]);
  12797. };
  12798. MathBackendWebGL.prototype.reduce = function (x, reduceType, dtype) {
  12799. var batchSize = x.shape[0];
  12800. var inSize = x.shape[1];
  12801. var windowSize = reduce_util.computeOptimalWindowSize(inSize);
  12802. var reduceInfo = { windowSize: windowSize, inSize: inSize, batchSize: batchSize };
  12803. var program = new reduce_gpu_1.ReduceProgram(reduceInfo, reduceType);
  12804. var _a = program.outputShape, rows = _a[0], cols = _a[1];
  12805. var output = this.makeOutputArray([rows, cols], dtype);
  12806. this.compileAndRun(program, [x], output);
  12807. if (output.shape[1] === 1) {
  12808. return output;
  12809. }
  12810. return this.reduce(output, reduceType, dtype);
  12811. };
  12812. MathBackendWebGL.prototype.argReduce = function (x, reduceType, bestIndicesA) {
  12813. if (bestIndicesA === void 0) { bestIndicesA = null; }
  12814. var batchSize = x.shape[0];
  12815. var inSize = x.shape[1];
  12816. if (bestIndicesA != null) {
  12817. batchSize = bestIndicesA.shape[0];
  12818. inSize = bestIndicesA.shape[1];
  12819. }
  12820. var windowSize = reduce_util.computeOptimalWindowSize(inSize);
  12821. var reduceInfo = { windowSize: windowSize, inSize: inSize, batchSize: batchSize };
  12822. var program = new argminmax_gpu_1.ArgMinMaxProgram(reduceInfo, reduceType, bestIndicesA == null);
  12823. var _a = program.outputShape, rows = _a[0], cols = _a[1];
  12824. var output = this.makeOutputArray([rows, cols], 'int32');
  12825. var inputs = [x];
  12826. if (bestIndicesA != null) {
  12827. inputs.push(bestIndicesA);
  12828. }
  12829. this.compileAndRun(program, inputs, output);
  12830. if (output.shape[1] === 1) {
  12831. return output;
  12832. }
  12833. return this.argReduce(x, reduceType, output);
  12834. };
  12835. MathBackendWebGL.prototype.sum = function (x, axes) {
  12836. axis_util.assertAxesAreInnerMostDims('sum', axes, x.rank);
  12837. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  12838. var inSize = util.sizeFromShape(reduceShape);
  12839. var a2D = x.as2D(-1, inSize);
  12840. var outputDType = types.sumOutType(x.dtype);
  12841. return this.reduce(a2D, 'sum', outputDType).reshape(outShape);
  12842. };
  12843. MathBackendWebGL.prototype.unsortedSegmentSum = function (x, segmentIds, numSegments) {
  12844. var axis = 0;
  12845. var permutation = axis_util.getAxesPermutation([axis], x.rank);
  12846. var permutedX = x;
  12847. if (permutation != null) {
  12848. permutedX = x.transpose(permutation);
  12849. axis = axis_util.getInnerMostAxes(1, x.rank)[0];
  12850. }
  12851. var outShape = segment_util.computeOutShape(permutedX.shape, axis, numSegments);
  12852. var inSize = util.sizeFromShape([permutedX.shape[axis]]);
  12853. var a2D = permutedX.as2D(-1, inSize);
  12854. var outputDType = types.sumOutType(x.dtype);
  12855. var result = this.segOpCompute(a2D, 'unsortedSegmentSum', segmentIds, outputDType, numSegments)
  12856. .reshape(outShape);
  12857. if (permutation != null) {
  12858. result = result.transpose(axis_util.getUndoAxesPermutation(permutation));
  12859. }
  12860. return result;
  12861. };
  12862. MathBackendWebGL.prototype.segOpCompute = function (x, segOpType, segmentIds, dtype, numSegments) {
  12863. var batchSize = x.shape[0];
  12864. var inSize = x.shape[1];
  12865. var windowSize = segment_util.segOpComputeOptimalWindowSize(inSize, numSegments);
  12866. var segOpInfo = { windowSize: windowSize, inSize: inSize, batchSize: batchSize, numSegments: numSegments };
  12867. var program = new segment_gpu_1.SegmentOpProgram(segOpInfo, segOpType);
  12868. var _a = program.outputShape, rows = _a[0], cols = _a[1];
  12869. var output = this.makeOutputArray([rows, cols], dtype);
  12870. this.compileAndRun(program, [x, segmentIds], output);
  12871. if (output.shape[1] === numSegments) {
  12872. return output;
  12873. }
  12874. segmentIds = ops.range(0, numSegments).tile([inSize / windowSize]);
  12875. return this.segOpCompute(output, segOpType, segmentIds, dtype, numSegments);
  12876. };
  12877. MathBackendWebGL.prototype.argMin = function (x, axis) {
  12878. var axes = [axis];
  12879. axis_util.assertAxesAreInnerMostDims('argMin', axes, x.rank);
  12880. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  12881. var inSize = util.sizeFromShape(reduceShape);
  12882. var a2D = x.as2D(-1, inSize);
  12883. return this.argReduce(a2D, 'min').reshape(outShape);
  12884. };
  12885. MathBackendWebGL.prototype.argMax = function (x, axis) {
  12886. var axes = [axis];
  12887. axis_util.assertAxesAreInnerMostDims('argMax', axes, x.rank);
  12888. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  12889. var inSize = util.sizeFromShape(reduceShape);
  12890. var a2D = x.as2D(-1, inSize);
  12891. return this.argReduce(a2D, 'max').reshape(outShape);
  12892. };
  12893. MathBackendWebGL.prototype.cumsum = function (x, axis, exclusive, reverse) {
  12894. if (axis !== x.rank - 1) {
  12895. throw new Error("WebGL cumsum shader expects an inner-most axis=" + (x.rank - 1) + " " +
  12896. ("but got axis=" + axis));
  12897. }
  12898. var program = new cumsum_gpu_1.CumSumProgram(x.shape, exclusive, reverse);
  12899. return this.compileAndRun(program, [x]);
  12900. };
  12901. MathBackendWebGL.prototype.equal = function (a, b) {
  12902. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.EQUAL, a.shape, b.shape);
  12903. var output = this.makeOutputArray(program.outputShape, 'bool');
  12904. return this.compileAndRun(program, [a, b], output);
  12905. };
  12906. MathBackendWebGL.prototype.notEqual = function (a, b) {
  12907. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.NOT_EQUAL, a.shape, b.shape);
  12908. var output = this.makeOutputArray(program.outputShape, 'bool');
  12909. return this.compileAndRun(program, [a, b], output);
  12910. };
  12911. MathBackendWebGL.prototype.less = function (a, b) {
  12912. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.LESS, a.shape, b.shape);
  12913. var output = this.makeOutputArray(program.outputShape, 'bool');
  12914. return this.compileAndRun(program, [a, b], output);
  12915. };
  12916. MathBackendWebGL.prototype.lessEqual = function (a, b) {
  12917. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.LESS_EQUAL, a.shape, b.shape);
  12918. var output = this.makeOutputArray(program.outputShape, 'bool');
  12919. return this.compileAndRun(program, [a, b], output);
  12920. };
  12921. MathBackendWebGL.prototype.greater = function (a, b) {
  12922. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.GREATER, a.shape, b.shape);
  12923. var output = this.makeOutputArray(program.outputShape, 'bool');
  12924. return this.compileAndRun(program, [a, b], output);
  12925. };
  12926. MathBackendWebGL.prototype.greaterEqual = function (a, b) {
  12927. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.GREATER_EQUAL, a.shape, b.shape);
  12928. var output = this.makeOutputArray(program.outputShape, 'bool');
  12929. return this.compileAndRun(program, [a, b], output);
  12930. };
  12931. MathBackendWebGL.prototype.logicalNot = function (x) {
  12932. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.LOGICAL_NOT);
  12933. return this.compileAndRun(program, [x]);
  12934. };
  12935. MathBackendWebGL.prototype.logicalAnd = function (a, b) {
  12936. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.LOGICAL_AND, a.shape, b.shape);
  12937. var output = this.makeOutputArray(program.outputShape, 'bool');
  12938. return this.compileAndRun(program, [a, b], output);
  12939. };
  12940. MathBackendWebGL.prototype.logicalOr = function (a, b) {
  12941. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.LOGICAL_OR, a.shape, b.shape);
  12942. var output = this.makeOutputArray(program.outputShape, 'bool');
  12943. return this.compileAndRun(program, [a, b], output);
  12944. };
  12945. MathBackendWebGL.prototype.where = function (condition, a, b, dtype) {
  12946. var program = new logical_gpu_1.WhereProgram(condition.rank, a.shape, a.rank);
  12947. var output = this.makeOutputArray(program.outputShape, dtype);
  12948. return this.compileAndRun(program, [condition, a, b], output);
  12949. };
  12950. MathBackendWebGL.prototype.topKValues = function (x, k) {
  12951. throw new Error('topKValues GPU not yet implemented!');
  12952. };
  12953. MathBackendWebGL.prototype.topKIndices = function (x, k) {
  12954. throw new Error('topKIndices GPU not yet implemented!');
  12955. };
  12956. MathBackendWebGL.prototype.min = function (x, axes) {
  12957. axis_util.assertAxesAreInnerMostDims('min', axes, x.rank);
  12958. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  12959. var inSize = util.sizeFromShape(reduceShape);
  12960. var a2D = x.as2D(-1, inSize);
  12961. return this.reduce(a2D, 'min', a2D.dtype).reshape(outShape);
  12962. };
  12963. MathBackendWebGL.prototype.minimum = function (a, b) {
  12964. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.MIN, a.shape, b.shape);
  12965. return this.compileAndRun(program, [a, b]);
  12966. };
  12967. MathBackendWebGL.prototype.mod = function (a, b) {
  12968. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.MOD, a.shape, b.shape);
  12969. return this.compileAndRun(program, [a, b]);
  12970. };
  12971. MathBackendWebGL.prototype.max = function (x, axes) {
  12972. axis_util.assertAxesAreInnerMostDims('max', axes, x.rank);
  12973. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  12974. var inSize = util.sizeFromShape(reduceShape);
  12975. var a2D = x.as2D(-1, inSize);
  12976. return this.reduce(a2D, 'max', a2D.dtype).reshape(outShape);
  12977. };
  12978. MathBackendWebGL.prototype.maximum = function (a, b) {
  12979. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.MAX, a.shape, b.shape);
  12980. return this.compileAndRun(program, [a, b]);
  12981. };
  12982. MathBackendWebGL.prototype.all = function (x, axes) {
  12983. axis_util.assertAxesAreInnerMostDims('all', axes, x.rank);
  12984. var _a = axis_util.computeOutAndReduceShapes(x.shape, axes), outShape = _a[0], reduceShape = _a[1];
  12985. var inSize = util.sizeFromShape(reduceShape);
  12986. var a2D = x.as2D(-1, inSize);
  12987. return this.reduce(a2D, 'all', a2D.dtype).reshape(outShape);
  12988. };
  12989. MathBackendWebGL.prototype.squaredDifference = function (a, b) {
  12990. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.SQUARED_DIFFERENCE, a.shape, b.shape);
  12991. return this.compileAndRun(program, [a, b]);
  12992. };
  12993. MathBackendWebGL.prototype.realDivide = function (a, b) {
  12994. var op = binaryop_gpu.DIV;
  12995. var outputDtype = 'float32';
  12996. var program = new binaryop_gpu_1.BinaryOpProgram(op, a.shape, b.shape);
  12997. var output = this.makeOutputArray(program.outputShape, outputDtype);
  12998. return this.compileAndRun(program, [a, b], output);
  12999. };
  13000. MathBackendWebGL.prototype.floorDiv = function (a, b) {
  13001. var op = binaryop_gpu.INT_DIV;
  13002. var outputDtype = 'int32';
  13003. var program = new binaryop_gpu_1.BinaryOpProgram(op, a.shape, b.shape);
  13004. var output = this.makeOutputArray(program.outputShape, outputDtype);
  13005. return this.compileAndRun(program, [a, b], output);
  13006. };
  13007. MathBackendWebGL.prototype.add = function (a, b) {
  13008. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.ADD, a.shape, b.shape);
  13009. var output = this.makeOutputArray(program.outputShape, types.upcastType(a.dtype, b.dtype));
  13010. return this.compileAndRun(program, [a, b], output);
  13011. };
  13012. MathBackendWebGL.prototype.subtract = function (a, b) {
  13013. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.SUB, a.shape, b.shape);
  13014. var output = this.makeOutputArray(program.outputShape, types.upcastType(a.dtype, b.dtype));
  13015. return this.compileAndRun(program, [a, b], output);
  13016. };
  13017. MathBackendWebGL.prototype.pow = function (a, b) {
  13018. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.POW, a.shape, b.shape);
  13019. var output = this.makeOutputArray(program.outputShape, types.upcastType(a.dtype, b.dtype));
  13020. return this.compileAndRun(program, [a, b], output);
  13021. };
  13022. MathBackendWebGL.prototype.ceil = function (x) {
  13023. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.CEIL);
  13024. return this.compileAndRun(program, [x]);
  13025. };
  13026. MathBackendWebGL.prototype.floor = function (x) {
  13027. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.FLOOR);
  13028. return this.compileAndRun(program, [x]);
  13029. };
  13030. MathBackendWebGL.prototype.sign = function (x) {
  13031. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.SIGN);
  13032. return this.compileAndRun(program, [x]);
  13033. };
  13034. MathBackendWebGL.prototype.round = function (x) {
  13035. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ROUND);
  13036. return this.compileAndRun(program, [x]);
  13037. };
  13038. MathBackendWebGL.prototype.exp = function (x) {
  13039. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.EXP);
  13040. return this.compileAndRun(program, [x]);
  13041. };
  13042. MathBackendWebGL.prototype.expm1 = function (x) {
  13043. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.EXPM1);
  13044. return this.compileAndRun(program, [x]);
  13045. };
  13046. MathBackendWebGL.prototype.log = function (x) {
  13047. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.LOG);
  13048. return this.compileAndRun(program, [x]);
  13049. };
  13050. MathBackendWebGL.prototype.log1p = function (x) {
  13051. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.LOG1P);
  13052. return this.compileAndRun(program, [x]);
  13053. };
  13054. MathBackendWebGL.prototype.sqrt = function (x) {
  13055. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.SQRT);
  13056. return this.compileAndRun(program, [x]);
  13057. };
  13058. MathBackendWebGL.prototype.rsqrt = function (x) {
  13059. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.RSQRT);
  13060. return this.compileAndRun(program, [x]);
  13061. };
  13062. MathBackendWebGL.prototype.square = function (x) {
  13063. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.SQUARE);
  13064. return this.compileAndRun(program, [x]);
  13065. };
  13066. MathBackendWebGL.prototype.reciprocal = function (x) {
  13067. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.RECIPROCAL);
  13068. return this.compileAndRun(program, [x]);
  13069. };
  13070. MathBackendWebGL.prototype.relu = function (x) {
  13071. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.RELU);
  13072. return this.compileAndRun(program, [x]);
  13073. };
  13074. MathBackendWebGL.prototype.elu = function (x) {
  13075. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ELU);
  13076. return this.compileAndRun(program, [x]);
  13077. };
  13078. MathBackendWebGL.prototype.eluDer = function (dy, y) {
  13079. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.ELU_DER, dy.shape, y.shape);
  13080. return this.compileAndRun(program, [dy, y]);
  13081. };
  13082. MathBackendWebGL.prototype.selu = function (x) {
  13083. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.SELU);
  13084. return this.compileAndRun(program, [x]);
  13085. };
  13086. MathBackendWebGL.prototype.int = function (x) {
  13087. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.TO_INT);
  13088. var output = this.makeOutputArray(program.outputShape, 'int32');
  13089. return this.compileAndRun(program, [x], output);
  13090. };
  13091. MathBackendWebGL.prototype.clip = function (x, min, max) {
  13092. var program = new clip_gpu_1.ClipProgram(x.shape, min, max);
  13093. return this.compileAndRun(program, [x]);
  13094. };
  13095. MathBackendWebGL.prototype.abs = function (x) {
  13096. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ABS);
  13097. return this.compileAndRun(program, [x]);
  13098. };
  13099. MathBackendWebGL.prototype.sigmoid = function (x) {
  13100. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.SIGMOID);
  13101. return this.compileAndRun(program, [x]);
  13102. };
  13103. MathBackendWebGL.prototype.softplus = function (x) {
  13104. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.SOFTPLUS);
  13105. return this.compileAndRun(program, [x]);
  13106. };
  13107. MathBackendWebGL.prototype.sin = function (x) {
  13108. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.SIN);
  13109. return this.compileAndRun(program, [x]);
  13110. };
  13111. MathBackendWebGL.prototype.cos = function (x) {
  13112. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.COS);
  13113. return this.compileAndRun(program, [x]);
  13114. };
  13115. MathBackendWebGL.prototype.tan = function (x) {
  13116. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.TAN);
  13117. return this.compileAndRun(program, [x]);
  13118. };
  13119. MathBackendWebGL.prototype.asin = function (x) {
  13120. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ASIN);
  13121. return this.compileAndRun(program, [x]);
  13122. };
  13123. MathBackendWebGL.prototype.acos = function (x) {
  13124. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ACOS);
  13125. return this.compileAndRun(program, [x]);
  13126. };
  13127. MathBackendWebGL.prototype.atan = function (x) {
  13128. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ATAN);
  13129. return this.compileAndRun(program, [x]);
  13130. };
  13131. MathBackendWebGL.prototype.atan2 = function (a, b) {
  13132. var program = new binaryop_gpu_1.BinaryOpProgram(binaryop_gpu.ATAN2, a.shape, b.shape);
  13133. return this.compileAndRun(program, [a, b]);
  13134. };
  13135. MathBackendWebGL.prototype.sinh = function (x) {
  13136. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.SINH);
  13137. return this.compileAndRun(program, [x]);
  13138. };
  13139. MathBackendWebGL.prototype.cosh = function (x) {
  13140. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.COSH);
  13141. return this.compileAndRun(program, [x]);
  13142. };
  13143. MathBackendWebGL.prototype.tanh = function (x) {
  13144. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.TANH);
  13145. return this.compileAndRun(program, [x]);
  13146. };
  13147. MathBackendWebGL.prototype.asinh = function (x) {
  13148. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ASINH);
  13149. return this.compileAndRun(program, [x]);
  13150. };
  13151. MathBackendWebGL.prototype.acosh = function (x) {
  13152. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ACOSH);
  13153. return this.compileAndRun(program, [x]);
  13154. };
  13155. MathBackendWebGL.prototype.atanh = function (x) {
  13156. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ATANH);
  13157. return this.compileAndRun(program, [x]);
  13158. };
  13159. MathBackendWebGL.prototype.erf = function (x) {
  13160. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.ERF);
  13161. return this.compileAndRun(program, [x]);
  13162. };
  13163. MathBackendWebGL.prototype.step = function (x, alpha) {
  13164. var program = new unaryop_gpu_1.UnaryOpProgram(x.shape, unary_op.STEP(alpha));
  13165. return this.compileAndRun(program, [x]);
  13166. };
  13167. MathBackendWebGL.prototype.conv2d = function (x, filter, convInfo) {
  13168. var program = new conv_gpu_1.Conv2DProgram(convInfo);
  13169. return this.compileAndRun(program, [x, filter]);
  13170. };
  13171. MathBackendWebGL.prototype.conv2dDerInput = function (dy, filter, convInfo) {
  13172. var program = new conv_backprop_gpu_1.Conv2DDerInputProgram(convInfo);
  13173. return this.compileAndRun(program, [dy, filter]);
  13174. };
  13175. MathBackendWebGL.prototype.conv2dDerFilter = function (x, dy, convInfo) {
  13176. var program = new conv_backprop_gpu_1.Conv2DDerFilterProgram(convInfo);
  13177. return this.compileAndRun(program, [x, dy]);
  13178. };
  13179. MathBackendWebGL.prototype.depthwiseConv2D = function (x, filter, convInfo) {
  13180. var program = new conv_gpu_depthwise_1.DepthwiseConv2DProgram(convInfo);
  13181. return this.compileAndRun(program, [x, filter]);
  13182. };
  13183. MathBackendWebGL.prototype.depthwiseConv2DDerInput = function (dy, filter, convInfo) {
  13184. var program = new conv_backprop_gpu_depthwise_1.DepthwiseConv2DDerInputProgram(convInfo);
  13185. return this.compileAndRun(program, [dy, filter]);
  13186. };
  13187. MathBackendWebGL.prototype.depthwiseConv2DDerFilter = function (x, dy, convInfo) {
  13188. var program = new conv_backprop_gpu_depthwise_1.DepthwiseConv2DDerFilterProgram(convInfo);
  13189. return this.compileAndRun(program, [x, dy]);
  13190. };
  13191. MathBackendWebGL.prototype.maxPool = function (x, convInfo) {
  13192. var program = new pool_gpu_1.Pool2DProgram(convInfo, 'max', false);
  13193. var output = this.makeOutputArray(program.outputShape, x.dtype);
  13194. return this.compileAndRun(program, [x], output);
  13195. };
  13196. MathBackendWebGL.prototype.avgPool = function (x, convInfo) {
  13197. var program = new pool_gpu_1.Pool2DProgram(convInfo, 'avg', false);
  13198. var output = this.makeOutputArray(program.outputShape, 'float32');
  13199. return this.compileAndRun(program, [x], output);
  13200. };
  13201. MathBackendWebGL.prototype.maxPoolBackprop = function (dy, x, y, convInfo) {
  13202. var getPositions = true;
  13203. var maxPoolPositionsProgram = new pool_gpu_1.Pool2DProgram(convInfo, 'max', getPositions);
  13204. var maxPoolPositions = this.compileAndRun(maxPoolPositionsProgram, [x]);
  13205. var maxPoolBackPropProgram = new max_pool_backprop_gpu_1.MaxPool2DBackpropProgram(convInfo);
  13206. var output = this.makeOutputArray(maxPoolBackPropProgram.outputShape, x.dtype);
  13207. var result = this.compileAndRun(maxPoolBackPropProgram, [dy, maxPoolPositions], output);
  13208. maxPoolPositions.dispose();
  13209. return result;
  13210. };
  13211. MathBackendWebGL.prototype.avgPoolBackprop = function (dy, x, convInfo) {
  13212. var avgPoolBackpropProgram = new avg_pool_backprop_gpu_1.AvgPool2DBackpropProgram(convInfo);
  13213. var output = this.makeOutputArray(avgPoolBackpropProgram.outputShape, x.dtype);
  13214. return this.compileAndRun(avgPoolBackpropProgram, [dy], output);
  13215. };
  13216. MathBackendWebGL.prototype.cast = function (x, dtype) {
  13217. return backend_util.castTensor(x, dtype, this);
  13218. };
  13219. MathBackendWebGL.prototype.reshape = function (x, shape) {
  13220. return backend_util.reshapeTensor(x, shape);
  13221. };
  13222. MathBackendWebGL.prototype.resizeBilinear = function (x, newHeight, newWidth, alignCorners) {
  13223. var program = new resize_bilinear_gpu_1.ResizeBilinearProgram(x.shape, newHeight, newWidth, alignCorners);
  13224. return this.compileAndRun(program, [x]);
  13225. };
  13226. MathBackendWebGL.prototype.resizeBilinearBackprop = function (dy, x, alignCorners) {
  13227. var program = new resize_bilinear_backprop_gpu_1.ResizeBilinearBackpropProgram(dy, x, alignCorners);
  13228. return this.compileAndRun(program, [dy]);
  13229. };
  13230. MathBackendWebGL.prototype.resizeNearestNeighbor = function (x, newHeight, newWidth, alignCorners) {
  13231. var program = new resize_nearest_neighbor_gpu_1.ResizeNearestNeighborProgram(x.shape, newHeight, newWidth, alignCorners);
  13232. return this.compileAndRun(program, [x]);
  13233. };
  13234. MathBackendWebGL.prototype.multinomial = function (logits, normalized, numSamples, seed) {
  13235. var probs = normalized ? logits : ops.softmax(logits);
  13236. var batchSize = probs.shape[0];
  13237. var numOutcomes = probs.shape[1];
  13238. var program = new multinomial_gpu_1.MultinomialProgram(batchSize, numOutcomes, numSamples);
  13239. var output = this.makeOutputArray(program.outputShape, 'int32');
  13240. var customSetup = program.getCustomSetupFunc(seed);
  13241. return this.compileAndRun(program, [probs], output, customSetup);
  13242. };
  13243. MathBackendWebGL.prototype.oneHot = function (indices, depth, onValue, offValue) {
  13244. var program = new onehot_gpu_1.OneHotProgram(indices.size, depth, onValue, offValue);
  13245. return this.compileAndRun(program, [indices]);
  13246. };
  13247. MathBackendWebGL.prototype.makeOutputArray = function (shape, dtype) {
  13248. return tensor_1.Tensor.make(shape, {}, dtype);
  13249. };
  13250. MathBackendWebGL.prototype.compileAndRun = function (program, inputs, output, customSetup) {
  13251. var _this = this;
  13252. if (output == null) {
  13253. output = this.makeOutputArray(program.outputShape, inputs[0].dtype);
  13254. }
  13255. var inputsData = inputs.map(function (tensor) {
  13256. var texData = _this.texData.get(tensor.dataId);
  13257. if (texData.texture == null && tensor.size <= exports.SIZE_UPLOAD_UNIFORM) {
  13258. return { tensor: tensor, texData: null, isUniform: true };
  13259. }
  13260. _this.uploadToGPU(tensor.dataId);
  13261. return { tensor: tensor, texData: texData, isUniform: false };
  13262. });
  13263. this.uploadToGPU(output.dataId);
  13264. var outputData = {
  13265. tensor: output,
  13266. texData: this.texData.get(output.dataId),
  13267. isUniform: false
  13268. };
  13269. var key = gpgpu_math.makeShaderKey(program, inputsData, outputData);
  13270. var binary = this.getAndSaveBinary(key, function () {
  13271. return gpgpu_math.compileProgram(_this.gpgpu, program, inputsData, outputData);
  13272. });
  13273. var shouldTimeProgram = this.activeTimers != null;
  13274. var query;
  13275. if (shouldTimeProgram) {
  13276. query = this.startTimer();
  13277. }
  13278. gpgpu_math.runProgram(binary, inputsData, outputData, customSetup);
  13279. if (this.numBytesInGPU > this.NUM_BYTES_BEFORE_PAGING) {
  13280. var numBytesToPage = this.numBytesInGPU - this.NUM_BYTES_BEFORE_PAGING;
  13281. while (numBytesToPage > 0) {
  13282. var dataId = this.lruDataGPU.shift();
  13283. var _a = this.texData.get(dataId), shape = _a.shape, dtype = _a.dtype;
  13284. numBytesToPage -= this.computeBytes(shape, dtype);
  13285. this.read(dataId);
  13286. }
  13287. }
  13288. if (shouldTimeProgram) {
  13289. query = this.endTimer(query);
  13290. this.activeTimers.push(this.getQueryTime(query));
  13291. }
  13292. return output;
  13293. };
  13294. MathBackendWebGL.prototype.getAndSaveBinary = function (key, getBinary) {
  13295. if (!(key in this.binaryCache)) {
  13296. this.binaryCache[key] = getBinary();
  13297. }
  13298. return this.binaryCache[key];
  13299. };
  13300. MathBackendWebGL.prototype.getTextureManager = function () {
  13301. return this.textureManager;
  13302. };
  13303. MathBackendWebGL.prototype.dispose = function () {
  13304. if (this.disposed) {
  13305. return;
  13306. }
  13307. for (var key in this.binaryCache) {
  13308. this.gpgpu.deleteProgram(this.binaryCache[key].webGLProgram);
  13309. }
  13310. this.textureManager.dispose();
  13311. this.canvas.remove();
  13312. if (this.fromPixelsCanvas != null) {
  13313. this.fromPixelsCanvas.remove();
  13314. }
  13315. if (this.gpgpuCreatedLocally) {
  13316. this.gpgpu.dispose();
  13317. }
  13318. this.disposed = true;
  13319. };
  13320. MathBackendWebGL.prototype.throwIfNoData = function (dataId) {
  13321. if (!this.texData.has(dataId)) {
  13322. throw new Error("WebGL backend: No data found for this tensor. " +
  13323. "Did you change your backend in the middle of the program? " +
  13324. "New backends can't use Tensors created with previous backends");
  13325. }
  13326. };
  13327. MathBackendWebGL.prototype.uploadToGPU = function (dataId) {
  13328. this.throwIfNoData(dataId);
  13329. var texData = this.texData.get(dataId);
  13330. var shape = texData.shape, values = texData.values, texture = texData.texture, dtype = texData.dtype, usage = texData.usage;
  13331. if (texture != null) {
  13332. this.lruDataGPU.splice(this.lruDataGPU.indexOf(dataId), 1);
  13333. this.lruDataGPU.push(dataId);
  13334. return;
  13335. }
  13336. var shouldTimeProgram = this.activeTimers != null;
  13337. var start;
  13338. if (shouldTimeProgram) {
  13339. start = performance.now();
  13340. }
  13341. var texShape = webgl_util.getTextureShapeFromLogicalShape(this.gpgpu.gl, shape);
  13342. texData.texShape = texShape;
  13343. var newTexture = this.acquireTexture(dataId, texShape, usage);
  13344. texData.texture = newTexture;
  13345. if (values != null) {
  13346. this.gpgpu.uploadMatrixToTexture(newTexture, texShape[0], texShape[1], typedArrayToFloat32(values, dtype));
  13347. texData.values = null;
  13348. if (shouldTimeProgram) {
  13349. this.uploadWaitMs += performance.now() - start;
  13350. }
  13351. }
  13352. };
  13353. MathBackendWebGL.prototype.cacheOnCPU = function (dataId, float32Values) {
  13354. var dontKeepCopyOnGPU = this.delayedStorage;
  13355. var texData = this.texData.get(dataId);
  13356. var texture = texData.texture, texShape = texData.texShape, dtype = texData.dtype, usage = texData.usage;
  13357. if (dontKeepCopyOnGPU && texture != null) {
  13358. this.releaseTexture(dataId, texture, texShape, usage);
  13359. texData.texture = null;
  13360. texData.texShape = null;
  13361. }
  13362. if (float32Values != null) {
  13363. texData.values = float32ToTypedArray(float32Values, dtype);
  13364. }
  13365. };
  13366. MathBackendWebGL.prototype.releaseTexture = function (dataId, texture, texShape, texType) {
  13367. var _a = this.texData.get(dataId), shape = _a.shape, dtype = _a.dtype;
  13368. var idx = this.lruDataGPU.indexOf(dataId);
  13369. if (idx >= 0) {
  13370. this.lruDataGPU.splice(idx, 1);
  13371. }
  13372. this.numBytesInGPU -= this.computeBytes(shape, dtype);
  13373. this.textureManager.releaseTexture(texture, texShape, texType);
  13374. };
  13375. MathBackendWebGL.prototype.acquireTexture = function (dataId, texShape, texType) {
  13376. var _a = this.texData.get(dataId), shape = _a.shape, dtype = _a.dtype;
  13377. this.lruDataGPU.push(dataId);
  13378. this.numBytesInGPU += this.computeBytes(shape, dtype);
  13379. return this.textureManager.acquireTexture(texShape, texType);
  13380. };
  13381. MathBackendWebGL.prototype.computeBytes = function (shape, dtype) {
  13382. return util.sizeFromShape(shape) * util.bytesPerElement(dtype);
  13383. };
  13384. return MathBackendWebGL;
  13385. }());
  13386. exports.MathBackendWebGL = MathBackendWebGL;
  13387. if (environment_1.ENV.get('IS_BROWSER')) {
  13388. environment_1.ENV.registerBackend('webgl', function () { return new MathBackendWebGL(); }, 2);
  13389. }
  13390. function float32ToTypedArray(a, dtype) {
  13391. if (dtype === 'float32') {
  13392. return a;
  13393. }
  13394. else if (dtype === 'int32' || dtype === 'bool') {
  13395. var result = (dtype === 'int32') ? new Int32Array(a.length) :
  13396. new Uint8Array(a.length);
  13397. for (var i = 0; i < result.length; ++i) {
  13398. result[i] = Math.round(a[i]);
  13399. }
  13400. return result;
  13401. }
  13402. else {
  13403. throw new Error("Unknown dtype " + dtype);
  13404. }
  13405. }
  13406. function typedArrayToFloat32(a, dtype) {
  13407. return (a instanceof Float32Array) ? a : new Float32Array(a);
  13408. }
  13409. },{"../environment":51,"../ops/axis_util":109,"../ops/ops":129,"../ops/reduce_util":132,"../ops/segment_util":136,"../ops/slice_util":140,"../tensor":158,"../types":163,"../util":164,"./backend_util":66,"./webgl/argminmax_gpu":68,"./webgl/avg_pool_backprop_gpu":69,"./webgl/batchnorm_gpu":70,"./webgl/binaryop_gpu":71,"./webgl/clip_gpu":72,"./webgl/concat_gpu":73,"./webgl/conv_backprop_gpu":74,"./webgl/conv_backprop_gpu_depthwise":75,"./webgl/conv_gpu":76,"./webgl/conv_gpu_depthwise":77,"./webgl/cumsum_gpu":78,"./webgl/encode_float_gpu":79,"./webgl/from_pixels_gpu":80,"./webgl/gather_gpu":81,"./webgl/gpgpu_context":82,"./webgl/gpgpu_math":83,"./webgl/gpgpu_util":84,"./webgl/logical_gpu":85,"./webgl/lrn_gpu":86,"./webgl/max_pool_backprop_gpu":87,"./webgl/mulmat_gpu":88,"./webgl/multinomial_gpu":89,"./webgl/onehot_gpu":90,"./webgl/pad_gpu":91,"./webgl/pool_gpu":92,"./webgl/reduce_gpu":93,"./webgl/resize_bilinear_backprop_gpu":94,"./webgl/resize_bilinear_gpu":95,"./webgl/resize_nearest_neighbor_gpu":96,"./webgl/reverse_gpu":97,"./webgl/segment_gpu":98,"./webgl/slice_gpu":100,"./webgl/strided_slice_gpu":101,"./webgl/tex_util":102,"./webgl/texture_manager":103,"./webgl/tile_gpu":104,"./webgl/transpose_gpu":105,"./webgl/unaryop_gpu":106,"./webgl/webgl_util":107}],68:[function(require,module,exports){
  13410. "use strict";
  13411. Object.defineProperty(exports, "__esModule", { value: true });
  13412. var ArgMinMaxProgram = (function () {
  13413. function ArgMinMaxProgram(reduceInfo, op, firstPass) {
  13414. this.variableNames = ['A'];
  13415. var windowSize = reduceInfo.windowSize;
  13416. var batchSize = reduceInfo.batchSize;
  13417. var inSize = reduceInfo.inSize;
  13418. var outSize = Math.ceil(inSize / windowSize);
  13419. if (!firstPass) {
  13420. this.variableNames.push('bestIndicesA');
  13421. }
  13422. this.outputShape = [batchSize, outSize];
  13423. var compOp = (op === 'max') ? '>' : '<';
  13424. var indexSnippet = firstPass ?
  13425. 'inOffset + i;' :
  13426. 'round(getBestIndicesA(batch, inOffset + i));';
  13427. this.userCode = "\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * " + windowSize + ";\n\n int bestIndex = 0;\n float bestValue = getA(batch, inOffset);\n\n for (int i = 0; i < " + windowSize + "; i++) {\n int inIdx = " + indexSnippet + ";\n float candidate = getA(batch, inIdx);\n if (candidate " + compOp + " bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n ";
  13428. }
  13429. return ArgMinMaxProgram;
  13430. }());
  13431. exports.ArgMinMaxProgram = ArgMinMaxProgram;
  13432. },{}],69:[function(require,module,exports){
  13433. "use strict";
  13434. Object.defineProperty(exports, "__esModule", { value: true });
  13435. var AvgPool2DBackpropProgram = (function () {
  13436. function AvgPool2DBackpropProgram(convInfo) {
  13437. this.variableNames = ['dy'];
  13438. this.outputShape = convInfo.inShape;
  13439. var filterHeight = convInfo.filterHeight;
  13440. var filterWidth = convInfo.filterWidth;
  13441. var strideHeight = convInfo.strideHeight;
  13442. var strideWidth = convInfo.strideWidth;
  13443. var padTop = filterHeight - 1 - convInfo.padInfo.top;
  13444. var padLeft = filterWidth - 1 - convInfo.padInfo.left;
  13445. var avgMultiplier = 1 / (filterHeight * filterWidth);
  13446. this.userCode = "\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n const float avgMultiplier = float(" + avgMultiplier + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.outWidth + ".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n ";
  13447. }
  13448. return AvgPool2DBackpropProgram;
  13449. }());
  13450. exports.AvgPool2DBackpropProgram = AvgPool2DBackpropProgram;
  13451. },{}],70:[function(require,module,exports){
  13452. "use strict";
  13453. Object.defineProperty(exports, "__esModule", { value: true });
  13454. var broadcast_util = require("../../ops/broadcast_util");
  13455. var BatchNormProgram = (function () {
  13456. function BatchNormProgram(xShape, meanShape, varianceShape, offsetShape, scaleShape, varianceEpsilon) {
  13457. this.outputShape = [];
  13458. this.supportsBroadcasting = true;
  13459. this.variableNames = ['x', 'mean', 'variance'];
  13460. broadcast_util.assertAndGetBroadcastShape(xShape, meanShape);
  13461. broadcast_util.assertAndGetBroadcastShape(xShape, varianceShape);
  13462. var offsetSnippet = '0.0';
  13463. if (offsetShape != null) {
  13464. broadcast_util.assertAndGetBroadcastShape(xShape, offsetShape);
  13465. this.variableNames.push('offset');
  13466. offsetSnippet = 'getOffsetAtOutCoords()';
  13467. }
  13468. var scaleSnippet = '1.0';
  13469. if (scaleShape != null) {
  13470. broadcast_util.assertAndGetBroadcastShape(xShape, scaleShape);
  13471. this.variableNames.push('scale');
  13472. scaleSnippet = 'getScaleAtOutCoords()';
  13473. }
  13474. this.outputShape = xShape;
  13475. this.userCode = "\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = " + offsetSnippet + ";\n float scale = " + scaleSnippet + ";\n float inv = scale * inversesqrt(variance + float(" + varianceEpsilon + "));\n setOutput((x - mean) * inv + offset);\n }\n ";
  13476. }
  13477. return BatchNormProgram;
  13478. }());
  13479. exports.BatchNormProgram = BatchNormProgram;
  13480. },{"../../ops/broadcast_util":112}],71:[function(require,module,exports){
  13481. "use strict";
  13482. Object.defineProperty(exports, "__esModule", { value: true });
  13483. var broadcast_util = require("../../ops/broadcast_util");
  13484. var CHECK_NAN_SNIPPET = "\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n";
  13485. exports.ADD = 'return a + b;';
  13486. exports.SUB = 'return a - b;';
  13487. exports.MUL = 'return a * b;';
  13488. exports.DIV = 'return a / b;';
  13489. exports.INT_DIV = "\n float resultSign = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n int result = ia / ib;\n int amodb = ia - ib * result;\n\n if (resultSign < 0.0 && amodb != 0) {\n result -= 1;\n }\n return float(result);\n";
  13490. exports.POW = "\n return (round(mod(b, 2.0)) == 0 || round(mod(b, 2.0)) == 2) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n";
  13491. exports.SQUARED_DIFFERENCE = 'return (a - b) * (a - b);';
  13492. exports.EQUAL = "return float(a == b);";
  13493. exports.NOT_EQUAL = "return float(a != b);";
  13494. exports.LESS = "return float(a < b);";
  13495. exports.LESS_EQUAL = "return float(a <= b);";
  13496. exports.GREATER = "return float(a > b);";
  13497. exports.GREATER_EQUAL = "return float(a >= b);";
  13498. exports.LOGICAL_AND = "return float(a >= 1.0 && b >= 1.0);";
  13499. exports.LOGICAL_OR = "return float(a >= 1.0 || b >= 1.0);";
  13500. exports.MAX = CHECK_NAN_SNIPPET + "\n return max(a, b);\n";
  13501. exports.MIN = CHECK_NAN_SNIPPET + "\n return min(a, b);\n";
  13502. exports.MOD = "return mod(a, b);";
  13503. exports.ATAN2 = CHECK_NAN_SNIPPET + "\n return atan(a, b);\n";
  13504. exports.ELU_DER = "return (b >= 1.0) ? a : a * (b + 1.0);";
  13505. var BinaryOpProgram = (function () {
  13506. function BinaryOpProgram(op, aShape, bShape) {
  13507. this.variableNames = ['A', 'B'];
  13508. this.supportsBroadcasting = true;
  13509. this.outputShape =
  13510. broadcast_util.assertAndGetBroadcastShape(aShape, bShape);
  13511. this.userCode = "\n float binaryOperation(float a, float b) {\n " + op + "\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n ";
  13512. }
  13513. return BinaryOpProgram;
  13514. }());
  13515. exports.BinaryOpProgram = BinaryOpProgram;
  13516. },{"../../ops/broadcast_util":112}],72:[function(require,module,exports){
  13517. "use strict";
  13518. Object.defineProperty(exports, "__esModule", { value: true });
  13519. var ClipProgram = (function () {
  13520. function ClipProgram(aShape, min, max) {
  13521. this.variableNames = ['A'];
  13522. this.outputShape = aShape;
  13523. var minFixed = min.toFixed(20);
  13524. var maxFixed = max.toFixed(20);
  13525. this.userCode = "\n void main() {\n float value = getAAtOutCoords();\n if (isNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, " + minFixed + ", " + maxFixed + "));\n }\n ";
  13526. }
  13527. return ClipProgram;
  13528. }());
  13529. exports.ClipProgram = ClipProgram;
  13530. },{}],73:[function(require,module,exports){
  13531. "use strict";
  13532. Object.defineProperty(exports, "__esModule", { value: true });
  13533. var concat_util = require("../../ops/concat_util");
  13534. var ConcatProgram = (function () {
  13535. function ConcatProgram(aShape, bShape) {
  13536. this.variableNames = ['A', 'B'];
  13537. this.outputShape = [];
  13538. this.outputShape =
  13539. concat_util.computeOutShape(aShape, bShape, 1);
  13540. this.userCode = "\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n float value = 0.0;\n if (yC < " + aShape[1] + ") {\n value = getA(yR, yC);\n } else {\n yC -= " + aShape[1] + ";\n value = getB(yR, yC);\n }\n\n setOutput(value);\n }\n ";
  13541. }
  13542. return ConcatProgram;
  13543. }());
  13544. exports.ConcatProgram = ConcatProgram;
  13545. },{"../../ops/concat_util":115}],74:[function(require,module,exports){
  13546. "use strict";
  13547. Object.defineProperty(exports, "__esModule", { value: true });
  13548. var Conv2DDerFilterProgram = (function () {
  13549. function Conv2DDerFilterProgram(convInfo) {
  13550. this.variableNames = ['x', 'dy'];
  13551. this.outputShape = convInfo.filterShape;
  13552. var strideHeight = convInfo.strideHeight;
  13553. var strideWidth = convInfo.strideWidth;
  13554. var padTop = convInfo.padInfo.top;
  13555. var padLeft = convInfo.padInfo.left;
  13556. this.userCode = "\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < " + convInfo.batchSize + "; b++) {\n for (int yR = 0; yR < " + convInfo.outHeight + "; yR++) {\n int xR = wR + yR * " + strideHeight + " - " + padTop + ";\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int yC = 0; yC < " + convInfo.outWidth + "; yC++) {\n int xC = wC + yC * " + strideWidth + " - " + padLeft + ";\n\n if (xC < 0 || xC >= " + convInfo.inWidth + ") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n ";
  13557. }
  13558. return Conv2DDerFilterProgram;
  13559. }());
  13560. exports.Conv2DDerFilterProgram = Conv2DDerFilterProgram;
  13561. var Conv2DDerInputProgram = (function () {
  13562. function Conv2DDerInputProgram(convInfo) {
  13563. this.variableNames = ['dy', 'W'];
  13564. this.outputShape = convInfo.inShape;
  13565. var filterHeight = convInfo.filterHeight;
  13566. var filterWidth = convInfo.filterWidth;
  13567. var strideHeight = convInfo.strideHeight;
  13568. var strideWidth = convInfo.strideWidth;
  13569. var padTop = filterHeight - 1 - convInfo.padInfo.top;
  13570. var padLeft = filterWidth - 1 - convInfo.padInfo.left;
  13571. this.userCode = "\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = " + filterHeight + " - 1 - wR;\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.outWidth + ".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = " + filterWidth + " - 1 - wC;\n\n for (int d2 = 0; d2 < " + convInfo.outChannels + "; d2++) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n ";
  13572. }
  13573. return Conv2DDerInputProgram;
  13574. }());
  13575. exports.Conv2DDerInputProgram = Conv2DDerInputProgram;
  13576. },{}],75:[function(require,module,exports){
  13577. "use strict";
  13578. Object.defineProperty(exports, "__esModule", { value: true });
  13579. var DepthwiseConv2DDerFilterProgram = (function () {
  13580. function DepthwiseConv2DDerFilterProgram(convInfo) {
  13581. this.variableNames = ['x', 'dy'];
  13582. this.outputShape = convInfo.filterShape;
  13583. var strideHeight = convInfo.strideHeight;
  13584. var strideWidth = convInfo.strideWidth;
  13585. var padTop = convInfo.padInfo.top;
  13586. var padLeft = convInfo.padInfo.left;
  13587. var channelMul = convInfo.outChannels / convInfo.inChannels;
  13588. this.userCode = "\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * " + channelMul + " + dm;\n\n float dotProd = 0.0;\n\n // TODO: Vec4 over the batch size\n for (int b = 0; b < " + convInfo.batchSize + "; b++) {\n for (int yR = 0; yR < " + convInfo.outHeight + "; yR++) {\n int xR = wR + yR * " + strideHeight + " - " + padTop + ";\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int yC = 0; yC < " + convInfo.outWidth + "; yC++) {\n int xC = wC + yC * " + strideWidth + " - " + padLeft + ";\n\n if (xC < 0 || xC >= " + convInfo.inWidth + ") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n ";
  13589. }
  13590. return DepthwiseConv2DDerFilterProgram;
  13591. }());
  13592. exports.DepthwiseConv2DDerFilterProgram = DepthwiseConv2DDerFilterProgram;
  13593. var DepthwiseConv2DDerInputProgram = (function () {
  13594. function DepthwiseConv2DDerInputProgram(convInfo) {
  13595. this.variableNames = ['dy', 'W'];
  13596. this.outputShape = convInfo.inShape;
  13597. var filterHeight = convInfo.filterHeight;
  13598. var filterWidth = convInfo.filterWidth;
  13599. var strideHeight = convInfo.strideHeight;
  13600. var strideWidth = convInfo.strideWidth;
  13601. var padTop = filterHeight - 1 - convInfo.padInfo.top;
  13602. var padLeft = filterWidth - 1 - convInfo.padInfo.left;
  13603. var channelMul = convInfo.outChannels / convInfo.inChannels;
  13604. this.userCode = "\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = " + filterHeight + " - 1 - wR;\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.outWidth + ".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = " + filterWidth + " - 1 - wC;\n\n // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < " + channelMul + "; dm++) {\n int d2 = d1 * " + channelMul + " + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n ";
  13605. }
  13606. return DepthwiseConv2DDerInputProgram;
  13607. }());
  13608. exports.DepthwiseConv2DDerInputProgram = DepthwiseConv2DDerInputProgram;
  13609. },{}],76:[function(require,module,exports){
  13610. "use strict";
  13611. Object.defineProperty(exports, "__esModule", { value: true });
  13612. var Conv2DProgram = (function () {
  13613. function Conv2DProgram(convInfo) {
  13614. this.variableNames = ['x', 'W'];
  13615. this.outputShape = convInfo.outShape;
  13616. var padTop = convInfo.padInfo.top;
  13617. var padLeft = convInfo.padInfo.left;
  13618. var strideHeight = convInfo.strideHeight;
  13619. var strideWidth = convInfo.strideWidth;
  13620. var dilationHeight = convInfo.dilationHeight;
  13621. var dilationWidth = convInfo.dilationWidth;
  13622. var filterHeight = convInfo.filterHeight;
  13623. var filterWidth = convInfo.filterWidth;
  13624. var inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;
  13625. var inputDepthVec4Remainder = convInfo.inChannels % 4;
  13626. this.userCode = "\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n int xR = xRCorner + wR * " + dilationHeight + ";\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n int xC = xCCorner + wC * " + dilationWidth + ";\n\n if (xC < 0 || xC >= " + convInfo.inWidth + ") {\n continue;\n }\n\n for (int d1 = 0; d1 < " + inputDepthNearestVec4 + "; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if (" + (inputDepthVec4Remainder === 1) + ") {\n dotProd +=\n getX(batch, xR, xC, " + inputDepthNearestVec4 + ") *\n getW(wR, wC, " + inputDepthNearestVec4 + ", d2);\n } else if (" + (inputDepthVec4Remainder === 2) + ") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, " + inputDepthNearestVec4 + "),\n getX(batch, xR, xC, " + inputDepthNearestVec4 + " + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, " + inputDepthNearestVec4 + ", d2),\n getW(wR, wC, " + inputDepthNearestVec4 + " + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (" + (inputDepthVec4Remainder === 3) + ") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, " + inputDepthNearestVec4 + "),\n getX(batch, xR, xC, " + inputDepthNearestVec4 + " + 1),\n getX(batch, xR, xC, " + inputDepthNearestVec4 + " + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, " + inputDepthNearestVec4 + ", d2),\n getW(wR, wC, " + inputDepthNearestVec4 + " + 1, d2),\n getW(wR, wC, " + inputDepthNearestVec4 + " + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n ";
  13627. }
  13628. return Conv2DProgram;
  13629. }());
  13630. exports.Conv2DProgram = Conv2DProgram;
  13631. },{}],77:[function(require,module,exports){
  13632. "use strict";
  13633. Object.defineProperty(exports, "__esModule", { value: true });
  13634. var DepthwiseConv2DProgram = (function () {
  13635. function DepthwiseConv2DProgram(convInfo) {
  13636. this.variableNames = ['x', 'W'];
  13637. this.outputShape = convInfo.outShape;
  13638. var xNumRows = convInfo.inHeight;
  13639. var xNumCols = convInfo.inWidth;
  13640. var padTop = convInfo.padInfo.top;
  13641. var padLeft = convInfo.padInfo.left;
  13642. var strideHeight = convInfo.strideHeight;
  13643. var strideWidth = convInfo.strideWidth;
  13644. var dilationHeight = convInfo.dilationHeight;
  13645. var dilationWidth = convInfo.dilationWidth;
  13646. var filterHeight = convInfo.filterHeight;
  13647. var filterWidth = convInfo.filterWidth;
  13648. var channelMul = convInfo.outChannels / convInfo.inChannels;
  13649. this.userCode = "\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / " + channelMul + ";\n int q = d2 - d1 * " + channelMul + ";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n int xR = xRCorner + wR * " + dilationHeight + ";\n\n if (xR < 0 || xR >= " + xNumRows + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n int xC = xCCorner + wC * " + dilationWidth + ";\n\n if (xC < 0 || xC >= " + xNumCols + ") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n ";
  13650. }
  13651. return DepthwiseConv2DProgram;
  13652. }());
  13653. exports.DepthwiseConv2DProgram = DepthwiseConv2DProgram;
  13654. },{}],78:[function(require,module,exports){
  13655. "use strict";
  13656. Object.defineProperty(exports, "__esModule", { value: true });
  13657. var shader_compiler_1 = require("./shader_compiler");
  13658. var CumSumProgram = (function () {
  13659. function CumSumProgram(shape, exclusive, reverse) {
  13660. this.variableNames = ['x'];
  13661. this.outputShape = shape;
  13662. var rank = shape.length;
  13663. var finalDim = shape[shape.length - 1];
  13664. var comparator = reverse ? '<' : '>';
  13665. this.userCode = "\n int getIndex(int i) {\n " + (reverse ? "return " + finalDim + " -i - 1;" : 'return i;') + "\n }\n\n void main() {\n " + shader_compiler_1.getCoordsDataType(rank) + " coords = getOutputCoords();\n int end = " + getFinalCoord(rank, 'coords') + ";\n float val = 0.0;\n for (int i = " + finalDim + " - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx " + comparator + " end) {\n continue;\n }\n if (idx == end && " + exclusive + ") {\n continue;\n }\n " + getFinalCoord(rank, 'coords') + " = idx;\n val += getX(" + getCoords(rank, 'coords') + ");\n }\n setOutput(val);\n }\n ";
  13666. }
  13667. return CumSumProgram;
  13668. }());
  13669. exports.CumSumProgram = CumSumProgram;
  13670. function getCoords(rank, name) {
  13671. if (rank === 1) {
  13672. return "" + name;
  13673. }
  13674. else if (rank === 2) {
  13675. return name + ".x, " + name + ".y";
  13676. }
  13677. else if (rank === 3) {
  13678. return name + ".x, " + name + ".y, " + name + ".z";
  13679. }
  13680. else if (rank === 4) {
  13681. return name + ".x, " + name + ".y, " + name + ".z, " + name + ".w";
  13682. }
  13683. else {
  13684. throw Error("Cumulative sum for rank " + rank + " is not yet supported");
  13685. }
  13686. }
  13687. function getFinalCoord(rank, name) {
  13688. if (rank === 1) {
  13689. return "" + name;
  13690. }
  13691. else if (rank === 2) {
  13692. return name + ".y";
  13693. }
  13694. else if (rank === 3) {
  13695. return name + ".z";
  13696. }
  13697. else if (rank === 4) {
  13698. return name + ".w";
  13699. }
  13700. else {
  13701. throw Error("Cumulative sum for rank " + rank + " is not yet supported");
  13702. }
  13703. }
  13704. },{"./shader_compiler":99}],79:[function(require,module,exports){
  13705. "use strict";
  13706. Object.defineProperty(exports, "__esModule", { value: true });
  13707. var EncodeFloatProgram = (function () {
  13708. function EncodeFloatProgram(outputShape) {
  13709. this.variableNames = ['A'];
  13710. this.outputShape = outputShape;
  13711. this.userCode = "\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float x = getAAtOutCoords();\n gl_FragColor = encode_float(x);\n }\n ";
  13712. }
  13713. return EncodeFloatProgram;
  13714. }());
  13715. exports.EncodeFloatProgram = EncodeFloatProgram;
  13716. },{}],80:[function(require,module,exports){
  13717. "use strict";
  13718. Object.defineProperty(exports, "__esModule", { value: true });
  13719. var FromPixelsProgram = (function () {
  13720. function FromPixelsProgram(outputShape) {
  13721. this.variableNames = ['A'];
  13722. var height = outputShape[0], width = outputShape[1];
  13723. this.outputShape = outputShape;
  13724. this.userCode = "\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(" + width + ".0, " + height + ".0);\n\n vec4 values = texture2D(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n ";
  13725. }
  13726. return FromPixelsProgram;
  13727. }());
  13728. exports.FromPixelsProgram = FromPixelsProgram;
  13729. },{}],81:[function(require,module,exports){
  13730. "use strict";
  13731. Object.defineProperty(exports, "__esModule", { value: true });
  13732. var shader_compiler_1 = require("./shader_compiler");
  13733. var GatherProgram = (function () {
  13734. function GatherProgram(aShape, indicesLength, axis) {
  13735. this.variableNames = ['A', 'indices'];
  13736. var outputShape = aShape.slice();
  13737. outputShape[axis] = indicesLength;
  13738. this.outputShape = outputShape;
  13739. this.rank = outputShape.length;
  13740. var dtype = shader_compiler_1.getCoordsDataType(this.rank);
  13741. var sourceCoords = getSourceCoords(aShape, axis);
  13742. this.userCode = "\n void main() {\n " + dtype + " resRC = getOutputCoords();\n setOutput(getA(" + sourceCoords + "));\n }\n ";
  13743. }
  13744. return GatherProgram;
  13745. }());
  13746. exports.GatherProgram = GatherProgram;
  13747. function getSourceCoords(aShape, axis) {
  13748. var rank = aShape.length;
  13749. if (rank > 4) {
  13750. throw Error("Gather for rank " + rank + " is not yet supported");
  13751. }
  13752. if (rank === 1) {
  13753. return "int(getIndices(resRC))";
  13754. }
  13755. var currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w'];
  13756. var sourceCoords = [];
  13757. for (var i = 0; i < aShape.length; i++) {
  13758. if (i === axis) {
  13759. sourceCoords.push("int(getIndices(" + currentCoords[i] + "))");
  13760. }
  13761. else {
  13762. sourceCoords.push("" + currentCoords[i]);
  13763. }
  13764. }
  13765. return sourceCoords.join();
  13766. }
  13767. },{"./shader_compiler":99}],82:[function(require,module,exports){
  13768. "use strict";
  13769. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  13770. return new (P || (P = Promise))(function (resolve, reject) {
  13771. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  13772. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  13773. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  13774. step((generator = generator.apply(thisArg, _arguments || [])).next());
  13775. });
  13776. };
  13777. var __generator = (this && this.__generator) || function (thisArg, body) {
  13778. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  13779. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  13780. function verb(n) { return function (v) { return step([n, v]); }; }
  13781. function step(op) {
  13782. if (f) throw new TypeError("Generator is already executing.");
  13783. while (_) try {
  13784. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  13785. if (y = 0, t) op = [0, t.value];
  13786. switch (op[0]) {
  13787. case 0: case 1: t = op; break;
  13788. case 4: _.label++; return { value: op[1], done: false };
  13789. case 5: _.label++; y = op[1]; op = [0]; continue;
  13790. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  13791. default:
  13792. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  13793. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  13794. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  13795. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  13796. if (t[2]) _.ops.pop();
  13797. _.trys.pop(); continue;
  13798. }
  13799. op = body.call(thisArg, _);
  13800. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  13801. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  13802. }
  13803. };
  13804. Object.defineProperty(exports, "__esModule", { value: true });
  13805. var environment_1 = require("../../environment");
  13806. var util = require("../../util");
  13807. var gpgpu_util = require("./gpgpu_util");
  13808. var tex_util = require("./tex_util");
  13809. var webgl_util = require("./webgl_util");
  13810. var GPGPUContext = (function () {
  13811. function GPGPUContext(gl) {
  13812. this.outputTexture = null;
  13813. this.program = null;
  13814. this.disposed = false;
  13815. this.autoDebugValidate = false;
  13816. this.vertexAttrsAreBound = false;
  13817. this.itemsToPoll = [];
  13818. if (gl != null) {
  13819. this.gl = gl;
  13820. }
  13821. else {
  13822. this.gl = gpgpu_util.createWebGLContext();
  13823. }
  13824. if (environment_1.ENV.get('WEBGL_VERSION') === 1) {
  13825. this.textureFloatExtension =
  13826. webgl_util.getExtensionOrThrow(this.gl, 'OES_texture_float');
  13827. this.colorBufferFloatExtension =
  13828. this.gl.getExtension('WEBGL_color_buffer_float');
  13829. if (!environment_1.ENV.get('WEBGL_RENDER_FLOAT32_ENABLED')) {
  13830. this.textureHalfFloatExtension =
  13831. webgl_util.getExtensionOrThrow(this.gl, 'OES_texture_half_float');
  13832. this.colorBufferHalfFloatExtension =
  13833. this.gl.getExtension('EXT_color_buffer_half_float');
  13834. }
  13835. }
  13836. else {
  13837. this.colorBufferFloatExtension =
  13838. webgl_util.getExtensionOrThrow(this.gl, 'EXT_color_buffer_float');
  13839. }
  13840. this.loseContextExtension =
  13841. webgl_util.getExtensionOrThrow(this.gl, 'WEBGL_lose_context');
  13842. if (environment_1.ENV.get('WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED')) {
  13843. this.getBufferSubDataAsyncExtension =
  13844. this.gl.getExtension('WEBGL_get_buffer_sub_data_async');
  13845. }
  13846. this.vertexBuffer = gpgpu_util.createVertexBuffer(this.gl);
  13847. this.indexBuffer = gpgpu_util.createIndexBuffer(this.gl);
  13848. this.framebuffer = webgl_util.createFramebuffer(this.gl);
  13849. this.textureConfig =
  13850. gpgpu_util.getTextureConfig(this.gl, this.textureHalfFloatExtension);
  13851. }
  13852. GPGPUContext.prototype.dispose = function () {
  13853. var _this = this;
  13854. if (this.disposed) {
  13855. return;
  13856. }
  13857. if (this.program != null) {
  13858. console.warn('Disposing a GPGPUContext that still has a bound WebGLProgram.' +
  13859. ' This is probably a resource leak, delete the program with ' +
  13860. 'GPGPUContext.deleteProgram before disposing.');
  13861. }
  13862. if (this.outputTexture != null) {
  13863. console.warn('Disposing a GPGPUContext that still has a bound output matrix ' +
  13864. 'texture. This is probably a resource leak, delete the output ' +
  13865. 'matrix texture with GPGPUContext.deleteMatrixTexture before ' +
  13866. 'disposing.');
  13867. }
  13868. var gl = this.gl;
  13869. webgl_util.callAndCheck(gl, function () { return gl.finish(); });
  13870. webgl_util.callAndCheck(gl, function () { return gl.bindFramebuffer(gl.FRAMEBUFFER, null); });
  13871. webgl_util.callAndCheck(gl, function () { return gl.deleteFramebuffer(_this.framebuffer); });
  13872. webgl_util.callAndCheck(gl, function () { return gl.bindBuffer(gl.ARRAY_BUFFER, null); });
  13873. webgl_util.callAndCheck(gl, function () { return gl.deleteBuffer(_this.vertexBuffer); });
  13874. webgl_util.callAndCheck(gl, function () { return gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); });
  13875. webgl_util.callAndCheck(gl, function () { return gl.deleteBuffer(_this.indexBuffer); });
  13876. this.loseContextExtension.loseContext();
  13877. this.disposed = true;
  13878. };
  13879. GPGPUContext.prototype.enableAutomaticDebugValidation = function (enabled) {
  13880. this.autoDebugValidate = enabled;
  13881. webgl_util.enableDebugWebGLErrorChecking(enabled);
  13882. };
  13883. GPGPUContext.prototype.createFloat32MatrixTexture = function (rows, columns) {
  13884. this.throwIfDisposed();
  13885. return gpgpu_util.createFloat32MatrixTexture(this.gl, rows, columns, this.textureConfig);
  13886. };
  13887. GPGPUContext.prototype.createFloat16MatrixTexture = function (rows, columns) {
  13888. this.throwIfDisposed();
  13889. return gpgpu_util.createFloat16MatrixTexture(this.gl, rows, columns, this.textureConfig);
  13890. };
  13891. GPGPUContext.prototype.createUnsignedBytesMatrixTexture = function (rows, columns) {
  13892. this.throwIfDisposed();
  13893. return gpgpu_util.createUnsignedBytesMatrixTexture(this.gl, rows, columns, this.textureConfig);
  13894. };
  13895. GPGPUContext.prototype.uploadPixelDataToTexture = function (texture, pixels) {
  13896. this.throwIfDisposed();
  13897. gpgpu_util.uploadPixelDataToTexture(this.gl, texture, pixels);
  13898. };
  13899. GPGPUContext.prototype.createPackedMatrixTexture = function (rows, columns) {
  13900. this.throwIfDisposed();
  13901. return gpgpu_util.createPackedMatrixTexture(this.gl, rows, columns, this.textureConfig);
  13902. };
  13903. GPGPUContext.prototype.deleteMatrixTexture = function (texture) {
  13904. var _this = this;
  13905. this.throwIfDisposed();
  13906. if (this.outputTexture === texture) {
  13907. webgl_util.unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);
  13908. this.outputTexture = null;
  13909. }
  13910. webgl_util.callAndCheck(this.gl, function () { return _this.gl.deleteTexture(texture); });
  13911. };
  13912. GPGPUContext.prototype.uploadMatrixToTexture = function (texture, rows, columns, matrix) {
  13913. this.throwIfDisposed();
  13914. var numChannels = webgl_util.getNumChannels();
  13915. return gpgpu_util.uploadMatrixToTexture(this.gl, texture, rows, columns, matrix, numChannels, this.textureConfig);
  13916. };
  13917. GPGPUContext.prototype.uploadMatrixToPackedTexture = function (texture, rows, columns, matrix) {
  13918. this.throwIfDisposed();
  13919. return gpgpu_util.uploadMatrixToPackedTexture(this.gl, texture, rows, columns, matrix, this.textureConfig);
  13920. };
  13921. GPGPUContext.prototype.downloadFloat32MatrixFromOutputTexture = function (texture, rows, columns) {
  13922. var _this = this;
  13923. return this.downloadMatrixDriver(texture, function () { return gpgpu_util.downloadFloat32MatrixFromOutputTexture(_this.gl, rows, columns, _this.textureConfig); });
  13924. };
  13925. GPGPUContext.prototype.downloadByteEncodedFloatMatrixFromOutputTexture = function (texture, rows, columns) {
  13926. var _this = this;
  13927. return this.downloadMatrixDriver(texture, function () { return gpgpu_util.downloadByteEncodedFloatMatrixFromOutputTexture(_this.gl, rows, columns, _this.textureConfig); });
  13928. };
  13929. GPGPUContext.prototype.downloadMatrixFromTextureAsync = function (texture, rows, columns) {
  13930. return __awaiter(this, void 0, void 0, function () {
  13931. var _this = this;
  13932. return __generator(this, function (_a) {
  13933. if (this.getBufferSubDataAsyncExtension == null) {
  13934. throw new Error("Cannot download matrix from output texture asynchronously, " +
  13935. "WEBGL_get_buffer_sub_data_async is not enabled.");
  13936. }
  13937. return [2, this.downloadMatrixDriverAsync(texture, function () { return gpgpu_util.downloadMatrixFromOutputTextureAsync(_this.gl, _this.getBufferSubDataAsyncExtension, rows, columns, _this.textureConfig); })];
  13938. });
  13939. });
  13940. };
  13941. GPGPUContext.prototype.downloadMatrixFromPackedTexture = function (texture, rows, columns) {
  13942. var _this = this;
  13943. return this.downloadMatrixDriver(texture, function () { return gpgpu_util.downloadMatrixFromPackedOutputTexture(_this.gl, rows, columns, _this.textureConfig); });
  13944. };
  13945. GPGPUContext.prototype.createProgram = function (fragmentShaderSource) {
  13946. this.throwIfDisposed();
  13947. var gl = this.gl;
  13948. var fragmentShader = webgl_util.createFragmentShader(gl, fragmentShaderSource);
  13949. var vertexShader = gpgpu_util.createVertexShader(gl);
  13950. var program = webgl_util.createProgram(gl);
  13951. webgl_util.callAndCheck(gl, function () { return gl.attachShader(program, vertexShader); });
  13952. webgl_util.callAndCheck(gl, function () { return gl.attachShader(program, fragmentShader); });
  13953. webgl_util.linkProgram(gl, program);
  13954. if (this.autoDebugValidate) {
  13955. webgl_util.validateProgram(gl, program);
  13956. }
  13957. if (!this.vertexAttrsAreBound) {
  13958. this.setProgram(program);
  13959. this.vertexAttrsAreBound = gpgpu_util.bindVertexProgramAttributeStreams(gl, this.program, this.vertexBuffer);
  13960. }
  13961. return program;
  13962. };
  13963. GPGPUContext.prototype.deleteProgram = function (program) {
  13964. var _this = this;
  13965. this.throwIfDisposed();
  13966. if (program === this.program) {
  13967. this.program = null;
  13968. }
  13969. if (program != null) {
  13970. webgl_util.callAndCheck(this.gl, function () { return _this.gl.deleteProgram(program); });
  13971. }
  13972. };
  13973. GPGPUContext.prototype.setProgram = function (program) {
  13974. var _this = this;
  13975. this.throwIfDisposed();
  13976. this.program = program;
  13977. if ((this.program != null) && this.autoDebugValidate) {
  13978. webgl_util.validateProgram(this.gl, this.program);
  13979. }
  13980. webgl_util.callAndCheck(this.gl, function () { return _this.gl.useProgram(program); });
  13981. };
  13982. GPGPUContext.prototype.getUniformLocation = function (program, uniformName, shouldThrow) {
  13983. if (shouldThrow === void 0) { shouldThrow = true; }
  13984. this.throwIfDisposed();
  13985. if (shouldThrow) {
  13986. return webgl_util.getProgramUniformLocationOrThrow(this.gl, program, uniformName);
  13987. }
  13988. else {
  13989. return webgl_util.getProgramUniformLocation(this.gl, program, uniformName);
  13990. }
  13991. };
  13992. GPGPUContext.prototype.getAttributeLocation = function (program, attribute) {
  13993. var _this = this;
  13994. this.throwIfDisposed();
  13995. return webgl_util.callAndCheck(this.gl, function () { return _this.gl.getAttribLocation(program, attribute); });
  13996. };
  13997. GPGPUContext.prototype.getUniformLocationNoThrow = function (program, uniformName) {
  13998. this.throwIfDisposed();
  13999. return this.gl.getUniformLocation(program, uniformName);
  14000. };
  14001. GPGPUContext.prototype.setInputMatrixTexture = function (inputMatrixTexture, uniformLocation, textureUnit) {
  14002. this.throwIfDisposed();
  14003. this.throwIfNoProgram();
  14004. webgl_util.bindTextureToProgramUniformSampler(this.gl, this.program, inputMatrixTexture, uniformLocation, textureUnit);
  14005. };
  14006. GPGPUContext.prototype.setOutputMatrixTexture = function (outputMatrixTexture, rows, columns) {
  14007. this.setOutputMatrixTextureDriver(outputMatrixTexture, columns, rows);
  14008. };
  14009. GPGPUContext.prototype.setOutputPackedMatrixTexture = function (outputPackedMatrixTexture, rows, columns) {
  14010. this.throwIfDisposed();
  14011. var _a = tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
  14012. this.setOutputMatrixTextureDriver(outputPackedMatrixTexture, width, height);
  14013. };
  14014. GPGPUContext.prototype.setOutputMatrixWriteRegion = function (startRow, numRows, startColumn, numColumns) {
  14015. this.setOutputMatrixWriteRegionDriver(startColumn, startRow, numColumns, numRows);
  14016. };
  14017. GPGPUContext.prototype.setOutputPackedMatrixWriteRegion = function (startRow, numRows, startColumn, numColumns) {
  14018. throw new Error('setOutputPackedMatrixWriteRegion not implemented.');
  14019. };
  14020. GPGPUContext.prototype.debugValidate = function () {
  14021. if (this.program != null) {
  14022. webgl_util.validateProgram(this.gl, this.program);
  14023. }
  14024. webgl_util.validateFramebuffer(this.gl);
  14025. };
  14026. GPGPUContext.prototype.executeProgram = function () {
  14027. this.throwIfDisposed();
  14028. this.throwIfNoProgram();
  14029. var gl = this.gl;
  14030. if (this.autoDebugValidate) {
  14031. this.debugValidate();
  14032. }
  14033. webgl_util.callAndCheck(gl, function () { return gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0); });
  14034. };
  14035. GPGPUContext.prototype.blockUntilAllProgramsCompleted = function () {
  14036. var _this = this;
  14037. this.throwIfDisposed();
  14038. webgl_util.callAndCheck(this.gl, function () { return _this.gl.finish(); });
  14039. };
  14040. GPGPUContext.prototype.getQueryTimerExtension = function () {
  14041. if (this.disjointQueryTimerExtension == null) {
  14042. this.disjointQueryTimerExtension =
  14043. webgl_util.getExtensionOrThrow(this.gl, environment_1.ENV.get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2 ?
  14044. 'EXT_disjoint_timer_query_webgl2' :
  14045. 'EXT_disjoint_timer_query');
  14046. }
  14047. return this.disjointQueryTimerExtension;
  14048. };
  14049. GPGPUContext.prototype.getQueryTimerExtensionWebGL2 = function () {
  14050. return this.getQueryTimerExtension();
  14051. };
  14052. GPGPUContext.prototype.getQueryTimerExtensionWebGL1 = function () {
  14053. return this.getQueryTimerExtension();
  14054. };
  14055. GPGPUContext.prototype.runQuery = function (queryFn) {
  14056. var query = this.beginQuery();
  14057. queryFn();
  14058. this.endQuery();
  14059. return this.pollQueryTime(query);
  14060. };
  14061. GPGPUContext.prototype.beginQuery = function () {
  14062. if (environment_1.ENV.get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2) {
  14063. var gl2 = this.gl;
  14064. var ext_1 = this.getQueryTimerExtensionWebGL2();
  14065. var query_1 = gl2.createQuery();
  14066. gl2.beginQuery(ext_1.TIME_ELAPSED_EXT, query_1);
  14067. return query_1;
  14068. }
  14069. var ext = this.getQueryTimerExtensionWebGL1();
  14070. var query = ext.createQueryEXT();
  14071. ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, query);
  14072. return query;
  14073. };
  14074. GPGPUContext.prototype.endQuery = function () {
  14075. if (environment_1.ENV.get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2) {
  14076. var gl2 = this.gl;
  14077. var ext_2 = this.getQueryTimerExtensionWebGL2();
  14078. gl2.endQuery(ext_2.TIME_ELAPSED_EXT);
  14079. return;
  14080. }
  14081. var ext = this.getQueryTimerExtensionWebGL1();
  14082. ext.endQueryEXT(ext.TIME_ELAPSED_EXT);
  14083. };
  14084. GPGPUContext.prototype.isQueryAvailable = function (query, queryTimerVersion) {
  14085. if (queryTimerVersion === 0) {
  14086. return true;
  14087. }
  14088. if (queryTimerVersion === 2) {
  14089. var gl2 = this.gl;
  14090. var ext = this.getQueryTimerExtensionWebGL2();
  14091. var available = gl2.getQueryParameter(query, gl2.QUERY_RESULT_AVAILABLE);
  14092. if (this.disjoint == null) {
  14093. this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);
  14094. }
  14095. return available && !this.disjoint;
  14096. }
  14097. else {
  14098. var ext = this.getQueryTimerExtensionWebGL1();
  14099. var available = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_AVAILABLE_EXT);
  14100. if (this.disjoint == null) {
  14101. this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);
  14102. }
  14103. return available && !this.disjoint;
  14104. }
  14105. };
  14106. GPGPUContext.prototype.pollQueryTime = function (query) {
  14107. var _this = this;
  14108. return new Promise(function (resolve) {
  14109. var queryTimerVersion = environment_1.ENV.get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION');
  14110. _this.addItemToPoll(function () { return _this.isQueryAvailable(query, queryTimerVersion); }, function () { return resolve(_this.getQueryTime(query, queryTimerVersion)); });
  14111. });
  14112. };
  14113. GPGPUContext.prototype.pollItems = function () {
  14114. var index = binSearchLastTrue(this.itemsToPoll.map(function (x) { return x.isDoneFn; }));
  14115. for (var i = 0; i <= index; ++i) {
  14116. var resolveFn = this.itemsToPoll[i].resolveFn;
  14117. resolveFn();
  14118. }
  14119. this.itemsToPoll = this.itemsToPoll.slice(index + 1);
  14120. };
  14121. GPGPUContext.prototype.addItemToPoll = function (isDoneFn, resolveFn) {
  14122. var _this = this;
  14123. this.itemsToPoll.push({ isDoneFn: isDoneFn, resolveFn: resolveFn });
  14124. if (this.itemsToPoll.length > 1) {
  14125. return;
  14126. }
  14127. util.repeatedTry(function () {
  14128. _this.pollItems();
  14129. return _this.itemsToPoll.length === 0;
  14130. });
  14131. };
  14132. GPGPUContext.prototype.getQueryTime = function (query, queryTimerVersion) {
  14133. if (queryTimerVersion === 0) {
  14134. return null;
  14135. }
  14136. if (queryTimerVersion === 2) {
  14137. var gl2 = this.gl;
  14138. var timeElapsedNanos = gl2.getQueryParameter(query, gl2.QUERY_RESULT);
  14139. return timeElapsedNanos / 1000000;
  14140. }
  14141. else {
  14142. var ext = this.getQueryTimerExtensionWebGL1();
  14143. var timeElapsedNanos = ext.getQueryObjectEXT(query, ext.QUERY_RESULT_EXT);
  14144. return timeElapsedNanos / 1000000;
  14145. }
  14146. };
  14147. GPGPUContext.prototype.downloadMatrixDriverSetup = function (texture) {
  14148. this.throwIfDisposed();
  14149. webgl_util.bindColorTextureToFramebuffer(this.gl, texture, this.framebuffer);
  14150. if (this.autoDebugValidate) {
  14151. webgl_util.validateFramebuffer(this.gl);
  14152. }
  14153. };
  14154. GPGPUContext.prototype.downloadMatrixDriverTeardown = function () {
  14155. if (this.outputTexture != null) {
  14156. webgl_util.bindColorTextureToFramebuffer(this.gl, this.outputTexture, this.framebuffer);
  14157. if (this.autoDebugValidate) {
  14158. webgl_util.validateFramebuffer(this.gl);
  14159. }
  14160. }
  14161. else {
  14162. webgl_util.unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);
  14163. }
  14164. };
  14165. GPGPUContext.prototype.downloadMatrixDriver = function (texture, downloadAndDecode) {
  14166. this.downloadMatrixDriverSetup(texture);
  14167. var result = downloadAndDecode();
  14168. this.downloadMatrixDriverTeardown();
  14169. return result;
  14170. };
  14171. GPGPUContext.prototype.downloadMatrixDriverAsync = function (texture, downloadAndDecode) {
  14172. return __awaiter(this, void 0, void 0, function () {
  14173. var result;
  14174. return __generator(this, function (_a) {
  14175. switch (_a.label) {
  14176. case 0:
  14177. this.downloadMatrixDriverSetup(texture);
  14178. return [4, downloadAndDecode()];
  14179. case 1:
  14180. result = _a.sent();
  14181. this.downloadMatrixDriverTeardown();
  14182. return [2, result];
  14183. }
  14184. });
  14185. });
  14186. };
  14187. GPGPUContext.prototype.setOutputMatrixTextureDriver = function (outputMatrixTextureMaybePacked, width, height) {
  14188. this.throwIfDisposed();
  14189. var gl = this.gl;
  14190. webgl_util.bindColorTextureToFramebuffer(gl, outputMatrixTextureMaybePacked, this.framebuffer);
  14191. if (this.autoDebugValidate) {
  14192. webgl_util.validateFramebuffer(gl);
  14193. }
  14194. this.outputTexture = outputMatrixTextureMaybePacked;
  14195. webgl_util.callAndCheck(gl, function () { return gl.viewport(0, 0, width, height); });
  14196. webgl_util.callAndCheck(gl, function () { return gl.scissor(0, 0, width, height); });
  14197. };
  14198. GPGPUContext.prototype.setOutputMatrixWriteRegionDriver = function (x, y, width, height) {
  14199. var _this = this;
  14200. this.throwIfDisposed();
  14201. webgl_util.callAndCheck(this.gl, function () { return _this.gl.scissor(x, y, width, height); });
  14202. };
  14203. GPGPUContext.prototype.throwIfDisposed = function () {
  14204. if (this.disposed) {
  14205. throw new Error('Attempted to use disposed GPGPUContext.');
  14206. }
  14207. };
  14208. GPGPUContext.prototype.throwIfNoProgram = function () {
  14209. if (this.program == null) {
  14210. throw new Error('No GPU program is currently set.');
  14211. }
  14212. };
  14213. return GPGPUContext;
  14214. }());
  14215. exports.GPGPUContext = GPGPUContext;
  14216. function binSearchLastTrue(arr) {
  14217. var start = 0;
  14218. var end = arr.length - 1;
  14219. var best = -1;
  14220. while (start <= end) {
  14221. var mid = (start + end) >> 1;
  14222. var isDone = arr[mid]();
  14223. if (isDone) {
  14224. best = mid;
  14225. start = mid + 1;
  14226. }
  14227. else {
  14228. end = mid - 1;
  14229. }
  14230. }
  14231. return best;
  14232. }
  14233. exports.binSearchLastTrue = binSearchLastTrue;
  14234. },{"../../environment":51,"../../util":164,"./gpgpu_util":84,"./tex_util":102,"./webgl_util":107}],83:[function(require,module,exports){
  14235. "use strict";
  14236. Object.defineProperty(exports, "__esModule", { value: true });
  14237. var util = require("../../util");
  14238. var shader_compiler = require("./shader_compiler");
  14239. function compileProgram(gpgpu, program, inputs, output) {
  14240. var userCode = program.userCode;
  14241. var inputInfos = inputs.map(function (input, i) {
  14242. var shapeInfo = {
  14243. logicalShape: input.tensor.shape,
  14244. texShape: input.isUniform ? null : input.texData.texShape,
  14245. isUniform: input.isUniform
  14246. };
  14247. return { name: program.variableNames[i], shapeInfo: shapeInfo };
  14248. });
  14249. var inShapeInfos = inputInfos.map(function (x) { return x.shapeInfo; });
  14250. var outShapeInfo = {
  14251. logicalShape: output.tensor.shape,
  14252. texShape: output.texData.texShape,
  14253. isUniform: false
  14254. };
  14255. var source = shader_compiler.makeShader(inputInfos, outShapeInfo, userCode, program.supportsBroadcasting === true);
  14256. var webGLProgram = gpgpu.createProgram(source);
  14257. var uniformLocations = {};
  14258. for (var i = 0; i < program.variableNames.length; i++) {
  14259. var uniformName = program.variableNames[i];
  14260. var shouldThrow = false;
  14261. uniformLocations[uniformName] =
  14262. gpgpu.getUniformLocation(webGLProgram, uniformName, shouldThrow);
  14263. }
  14264. return {
  14265. program: program,
  14266. source: source,
  14267. webGLProgram: webGLProgram,
  14268. uniformLocations: uniformLocations,
  14269. gpgpu: gpgpu,
  14270. inShapeInfos: inShapeInfos,
  14271. outShapeInfo: outShapeInfo
  14272. };
  14273. }
  14274. exports.compileProgram = compileProgram;
  14275. function validateBinaryAndProgram(shapeInfos, inputs) {
  14276. if (shapeInfos.length !== inputs.length) {
  14277. throw Error("Binary was compiled with " + shapeInfos.length + " inputs, but " +
  14278. ("was executed with " + inputs.length + " inputs"));
  14279. }
  14280. shapeInfos.forEach(function (s, i) {
  14281. var shapeA = s.logicalShape;
  14282. var input = inputs[i];
  14283. var shapeB = input.tensor.shape;
  14284. if (!util.arraysEqual(shapeA, shapeB)) {
  14285. throw Error("Binary was compiled with different shapes than " +
  14286. ("the current args. Shapes " + shapeA + " and " + shapeB + " must match"));
  14287. }
  14288. if (s.isUniform && input.isUniform) {
  14289. return;
  14290. }
  14291. var texShapeA = s.texShape;
  14292. var texShapeB = input.isUniform ? null : input.texData.texShape;
  14293. if (!util.arraysEqual(texShapeA, texShapeB)) {
  14294. throw Error("Binary was compiled with different texture shapes than the" +
  14295. (" current args. Shape " + texShapeA + " and " + texShapeB + " must match"));
  14296. }
  14297. });
  14298. }
  14299. function runProgram(binary, inputs, output, customSetup) {
  14300. validateBinaryAndProgram(binary.inShapeInfos, inputs);
  14301. validateBinaryAndProgram([binary.outShapeInfo], [output]);
  14302. var outTex = output.texData.texture;
  14303. var outTexShape = output.texData.texShape;
  14304. var gpgpu = binary.gpgpu;
  14305. gpgpu.setOutputMatrixTexture(outTex, outTexShape[0], outTexShape[1]);
  14306. gpgpu.setProgram(binary.webGLProgram);
  14307. inputs.forEach(function (input, i) {
  14308. var variableName = binary.program.variableNames[i];
  14309. var variableUniformLocation = binary.uniformLocations[variableName];
  14310. if (variableUniformLocation != null) {
  14311. if (input.isUniform) {
  14312. if (input.tensor.size === 1) {
  14313. gpgpu.gl.uniform1f(variableUniformLocation, input.tensor.dataSync()[0]);
  14314. }
  14315. else {
  14316. var vals = input.tensor.dataSync();
  14317. if (!(vals instanceof Float32Array)) {
  14318. vals = new Float32Array(vals);
  14319. }
  14320. gpgpu.gl.uniform1fv(variableUniformLocation, vals);
  14321. }
  14322. return;
  14323. }
  14324. var tex = input.texData.texture;
  14325. gpgpu.setInputMatrixTexture(tex, variableUniformLocation, i);
  14326. }
  14327. });
  14328. if (customSetup != null) {
  14329. customSetup(gpgpu, binary.webGLProgram);
  14330. }
  14331. gpgpu.executeProgram();
  14332. }
  14333. exports.runProgram = runProgram;
  14334. function makeShaderKey(program, inputs, output) {
  14335. var keyInputs = '';
  14336. inputs.concat(output).forEach(function (x) {
  14337. keyInputs +=
  14338. x.tensor.shape + "_" + (x.isUniform ? 'uniform' : x.texData.texShape);
  14339. });
  14340. var keyUserCode = program.userCode;
  14341. var keyBroadcast = (program.supportsBroadcasting === true).toString();
  14342. var key = program.constructor.name;
  14343. key += '_' + keyBroadcast + '_' + keyInputs + '_' + keyUserCode;
  14344. return key;
  14345. }
  14346. exports.makeShaderKey = makeShaderKey;
  14347. },{"../../util":164,"./shader_compiler":99}],84:[function(require,module,exports){
  14348. "use strict";
  14349. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  14350. return new (P || (P = Promise))(function (resolve, reject) {
  14351. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  14352. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  14353. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  14354. step((generator = generator.apply(thisArg, _arguments || [])).next());
  14355. });
  14356. };
  14357. var __generator = (this && this.__generator) || function (thisArg, body) {
  14358. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  14359. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  14360. function verb(n) { return function (v) { return step([n, v]); }; }
  14361. function step(op) {
  14362. if (f) throw new TypeError("Generator is already executing.");
  14363. while (_) try {
  14364. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  14365. if (y = 0, t) op = [0, t.value];
  14366. switch (op[0]) {
  14367. case 0: case 1: t = op; break;
  14368. case 4: _.label++; return { value: op[1], done: false };
  14369. case 5: _.label++; y = op[1]; op = [0]; continue;
  14370. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  14371. default:
  14372. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  14373. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  14374. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  14375. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  14376. if (t[2]) _.ops.pop();
  14377. _.trys.pop(); continue;
  14378. }
  14379. op = body.call(thisArg, _);
  14380. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  14381. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  14382. }
  14383. };
  14384. Object.defineProperty(exports, "__esModule", { value: true });
  14385. var environment_1 = require("../../environment");
  14386. var tex_util = require("./tex_util");
  14387. var webgl_util = require("./webgl_util");
  14388. function getWebGLContextAttributes() {
  14389. return {
  14390. alpha: false,
  14391. antialias: false,
  14392. premultipliedAlpha: false,
  14393. preserveDrawingBuffer: false,
  14394. depth: false,
  14395. stencil: false,
  14396. failIfMajorPerformanceCaveat: true
  14397. };
  14398. }
  14399. exports.getWebGLContextAttributes = getWebGLContextAttributes;
  14400. function createWebGLContext(canvas) {
  14401. var attributes = getWebGLContextAttributes();
  14402. var gl;
  14403. if (canvas != null) {
  14404. gl = webgl_util.createWebGLRenderingContextFromCanvas(canvas, attributes);
  14405. }
  14406. else {
  14407. gl = webgl_util.createWebGLRenderingContext(attributes);
  14408. }
  14409. webgl_util.callAndCheck(gl, function () { return gl.disable(gl.DEPTH_TEST); });
  14410. webgl_util.callAndCheck(gl, function () { return gl.disable(gl.STENCIL_TEST); });
  14411. webgl_util.callAndCheck(gl, function () { return gl.disable(gl.BLEND); });
  14412. webgl_util.callAndCheck(gl, function () { return gl.disable(gl.DITHER); });
  14413. webgl_util.callAndCheck(gl, function () { return gl.disable(gl.POLYGON_OFFSET_FILL); });
  14414. webgl_util.callAndCheck(gl, function () { return gl.disable(gl.SAMPLE_COVERAGE); });
  14415. webgl_util.callAndCheck(gl, function () { return gl.enable(gl.SCISSOR_TEST); });
  14416. webgl_util.callAndCheck(gl, function () { return gl.enable(gl.CULL_FACE); });
  14417. webgl_util.callAndCheck(gl, function () { return gl.cullFace(gl.BACK); });
  14418. return gl;
  14419. }
  14420. exports.createWebGLContext = createWebGLContext;
  14421. function createVertexShader(gl) {
  14422. var vertexShaderSource = "\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }";
  14423. return webgl_util.createVertexShader(gl, vertexShaderSource);
  14424. }
  14425. exports.createVertexShader = createVertexShader;
  14426. function createVertexBuffer(gl) {
  14427. var vertexArray = new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);
  14428. return webgl_util.createStaticVertexBuffer(gl, vertexArray);
  14429. }
  14430. exports.createVertexBuffer = createVertexBuffer;
  14431. function createIndexBuffer(gl) {
  14432. var triangleVertexIndices = new Uint16Array([0, 1, 2, 2, 1, 3]);
  14433. return webgl_util.createStaticIndexBuffer(gl, triangleVertexIndices);
  14434. }
  14435. exports.createIndexBuffer = createIndexBuffer;
  14436. function getTextureConfig(gl, textureHalfFloatExtension) {
  14437. var glany = gl;
  14438. var internalFormatFloat;
  14439. var internalFormatHalfFloat;
  14440. var internalFormatPackedFloat;
  14441. var textureFormatFloat;
  14442. var downloadTextureFormat;
  14443. var downloadUnpackNumChannels;
  14444. var defaultNumChannels;
  14445. var textureTypeHalfFloat;
  14446. if (environment_1.ENV.get('WEBGL_VERSION') === 2) {
  14447. internalFormatFloat = glany.R32F;
  14448. internalFormatHalfFloat = glany.R16F;
  14449. internalFormatPackedFloat = glany.RGBA32F;
  14450. textureFormatFloat = glany.RED;
  14451. downloadUnpackNumChannels = 4;
  14452. defaultNumChannels = 1;
  14453. textureTypeHalfFloat = glany.HALF_FLOAT;
  14454. }
  14455. else {
  14456. internalFormatFloat = gl.RGBA;
  14457. internalFormatHalfFloat = gl.RGBA;
  14458. internalFormatPackedFloat = glany.RGBA;
  14459. textureFormatFloat = gl.RGBA;
  14460. downloadUnpackNumChannels = 4;
  14461. defaultNumChannels = 4;
  14462. textureTypeHalfFloat = textureHalfFloatExtension != null ?
  14463. textureHalfFloatExtension.HALF_FLOAT_OES :
  14464. null;
  14465. }
  14466. downloadTextureFormat = gl.RGBA;
  14467. return {
  14468. internalFormatFloat: internalFormatFloat,
  14469. internalFormatHalfFloat: internalFormatHalfFloat,
  14470. internalFormatPackedFloat: internalFormatPackedFloat,
  14471. textureFormatFloat: textureFormatFloat,
  14472. downloadTextureFormat: downloadTextureFormat,
  14473. downloadUnpackNumChannels: downloadUnpackNumChannels,
  14474. defaultNumChannels: defaultNumChannels,
  14475. textureTypeHalfFloat: textureTypeHalfFloat
  14476. };
  14477. }
  14478. exports.getTextureConfig = getTextureConfig;
  14479. function createAndConfigureTexture(gl, width, height, internalFormat, textureFormat, textureType) {
  14480. webgl_util.validateTextureSize(gl, width, height);
  14481. var texture = webgl_util.createTexture(gl);
  14482. var tex2d = gl.TEXTURE_2D;
  14483. webgl_util.callAndCheck(gl, function () { return gl.bindTexture(tex2d, texture); });
  14484. webgl_util.callAndCheck(gl, function () { return gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); });
  14485. webgl_util.callAndCheck(gl, function () { return gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); });
  14486. webgl_util.callAndCheck(gl, function () { return gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST); });
  14487. webgl_util.callAndCheck(gl, function () { return gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST); });
  14488. webgl_util.callAndCheck(gl, function () { return gl.texImage2D(tex2d, 0, internalFormat, width, height, 0, textureFormat, textureType, null); });
  14489. webgl_util.callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, null); });
  14490. return texture;
  14491. }
  14492. function createFloat32MatrixTexture(gl, rows, columns, textureConfig) {
  14493. var _a = tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
  14494. return createAndConfigureTexture(gl, width, height, textureConfig.internalFormatFloat, textureConfig.textureFormatFloat, gl.FLOAT);
  14495. }
  14496. exports.createFloat32MatrixTexture = createFloat32MatrixTexture;
  14497. function createFloat16MatrixTexture(gl, rows, columns, textureConfig) {
  14498. var _a = tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
  14499. return createAndConfigureTexture(gl, width, height, textureConfig.internalFormatFloat, textureConfig.textureFormatFloat, textureConfig.textureTypeHalfFloat);
  14500. }
  14501. exports.createFloat16MatrixTexture = createFloat16MatrixTexture;
  14502. function createUnsignedBytesMatrixTexture(gl, rows, columns, textureConfig) {
  14503. var _a = tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
  14504. return createAndConfigureTexture(gl, width, height, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE);
  14505. }
  14506. exports.createUnsignedBytesMatrixTexture = createUnsignedBytesMatrixTexture;
  14507. function createPackedMatrixTexture(gl, rows, columns, textureConfig) {
  14508. var _a = tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns), width = _a[0], height = _a[1];
  14509. return createAndConfigureTexture(gl, width, height, textureConfig.internalFormatPackedFloat, gl.RGBA, gl.FLOAT);
  14510. }
  14511. exports.createPackedMatrixTexture = createPackedMatrixTexture;
  14512. function bindVertexProgramAttributeStreams(gl, program, vertexBuffer) {
  14513. var posOffset = 0;
  14514. var uvOffset = 3 * 4;
  14515. var stride = (3 * 4) + (2 * 4);
  14516. webgl_util.callAndCheck(gl, function () { return gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); });
  14517. var success = webgl_util.bindVertexBufferToProgramAttribute(gl, program, 'clipSpacePos', vertexBuffer, 3, stride, posOffset);
  14518. return success &&
  14519. webgl_util.bindVertexBufferToProgramAttribute(gl, program, 'uv', vertexBuffer, 2, stride, uvOffset);
  14520. }
  14521. exports.bindVertexProgramAttributeStreams = bindVertexProgramAttributeStreams;
  14522. function uploadPixelDataToTexture(gl, texture, pixels) {
  14523. webgl_util.callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, texture); });
  14524. webgl_util.callAndCheck(gl, function () { return gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, pixels); });
  14525. webgl_util.callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, null); });
  14526. }
  14527. exports.uploadPixelDataToTexture = uploadPixelDataToTexture;
  14528. function uploadDataToTexture(gl, texture, width, height, data, textureFormat) {
  14529. webgl_util.validateTextureSize(gl, width, height);
  14530. webgl_util.callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, texture); });
  14531. webgl_util.callAndCheck(gl, function () { return gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, textureFormat, gl.FLOAT, data); });
  14532. webgl_util.callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, null); });
  14533. }
  14534. function uploadMatrixToTexture(gl, texture, rows, columns, matrix, numChannels, textureConfig) {
  14535. var _a = tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns), w = _a[0], h = _a[1];
  14536. var unpackedArray;
  14537. if (textureConfig.defaultNumChannels === 1) {
  14538. unpackedArray = matrix;
  14539. }
  14540. else {
  14541. unpackedArray =
  14542. new Float32Array(tex_util.getUnpackedArraySizeFromMatrixSize(matrix.length, numChannels));
  14543. tex_util.encodeMatrixToUnpackedArray(matrix, unpackedArray, numChannels);
  14544. }
  14545. uploadDataToTexture(gl, texture, w, h, unpackedArray, textureConfig.textureFormatFloat);
  14546. }
  14547. exports.uploadMatrixToTexture = uploadMatrixToTexture;
  14548. function uploadMatrixToPackedTexture(gl, texture, rows, columns, matrix, textureConfig) {
  14549. var _a = tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns), w = _a[0], h = _a[1];
  14550. var packedRGBA = new Float32Array(tex_util.getPackedRGBAArraySizeFromMatrixShape(rows, columns));
  14551. tex_util.encodeMatrixToPackedRGBA(matrix, rows, columns, packedRGBA);
  14552. uploadDataToTexture(gl, texture, w, h, packedRGBA, gl.RGBA);
  14553. }
  14554. exports.uploadMatrixToPackedTexture = uploadMatrixToPackedTexture;
  14555. function downloadMatrixFromOutputTextureAsync(gl, getBufferSubDataAsyncExtension, rows, columns, textureConfig) {
  14556. return __awaiter(this, void 0, void 0, function () {
  14557. var gl2, downloadTarget, bufferSizeBytes, buffer, matrix;
  14558. return __generator(this, function (_a) {
  14559. switch (_a.label) {
  14560. case 0:
  14561. gl2 = gl;
  14562. downloadTarget = new Float32Array(tex_util.getUnpackedArraySizeFromMatrixSize(rows * columns, textureConfig.downloadUnpackNumChannels));
  14563. bufferSizeBytes = downloadTarget instanceof Float32Array ?
  14564. downloadTarget.length * 4 :
  14565. downloadTarget;
  14566. buffer = gl.createBuffer();
  14567. webgl_util.callAndCheck(gl, function () { return gl.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer); });
  14568. webgl_util.callAndCheck(gl, function () { return gl.bufferData(gl2.PIXEL_PACK_BUFFER, bufferSizeBytes, gl.STATIC_DRAW); });
  14569. webgl_util.callAndCheck(gl, function () { return gl2.readPixels(0, 0, columns, rows, gl.RGBA, gl.FLOAT, 0); });
  14570. return [4, getBufferSubDataAsyncExtension.getBufferSubDataAsync(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget)];
  14571. case 1:
  14572. _a.sent();
  14573. matrix = new Float32Array(rows * columns);
  14574. tex_util.decodeMatrixFromUnpackedArray(downloadTarget, matrix, textureConfig.downloadUnpackNumChannels);
  14575. return [2, matrix];
  14576. }
  14577. });
  14578. });
  14579. }
  14580. exports.downloadMatrixFromOutputTextureAsync = downloadMatrixFromOutputTextureAsync;
  14581. function downloadFloat32MatrixFromOutputTexture(gl, rows, columns, textureConfig) {
  14582. var _a = tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns), w = _a[0], h = _a[1];
  14583. var downloadTarget = new Float32Array(tex_util.getUnpackedArraySizeFromMatrixSize(rows * columns, textureConfig.downloadUnpackNumChannels));
  14584. webgl_util.callAndCheck(gl, function () { return gl.readPixels(0, 0, w, h, textureConfig.downloadTextureFormat, gl.FLOAT, downloadTarget); });
  14585. var matrix = new Float32Array(rows * columns);
  14586. tex_util.decodeMatrixFromUnpackedArray(downloadTarget, matrix, textureConfig.downloadUnpackNumChannels);
  14587. return matrix;
  14588. }
  14589. exports.downloadFloat32MatrixFromOutputTexture = downloadFloat32MatrixFromOutputTexture;
  14590. function downloadByteEncodedFloatMatrixFromOutputTexture(gl, rows, columns, textureConfig) {
  14591. var _a = tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns), w = _a[0], h = _a[1];
  14592. var numChannels = 4;
  14593. var downloadTarget = new Uint8Array(tex_util.getUnpackedArraySizeFromMatrixSize(rows * columns, numChannels));
  14594. webgl_util.callAndCheck(gl, function () { return gl.readPixels(0, 0, w, h, textureConfig.downloadTextureFormat, gl.UNSIGNED_BYTE, downloadTarget); });
  14595. return new Float32Array(downloadTarget.buffer);
  14596. }
  14597. exports.downloadByteEncodedFloatMatrixFromOutputTexture = downloadByteEncodedFloatMatrixFromOutputTexture;
  14598. function downloadMatrixFromPackedOutputTexture(gl, rows, columns, textureConfig) {
  14599. var _a = tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns), w = _a[0], h = _a[1];
  14600. var packedRGBA = new Float32Array(tex_util.getPackedRGBAArraySizeFromMatrixShape(rows, columns));
  14601. webgl_util.callAndCheck(gl, function () { return gl.readPixels(0, 0, w, h, gl.RGBA, gl.FLOAT, packedRGBA); });
  14602. var matrix = new Float32Array(rows * columns);
  14603. return tex_util.decodeMatrixFromPackedRGBA(packedRGBA, rows, columns, matrix);
  14604. }
  14605. exports.downloadMatrixFromPackedOutputTexture = downloadMatrixFromPackedOutputTexture;
  14606. },{"../../environment":51,"./tex_util":102,"./webgl_util":107}],85:[function(require,module,exports){
  14607. "use strict";
  14608. Object.defineProperty(exports, "__esModule", { value: true });
  14609. var shader_compiler_1 = require("./shader_compiler");
  14610. var WhereProgram = (function () {
  14611. function WhereProgram(cRank, shape, rank) {
  14612. this.variableNames = ['c', 'a', 'b'];
  14613. this.outputShape = shape;
  14614. var cCoords;
  14615. var abCoords;
  14616. if (rank > 4) {
  14617. throw Error("Where for rank " + rank + " is not yet supported");
  14618. }
  14619. if (rank === 1) {
  14620. abCoords = "resRC";
  14621. cCoords = "resRC";
  14622. }
  14623. else {
  14624. var currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w'];
  14625. var cCoordVars = [];
  14626. var abCoordVars = [];
  14627. for (var i = 0; i < shape.length; i++) {
  14628. abCoordVars.push("" + currentCoords[i]);
  14629. if (i < cRank) {
  14630. cCoordVars.push("" + currentCoords[i]);
  14631. }
  14632. }
  14633. cCoords = cCoordVars.join();
  14634. abCoords = abCoordVars.join();
  14635. }
  14636. var dtype = shader_compiler_1.getCoordsDataType(rank);
  14637. this.userCode = "\n void main() {\n " + dtype + " resRC = getOutputCoords();\n float cVal = getC(" + cCoords + ");\n if (cVal >= 1.0) {\n setOutput(getA(" + abCoords + "));\n } else {\n setOutput(getB(" + abCoords + "));\n }\n }\n ";
  14638. }
  14639. return WhereProgram;
  14640. }());
  14641. exports.WhereProgram = WhereProgram;
  14642. },{"./shader_compiler":99}],86:[function(require,module,exports){
  14643. "use strict";
  14644. Object.defineProperty(exports, "__esModule", { value: true });
  14645. var LRNProgram = (function () {
  14646. function LRNProgram(xShape, radius, bias, alpha, beta) {
  14647. this.variableNames = ['x'];
  14648. this.outputShape = [];
  14649. var rad = radius;
  14650. var maxD = xShape[3] - 1;
  14651. this.outputShape = xShape;
  14652. var powOperator;
  14653. var basis = "float(" + bias + ") + float(" + alpha + ") * sum";
  14654. if (beta === 0.5) {
  14655. powOperator = "inversesqrt(" + basis + ")";
  14656. }
  14657. else if (beta === 1.0) {
  14658. powOperator = "1.0/(" + basis + ")";
  14659. }
  14660. else {
  14661. powOperator = "exp(log(" + basis + ") * float(-" + beta + "));";
  14662. }
  14663. this.userCode = "\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -" + rad + "; j <= " + rad + "; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= " + maxD + ") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * " + powOperator + ";\n setOutput(val);\n }\n ";
  14664. }
  14665. return LRNProgram;
  14666. }());
  14667. exports.LRNProgram = LRNProgram;
  14668. },{}],87:[function(require,module,exports){
  14669. "use strict";
  14670. Object.defineProperty(exports, "__esModule", { value: true });
  14671. var MaxPool2DBackpropProgram = (function () {
  14672. function MaxPool2DBackpropProgram(convInfo) {
  14673. this.variableNames = ['dy', 'maxPos'];
  14674. this.outputShape = convInfo.inShape;
  14675. var filterHeight = convInfo.filterHeight;
  14676. var filterWidth = convInfo.filterWidth;
  14677. var strideHeight = convInfo.strideHeight;
  14678. var strideWidth = convInfo.strideWidth;
  14679. var padTop = filterHeight - 1 - convInfo.padInfo.top;
  14680. var padLeft = filterWidth - 1 - convInfo.padInfo.left;
  14681. var lastIndex = filterHeight * filterWidth - 1;
  14682. this.userCode = "\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n float dyR = float(dyRCorner + wR) / " + strideHeight + ".0;\n\n if (dyR < 0.0 || dyR >= " + convInfo.outHeight + ".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n float dyC = float(dyCCorner + wC) / " + strideWidth + ".0;\n\n if (dyC < 0.0 || dyC >= " + convInfo.outWidth + ".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = " + lastIndex + " - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * " + filterWidth + " + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n ";
  14683. }
  14684. return MaxPool2DBackpropProgram;
  14685. }());
  14686. exports.MaxPool2DBackpropProgram = MaxPool2DBackpropProgram;
  14687. },{}],88:[function(require,module,exports){
  14688. "use strict";
  14689. Object.defineProperty(exports, "__esModule", { value: true });
  14690. var MatMulProgram = (function () {
  14691. function MatMulProgram(aShape, bShape, transposeA, transposeB) {
  14692. if (transposeA === void 0) { transposeA = false; }
  14693. if (transposeB === void 0) { transposeB = false; }
  14694. this.variableNames = ['matrixA', 'matrixB'];
  14695. var outerShapeA = transposeA ? aShape[1] : aShape[0];
  14696. var outerShapeB = transposeB ? bShape[0] : bShape[1];
  14697. var sharedDim = transposeA ? aShape[0] : aShape[1];
  14698. this.outputShape = [outerShapeA, outerShapeB];
  14699. var aSnippetFromOffset = function (vec4Offset, indexVar) {
  14700. return transposeA ? indexVar + " + " + vec4Offset + ", aRow" :
  14701. "aRow, " + indexVar + " + " + vec4Offset;
  14702. };
  14703. var bSnippetFromOffset = function (vec4Offset, indexVar) {
  14704. return transposeB ? "bCol, " + indexVar + " + " + vec4Offset :
  14705. indexVar + " + " + vec4Offset + ", bCol";
  14706. };
  14707. var sharedDimNearestVec4 = Math.floor(sharedDim / 4) * 4;
  14708. var sharedDimVec4Remainder = sharedDim % 4;
  14709. this.userCode = " float dotARowBCol(int aRow, int bCol) {\n float result = 0.0;\n for (int i = 0; i < " + sharedDimNearestVec4 + "; i += 4) {\n vec4 a = vec4(\n getMatrixA(" + aSnippetFromOffset(0, 'i') + "),\n getMatrixA(" + aSnippetFromOffset(1, 'i') + "),\n getMatrixA(" + aSnippetFromOffset(2, 'i') + "),\n getMatrixA(" + aSnippetFromOffset(3, 'i') + ")\n );\n vec4 b = vec4(\n getMatrixB(" + bSnippetFromOffset(0, 'i') + "),\n getMatrixB(" + bSnippetFromOffset(1, 'i') + "),\n getMatrixB(" + bSnippetFromOffset(2, 'i') + "),\n getMatrixB(" + bSnippetFromOffset(3, 'i') + ")\n );\n\n result += dot(a, b);\n }\n\n if (" + (sharedDimVec4Remainder === 1) + ") {\n result += getMatrixA(" + aSnippetFromOffset(0, sharedDimNearestVec4) + ") *\n getMatrixB(" + bSnippetFromOffset(0, sharedDimNearestVec4) + ");\n } else if (" + (sharedDimVec4Remainder === 2) + ") {\n vec2 a = vec2(\n getMatrixA(" + aSnippetFromOffset(0, sharedDimNearestVec4) + "),\n getMatrixA(" + aSnippetFromOffset(1, sharedDimNearestVec4) + ")\n );\n vec2 b = vec2(\n getMatrixB(" + bSnippetFromOffset(0, sharedDimNearestVec4) + "),\n getMatrixB(" + bSnippetFromOffset(1, sharedDimNearestVec4) + ")\n );\n result += dot(a, b);\n } else if (" + (sharedDimVec4Remainder === 3) + ") {\n vec3 a = vec3(\n getMatrixA(" + aSnippetFromOffset(0, sharedDimNearestVec4) + "),\n getMatrixA(" + aSnippetFromOffset(1, sharedDimNearestVec4) + "),\n getMatrixA(" + aSnippetFromOffset(2, sharedDimNearestVec4) + ")\n );\n vec3 b = vec3(\n getMatrixB(" + bSnippetFromOffset(0, sharedDimNearestVec4) + "),\n getMatrixB(" + bSnippetFromOffset(1, sharedDimNearestVec4) + "),\n getMatrixB(" + bSnippetFromOffset(2, sharedDimNearestVec4) + ")\n );\n result += dot(a, b);\n }\n\n return result;\n }\n\n void main() {\n ivec2 resRC = getOutputCoords();\n setOutput(dotARowBCol(resRC.x, resRC.y));\n }\n ";
  14710. }
  14711. return MatMulProgram;
  14712. }());
  14713. exports.MatMulProgram = MatMulProgram;
  14714. },{}],89:[function(require,module,exports){
  14715. "use strict";
  14716. Object.defineProperty(exports, "__esModule", { value: true });
  14717. var MultinomialProgram = (function () {
  14718. function MultinomialProgram(batchSize, numOutcomes, numSamples) {
  14719. this.variableNames = ['probs'];
  14720. this.outputShape = [batchSize, numSamples];
  14721. this.userCode = "\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < " + (numOutcomes - 1) + "; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float(" + (numOutcomes - 1) + "));\n }\n ";
  14722. }
  14723. MultinomialProgram.prototype.getCustomSetupFunc = function (seed) {
  14724. var _this = this;
  14725. return function (gpgpu, webGLProgram) {
  14726. if (_this.seedLoc == null) {
  14727. _this.seedLoc = gpgpu.getUniformLocation(webGLProgram, 'seed');
  14728. }
  14729. gpgpu.gl.uniform1f(_this.seedLoc, seed);
  14730. };
  14731. };
  14732. return MultinomialProgram;
  14733. }());
  14734. exports.MultinomialProgram = MultinomialProgram;
  14735. },{}],90:[function(require,module,exports){
  14736. "use strict";
  14737. Object.defineProperty(exports, "__esModule", { value: true });
  14738. var OneHotProgram = (function () {
  14739. function OneHotProgram(numIndices, depth, onValue, offValue) {
  14740. this.variableNames = ['indices'];
  14741. this.outputShape = [numIndices, depth];
  14742. this.userCode = "\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(" + offValue + "), float(" + onValue + "),\n float(index == coords.y)));\n }\n ";
  14743. }
  14744. return OneHotProgram;
  14745. }());
  14746. exports.OneHotProgram = OneHotProgram;
  14747. },{}],91:[function(require,module,exports){
  14748. "use strict";
  14749. Object.defineProperty(exports, "__esModule", { value: true });
  14750. var shader_compiler_1 = require("./shader_compiler");
  14751. var PadProgram = (function () {
  14752. function PadProgram(xShape, paddings, constantValue) {
  14753. this.variableNames = ['x'];
  14754. this.outputShape = paddings.map(function (p, i) { return p[0] + xShape[i] + p[1]; });
  14755. var rank = xShape.length;
  14756. var type = shader_compiler_1.getCoordsDataType(rank);
  14757. var start = paddings.map(function (p) { return p[0]; }).join(',');
  14758. var end = paddings.map(function (p, i) { return p[0] + xShape[i]; }).join(',');
  14759. var unpackedCoords = ['coords[0]', 'coords[1]', 'coords[2]', 'coords[3]'].slice(0, rank);
  14760. if (rank === 1) {
  14761. this.userCode = "\n int start = " + start + ";\n int end = " + end + ";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float(" + constantValue + "));\n } else {\n setOutput(getX(outC - start));\n }\n }\n ";
  14762. return;
  14763. }
  14764. this.userCode = "\n " + type + " start = " + type + "(" + start + ");\n " + type + " end = " + type + "(" + end + ");\n\n void main() {\n " + type + " outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float(" + constantValue + "));\n } else {\n " + type + " coords = outC - start;\n setOutput(getX(" + unpackedCoords + "));\n }\n }\n ";
  14765. }
  14766. return PadProgram;
  14767. }());
  14768. exports.PadProgram = PadProgram;
  14769. },{"./shader_compiler":99}],92:[function(require,module,exports){
  14770. "use strict";
  14771. Object.defineProperty(exports, "__esModule", { value: true });
  14772. var Pool2DProgram = (function () {
  14773. function Pool2DProgram(convInfo, poolType, computePositions) {
  14774. this.variableNames = ['x'];
  14775. if (poolType === 'avg' && computePositions) {
  14776. throw new Error('Cannot compute positions for average pool.');
  14777. }
  14778. var filterHeight = convInfo.filterHeight;
  14779. var filterWidth = convInfo.filterWidth;
  14780. var strideHeight = convInfo.strideHeight;
  14781. var strideWidth = convInfo.strideWidth;
  14782. var padTop = convInfo.padInfo.top;
  14783. var padLeft = convInfo.padInfo.left;
  14784. this.outputShape = convInfo.outShape;
  14785. var isAvgPool = poolType === 'avg';
  14786. var initializationValue = '0.0';
  14787. if (!isAvgPool) {
  14788. initializationValue = '-1.0 / 0.0';
  14789. }
  14790. if (computePositions) {
  14791. var compareOp_1 = '>=';
  14792. this.userCode = "\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + filterWidth + "; wC++) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= " + convInfo.inWidth + ") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value " + compareOp_1 + " currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * " + filterWidth + " + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";
  14793. return;
  14794. }
  14795. var compareOp = 'max';
  14796. var returnValue = poolType + "(" + poolType + "(" + poolType + "(" +
  14797. 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';
  14798. if (poolType === 'avg') {
  14799. returnValue = "avgValue / count";
  14800. }
  14801. var filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;
  14802. var filterWidthVec4Remainder = filterWidth % 4;
  14803. var updateSnippet = "\n if (" + isAvgPool + ") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = " + compareOp + "(values, minMaxValue);\n }\n ";
  14804. this.userCode = "\n const ivec2 strides = ivec2(" + strideHeight + ", " + strideWidth + ");\n const ivec2 pads = ivec2(" + padTop + ", " + padLeft + ");\n const float initializationValue = " + initializationValue + ";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= " + convInfo.inWidth + ") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(" + initializationValue + ");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < " + filterHeight + "; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= " + convInfo.inHeight + ") {\n continue;\n }\n\n for (int wC = 0; wC < " + filterWidthNearestVec4 + "; wC += 4) {\n int xC = xCCorner + wC;\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n getValue(batch, xR, xC + 3, d)\n );\n\n " + updateSnippet + "\n }\n\n int xC = xCCorner + " + filterWidthNearestVec4 + ";\n if (" + (filterWidthVec4Remainder === 1) + ") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (filterWidthVec4Remainder === 2) + ") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (filterWidthVec4Remainder === 3) + ") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n initializationValue\n );\n\n " + updateSnippet + "\n }\n }\n setOutput(" + returnValue + ");\n }\n ";
  14805. }
  14806. return Pool2DProgram;
  14807. }());
  14808. exports.Pool2DProgram = Pool2DProgram;
  14809. },{}],93:[function(require,module,exports){
  14810. "use strict";
  14811. Object.defineProperty(exports, "__esModule", { value: true });
  14812. var ReduceProgram = (function () {
  14813. function ReduceProgram(reduceInfo, reduceType) {
  14814. this.variableNames = ['x'];
  14815. var windowSize = reduceInfo.windowSize;
  14816. var batchSize = reduceInfo.batchSize;
  14817. var inSize = reduceInfo.inSize;
  14818. var outSize = Math.ceil(inSize / windowSize);
  14819. this.outputShape = [batchSize, outSize];
  14820. var initializationValue = '0.0';
  14821. var compareOp = "";
  14822. if (reduceType === 'min') {
  14823. initializationValue = '1.0 / 0.0';
  14824. compareOp = "min";
  14825. }
  14826. else if (reduceType === 'max') {
  14827. initializationValue = '-1.0 / 0.0';
  14828. compareOp = "max";
  14829. }
  14830. var returnValue = reduceType + "(" + reduceType + "(" + reduceType + "(" +
  14831. 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';
  14832. if (reduceType === 'sum') {
  14833. returnValue = "sumValue";
  14834. }
  14835. else if (reduceType === 'all') {
  14836. returnValue = "allValue";
  14837. }
  14838. var windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
  14839. var windowSizeVec4Remainder = windowSize % 4;
  14840. var updateSnippet = "\n if (" + (reduceType === 'sum') + ") {\n sumValue += dot(values, ones);\n } else {\n minMaxValue = " + compareOp + "(values, minMaxValue);\n }\n ";
  14841. var vecType = "vec4";
  14842. if (reduceType === 'all') {
  14843. initializationValue = '1.0';
  14844. updateSnippet = "\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ";
  14845. vecType = "bvec4";
  14846. }
  14847. var checkOutOfBounds = '';
  14848. if (inSize % windowSize > 0) {
  14849. checkOutOfBounds = "\n if (inIdx < 0 || inIdx >= " + inSize + ") {\n return initializationValue;\n }\n ";
  14850. }
  14851. this.userCode = "\n const float initializationValue = " + initializationValue + ";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n " + checkOutOfBounds + "\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * " + windowSize + ";\n\n vec4 minMaxValue = vec4(" + initializationValue + ");\n float sumValue = 0.0;\n float allValue = 1.0;\n\n for (int i = 0; i < " + windowSizeNearestVec4 + "; i += 4) {\n int inIdx = inOffset + i;\n " + vecType + " values = " + vecType + "(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n " + updateSnippet + "\n }\n\n int inIdx = inOffset + " + windowSizeNearestVec4 + ";\n if (" + (windowSizeVec4Remainder === 1) + ") {\n " + vecType + " values = " + vecType + "(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 2) + ") {\n " + vecType + " values = " + vecType + "(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 3) + ") {\n " + vecType + " values = " + vecType + "(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n " + updateSnippet + "\n }\n setOutput(" + returnValue + ");\n }\n ";
  14852. }
  14853. return ReduceProgram;
  14854. }());
  14855. exports.ReduceProgram = ReduceProgram;
  14856. },{}],94:[function(require,module,exports){
  14857. "use strict";
  14858. Object.defineProperty(exports, "__esModule", { value: true });
  14859. var ResizeBilinearBackpropProgram = (function () {
  14860. function ResizeBilinearBackpropProgram(dy, x, alignCorners) {
  14861. this.variableNames = ['dy'];
  14862. this.outputShape = [];
  14863. this.outputShape = x.shape;
  14864. var _a = x.shape, xHeight = _a[1], xWidth = _a[2];
  14865. var _b = dy.shape, yHeight = _b[1], yWidth = _b[2];
  14866. var effectiveXSize = [
  14867. (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,
  14868. (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth
  14869. ];
  14870. var effectiveYSize = [
  14871. (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,
  14872. (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth
  14873. ];
  14874. var heightScale = effectiveXSize[0] / effectiveYSize[0];
  14875. var widthScale = effectiveXSize[1] / effectiveYSize[1];
  14876. var invHeightScale = 1 / heightScale;
  14877. var invWidthScale = 1 / widthScale;
  14878. var winHeight = (Math.ceil(invHeightScale) * 2) + 2;
  14879. var winWidth = (Math.ceil(invWidthScale) * 2) + 2;
  14880. this.userCode = "\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(" + heightScale + ");\n const float widthScale = float(" + widthScale + ");\n\n const float invHeightScale = float(" + invHeightScale + ");\n const float invWidthScale = float(" + invWidthScale + ");\n\n const int winHeight = int(" + winHeight + ");\n const int winWidth = int(" + winWidth + ");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= " + yHeight + ") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= " + yWidth + ") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), " + (xHeight - 1) + ".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), " + (xWidth - 1) + ".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n ";
  14881. }
  14882. return ResizeBilinearBackpropProgram;
  14883. }());
  14884. exports.ResizeBilinearBackpropProgram = ResizeBilinearBackpropProgram;
  14885. },{}],95:[function(require,module,exports){
  14886. "use strict";
  14887. Object.defineProperty(exports, "__esModule", { value: true });
  14888. var ResizeBilinearProgram = (function () {
  14889. function ResizeBilinearProgram(inputShape, newHeight, newWidth, alignCorners) {
  14890. this.variableNames = ['A'];
  14891. this.outputShape = [];
  14892. var batch = inputShape[0], oldHeight = inputShape[1], oldWidth = inputShape[2], depth = inputShape[3];
  14893. this.outputShape = [batch, newHeight, newWidth, depth];
  14894. var effectiveInSize = [
  14895. (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,
  14896. (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth
  14897. ];
  14898. var effectiveOutSize = [
  14899. (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,
  14900. (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth
  14901. ];
  14902. this.userCode = "\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n " + effectiveInSize[0] / effectiveOutSize[0] + ",\n " + effectiveInSize[1] / effectiveOutSize[1] + ");\n const vec2 inputShapeRC = vec2(" + oldHeight + ".0, " + oldWidth + ".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n ";
  14903. }
  14904. return ResizeBilinearProgram;
  14905. }());
  14906. exports.ResizeBilinearProgram = ResizeBilinearProgram;
  14907. },{}],96:[function(require,module,exports){
  14908. "use strict";
  14909. Object.defineProperty(exports, "__esModule", { value: true });
  14910. var ResizeNearestNeighborProgram = (function () {
  14911. function ResizeNearestNeighborProgram(inputShape, newHeight, newWidth, alignCorners) {
  14912. this.variableNames = ['A'];
  14913. this.outputShape = [];
  14914. var batch = inputShape[0], oldHeight = inputShape[1], oldWidth = inputShape[2], depth = inputShape[3];
  14915. this.outputShape = [batch, newHeight, newWidth, depth];
  14916. var effectiveInSize = alignCorners ? [oldHeight - 1, oldWidth - 1] : [oldHeight, oldWidth];
  14917. var effectiveOutSize = alignCorners ? [newHeight - 1, newWidth - 1] : [newHeight, newWidth];
  14918. var roundBase = alignCorners ? '0.5' : '0.0';
  14919. this.userCode = "\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n " + effectiveInSize[0] / effectiveOutSize[0] + ",\n " + effectiveInSize[1] / effectiveOutSize[1] + ");\n const vec2 inputShapeRC = vec2(" + oldHeight + ".0, " + oldWidth + ".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + " + roundBase + ")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n ";
  14920. }
  14921. return ResizeNearestNeighborProgram;
  14922. }());
  14923. exports.ResizeNearestNeighborProgram = ResizeNearestNeighborProgram;
  14924. },{}],97:[function(require,module,exports){
  14925. "use strict";
  14926. Object.defineProperty(exports, "__esModule", { value: true });
  14927. var shader_compiler_1 = require("./shader_compiler");
  14928. var ReverseProgram = (function () {
  14929. function ReverseProgram(xShape, axis) {
  14930. this.variableNames = ['x'];
  14931. var rank = xShape.length;
  14932. if (rank > 4) {
  14933. throw new Error("WebGL backend: Reverse of rank-" + rank + " tensor is not yet supported");
  14934. }
  14935. this.outputShape = xShape;
  14936. if (rank === 1) {
  14937. this.userCode = "\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(" + xShape[0] + " - coord - 1));\n }\n ";
  14938. return;
  14939. }
  14940. var getInCoord = function (i) {
  14941. if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {
  14942. return xShape[i] + " - coords[" + i + "] - 1";
  14943. }
  14944. return "coords[" + i + "]";
  14945. };
  14946. var inCoords = xShape.map(function (_, i) { return getInCoord(i); }).join(',');
  14947. var type = shader_compiler_1.getCoordsDataType(rank);
  14948. this.userCode = "\n void main() {\n " + type + " coords = getOutputCoords();\n setOutput(getX(" + inCoords + "));\n }\n ";
  14949. }
  14950. return ReverseProgram;
  14951. }());
  14952. exports.ReverseProgram = ReverseProgram;
  14953. },{"./shader_compiler":99}],98:[function(require,module,exports){
  14954. "use strict";
  14955. Object.defineProperty(exports, "__esModule", { value: true });
  14956. var SegmentOpProgram = (function () {
  14957. function SegmentOpProgram(segOpInfo, segOpType) {
  14958. this.variableNames = ['x', 'segmentIds'];
  14959. var windowSize = segOpInfo.windowSize;
  14960. var batchSize = segOpInfo.batchSize;
  14961. var inSize = segOpInfo.inSize;
  14962. var numSegments = segOpInfo.numSegments;
  14963. var outSize = numSegments * Math.ceil(inSize / windowSize);
  14964. this.outputShape = [batchSize, outSize];
  14965. var initializationValue = '0.0';
  14966. var returnValue = "sumValue";
  14967. var windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;
  14968. var windowSizeVec4Remainder = windowSize % 4;
  14969. var updateSnippet = "\n sumValue += dot(values, filter);\n ";
  14970. var checkValueOutOfBounds = '';
  14971. if (inSize % windowSize > 0) {
  14972. checkValueOutOfBounds = "\n if (inIdx < 0 || inIdx >= " + inSize + ") {\n return initializationValue;\n }\n ";
  14973. }
  14974. var checkSegmentIdOutOfBounds = '';
  14975. if (inSize % windowSize > 0) {
  14976. checkSegmentIdOutOfBounds = "\n if (inIdx < 0 || inIdx >= " + inSize + ") {\n return -1.0;\n }\n ";
  14977. }
  14978. this.userCode = "\n const float initializationValue = " + initializationValue + ";\n\n float getValue(int batch, int inIdx) {\n " + checkValueOutOfBounds + "\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n " + checkSegmentIdOutOfBounds + "\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n " + numSegments + ")) * float(" + windowSize + "));\n int currentSeg = int(mod(float(outIdx), float(" + numSegments + ")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < " + windowSizeNearestVec4 + "; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n " + updateSnippet + "\n }\n\n int inIdx = inOffset + " + windowSizeNearestVec4 + ";\n if (" + (windowSizeVec4Remainder === 1) + ") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 2) + ") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n " + updateSnippet + "\n } else if (" + (windowSizeVec4Remainder === 3) + ") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n " + updateSnippet + "\n }\n setOutput(" + returnValue + ");\n }\n ";
  14979. }
  14980. return SegmentOpProgram;
  14981. }());
  14982. exports.SegmentOpProgram = SegmentOpProgram;
  14983. },{}],99:[function(require,module,exports){
  14984. "use strict";
  14985. Object.defineProperty(exports, "__esModule", { value: true });
  14986. var broadcast_util = require("../../ops/broadcast_util");
  14987. var util = require("../../util");
  14988. function makeShader(inputsInfo, outputShape, userCode, broadcast) {
  14989. var inputPrefixSnippet = inputsInfo.map(function (x) {
  14990. var size = util.sizeFromShape(x.shapeInfo.logicalShape);
  14991. if (x.shapeInfo.isUniform) {
  14992. return "uniform float " + x.name + (size > 1 ? "[" + size + "]" : '') + ";";
  14993. }
  14994. return "uniform sampler2D " + x.name + ";";
  14995. });
  14996. inputPrefixSnippet = inputPrefixSnippet.join('\n');
  14997. var inputSamplingSnippet = inputsInfo.map(function (x) { return getInputSamplingSnippet(x, outputShape, broadcast); })
  14998. .join('\n');
  14999. var outTexShape = outputShape.texShape;
  15000. var outputSamplingSnippet = getOutputSamplingSnippet(outputShape.logicalShape, outTexShape);
  15001. var source = [
  15002. SHADER_PREFIX, FLOAT_TEXTURE_SAMPLE_SNIPPET,
  15003. FLOAT_TEXTURE_SETOUTPUT_SNIPPET, inputPrefixSnippet, outputSamplingSnippet,
  15004. inputSamplingSnippet, userCode
  15005. ].join('\n');
  15006. return source;
  15007. }
  15008. exports.makeShader = makeShader;
  15009. function getSamplerFromInInfo(inInfo) {
  15010. var shape = inInfo.shapeInfo.logicalShape;
  15011. switch (shape.length) {
  15012. case 0:
  15013. return getSamplerScalar(inInfo);
  15014. case 1:
  15015. return getSampler1D(inInfo);
  15016. case 2:
  15017. return getSampler2D(inInfo);
  15018. case 3:
  15019. return getSampler3D(inInfo);
  15020. case 4:
  15021. return getSampler4D(inInfo);
  15022. case 5:
  15023. return getSampler5D(inInfo);
  15024. case 6:
  15025. return getSampler6D(inInfo);
  15026. default:
  15027. throw new Error(shape.length + "-D input sampling" +
  15028. " is not yet supported");
  15029. }
  15030. }
  15031. function getInputSamplingSnippet(inInfo, outShapeInfo, broadcast) {
  15032. var res = getSamplerFlat(inInfo);
  15033. res += getSamplerFromInInfo(inInfo);
  15034. if (broadcast ||
  15035. util.arraysEqual(inInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape)) {
  15036. res += getSamplerAtOutputCoords(inInfo, outShapeInfo, broadcast);
  15037. }
  15038. return res;
  15039. }
  15040. function getOutputSamplingSnippet(outShape, outTexShape) {
  15041. switch (outShape.length) {
  15042. case 0:
  15043. return getOutputScalarCoords();
  15044. case 1:
  15045. return getOutput1DCoords(outShape, outTexShape);
  15046. case 2:
  15047. return getOutput2DCoords(outShape, outTexShape);
  15048. case 3:
  15049. return getOutput3DCoords(outShape, outTexShape);
  15050. case 4:
  15051. return getOutput4DCoords(outShape, outTexShape);
  15052. case 5:
  15053. return getOutput5DCoords(outShape, outTexShape);
  15054. case 6:
  15055. return getOutput6DCoords(outShape, outTexShape);
  15056. default:
  15057. throw new Error(outShape.length + "-D output sampling is not yet supported");
  15058. }
  15059. }
  15060. var SAMPLE_1D_SNIPPET = "\nvec2 UVfrom1D(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";
  15061. var SAMPLE_2D_SNIPPET = "\nvec2 UVfrom2D(int texNumR, int texNumC, int numC, int row, int col) {\n int index = row * numC + col;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";
  15062. var SAMPLE_3D_SNIPPET = "\nvec2 UVfrom3D(int texNumR, int texNumC, int stride0,\n int stride1, int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";
  15063. var SAMPLE_4D_SNIPPET = "\nvec2 UVfrom4D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int row, int col, int depth,\n int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";
  15064. var SAMPLE_5D_SNIPPET = "\nvec2 UVfrom5D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int row, int col, int depth,\n int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2 * stride3 + depth3;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";
  15065. var SAMPLE_6D_SNIPPET = "\nvec2 UVfrom6D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int stride4,\n int row, int col, int depth, int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2 *\n stride3 + depth3 * stride4 + depth4;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n";
  15066. var FLOAT_TEXTURE_SAMPLE_SNIPPET = "\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return texture2D(textureSampler, uv).r;\n }\n";
  15067. var FLOAT_TEXTURE_SETOUTPUT_SNIPPET = "\n void setOutput(float val) {\n gl_FragColor = vec4(val, 0, 0, 0);\n }\n";
  15068. var SHADER_PREFIX = "\n precision highp float;\n precision highp int;\n varying vec2 resultUV;\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n bool isNaN(float val) {\n return (val < 0.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n bool hasNaN(vec4 values) {\n vec4 v1 = values * values;\n vec4 v2 = values * values;\n return any(notEqual(v1, v2));\n }\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n " + SAMPLE_1D_SNIPPET + "\n " + SAMPLE_2D_SNIPPET + "\n " + SAMPLE_3D_SNIPPET + "\n " + SAMPLE_4D_SNIPPET + "\n " + SAMPLE_5D_SNIPPET + "\n " + SAMPLE_6D_SNIPPET + "\n";
  15069. function getOutputScalarCoords() {
  15070. return "\n int getOutputCoords() {\n return 0;\n }\n ";
  15071. }
  15072. function getOutput1DCoords(shape, texShape) {
  15073. if (texShape[0] === 1) {
  15074. return "\n int getOutputCoords() {\n return int(resultUV.x * " + texShape[1] + ".0);\n }\n ";
  15075. }
  15076. if (texShape[1] === 1) {
  15077. return "\n int getOutputCoords() {\n return int(resultUV.y * " + texShape[0] + ".0);\n }\n ";
  15078. }
  15079. return "\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n return resTexRC.x * " + texShape[1] + " + resTexRC.y;\n }\n ";
  15080. }
  15081. function getOutput3DCoords(shape, texShape) {
  15082. var stride0 = shape[1] * shape[2];
  15083. var stride1 = shape[2];
  15084. return "\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n int r = index / " + stride0 + ";\n index -= r * " + stride0 + ";\n int c = index / " + stride1 + ";\n int d = index - c * " + stride1 + ";\n return ivec3(r, c, d);\n }\n ";
  15085. }
  15086. function getOutput4DCoords(shape, texShape) {
  15087. var stride2 = shape[3];
  15088. var stride1 = shape[2] * stride2;
  15089. var stride0 = shape[1] * stride1;
  15090. return "\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n\n int r = index / " + stride0 + ";\n index -= r * " + stride0 + ";\n\n int c = index / " + stride1 + ";\n index -= c * " + stride1 + ";\n\n int d = index / " + stride2 + ";\n int d2 = index - d * " + stride2 + ";\n\n return ivec4(r, c, d, d2);\n }\n ";
  15091. }
  15092. function getOutput5DCoords(shape, texShape) {
  15093. var stride3 = shape[4];
  15094. var stride2 = shape[3] * stride3;
  15095. var stride1 = shape[2] * stride2;
  15096. var stride0 = shape[1] * stride1;
  15097. return "\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(" + texShape[0] + ",\n " + texShape[1] + "));\n\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n\n int r = index / " + stride0 + ";\n index -= r * " + stride0 + ";\n\n int c = index / " + stride1 + ";\n index -= c * " + stride1 + ";\n\n int d = index / " + stride2 + ";\n index -= d * " + stride2 + ";\n\n int d2 = index / " + stride3 + ";\n int d3 = index - d2 * " + stride3 + ";\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n ";
  15098. }
  15099. function getOutput6DCoords(shape, texShape) {
  15100. var stride4 = shape[5];
  15101. var stride3 = shape[4] * stride4;
  15102. var stride2 = shape[3] * stride3;
  15103. var stride1 = shape[2] * stride2;
  15104. var stride0 = shape[1] * stride1;
  15105. return "\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n\n int r = index / " + stride0 + ";\n index -= r * " + stride0 + ";\n\n int c = index / " + stride1 + ";\n index -= c * " + stride1 + ";\n\n int d = index / " + stride2 + ";\n index -= d * " + stride2 + ";\n\n int d2 = index / " + stride3 + ";\n index -= d2 * " + stride3 + ";\n\n int d3 = index / " + stride4 + ";\n int d4 = index - d3 * " + stride4 + ";\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n ";
  15106. }
  15107. function getOutput2DCoords(shape, texShape) {
  15108. if (util.arraysEqual(shape, texShape)) {
  15109. return "\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(" + texShape[0] + ", " + texShape[1] + "));\n }\n ";
  15110. }
  15111. if (shape[1] === 1) {
  15112. return "\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n return ivec2(index, 0);\n }\n ";
  15113. }
  15114. if (shape[0] === 1) {
  15115. return "\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n return ivec2(0, index);\n }\n ";
  15116. }
  15117. return "\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + texShape[0] + ", " + texShape[1] + "));\n int index = resTexRC.x * " + texShape[1] + " + resTexRC.y;\n int r = index / " + shape[1] + ";\n int c = index - r * " + shape[1] + ";\n return ivec2(r, c);\n }\n ";
  15118. }
  15119. function getSamplerScalar(inputInfo) {
  15120. var texName = inputInfo.name;
  15121. var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
  15122. if (inputInfo.shapeInfo.isUniform) {
  15123. return "float " + funcName + "() {return " + texName + ";}";
  15124. }
  15125. return "\n float " + funcName + "() {\n return sampleTexture(" + texName + ", halfCR);\n }\n ";
  15126. }
  15127. function getSampler1D(inputInfo) {
  15128. var texName = inputInfo.name;
  15129. var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
  15130. return "\n float " + funcName + "(int index) {\n return " + funcName + "Flat(index);\n }\n ";
  15131. }
  15132. function getSampler2D(inputInfo) {
  15133. var shape = inputInfo.shapeInfo.logicalShape;
  15134. var texName = inputInfo.name;
  15135. var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
  15136. var texShape = inputInfo.shapeInfo.texShape;
  15137. if (texShape != null && util.arraysEqual(shape, texShape)) {
  15138. var texNumR_1 = texShape[0];
  15139. var texNumC_1 = texShape[1];
  15140. return "\n float " + funcName + "(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(" + texNumC_1 + ".0, " + texNumR_1 + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15141. }
  15142. var _a = util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
  15143. var squeezedShape = newShape;
  15144. if (squeezedShape.length < shape.length) {
  15145. var newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
  15146. var params = ['row', 'col'];
  15147. return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
  15148. }
  15149. if (inputInfo.shapeInfo.isUniform) {
  15150. return "\n float " + funcName + "(int row, int col) {\n int index = row * " + shape[1] + " + col;\n return " + funcName + "Flat(index);\n }\n ";
  15151. }
  15152. var texNumR = texShape[0];
  15153. var texNumC = texShape[1];
  15154. if (texNumC === 1) {
  15155. return "\n float " + funcName + "(int row, int col) {\n int index = row * " + shape[1] + " + col;\n vec2 uv = vec2(0.5, (float(index) + 0.5) / " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15156. }
  15157. if (texNumR === 1) {
  15158. return "\n float " + funcName + "(int row, int col) {\n int index = row * " + shape[1] + " + col;\n vec2 uv = vec2((float(index) + 0.5) / " + texNumC + ".0, 0.5);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15159. }
  15160. return "\n float " + funcName + "(int row, int col) {\n vec2 uv = UVfrom2D(" + texNumR + ", " + texNumC + ", " + shape[1] + ", row, col);\n return sampleTexture(" + texName + ", uv);\n }\n";
  15161. }
  15162. function getSampler3D(inputInfo) {
  15163. var shape = inputInfo.shapeInfo.logicalShape;
  15164. var texName = inputInfo.name;
  15165. var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
  15166. var stride0 = shape[1] * shape[2];
  15167. var stride1 = shape[2];
  15168. var _a = util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
  15169. var squeezedShape = newShape;
  15170. if (squeezedShape.length < shape.length) {
  15171. var newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);
  15172. var params = ['row', 'col', 'depth'];
  15173. return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col, int depth) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
  15174. }
  15175. if (inputInfo.shapeInfo.isUniform) {
  15176. return "\n float " + funcName + "(int row, int col, int depth) {\n int index = row * " + stride0 + " + col * " + stride1 + " + depth;\n return " + funcName + "Flat(index);\n }\n ";
  15177. }
  15178. var texShape = inputInfo.shapeInfo.texShape;
  15179. var texNumR = texShape[0];
  15180. var texNumC = texShape[1];
  15181. if (texNumC === stride0) {
  15182. return "\n float " + funcName + "(int row, int col, int depth) {\n int texR = row;\n int texC = col * " + stride1 + " + depth;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15183. }
  15184. if (texNumC === stride1) {
  15185. return "\n float " + funcName + "(int row, int col, int depth) {\n int texR = row * " + shape[1] + " + col;\n int texC = depth;\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15186. }
  15187. return "\n float " + funcName + "(int row, int col, int depth) {\n vec2 uv = UVfrom3D(\n " + texNumR + ", " + texNumC + ", " + stride0 + ", " + stride1 + ", row, col, depth);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15188. }
  15189. function getSampler4D(inputInfo) {
  15190. var shape = inputInfo.shapeInfo.logicalShape;
  15191. var texName = inputInfo.name;
  15192. var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
  15193. var stride2 = shape[3];
  15194. var stride1 = shape[2] * stride2;
  15195. var stride0 = shape[1] * stride1;
  15196. var _a = util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
  15197. if (newShape.length < shape.length) {
  15198. var newInputInfo = squeezeInputInfo(inputInfo, newShape);
  15199. var params = ['row', 'col', 'depth', 'depth2'];
  15200. return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
  15201. }
  15202. if (inputInfo.shapeInfo.isUniform) {
  15203. return "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n int index = row * " + stride0 + " + col * " + stride1 + " +\n depth * " + stride2 + " + depth2;\n return " + funcName + "Flat(index);\n }\n ";
  15204. }
  15205. var texShape = inputInfo.shapeInfo.texShape;
  15206. var texNumR = texShape[0];
  15207. var texNumC = texShape[1];
  15208. if (texNumC === stride0) {
  15209. return "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n int texR = row;\n int texC = col * " + stride1 + " + depth * " + stride2 + " + depth2;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15210. }
  15211. if (texNumC === stride2) {
  15212. return "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n int texR = row * " + shape[1] * shape[2] + " + col * " + shape[2] + " + depth;\n int texC = depth2;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15213. }
  15214. return "\n float " + funcName + "(int row, int col, int depth, int depth2) {\n vec2 uv = UVfrom4D(" + texNumR + ", " + texNumC + ", " + stride0 + ", " + stride1 + ",\n " + stride2 + ", row, col, depth, depth2);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15215. }
  15216. function getSampler5D(inputInfo) {
  15217. var shape = inputInfo.shapeInfo.logicalShape;
  15218. var texName = inputInfo.name;
  15219. var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
  15220. var stride3 = shape[4];
  15221. var stride2 = shape[3] * stride3;
  15222. var stride1 = shape[2] * stride2;
  15223. var stride0 = shape[1] * stride1;
  15224. var _a = util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
  15225. if (newShape.length < shape.length) {
  15226. var newInputInfo = squeezeInputInfo(inputInfo, newShape);
  15227. var params = ['row', 'col', 'depth', 'depth2', 'depth3'];
  15228. return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
  15229. }
  15230. if (inputInfo.shapeInfo.isUniform) {
  15231. return "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n int index = row * " + stride0 + " + col * " + stride1 + " +\n depth * " + stride2 + " + depth2 * " + stride3 + " + depth3;\n return " + funcName + "Flat(index);\n }\n ";
  15232. }
  15233. var texShape = inputInfo.shapeInfo.texShape;
  15234. var texNumR = texShape[0];
  15235. var texNumC = texShape[1];
  15236. if (texNumC === stride0) {
  15237. return "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n int texC = col * " + stride1 + " + depth * " + stride2 + " +\n depth2 * " + stride3 + " + depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15238. }
  15239. if (texNumC === stride3) {
  15240. return "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n int texR = row * " + shape[1] * shape[2] + " + col * " + shape[2] + " +\n depth * " + shape[3] + " + depth2;\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15241. }
  15242. return "\n float " + funcName + "(int row, int col, int depth, int depth2, int depth3) {\n vec2 uv = UVfrom5D(" + texNumR + ", " + texNumC + ", " + stride0 + ", " + stride1 + ",\n " + stride2 + ", " + stride3 + ", row, col, depth, depth2, depth3);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15243. }
  15244. function getSampler6D(inputInfo) {
  15245. var shape = inputInfo.shapeInfo.logicalShape;
  15246. var texName = inputInfo.name;
  15247. var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
  15248. var stride4 = shape[5];
  15249. var stride3 = shape[4] * stride4;
  15250. var stride2 = shape[3] * stride3;
  15251. var stride1 = shape[2] * stride2;
  15252. var stride0 = shape[1] * stride1;
  15253. var _a = util.squeezeShape(shape), newShape = _a.newShape, keptDims = _a.keptDims;
  15254. if (newShape.length < shape.length) {
  15255. var newInputInfo = squeezeInputInfo(inputInfo, newShape);
  15256. var params = ['row', 'col', 'depth', 'depth2', 'depth3', 'depth4'];
  15257. return "\n " + getSamplerFromInInfo(newInputInfo) + "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return " + funcName + "(" + getSqueezedParams(params, keptDims) + ");\n }\n ";
  15258. }
  15259. if (inputInfo.shapeInfo.isUniform) {
  15260. return "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = row * " + stride0 + " + col * " + stride1 + " +\n depth * " + stride2 + " + depth2 * " + stride3 + " + depth3 * " + stride3 + "\n + depth4\n return " + funcName + "Flat(index);\n }\n ";
  15261. }
  15262. var texShape = inputInfo.shapeInfo.texShape;
  15263. var texNumR = texShape[0];
  15264. var texNumC = texShape[1];
  15265. if (texNumC === stride0) {
  15266. return "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n int texC = col * " + stride1 + " + depth * " + stride2 + " + depth2;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15267. }
  15268. if (texNumC === stride4) {
  15269. return "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row * " + shape[1] * shape[2] + " + col * " + shape[2] + " + depth;\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + texNumC + ".0, " + texNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15270. }
  15271. return "\n float " + funcName + "(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n vec2 uv = UVfrom6D(" + texNumR + ", " + texNumC + ", " + stride0 + ", " + stride1 + ",\n " + stride2 + ", " + stride3 + ", " + stride4 + "\n ,row, col, depth, depth2, depth3, depth4);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15272. }
  15273. function getSamplerFlat(inputInfo) {
  15274. var texName = inputInfo.name;
  15275. var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1) + 'Flat';
  15276. var inSize = util.sizeFromShape(inputInfo.shapeInfo.logicalShape);
  15277. if (inputInfo.shapeInfo.isUniform) {
  15278. if (inSize === 1) {
  15279. return "float " + funcName + "(int index) {return " + texName + ";}";
  15280. }
  15281. return "\n float " + funcName + "(int index) {\n for (int i = 0; i < " + inSize + "; i++) {\n if (i == index) {\n return " + texName + "[i];\n }\n }\n }\n ";
  15282. }
  15283. var texShape = inputInfo.shapeInfo.texShape;
  15284. var tNumR = texShape[0];
  15285. var tNumC = texShape[1];
  15286. if (tNumC === 1 && tNumR === 1) {
  15287. return "\n float " + funcName + "(int index) {\n return sampleTexture(" + texName + ", halfCR);\n }\n ";
  15288. }
  15289. if (tNumC === 1) {
  15290. return "\n float " + funcName + "(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / " + tNumR + ".0);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15291. }
  15292. if (tNumR === 1) {
  15293. return "\n float " + funcName + "(int index) {\n vec2 uv = vec2((float(index) + 0.5) / " + tNumC + ".0, 0.5);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15294. }
  15295. return "\n float " + funcName + "(int index) {\n vec2 uv = UVfrom1D(" + tNumR + ", " + tNumC + ", index);\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15296. }
  15297. function getBroadcastOutputCoordsSampler(inputInfo, outShapeInfo, texFuncSnippet, funcName) {
  15298. var inRank = inputInfo.shapeInfo.logicalShape.length;
  15299. var outRank = outShapeInfo.logicalShape.length;
  15300. var type = 'int';
  15301. if (outRank === 2) {
  15302. type = 'ivec2';
  15303. }
  15304. else if (outRank === 3) {
  15305. type = 'ivec3';
  15306. }
  15307. else if (outRank === 4) {
  15308. type = 'ivec4';
  15309. }
  15310. var broadcastDims = broadcast_util.getBroadcastDims(inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);
  15311. var rankDiff = outRank - inRank;
  15312. var coordsSnippet;
  15313. if (inRank === 0) {
  15314. coordsSnippet = '';
  15315. }
  15316. else if (outRank < 2 && broadcastDims.length >= 1) {
  15317. coordsSnippet = 'coords = 0;';
  15318. }
  15319. else {
  15320. coordsSnippet =
  15321. broadcastDims.map(function (d) { return "coords[" + (d + rankDiff) + "] = 0;"; }).join('\n');
  15322. }
  15323. var unpackedCoordsSnippet = '';
  15324. if (outRank < 2 && inRank > 0) {
  15325. unpackedCoordsSnippet = 'coords';
  15326. }
  15327. else {
  15328. unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape
  15329. .map(function (s, i) { return "coords[" + (i + rankDiff) + "]"; })
  15330. .join(', ');
  15331. }
  15332. return "\n float " + funcName + "() {\n " + type + " coords = getOutputCoords();\n " + coordsSnippet + "\n return get" + texFuncSnippet + "(" + unpackedCoordsSnippet + ");\n }\n ";
  15333. }
  15334. function getSamplerAtOutputCoords(inputInfo, outShapeInfo, supportsBroadcasting) {
  15335. var texName = inputInfo.name;
  15336. var texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);
  15337. var funcName = 'get' + texFuncSnippet + 'AtOutCoords';
  15338. var broadcastDims = broadcast_util.getBroadcastDims(inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);
  15339. var inRank = inputInfo.shapeInfo.logicalShape.length;
  15340. var outRank = outShapeInfo.logicalShape.length;
  15341. var doBroadcast = supportsBroadcasting && ((outRank > inRank) || broadcastDims.length > 0);
  15342. var broadcastOverOuter = broadcast_util.broadcastDimsAreOuter(broadcastDims);
  15343. var isUniform = inputInfo.shapeInfo.isUniform;
  15344. if (doBroadcast && !broadcastOverOuter) {
  15345. return getBroadcastOutputCoordsSampler(inputInfo, outShapeInfo, texFuncSnippet, funcName);
  15346. }
  15347. var inSize = util.sizeFromShape(inputInfo.shapeInfo.logicalShape);
  15348. var broadcastSnippet = '';
  15349. if (doBroadcast && broadcastOverOuter) {
  15350. broadcastSnippet = "\n int mainPart = index / " + inSize + ";\n index -= mainPart * " + inSize + ";\n ";
  15351. }
  15352. var outTexShape = outShapeInfo.texShape;
  15353. if (isUniform) {
  15354. if (inSize === 1) {
  15355. return "float " + funcName + "() {return " + texName + ";}";
  15356. }
  15357. return "\n float " + funcName + "() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + outTexShape[0] + ", " + outTexShape[1] + "));\n int index = resTexRC.x * " + outTexShape[1] + " + resTexRC.y;\n " + broadcastSnippet + "\n return get" + texFuncSnippet + "Flat(index);\n }\n ";
  15358. }
  15359. var inTexShape = inputInfo.shapeInfo.texShape;
  15360. if (util.arraysEqual(inTexShape, outTexShape)) {
  15361. return "\n float " + funcName + "() {\n return sampleTexture(" + texName + ", resultUV);\n }\n ";
  15362. }
  15363. return "\n float " + funcName + "() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(" + outTexShape[0] + ", " + outTexShape[1] + "));\n int index = resTexRC.x * " + outTexShape[1] + " + resTexRC.y;\n " + broadcastSnippet + "\n int texR = index / " + inTexShape[1] + ";\n int texC = index - texR * " + inTexShape[1] + ";\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(" + inTexShape[1] + ".0, " + inTexShape[0] + ".0);\n\n return sampleTexture(" + texName + ", uv);\n }\n ";
  15364. }
  15365. function getCoordsDataType(rank) {
  15366. if (rank <= 1) {
  15367. return 'int';
  15368. }
  15369. else if (rank === 2) {
  15370. return 'ivec2';
  15371. }
  15372. else if (rank === 3) {
  15373. return 'ivec3';
  15374. }
  15375. else if (rank === 4) {
  15376. return 'ivec4';
  15377. }
  15378. else if (rank === 5) {
  15379. return 'ivec5';
  15380. }
  15381. else if (rank === 6) {
  15382. return 'ivec6';
  15383. }
  15384. else {
  15385. throw Error("GPU for rank " + rank + " is not yet supported");
  15386. }
  15387. }
  15388. exports.getCoordsDataType = getCoordsDataType;
  15389. function squeezeInputInfo(inInfo, squeezedShape) {
  15390. var newInputInfo = JSON.parse(JSON.stringify(inInfo));
  15391. newInputInfo.shapeInfo.logicalShape = squeezedShape;
  15392. return newInputInfo;
  15393. }
  15394. function getSqueezedParams(params, keptDims) {
  15395. return keptDims.map(function (d) { return params[d]; }).join(', ');
  15396. }
  15397. },{"../../ops/broadcast_util":112,"../../util":164}],100:[function(require,module,exports){
  15398. "use strict";
  15399. Object.defineProperty(exports, "__esModule", { value: true });
  15400. var shader_compiler_1 = require("./shader_compiler");
  15401. var SliceProgram = (function () {
  15402. function SliceProgram(destSize) {
  15403. this.variableNames = ['source'];
  15404. this.outputShape = destSize;
  15405. this.rank = destSize.length;
  15406. var dtype = shader_compiler_1.getCoordsDataType(this.rank);
  15407. var sourceCoords = getCoords(this.rank);
  15408. this.userCode = "\n uniform " + dtype + " start;\n\n void main() {\n " + dtype + " sourceLoc = start + getOutputCoords();\n setOutput(getSource(" + sourceCoords + "));\n }\n ";
  15409. }
  15410. SliceProgram.prototype.getCustomSetupFunc = function (start) {
  15411. var _this = this;
  15412. if (start.length !== this.rank) {
  15413. throw Error("The rank (" + this.rank + ") of the program must match the " +
  15414. ("length of start (" + start.length + ")"));
  15415. }
  15416. return function (gpgpu, webGLProgram) {
  15417. if (_this.startLoc == null) {
  15418. _this.startLoc = gpgpu.getUniformLocationNoThrow(webGLProgram, 'start');
  15419. if (_this.startLoc == null) {
  15420. return;
  15421. }
  15422. }
  15423. if (_this.rank === 1) {
  15424. gpgpu.gl.uniform1i(_this.startLoc, start[0]);
  15425. }
  15426. else if (_this.rank === 2) {
  15427. gpgpu.gl.uniform2i(_this.startLoc, start[0], start[1]);
  15428. }
  15429. else if (_this.rank === 3) {
  15430. gpgpu.gl.uniform3i(_this.startLoc, start[0], start[1], start[2]);
  15431. }
  15432. else if (_this.rank === 4) {
  15433. gpgpu.gl.uniform4i(_this.startLoc, start[0], start[1], start[2], start[3]);
  15434. }
  15435. else {
  15436. throw Error("Slicing for rank " + _this.rank + " is not yet supported");
  15437. }
  15438. };
  15439. };
  15440. return SliceProgram;
  15441. }());
  15442. exports.SliceProgram = SliceProgram;
  15443. function getCoords(rank) {
  15444. if (rank === 1) {
  15445. return 'sourceLoc';
  15446. }
  15447. else if (rank === 2) {
  15448. return 'sourceLoc.x, sourceLoc.y';
  15449. }
  15450. else if (rank === 3) {
  15451. return 'sourceLoc.x, sourceLoc.y, sourceLoc.z';
  15452. }
  15453. else if (rank === 4) {
  15454. return 'sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w';
  15455. }
  15456. else {
  15457. throw Error("Slicing for rank " + rank + " is not yet supported");
  15458. }
  15459. }
  15460. },{"./shader_compiler":99}],101:[function(require,module,exports){
  15461. "use strict";
  15462. Object.defineProperty(exports, "__esModule", { value: true });
  15463. var shader_compiler_1 = require("./shader_compiler");
  15464. var StridedSliceProgram = (function () {
  15465. function StridedSliceProgram(begin, strides, shape) {
  15466. this.variableNames = ['x'];
  15467. this.outputShape = shape;
  15468. this.rank = shape.length;
  15469. var dtype = shader_compiler_1.getCoordsDataType(this.rank);
  15470. var newCoords = '';
  15471. if (this.rank === 1) {
  15472. newCoords = 'coords * strides + begin';
  15473. }
  15474. else {
  15475. newCoords =
  15476. shape.map(function (_, i) { return "coords[" + i + "] * strides[" + i + "] + begin[" + i + "]"; })
  15477. .join(',');
  15478. }
  15479. this.userCode = "\n " + dtype + " begin = " + dtype + "(" + begin + ");\n " + dtype + " strides = " + dtype + "(" + strides + ");\n\n void main() {\n " + dtype + " coords = getOutputCoords();\n setOutput(getX(" + newCoords + "));\n }\n ";
  15480. }
  15481. return StridedSliceProgram;
  15482. }());
  15483. exports.StridedSliceProgram = StridedSliceProgram;
  15484. },{"./shader_compiler":99}],102:[function(require,module,exports){
  15485. "use strict";
  15486. Object.defineProperty(exports, "__esModule", { value: true });
  15487. var TextureUsage;
  15488. (function (TextureUsage) {
  15489. TextureUsage[TextureUsage["RENDER"] = 0] = "RENDER";
  15490. TextureUsage[TextureUsage["UPLOAD"] = 1] = "UPLOAD";
  15491. TextureUsage[TextureUsage["PIXELS"] = 2] = "PIXELS";
  15492. TextureUsage[TextureUsage["DOWNLOAD"] = 3] = "DOWNLOAD";
  15493. })(TextureUsage = exports.TextureUsage || (exports.TextureUsage = {}));
  15494. var PhysicalTextureType;
  15495. (function (PhysicalTextureType) {
  15496. PhysicalTextureType[PhysicalTextureType["FLOAT16"] = 0] = "FLOAT16";
  15497. PhysicalTextureType[PhysicalTextureType["FLOAT32"] = 1] = "FLOAT32";
  15498. PhysicalTextureType[PhysicalTextureType["UNSIGNED_BYTE"] = 2] = "UNSIGNED_BYTE";
  15499. })(PhysicalTextureType = exports.PhysicalTextureType || (exports.PhysicalTextureType = {}));
  15500. function getUnpackedMatrixTextureShapeWidthHeight(rows, columns) {
  15501. return [columns, rows];
  15502. }
  15503. exports.getUnpackedMatrixTextureShapeWidthHeight = getUnpackedMatrixTextureShapeWidthHeight;
  15504. function getUnpackedArraySizeFromMatrixSize(matrixSize, channelsPerTexture) {
  15505. return matrixSize * channelsPerTexture;
  15506. }
  15507. exports.getUnpackedArraySizeFromMatrixSize = getUnpackedArraySizeFromMatrixSize;
  15508. function getColorMatrixTextureShapeWidthHeight(rows, columns) {
  15509. return [columns * 4, rows];
  15510. }
  15511. exports.getColorMatrixTextureShapeWidthHeight = getColorMatrixTextureShapeWidthHeight;
  15512. function getMatrixSizeFromUnpackedArraySize(unpackedSize, channelsPerTexture) {
  15513. if (unpackedSize % channelsPerTexture !== 0) {
  15514. throw new Error("unpackedSize (" + unpackedSize + ") must be a multiple of " +
  15515. ("" + channelsPerTexture));
  15516. }
  15517. return unpackedSize / channelsPerTexture;
  15518. }
  15519. exports.getMatrixSizeFromUnpackedArraySize = getMatrixSizeFromUnpackedArraySize;
  15520. function encodeMatrixToUnpackedArray(matrix, unpackedArray, channelsPerTexture) {
  15521. var requiredSize = getUnpackedArraySizeFromMatrixSize(matrix.length, channelsPerTexture);
  15522. if (unpackedArray.length < requiredSize) {
  15523. throw new Error("unpackedArray length (" + unpackedArray.length + ") must be >= " +
  15524. ("" + requiredSize));
  15525. }
  15526. var dst = 0;
  15527. for (var src = 0; src < matrix.length; ++src) {
  15528. unpackedArray[dst] = matrix[src];
  15529. dst += channelsPerTexture;
  15530. }
  15531. }
  15532. exports.encodeMatrixToUnpackedArray = encodeMatrixToUnpackedArray;
  15533. function decodeMatrixFromUnpackedArray(unpackedArray, matrix, channelsPerTexture) {
  15534. var requiredSize = getMatrixSizeFromUnpackedArraySize(unpackedArray.length, channelsPerTexture);
  15535. if (matrix.length < requiredSize) {
  15536. throw new Error("matrix length (" + matrix.length + ") must be >= " + requiredSize);
  15537. }
  15538. var dst = 0;
  15539. for (var src = 0; src < unpackedArray.length; src += channelsPerTexture) {
  15540. matrix[dst++] = unpackedArray[src];
  15541. }
  15542. }
  15543. exports.decodeMatrixFromUnpackedArray = decodeMatrixFromUnpackedArray;
  15544. function decodeMatrixFromUnpackedColorRGBAArray(unpackedArray, matrix, channels) {
  15545. var requiredSize = unpackedArray.length * channels / 4;
  15546. if (matrix.length < requiredSize) {
  15547. throw new Error("matrix length (" + matrix.length + ") must be >= " + requiredSize);
  15548. }
  15549. var dst = 0;
  15550. for (var src = 0; src < unpackedArray.length; src += 4) {
  15551. for (var c = 0; c < channels; c++) {
  15552. matrix[dst++] = unpackedArray[src + c];
  15553. }
  15554. }
  15555. }
  15556. exports.decodeMatrixFromUnpackedColorRGBAArray = decodeMatrixFromUnpackedColorRGBAArray;
  15557. function getPackedMatrixTextureShapeWidthHeight(rows, columns) {
  15558. return [Math.ceil(columns / 2), Math.ceil(rows / 2)];
  15559. }
  15560. exports.getPackedMatrixTextureShapeWidthHeight = getPackedMatrixTextureShapeWidthHeight;
  15561. function getPackedRGBAArraySizeFromMatrixShape(rows, columns) {
  15562. var _a = getPackedMatrixTextureShapeWidthHeight(rows, columns), w = _a[0], h = _a[1];
  15563. return w * h * 4;
  15564. }
  15565. exports.getPackedRGBAArraySizeFromMatrixShape = getPackedRGBAArraySizeFromMatrixShape;
  15566. function encodeMatrixToPackedRGBA(matrix, rows, columns, packedRGBA) {
  15567. var requiredSize = getPackedRGBAArraySizeFromMatrixShape(rows, columns);
  15568. if (packedRGBA.length < requiredSize) {
  15569. throw new Error("packedRGBA length (" + packedRGBA.length + ") must be >= " + requiredSize);
  15570. }
  15571. var _a = getPackedMatrixTextureShapeWidthHeight(rows, columns), textureWidth = _a[0], textureHeight = _a[1];
  15572. var oddWidth = (columns % 2) === 1;
  15573. var oddHeight = (rows % 2) === 1;
  15574. var widthInFullBlocks = Math.floor(columns / 2);
  15575. var heightInFullBlocks = Math.floor(rows / 2);
  15576. {
  15577. var dstStride = (oddWidth ? 4 : 0);
  15578. var oneRow = columns;
  15579. var dst = 0;
  15580. for (var blockY = 0; blockY < heightInFullBlocks; ++blockY) {
  15581. var matrixSrcRow = (blockY * 2 * columns);
  15582. for (var blockX = 0; blockX < widthInFullBlocks; ++blockX) {
  15583. var matrixSrcCol = blockX * 2;
  15584. var src = matrixSrcRow + matrixSrcCol;
  15585. packedRGBA[dst] = matrix[src];
  15586. packedRGBA[dst + 1] = matrix[src + 1];
  15587. packedRGBA[dst + 2] = matrix[src + oneRow];
  15588. packedRGBA[dst + 3] = matrix[src + oneRow + 1];
  15589. dst += 4;
  15590. }
  15591. dst += dstStride;
  15592. }
  15593. }
  15594. if (oddWidth) {
  15595. var src = columns - 1;
  15596. var dst = (textureWidth - 1) * 4;
  15597. var srcStride = 2 * columns;
  15598. var dstStride = textureWidth * 4;
  15599. for (var blockY = 0; blockY < heightInFullBlocks; ++blockY) {
  15600. packedRGBA[dst] = matrix[src];
  15601. packedRGBA[dst + 2] = matrix[src + columns];
  15602. src += srcStride;
  15603. dst += dstStride;
  15604. }
  15605. }
  15606. if (oddHeight) {
  15607. var src = (rows - 1) * columns;
  15608. var dst = (textureHeight - 1) * textureWidth * 4;
  15609. for (var blockX = 0; blockX < widthInFullBlocks; ++blockX) {
  15610. packedRGBA[dst++] = matrix[src++];
  15611. packedRGBA[dst++] = matrix[src++];
  15612. dst += 2;
  15613. }
  15614. }
  15615. if (oddWidth && oddHeight) {
  15616. packedRGBA[packedRGBA.length - 4] = matrix[matrix.length - 1];
  15617. }
  15618. return packedRGBA;
  15619. }
  15620. exports.encodeMatrixToPackedRGBA = encodeMatrixToPackedRGBA;
  15621. function decodeMatrixFromPackedRGBA(packedRGBA, rows, columns, matrix) {
  15622. var requiredSize = rows * columns;
  15623. if (requiredSize < matrix.length) {
  15624. throw new Error("matrix length (" + matrix.length + ") must be >= " + requiredSize);
  15625. }
  15626. var oddWidth = (columns % 2) === 1;
  15627. var oddHeight = (rows % 2) === 1;
  15628. var widthInFullBlocks = Math.floor(columns / 2);
  15629. var heightInFullBlocks = Math.floor(rows / 2);
  15630. var _a = getPackedMatrixTextureShapeWidthHeight(rows, columns), textureWidth = _a[0], textureHeight = _a[1];
  15631. {
  15632. var srcStride = oddWidth ? 4 : 0;
  15633. var dstStride = columns + (oddWidth ? 1 : 0);
  15634. var src = 0;
  15635. var dstRow1 = 0;
  15636. var dstRow2 = columns;
  15637. for (var blockY = 0; blockY < heightInFullBlocks; ++blockY) {
  15638. for (var blockX = 0; blockX < widthInFullBlocks; ++blockX) {
  15639. matrix[dstRow1++] = packedRGBA[src++];
  15640. matrix[dstRow1++] = packedRGBA[src++];
  15641. matrix[dstRow2++] = packedRGBA[src++];
  15642. matrix[dstRow2++] = packedRGBA[src++];
  15643. }
  15644. src += srcStride;
  15645. dstRow1 += dstStride;
  15646. dstRow2 += dstStride;
  15647. }
  15648. }
  15649. if (oddWidth) {
  15650. var src = (textureWidth - 1) * 4;
  15651. var dst = columns - 1;
  15652. var srcStride = textureWidth * 4;
  15653. var dstStride = 2 * columns;
  15654. for (var blockY = 0; blockY < heightInFullBlocks; ++blockY) {
  15655. matrix[dst] = packedRGBA[src];
  15656. matrix[dst + columns] = packedRGBA[src + 2];
  15657. src += srcStride;
  15658. dst += dstStride;
  15659. }
  15660. }
  15661. if (oddHeight) {
  15662. var src = (textureHeight - 1) * textureWidth * 4;
  15663. var dst = (rows - 1) * columns;
  15664. for (var blockX = 0; blockX < widthInFullBlocks; ++blockX) {
  15665. matrix[dst++] = packedRGBA[src++];
  15666. matrix[dst++] = packedRGBA[src++];
  15667. src += 2;
  15668. }
  15669. }
  15670. if (oddWidth && oddHeight) {
  15671. matrix[matrix.length - 1] = packedRGBA[packedRGBA.length - 4];
  15672. }
  15673. return matrix;
  15674. }
  15675. exports.decodeMatrixFromPackedRGBA = decodeMatrixFromPackedRGBA;
  15676. },{}],103:[function(require,module,exports){
  15677. "use strict";
  15678. Object.defineProperty(exports, "__esModule", { value: true });
  15679. var environment_1 = require("../../environment");
  15680. var tex_util_1 = require("./tex_util");
  15681. var TextureManager = (function () {
  15682. function TextureManager(gpgpu) {
  15683. this.gpgpu = gpgpu;
  15684. this.numUsedTextures = 0;
  15685. this.numFreeTextures = 0;
  15686. this.freeTextures = {};
  15687. this.logEnabled = false;
  15688. this.usedTextures = {};
  15689. }
  15690. TextureManager.prototype.acquireTexture = function (shapeRC, usage) {
  15691. var physicalTexType = getPhysicalFromLogicalTextureType(usage);
  15692. var shapeKey = getKeyFromTextureShape(shapeRC, physicalTexType);
  15693. if (!(shapeKey in this.freeTextures)) {
  15694. this.freeTextures[shapeKey] = [];
  15695. }
  15696. if (!(shapeKey in this.usedTextures)) {
  15697. this.usedTextures[shapeKey] = [];
  15698. }
  15699. if (this.freeTextures[shapeKey].length > 0) {
  15700. this.numFreeTextures--;
  15701. this.numUsedTextures++;
  15702. this.log();
  15703. var newTexture_1 = this.freeTextures[shapeKey].shift();
  15704. this.usedTextures[shapeKey].push(newTexture_1);
  15705. return newTexture_1;
  15706. }
  15707. this.numUsedTextures++;
  15708. this.log();
  15709. var newTexture;
  15710. if (physicalTexType === tex_util_1.PhysicalTextureType.FLOAT32) {
  15711. newTexture =
  15712. this.gpgpu.createFloat32MatrixTexture(shapeRC[0], shapeRC[1]);
  15713. }
  15714. else if (physicalTexType === tex_util_1.PhysicalTextureType.FLOAT16) {
  15715. newTexture =
  15716. this.gpgpu.createFloat16MatrixTexture(shapeRC[0], shapeRC[1]);
  15717. }
  15718. else if (physicalTexType === tex_util_1.PhysicalTextureType.UNSIGNED_BYTE) {
  15719. newTexture =
  15720. this.gpgpu.createUnsignedBytesMatrixTexture(shapeRC[0], shapeRC[1]);
  15721. }
  15722. this.usedTextures[shapeKey].push(newTexture);
  15723. return newTexture;
  15724. };
  15725. TextureManager.prototype.releaseTexture = function (texture, shape, logicalTexType) {
  15726. var physicalTexType = getPhysicalFromLogicalTextureType(logicalTexType);
  15727. var shapeKey = getKeyFromTextureShape(shape, physicalTexType);
  15728. if (!(shapeKey in this.freeTextures)) {
  15729. this.freeTextures[shapeKey] = [];
  15730. }
  15731. this.freeTextures[shapeKey].push(texture);
  15732. this.numFreeTextures++;
  15733. this.numUsedTextures--;
  15734. var texList = this.usedTextures[shapeKey];
  15735. var texIndex = texList.indexOf(texture);
  15736. if (texIndex < 0) {
  15737. throw new Error('Cannot release a texture that was never provided by this ' +
  15738. 'texture manager');
  15739. }
  15740. texList.splice(texIndex, 1);
  15741. this.log();
  15742. };
  15743. TextureManager.prototype.log = function () {
  15744. if (!this.logEnabled) {
  15745. return;
  15746. }
  15747. var total = this.numFreeTextures + this.numUsedTextures;
  15748. console.log('Free/Used', this.numFreeTextures + " / " + this.numUsedTextures, "(" + total + ")");
  15749. };
  15750. TextureManager.prototype.getNumUsedTextures = function () {
  15751. return this.numUsedTextures;
  15752. };
  15753. TextureManager.prototype.getNumFreeTextures = function () {
  15754. return this.numFreeTextures;
  15755. };
  15756. TextureManager.prototype.dispose = function () {
  15757. var _this = this;
  15758. if (this.freeTextures == null) {
  15759. return;
  15760. }
  15761. for (var texShape in this.freeTextures) {
  15762. this.freeTextures[texShape].forEach(function (tex) {
  15763. _this.gpgpu.deleteMatrixTexture(tex);
  15764. });
  15765. }
  15766. for (var texShape in this.usedTextures) {
  15767. this.usedTextures[texShape].forEach(function (tex) {
  15768. _this.gpgpu.deleteMatrixTexture(tex);
  15769. });
  15770. }
  15771. this.freeTextures = null;
  15772. this.usedTextures = null;
  15773. this.numUsedTextures = 0;
  15774. this.numFreeTextures = 0;
  15775. };
  15776. return TextureManager;
  15777. }());
  15778. exports.TextureManager = TextureManager;
  15779. function getPhysicalFromLogicalTextureType(logicalTexType) {
  15780. if (logicalTexType === tex_util_1.TextureUsage.DOWNLOAD ||
  15781. logicalTexType === tex_util_1.TextureUsage.PIXELS) {
  15782. return tex_util_1.PhysicalTextureType.UNSIGNED_BYTE;
  15783. }
  15784. else if (logicalTexType === tex_util_1.TextureUsage.UPLOAD) {
  15785. return tex_util_1.PhysicalTextureType.FLOAT32;
  15786. }
  15787. else if (logicalTexType === tex_util_1.TextureUsage.RENDER) {
  15788. return environment_1.ENV.get('WEBGL_RENDER_FLOAT32_ENABLED') ?
  15789. tex_util_1.PhysicalTextureType.FLOAT32 :
  15790. tex_util_1.PhysicalTextureType.FLOAT16;
  15791. }
  15792. throw new Error("Unknown logical texture type " + logicalTexType);
  15793. }
  15794. function getKeyFromTextureShape(shapeRowsCol, physicalTexType) {
  15795. return shapeRowsCol[0] + "_" + shapeRowsCol[1] + "_" + physicalTexType;
  15796. }
  15797. },{"../../environment":51,"./tex_util":102}],104:[function(require,module,exports){
  15798. "use strict";
  15799. Object.defineProperty(exports, "__esModule", { value: true });
  15800. var shader_compiler_1 = require("./shader_compiler");
  15801. var TileProgram = (function () {
  15802. function TileProgram(aShape, reps) {
  15803. this.variableNames = ['A'];
  15804. var outputShape = new Array(aShape.length);
  15805. for (var i = 0; i < outputShape.length; i++) {
  15806. outputShape[i] = aShape[i] * reps[i];
  15807. }
  15808. this.outputShape = outputShape;
  15809. this.rank = outputShape.length;
  15810. var dtype = shader_compiler_1.getCoordsDataType(this.rank);
  15811. var sourceCoords = getSourceCoords(aShape);
  15812. this.userCode = "\n void main() {\n " + dtype + " resRC = getOutputCoords();\n setOutput(getA(" + sourceCoords + "));\n }\n ";
  15813. }
  15814. return TileProgram;
  15815. }());
  15816. exports.TileProgram = TileProgram;
  15817. function getSourceCoords(aShape) {
  15818. var rank = aShape.length;
  15819. if (rank > 5) {
  15820. throw Error("Tile for rank " + rank + " is not yet supported");
  15821. }
  15822. if (rank === 1) {
  15823. return "imod(resRC, " + aShape[0] + ")";
  15824. }
  15825. var currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u'];
  15826. var sourceCoords = [];
  15827. for (var i = 0; i < aShape.length; i++) {
  15828. sourceCoords.push("imod(" + currentCoords[i] + ", " + aShape[i] + ")");
  15829. }
  15830. return sourceCoords.join();
  15831. }
  15832. },{"./shader_compiler":99}],105:[function(require,module,exports){
  15833. "use strict";
  15834. Object.defineProperty(exports, "__esModule", { value: true });
  15835. var shader_compiler_1 = require("./shader_compiler");
  15836. var TransposeProgram = (function () {
  15837. function TransposeProgram(aShape, newDim) {
  15838. this.variableNames = ['A'];
  15839. var outputShape = new Array(aShape.length);
  15840. for (var i = 0; i < outputShape.length; i++) {
  15841. outputShape[i] = aShape[newDim[i]];
  15842. }
  15843. this.outputShape = outputShape;
  15844. this.rank = outputShape.length;
  15845. var dtype = shader_compiler_1.getCoordsDataType(this.rank);
  15846. var switched = getSwitchedCoords(newDim);
  15847. this.userCode = "\n void main() {\n " + dtype + " resRC = getOutputCoords();\n setOutput(getA(" + switched + "));\n }\n ";
  15848. }
  15849. return TransposeProgram;
  15850. }());
  15851. exports.TransposeProgram = TransposeProgram;
  15852. function getSwitchedCoords(newDim) {
  15853. var rank = newDim.length;
  15854. if (rank > 6) {
  15855. throw Error("Transpose for rank " + rank + " is not yet supported");
  15856. }
  15857. var originalOrder = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u', 'resRC.v'];
  15858. var switchedCoords = new Array(rank);
  15859. for (var i = 0; i < newDim.length; i++) {
  15860. switchedCoords[newDim[i]] = originalOrder[i];
  15861. }
  15862. return switchedCoords.join();
  15863. }
  15864. },{"./shader_compiler":99}],106:[function(require,module,exports){
  15865. "use strict";
  15866. Object.defineProperty(exports, "__esModule", { value: true });
  15867. var erf_util = require("../../ops/erf_util");
  15868. var selu_util = require("../../ops/selu_util");
  15869. var UnaryOpProgram = (function () {
  15870. function UnaryOpProgram(aShape, opSnippet) {
  15871. this.variableNames = ['A'];
  15872. this.outputShape = aShape;
  15873. this.userCode = "\n float unaryOperation(float x) {\n " + opSnippet + "\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n ";
  15874. }
  15875. return UnaryOpProgram;
  15876. }());
  15877. exports.UnaryOpProgram = UnaryOpProgram;
  15878. var CHECK_NAN_SNIPPET = "if (isNaN(x)) return x;";
  15879. exports.ABS = "return abs(x);";
  15880. exports.RELU = CHECK_NAN_SNIPPET + "\n return (x < 0.0) ? 0.0 : x;\n";
  15881. exports.ELU = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
  15882. exports.SELU = "\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = " + selu_util.SELU_SCALEALPHA + ";\n float scale = " + selu_util.SELU_SCALE + ";\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";
  15883. function STEP(alpha) {
  15884. if (alpha === void 0) { alpha = 0.0; }
  15885. return CHECK_NAN_SNIPPET + ("\n return x > 0.0 ? 1.0 : float(" + alpha + ");\n ");
  15886. }
  15887. exports.STEP = STEP;
  15888. exports.NEG = "return -x;";
  15889. exports.CEIL = "return ceil(x);";
  15890. exports.FLOOR = "return floor(x);";
  15891. exports.SIGN = "\n if (isNaN(x)) { return 0.0; }\n return sign(x);\n";
  15892. exports.ROUND = "\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n";
  15893. exports.EXP = "return exp(x);";
  15894. exports.EXPM1 = "return exp(x) - 1.0;";
  15895. exports.LOG = "return log(x);";
  15896. exports.LOG1P = "return log(1.0 + x);";
  15897. exports.SQRT = "return sqrt(x);";
  15898. exports.RSQRT = "return inversesqrt(x);";
  15899. exports.SIGMOID = "return 1.0 / (1.0 + exp(-1.0 * x));";
  15900. exports.SOFTPLUS = "\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n";
  15901. exports.SIN = CHECK_NAN_SNIPPET + "\n return sin(x);\n";
  15902. exports.COS = CHECK_NAN_SNIPPET + "\n return cos(x);\n";
  15903. exports.TAN = "return tan(x);";
  15904. exports.ASIN = "return asin(x);";
  15905. exports.ACOS = "return acos(x);";
  15906. exports.ATAN = CHECK_NAN_SNIPPET + "\n return atan(x);\n";
  15907. exports.SINH = "\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n";
  15908. exports.COSH = "\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n";
  15909. exports.TANH = "\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n";
  15910. exports.ASINH = "return log(x + sqrt(x * x + 1.0));";
  15911. exports.ACOSH = "return log(x + sqrt(x * x - 1.0));";
  15912. exports.ATANH = "return (log(1.0 + x) - log(1.0 - x)) / 2.0;";
  15913. exports.ERF = "\n // Error function is calculated approximately with elementary function.\n // See \"Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables\", Abramowitz and Stegun.\n float p = " + erf_util.ERF_P + ";\n float a1 = " + erf_util.ERF_A1 + ";\n float a2 = " + erf_util.ERF_A2 + ";\n float a3 = " + erf_util.ERF_A3 + ";\n float a4 = " + erf_util.ERF_A4 + ";\n float a5 = " + erf_util.ERF_A5 + ";\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n";
  15914. exports.SQUARE = "return x * x;";
  15915. exports.RECIPROCAL = "return 1.0 / x;";
  15916. exports.LOGICAL_NOT = "return float(!(x >= 1.0));";
  15917. exports.TO_INT = "return float(int(x));";
  15918. },{"../../ops/erf_util":118,"../../ops/selu_util":137}],107:[function(require,module,exports){
  15919. "use strict";
  15920. Object.defineProperty(exports, "__esModule", { value: true });
  15921. var MAX_TEXTURE_SIZE = null;
  15922. var util = require("../../util");
  15923. var environment_1 = require("../../environment");
  15924. function createWebGLRenderingContext(attributes) {
  15925. var canvas = document.createElement('canvas');
  15926. canvas.width = 1;
  15927. canvas.height = 1;
  15928. return createWebGLRenderingContextFromCanvas(canvas, attributes);
  15929. }
  15930. exports.createWebGLRenderingContext = createWebGLRenderingContext;
  15931. function createWebGLRenderingContextFromCanvas(canvas, attributes) {
  15932. var gl;
  15933. var webglVersion = environment_1.ENV.get('WEBGL_VERSION');
  15934. if (webglVersion === 2) {
  15935. gl = canvas.getContext('webgl2', attributes);
  15936. }
  15937. else if (webglVersion === 1) {
  15938. gl = (canvas.getContext('webgl', attributes) ||
  15939. canvas.getContext('experimental-webgl', attributes));
  15940. }
  15941. if (webglVersion === 0 || gl == null) {
  15942. throw new Error('This browser does not support WebGL.');
  15943. }
  15944. return gl;
  15945. }
  15946. exports.createWebGLRenderingContextFromCanvas = createWebGLRenderingContextFromCanvas;
  15947. function callAndCheck(gl, func) {
  15948. var returnValue = func();
  15949. checkWebGLError(gl);
  15950. return returnValue;
  15951. }
  15952. exports.callAndCheck = callAndCheck;
  15953. var webGLDebugErrorCheckingEnabled = false;
  15954. function enableDebugWebGLErrorChecking(enabled) {
  15955. webGLDebugErrorCheckingEnabled = enabled;
  15956. }
  15957. exports.enableDebugWebGLErrorChecking = enableDebugWebGLErrorChecking;
  15958. function checkWebGLError(gl) {
  15959. if (webGLDebugErrorCheckingEnabled) {
  15960. var error = gl.getError();
  15961. if (error !== gl.NO_ERROR) {
  15962. throw new Error('WebGL Error: ' + getWebGLErrorMessage(gl, error));
  15963. }
  15964. }
  15965. }
  15966. exports.checkWebGLError = checkWebGLError;
  15967. function getWebGLErrorMessage(gl, status) {
  15968. switch (status) {
  15969. case gl.NO_ERROR:
  15970. return 'NO_ERROR';
  15971. case gl.INVALID_ENUM:
  15972. return 'INVALID_ENUM';
  15973. case gl.INVALID_VALUE:
  15974. return 'INVALID_VALUE';
  15975. case gl.INVALID_OPERATION:
  15976. return 'INVALID_OPERATION';
  15977. case gl.INVALID_FRAMEBUFFER_OPERATION:
  15978. return 'INVALID_FRAMEBUFFER_OPERATION';
  15979. case gl.OUT_OF_MEMORY:
  15980. return 'OUT_OF_MEMORY';
  15981. case gl.CONTEXT_LOST_WEBGL:
  15982. return 'CONTEXT_LOST_WEBGL';
  15983. default:
  15984. return "Unknown error code " + status;
  15985. }
  15986. }
  15987. exports.getWebGLErrorMessage = getWebGLErrorMessage;
  15988. function getExtensionOrThrow(gl, extensionName) {
  15989. return throwIfNull(gl, function () { return gl.getExtension(extensionName); }, 'Extension "' + extensionName + '" not supported on this browser.');
  15990. }
  15991. exports.getExtensionOrThrow = getExtensionOrThrow;
  15992. function createVertexShader(gl, vertexShaderSource) {
  15993. var vertexShader = throwIfNull(gl, function () { return gl.createShader(gl.VERTEX_SHADER); }, 'Unable to create vertex WebGLShader.');
  15994. callAndCheck(gl, function () { return gl.shaderSource(vertexShader, vertexShaderSource); });
  15995. callAndCheck(gl, function () { return gl.compileShader(vertexShader); });
  15996. if (gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS) === false) {
  15997. console.log(gl.getShaderInfoLog(vertexShader));
  15998. throw new Error('Failed to compile vertex shader.');
  15999. }
  16000. return vertexShader;
  16001. }
  16002. exports.createVertexShader = createVertexShader;
  16003. function createFragmentShader(gl, fragmentShaderSource) {
  16004. var fragmentShader = throwIfNull(gl, function () { return gl.createShader(gl.FRAGMENT_SHADER); }, 'Unable to create fragment WebGLShader.');
  16005. callAndCheck(gl, function () { return gl.shaderSource(fragmentShader, fragmentShaderSource); });
  16006. callAndCheck(gl, function () { return gl.compileShader(fragmentShader); });
  16007. if (gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS) === false) {
  16008. logShaderSourceAndInfoLog(fragmentShaderSource, gl.getShaderInfoLog(fragmentShader));
  16009. throw new Error('Failed to compile fragment shader.');
  16010. }
  16011. return fragmentShader;
  16012. }
  16013. exports.createFragmentShader = createFragmentShader;
  16014. var lineNumberRegex = /ERROR: [0-9]+:([0-9]+):/g;
  16015. function logShaderSourceAndInfoLog(shaderSource, shaderInfoLog) {
  16016. var lineNumberRegexResult = lineNumberRegex.exec(shaderInfoLog);
  16017. if (lineNumberRegexResult == null) {
  16018. console.log("Couldn't parse line number in error: " + shaderInfoLog);
  16019. console.log(shaderSource);
  16020. return;
  16021. }
  16022. var lineNumber = +lineNumberRegexResult[1];
  16023. var shaderLines = shaderSource.split('\n');
  16024. var pad = shaderLines.length.toString().length + 2;
  16025. var linesWithLineNumbers = shaderLines.map(function (line, lineNumber) {
  16026. return util.rightPad((lineNumber + 1).toString(), pad) + line;
  16027. });
  16028. var maxLineLength = 0;
  16029. for (var i = 0; i < linesWithLineNumbers.length; i++) {
  16030. maxLineLength = Math.max(linesWithLineNumbers[i].length, maxLineLength);
  16031. }
  16032. var beforeErrorLines = linesWithLineNumbers.slice(0, lineNumber - 1);
  16033. var errorLine = linesWithLineNumbers.slice(lineNumber - 1, lineNumber);
  16034. var afterErrorLines = linesWithLineNumbers.slice(lineNumber);
  16035. console.log(beforeErrorLines.join('\n'));
  16036. console.log(shaderInfoLog.split('\n')[0]);
  16037. console.log("%c " + util.rightPad(errorLine[0], maxLineLength), 'border:1px solid red; background-color:#e3d2d2; color:#a61717');
  16038. console.log(afterErrorLines.join('\n'));
  16039. }
  16040. function createProgram(gl) {
  16041. return throwIfNull(gl, function () { return gl.createProgram(); }, 'Unable to create WebGLProgram.');
  16042. }
  16043. exports.createProgram = createProgram;
  16044. function linkProgram(gl, program) {
  16045. callAndCheck(gl, function () { return gl.linkProgram(program); });
  16046. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  16047. console.log(gl.getProgramInfoLog(program));
  16048. throw new Error('Failed to link vertex and fragment shaders.');
  16049. }
  16050. }
  16051. exports.linkProgram = linkProgram;
  16052. function validateProgram(gl, program) {
  16053. callAndCheck(gl, function () { return gl.validateProgram(program); });
  16054. if (gl.getProgramParameter(program, gl.VALIDATE_STATUS) === false) {
  16055. console.log(gl.getProgramInfoLog(program));
  16056. throw new Error('Shader program validation failed.');
  16057. }
  16058. }
  16059. exports.validateProgram = validateProgram;
  16060. function createStaticVertexBuffer(gl, data) {
  16061. var buffer = throwIfNull(gl, function () { return gl.createBuffer(); }, 'Unable to create WebGLBuffer');
  16062. callAndCheck(gl, function () { return gl.bindBuffer(gl.ARRAY_BUFFER, buffer); });
  16063. callAndCheck(gl, function () { return gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); });
  16064. return buffer;
  16065. }
  16066. exports.createStaticVertexBuffer = createStaticVertexBuffer;
  16067. function createStaticIndexBuffer(gl, data) {
  16068. var buffer = throwIfNull(gl, function () { return gl.createBuffer(); }, 'Unable to create WebGLBuffer');
  16069. callAndCheck(gl, function () { return gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer); });
  16070. callAndCheck(gl, function () { return gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW); });
  16071. return buffer;
  16072. }
  16073. exports.createStaticIndexBuffer = createStaticIndexBuffer;
  16074. function queryMaxTextureSize(gl) {
  16075. if (MAX_TEXTURE_SIZE != null) {
  16076. return MAX_TEXTURE_SIZE;
  16077. }
  16078. MAX_TEXTURE_SIZE =
  16079. callAndCheck(gl, function () { return gl.getParameter(gl.MAX_TEXTURE_SIZE); });
  16080. return MAX_TEXTURE_SIZE;
  16081. }
  16082. exports.queryMaxTextureSize = queryMaxTextureSize;
  16083. function getNumChannels() {
  16084. if (environment_1.ENV.get('WEBGL_VERSION') === 2) {
  16085. return 1;
  16086. }
  16087. return 4;
  16088. }
  16089. exports.getNumChannels = getNumChannels;
  16090. function createTexture(gl) {
  16091. return throwIfNull(gl, function () { return gl.createTexture(); }, 'Unable to create WebGLTexture.');
  16092. }
  16093. exports.createTexture = createTexture;
  16094. function validateTextureSize(gl, width, height) {
  16095. var maxTextureSize = queryMaxTextureSize(gl);
  16096. if ((width <= 0) || (height <= 0)) {
  16097. var requested = "[" + width + "x" + height + "]";
  16098. throw new Error('Requested texture size ' + requested + ' is invalid.');
  16099. }
  16100. if ((width > maxTextureSize) || (height > maxTextureSize)) {
  16101. var requested = "[" + width + "x" + height + "]";
  16102. var max = "[" + maxTextureSize + "x" + maxTextureSize + "]";
  16103. throw new Error('Requested texture size ' + requested +
  16104. ' greater than WebGL maximum on this browser / GPU ' + max + '.');
  16105. }
  16106. }
  16107. exports.validateTextureSize = validateTextureSize;
  16108. function createFramebuffer(gl) {
  16109. return throwIfNull(gl, function () { return gl.createFramebuffer(); }, 'Unable to create WebGLFramebuffer.');
  16110. }
  16111. exports.createFramebuffer = createFramebuffer;
  16112. function bindVertexBufferToProgramAttribute(gl, program, attribute, buffer, arrayEntriesPerItem, itemStrideInBytes, itemOffsetInBytes) {
  16113. var loc = gl.getAttribLocation(program, attribute);
  16114. if (loc === -1) {
  16115. return false;
  16116. }
  16117. callAndCheck(gl, function () { return gl.bindBuffer(gl.ARRAY_BUFFER, buffer); });
  16118. callAndCheck(gl, function () { return gl.vertexAttribPointer(loc, arrayEntriesPerItem, gl.FLOAT, false, itemStrideInBytes, itemOffsetInBytes); });
  16119. callAndCheck(gl, function () { return gl.enableVertexAttribArray(loc); });
  16120. return true;
  16121. }
  16122. exports.bindVertexBufferToProgramAttribute = bindVertexBufferToProgramAttribute;
  16123. function bindTextureUnit(gl, texture, textureUnit) {
  16124. validateTextureUnit(gl, textureUnit);
  16125. callAndCheck(gl, function () { return gl.activeTexture(gl.TEXTURE0 + textureUnit); });
  16126. callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, texture); });
  16127. }
  16128. exports.bindTextureUnit = bindTextureUnit;
  16129. function unbindTextureUnit(gl, textureUnit) {
  16130. validateTextureUnit(gl, textureUnit);
  16131. callAndCheck(gl, function () { return gl.activeTexture(gl.TEXTURE0 + textureUnit); });
  16132. callAndCheck(gl, function () { return gl.bindTexture(gl.TEXTURE_2D, null); });
  16133. }
  16134. exports.unbindTextureUnit = unbindTextureUnit;
  16135. function getProgramUniformLocationOrThrow(gl, program, uniformName) {
  16136. return throwIfNull(gl, function () { return gl.getUniformLocation(program, uniformName); }, 'uniform "' + uniformName + '" not present in program.');
  16137. }
  16138. exports.getProgramUniformLocationOrThrow = getProgramUniformLocationOrThrow;
  16139. function getProgramUniformLocation(gl, program, uniformName) {
  16140. return gl.getUniformLocation(program, uniformName);
  16141. }
  16142. exports.getProgramUniformLocation = getProgramUniformLocation;
  16143. function bindTextureToProgramUniformSampler(gl, program, texture, uniformSamplerLocation, textureUnit) {
  16144. callAndCheck(gl, function () { return bindTextureUnit(gl, texture, textureUnit); });
  16145. callAndCheck(gl, function () { return gl.uniform1i(uniformSamplerLocation, textureUnit); });
  16146. }
  16147. exports.bindTextureToProgramUniformSampler = bindTextureToProgramUniformSampler;
  16148. function bindCanvasToFramebuffer(gl) {
  16149. callAndCheck(gl, function () { return gl.bindFramebuffer(gl.FRAMEBUFFER, null); });
  16150. callAndCheck(gl, function () { return gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); });
  16151. callAndCheck(gl, function () { return gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); });
  16152. }
  16153. exports.bindCanvasToFramebuffer = bindCanvasToFramebuffer;
  16154. function bindColorTextureToFramebuffer(gl, texture, framebuffer) {
  16155. callAndCheck(gl, function () { return gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); });
  16156. callAndCheck(gl, function () { return gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); });
  16157. }
  16158. exports.bindColorTextureToFramebuffer = bindColorTextureToFramebuffer;
  16159. function unbindColorTextureFromFramebuffer(gl, framebuffer) {
  16160. callAndCheck(gl, function () { return gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); });
  16161. callAndCheck(gl, function () { return gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0); });
  16162. }
  16163. exports.unbindColorTextureFromFramebuffer = unbindColorTextureFromFramebuffer;
  16164. function validateFramebuffer(gl) {
  16165. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16166. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  16167. throw new Error('Error binding framebuffer: ' + getFramebufferErrorMessage(gl, status));
  16168. }
  16169. }
  16170. exports.validateFramebuffer = validateFramebuffer;
  16171. function getFramebufferErrorMessage(gl, status) {
  16172. switch (status) {
  16173. case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  16174. return 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT';
  16175. case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  16176. return 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT';
  16177. case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
  16178. return 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS';
  16179. case gl.FRAMEBUFFER_UNSUPPORTED:
  16180. return 'FRAMEBUFFER_UNSUPPORTED';
  16181. default:
  16182. return "unknown error " + status;
  16183. }
  16184. }
  16185. exports.getFramebufferErrorMessage = getFramebufferErrorMessage;
  16186. function throwIfNull(gl, returnTOrNull, failureMessage) {
  16187. var tOrNull = callAndCheck(gl, function () { return returnTOrNull(); });
  16188. if (tOrNull == null) {
  16189. throw new Error(failureMessage);
  16190. }
  16191. return tOrNull;
  16192. }
  16193. function validateTextureUnit(gl, textureUnit) {
  16194. var maxTextureUnit = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1;
  16195. var glTextureUnit = textureUnit + gl.TEXTURE0;
  16196. if (glTextureUnit < gl.TEXTURE0 || glTextureUnit > maxTextureUnit) {
  16197. var textureUnitRange = "[gl.TEXTURE0, gl.TEXTURE" + maxTextureUnit + "]";
  16198. throw new Error("textureUnit must be in " + textureUnitRange + ".");
  16199. }
  16200. }
  16201. function getTextureShapeFromLogicalShape(gl, logShape) {
  16202. if (logShape.length !== 2) {
  16203. var squeezeResult = util.squeezeShape(logShape);
  16204. logShape = squeezeResult.newShape;
  16205. }
  16206. var maxTexSize = queryMaxTextureSize(gl);
  16207. var size = util.sizeFromShape(logShape);
  16208. if (logShape.length <= 1 && size <= maxTexSize) {
  16209. return [size, 1];
  16210. }
  16211. else if (logShape.length === 2 && logShape[0] <= maxTexSize &&
  16212. logShape[1] <= maxTexSize) {
  16213. return logShape;
  16214. }
  16215. else if (logShape.length === 3 && logShape[0] <= maxTexSize &&
  16216. logShape[1] * logShape[2] <= maxTexSize) {
  16217. return [logShape[0], logShape[1] * logShape[2]];
  16218. }
  16219. else if (logShape.length === 4 && logShape[0] <= maxTexSize &&
  16220. logShape[1] * logShape[2] * logShape[3] <= maxTexSize) {
  16221. return [logShape[0], logShape[1] * logShape[2] * logShape[3]];
  16222. }
  16223. else {
  16224. return util.sizeToSquarishShape(size);
  16225. }
  16226. }
  16227. exports.getTextureShapeFromLogicalShape = getTextureShapeFromLogicalShape;
  16228. },{"../../environment":51,"../../util":164}],108:[function(require,module,exports){
  16229. "use strict";
  16230. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  16231. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  16232. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  16233. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  16234. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16235. };
  16236. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  16237. return new (P || (P = Promise))(function (resolve, reject) {
  16238. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  16239. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  16240. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  16241. step((generator = generator.apply(thisArg, _arguments || [])).next());
  16242. });
  16243. };
  16244. var __generator = (this && this.__generator) || function (thisArg, body) {
  16245. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  16246. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  16247. function verb(n) { return function (v) { return step([n, v]); }; }
  16248. function step(op) {
  16249. if (f) throw new TypeError("Generator is already executing.");
  16250. while (_) try {
  16251. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  16252. if (y = 0, t) op = [0, t.value];
  16253. switch (op[0]) {
  16254. case 0: case 1: t = op; break;
  16255. case 4: _.label++; return { value: op[1], done: false };
  16256. case 5: _.label++; y = op[1]; op = [0]; continue;
  16257. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  16258. default:
  16259. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  16260. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  16261. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  16262. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  16263. if (t[2]) _.ops.pop();
  16264. _.trys.pop(); continue;
  16265. }
  16266. op = body.call(thisArg, _);
  16267. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  16268. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  16269. }
  16270. };
  16271. Object.defineProperty(exports, "__esModule", { value: true });
  16272. var doc_1 = require("../doc");
  16273. var environment_1 = require("../environment");
  16274. var tensor_1 = require("../tensor");
  16275. var tensor_util = require("../tensor_util");
  16276. var util = require("../util");
  16277. var axis_util = require("./axis_util");
  16278. var axis_util_1 = require("./axis_util");
  16279. var concat_1 = require("./concat");
  16280. var operation_1 = require("./operation");
  16281. var rand_1 = require("./rand");
  16282. var segment_ops_1 = require("./segment_ops");
  16283. var ArrayOps = (function () {
  16284. function ArrayOps() {
  16285. }
  16286. ArrayOps.tensor = function (values, shape, dtype) {
  16287. if (dtype === void 0) { dtype = 'float32'; }
  16288. var inferredShape = util.inferShape(values);
  16289. if (shape != null && inferredShape.length !== 1) {
  16290. util.assertShapesMatch(shape, inferredShape, "Error creating a new Tensor. " +
  16291. ("Inferred shape (" + inferredShape + ") does not match the ") +
  16292. ("provided shape (" + shape + "). "));
  16293. }
  16294. if (!util.isTypedArray(values) && !Array.isArray(values)) {
  16295. values = [values];
  16296. }
  16297. shape = shape || inferredShape;
  16298. return tensor_1.Tensor.make(shape, { values: toTypedArray(values, dtype) }, dtype);
  16299. };
  16300. ArrayOps.scalar = function (value, dtype) {
  16301. if (dtype === void 0) { dtype = 'float32'; }
  16302. if (util.isTypedArray(value) || Array.isArray(value)) {
  16303. throw new Error('Error creating a new Scalar: value must be a primitive ' +
  16304. '(number|boolean)');
  16305. }
  16306. return ArrayOps.tensor(value, [], dtype);
  16307. };
  16308. ArrayOps.tensor1d = function (values, dtype) {
  16309. if (dtype === void 0) { dtype = 'float32'; }
  16310. var inferredShape = util.inferShape(values);
  16311. if (inferredShape.length !== 1) {
  16312. throw new Error('tensor1d() requires values to be a flat/TypedArray');
  16313. }
  16314. return ArrayOps.tensor(values, inferredShape, dtype);
  16315. };
  16316. ArrayOps.tensor2d = function (values, shape, dtype) {
  16317. if (dtype === void 0) { dtype = 'float32'; }
  16318. if (shape != null && shape.length !== 2) {
  16319. throw new Error('tensor2d() requires shape to have two numbers');
  16320. }
  16321. var inferredShape = util.inferShape(values);
  16322. if (inferredShape.length !== 2 && inferredShape.length !== 1) {
  16323. throw new Error('tensor2d() requires values to be number[][] or flat/TypedArray');
  16324. }
  16325. if (inferredShape.length === 1 && shape == null) {
  16326. throw new Error('tensor2d() requires shape to be provided when `values` ' +
  16327. 'are a flat/TypedArray');
  16328. }
  16329. shape = shape || inferredShape;
  16330. return ArrayOps.tensor(values, shape, dtype);
  16331. };
  16332. ArrayOps.tensor3d = function (values, shape, dtype) {
  16333. if (dtype === void 0) { dtype = 'float32'; }
  16334. if (shape != null && shape.length !== 3) {
  16335. throw new Error('tensor3d() requires shape to have three numbers');
  16336. }
  16337. var inferredShape = util.inferShape(values);
  16338. if (inferredShape.length !== 3 && inferredShape.length !== 1) {
  16339. throw new Error('tensor3d() requires values to be number[][][] or flat/TypedArray');
  16340. }
  16341. if (inferredShape.length === 1 && shape == null) {
  16342. throw new Error('tensor3d() requires shape to be provided when `values` ' +
  16343. 'are a flat array');
  16344. }
  16345. shape = shape || inferredShape;
  16346. return ArrayOps.tensor(values, shape, dtype);
  16347. };
  16348. ArrayOps.tensor4d = function (values, shape, dtype) {
  16349. if (dtype === void 0) { dtype = 'float32'; }
  16350. if (shape != null && shape.length !== 4) {
  16351. throw new Error('tensor4d() requires shape to have four numbers');
  16352. }
  16353. var inferredShape = util.inferShape(values);
  16354. if (inferredShape.length !== 4 && inferredShape.length !== 1) {
  16355. throw new Error('tensor4d() requires values to be number[][][][] or flat/TypedArray');
  16356. }
  16357. if (inferredShape.length === 1 && shape == null) {
  16358. throw new Error('tensor4d() requires shape to be provided when `values` ' +
  16359. 'are a flat array');
  16360. }
  16361. shape = shape || inferredShape;
  16362. return ArrayOps.tensor(values, shape, dtype);
  16363. };
  16364. ArrayOps.tensor5d = function (values, shape, dtype) {
  16365. if (dtype === void 0) { dtype = 'float32'; }
  16366. if (shape != null && shape.length !== 5) {
  16367. throw new Error('tensor5d() requires shape to have five numbers');
  16368. }
  16369. var inferredShape = util.inferShape(values);
  16370. if (inferredShape.length !== 5 && inferredShape.length !== 1) {
  16371. throw new Error('tensor5d() requires values to be \
  16372. number[][][][][] or flat/TypedArray');
  16373. }
  16374. if (inferredShape.length === 1 && shape == null) {
  16375. throw new Error('tensor5d() requires shape to be provided when `values` ' +
  16376. 'are a flat array');
  16377. }
  16378. shape = shape || inferredShape;
  16379. return ArrayOps.tensor(values, shape, dtype);
  16380. };
  16381. ArrayOps.tensor6d = function (values, shape, dtype) {
  16382. if (dtype === void 0) { dtype = 'float32'; }
  16383. if (shape != null && shape.length !== 6) {
  16384. throw new Error('tensor6d() requires shape to have six numbers');
  16385. }
  16386. var inferredShape = util.inferShape(values);
  16387. if (inferredShape.length !== 6 && inferredShape.length !== 1) {
  16388. throw new Error('tensor6d() requires values to be number[][][][] or flat/TypedArray');
  16389. }
  16390. if (inferredShape.length === 1 && shape == null) {
  16391. throw new Error('tensor6d() requires shape to be provided when `values` ' +
  16392. 'are a flat array');
  16393. }
  16394. shape = shape ||
  16395. inferredShape;
  16396. return ArrayOps.tensor(values, shape, dtype);
  16397. };
  16398. ArrayOps.ones = function (shape, dtype) {
  16399. if (dtype === void 0) { dtype = 'float32'; }
  16400. var values = makeOnesTypedArray(util.sizeFromShape(shape), dtype);
  16401. return tensor_1.Tensor.make(shape, { values: values }, dtype);
  16402. };
  16403. ArrayOps.zeros = function (shape, dtype) {
  16404. if (dtype === void 0) { dtype = 'float32'; }
  16405. var values = makeZerosTypedArray(util.sizeFromShape(shape), dtype);
  16406. return tensor_1.Tensor.make(shape, { values: values }, dtype);
  16407. };
  16408. ArrayOps.fill = function (shape, value, dtype) {
  16409. if (dtype === void 0) { dtype = 'float32'; }
  16410. var values = util.getTypedArrayFromDType(dtype, util.sizeFromShape(shape));
  16411. values.fill(value);
  16412. return tensor_1.Tensor.make(shape, { values: values }, dtype);
  16413. };
  16414. ArrayOps.onesLike = function (x) {
  16415. util.assertArgumentsAreTensors({ x: x }, 'onesLike');
  16416. return ArrayOps.ones(x.shape, x.dtype);
  16417. };
  16418. ArrayOps.zerosLike = function (x) {
  16419. util.assertArgumentsAreTensors({ x: x }, 'zerosLike');
  16420. return ArrayOps.zeros(x.shape, x.dtype);
  16421. };
  16422. ArrayOps.clone = function (x) {
  16423. util.assertArgumentsAreTensors({ x: x }, 'clone');
  16424. var der = function (dy) {
  16425. return { x: function () { return dy.toFloat(); } };
  16426. };
  16427. return environment_1.ENV.engine.runKernel(function (backend) {
  16428. return tensor_1.Tensor.make(x.shape, { dataId: x.dataId }, x.dtype);
  16429. }, { x: x }, der);
  16430. };
  16431. ArrayOps.eye = function (numRows, numColumns, batchShape, dtype) {
  16432. if (dtype === void 0) { dtype = 'float32'; }
  16433. if (numColumns == null) {
  16434. numColumns = numRows;
  16435. }
  16436. var buffer = ArrayOps.buffer([numRows, numColumns], dtype);
  16437. var n = numRows <= numColumns ? numRows : numColumns;
  16438. for (var i = 0; i < n; ++i) {
  16439. buffer.set(1, i, i);
  16440. }
  16441. var out = buffer.toTensor().as2D(numRows, numColumns);
  16442. if (batchShape == null) {
  16443. return out;
  16444. }
  16445. else {
  16446. if (batchShape.length === 1) {
  16447. return ArrayOps.tile(ArrayOps.expandDims(out, 0), [batchShape[0], 1, 1]);
  16448. }
  16449. else if (batchShape.length === 2) {
  16450. return ArrayOps.tile(ArrayOps.expandDims(ArrayOps.expandDims(out, 0), 0), [batchShape[0], batchShape[1], 1, 1]);
  16451. }
  16452. else {
  16453. throw new Error("eye() currently supports only 1D and 2D " +
  16454. ("batchShapes, but received " + batchShape.length + "D."));
  16455. }
  16456. }
  16457. };
  16458. ArrayOps.randomNormal = function (shape, mean, stdDev, dtype, seed) {
  16459. if (mean === void 0) { mean = 0; }
  16460. if (stdDev === void 0) { stdDev = 1; }
  16461. if (dtype != null && dtype === 'bool') {
  16462. throw new Error("Unsupported data type " + dtype);
  16463. }
  16464. var randGauss = new rand_1.MPRandGauss(mean, stdDev, dtype, false, seed);
  16465. var res = ArrayOps.buffer(shape, dtype);
  16466. for (var i = 0; i < res.values.length; i++) {
  16467. res.values[i] = randGauss.nextValue();
  16468. }
  16469. return res.toTensor();
  16470. };
  16471. ArrayOps.truncatedNormal = function (shape, mean, stdDev, dtype, seed) {
  16472. if (mean === void 0) { mean = 0; }
  16473. if (stdDev === void 0) { stdDev = 1; }
  16474. if (dtype != null && dtype === 'bool') {
  16475. throw new Error("Unsupported data type " + dtype);
  16476. }
  16477. var randGauss = new rand_1.MPRandGauss(mean, stdDev, dtype, true, seed);
  16478. var res = ArrayOps.buffer(shape, dtype);
  16479. for (var i = 0; i < res.values.length; i++) {
  16480. res.values[i] = randGauss.nextValue();
  16481. }
  16482. return res.toTensor();
  16483. };
  16484. ArrayOps.randomUniform = function (shape, minval, maxval, dtype) {
  16485. if (minval === void 0) { minval = 0; }
  16486. if (maxval === void 0) { maxval = 1; }
  16487. if (dtype === void 0) { dtype = 'float32'; }
  16488. var res = ArrayOps.buffer(shape, dtype);
  16489. for (var i = 0; i < res.values.length; i++) {
  16490. res.values[i] = util.randUniform(minval, maxval);
  16491. }
  16492. return res.toTensor();
  16493. };
  16494. ArrayOps.rand = function (shape, randFunction, dtype) {
  16495. var size = util.sizeFromShape(shape);
  16496. var values = null;
  16497. if (dtype == null || dtype === 'float32') {
  16498. values = new Float32Array(size);
  16499. }
  16500. else if (dtype === 'int32') {
  16501. values = new Int32Array(size);
  16502. }
  16503. else if (dtype === 'bool') {
  16504. values = new Uint8Array(size);
  16505. }
  16506. else {
  16507. throw new Error("Unknown data type " + dtype);
  16508. }
  16509. for (var i = 0; i < size; i++) {
  16510. values[i] = randFunction();
  16511. }
  16512. return tensor_1.Tensor.make(shape, { values: values }, dtype);
  16513. };
  16514. ArrayOps.multinomial = function (logits, numSamples, seed, normalized) {
  16515. if (normalized === void 0) { normalized = false; }
  16516. util.assertArgumentsAreTensors({ logits: logits }, 'multinomial');
  16517. var numOutcomes = logits.size;
  16518. var origRank = logits.rank;
  16519. if (numOutcomes < 2) {
  16520. throw new Error("Error in multinomial: you need at least 2 outcomes, but got " +
  16521. (numOutcomes + "."));
  16522. }
  16523. if (origRank > 2) {
  16524. throw new Error("Rank of probabilities must be 1 or 2, but is " + origRank);
  16525. }
  16526. seed = seed || Math.random();
  16527. var logits2D = origRank === 1 ? logits.as2D(1, -1) : logits;
  16528. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.multinomial(logits2D, normalized, numSamples, seed); }, { logits2D: logits2D });
  16529. return origRank === 1 ? res.as1D() : res;
  16530. };
  16531. ArrayOps.oneHot = function (indices, depth, onValue, offValue) {
  16532. if (onValue === void 0) { onValue = 1; }
  16533. if (offValue === void 0) { offValue = 0; }
  16534. util.assert(indices.dtype === 'int32', 'Indices must be of dtype `int32`');
  16535. if (depth < 2) {
  16536. throw new Error("Error in oneHot: depth must be >=2, but it is " + depth);
  16537. }
  16538. return environment_1.ENV.engine.runKernel(function (backend) { return backend.oneHot(indices, depth, onValue, offValue); }, { indices: indices });
  16539. };
  16540. ArrayOps.fromPixels = function (pixels, numChannels) {
  16541. if (numChannels === void 0) { numChannels = 3; }
  16542. if (numChannels > 4) {
  16543. throw new Error('Cannot construct Tensor with more than 4 channels from pixels.');
  16544. }
  16545. return environment_1.ENV.engine.fromPixels(pixels, numChannels);
  16546. };
  16547. ArrayOps.toPixels = function (img, canvas) {
  16548. return __awaiter(this, void 0, void 0, function () {
  16549. var _a, height, width, depth, minTensor, maxTensor, min, max, data, multiplier, bytes, i, r, g, b, a, j, ctx, imageData;
  16550. return __generator(this, function (_b) {
  16551. switch (_b.label) {
  16552. case 0:
  16553. util.assertArgumentsAreTensors({ img: img }, 'toPixels');
  16554. if (img.rank !== 2 && img.rank !== 3) {
  16555. throw new Error("toPixels only supports rank 2 or 3 tensors, got rank " + img.rank + ".");
  16556. }
  16557. _a = img.shape.slice(0, 2), height = _a[0], width = _a[1];
  16558. depth = img.rank === 2 ? 1 : img.shape[2];
  16559. if (depth > 4 || depth === 2) {
  16560. throw new Error("toPixels only supports depth of size " +
  16561. ("1, 3 or 4 but got " + depth));
  16562. }
  16563. minTensor = img.min();
  16564. maxTensor = img.max();
  16565. return [4, minTensor.data()];
  16566. case 1:
  16567. min = (_b.sent())[0];
  16568. return [4, maxTensor.data()];
  16569. case 2:
  16570. max = (_b.sent())[0];
  16571. minTensor.dispose();
  16572. maxTensor.dispose();
  16573. if (img.dtype === 'float32') {
  16574. if (min < 0 || max > 1) {
  16575. throw new Error("Tensor values for a float32 Tensor must be in the " +
  16576. ("range [0 - 1] but got range [" + min + " - " + max + "]."));
  16577. }
  16578. }
  16579. else if (img.dtype === 'int32') {
  16580. if (min < 0 || max > 255) {
  16581. throw new Error("Tensor values for a int32 Tensor must be in the " +
  16582. ("range [0 - 255] but got range [" + min + " - " + max + "]."));
  16583. }
  16584. }
  16585. else {
  16586. throw new Error("Unsupported type for toPixels: " + img.dtype + "." +
  16587. " Please use float32 or int32 tensors.");
  16588. }
  16589. return [4, img.data()];
  16590. case 3:
  16591. data = _b.sent();
  16592. multiplier = img.dtype === 'float32' ? 255 : 1;
  16593. bytes = new Uint8ClampedArray(width * height * 4);
  16594. for (i = 0; i < height * width; ++i) {
  16595. r = void 0, g = void 0, b = void 0, a = void 0;
  16596. if (depth === 1) {
  16597. r = data[i] * multiplier;
  16598. g = data[i] * multiplier;
  16599. b = data[i] * multiplier;
  16600. a = 255;
  16601. }
  16602. else if (depth === 3) {
  16603. r = data[i * 3] * multiplier;
  16604. g = data[i * 3 + 1] * multiplier;
  16605. b = data[i * 3 + 2] * multiplier;
  16606. a = 255;
  16607. }
  16608. else if (depth === 4) {
  16609. r = data[i * 4] * multiplier;
  16610. g = data[i * 4 + 1] * multiplier;
  16611. b = data[i * 4 + 2] * multiplier;
  16612. a = data[i * 4 + 3] * multiplier;
  16613. }
  16614. j = i * 4;
  16615. bytes[j + 0] = Math.round(r);
  16616. bytes[j + 1] = Math.round(g);
  16617. bytes[j + 2] = Math.round(b);
  16618. bytes[j + 3] = Math.round(a);
  16619. }
  16620. if (canvas != null) {
  16621. canvas.width = width;
  16622. canvas.height = height;
  16623. ctx = canvas.getContext('2d');
  16624. imageData = new ImageData(bytes, width, height);
  16625. ctx.putImageData(imageData, 0, 0);
  16626. }
  16627. return [2, bytes];
  16628. }
  16629. });
  16630. });
  16631. };
  16632. ArrayOps.reshape = function (x, shape) {
  16633. util.assertArgumentsAreTensors({ x: x }, 'reshape');
  16634. shape = util.inferFromImplicitShape(shape, x.size);
  16635. util.assert(x.size === util.sizeFromShape(shape), 'new shape and old shape must have the same number of elements.');
  16636. var grad = function (dy) {
  16637. return { x: function () { return dy.reshape(x.shape); } };
  16638. };
  16639. return environment_1.ENV.engine.runKernel(function (backend) { return backend.reshape(x, shape); }, { x: x }, grad);
  16640. };
  16641. ArrayOps.squeeze = function (x, axis) {
  16642. util.assertArgumentsAreTensors({ x: x }, 'squeeze');
  16643. return ArrayOps.reshape(x, util.squeezeShape(x.shape, axis).newShape);
  16644. };
  16645. ArrayOps.cast = function (x, dtype) {
  16646. util.assertArgumentsAreTensors({ x: x }, 'cast');
  16647. var grad = function (dy) {
  16648. return { x: function () { return dy.clone(); } };
  16649. };
  16650. return environment_1.ENV.engine.runKernel(function (backend) { return backend.cast(x, dtype); }, { x: x }, grad);
  16651. };
  16652. ArrayOps.tile = function (x, reps) {
  16653. util.assertArgumentsAreTensors({ x: x }, 'tile');
  16654. util.assert(x.rank === reps.length, "Error in transpose: rank of input " + x.rank + " " +
  16655. ("must match length of reps " + reps + "."));
  16656. var grad = function (dy) {
  16657. var derX = function () {
  16658. var xGrad = ArrayOps.zerosLike(x);
  16659. if (x.rank === 1) {
  16660. for (var i = 0; i < reps[0]; ++i) {
  16661. xGrad = xGrad.add(dy.slice([i * x.shape[0]], [x.shape[0]]));
  16662. }
  16663. }
  16664. else if (x.rank === 2) {
  16665. for (var i = 0; i < reps[0]; ++i) {
  16666. for (var j = 0; j < reps[1]; ++j) {
  16667. xGrad = xGrad.add(dy.slice([i * x.shape[0], j * x.shape[1]], [x.shape[0], x.shape[1]]));
  16668. }
  16669. }
  16670. }
  16671. else if (x.rank === 3) {
  16672. for (var i = 0; i < reps[0]; ++i) {
  16673. for (var j = 0; j < reps[1]; ++j) {
  16674. for (var k = 0; k < reps[2]; ++k) {
  16675. xGrad = xGrad.add(dy.slice([i * x.shape[0], j * x.shape[1], k * x.shape[2]], [x.shape[0], x.shape[1], x.shape[2]]));
  16676. }
  16677. }
  16678. }
  16679. }
  16680. else if (x.rank === 4) {
  16681. for (var i = 0; i < reps[0]; ++i) {
  16682. for (var j = 0; j < reps[1]; ++j) {
  16683. for (var k = 0; k < reps[2]; ++k) {
  16684. for (var l = 0; l < reps[3]; ++l) {
  16685. xGrad = xGrad.add(dy.slice([
  16686. i * x.shape[0], j * x.shape[1], k * x.shape[2],
  16687. l * x.shape[3]
  16688. ], [x.shape[0], x.shape[1], x.shape[2], x.shape[3]]));
  16689. }
  16690. }
  16691. }
  16692. }
  16693. }
  16694. else {
  16695. throw new Error("Gradient for tile operation is not implemented for rank-" +
  16696. (x.rank + " tensors yet."));
  16697. }
  16698. return xGrad;
  16699. };
  16700. return { x: derX };
  16701. };
  16702. return environment_1.ENV.engine.runKernel(function (backend) { return backend.tile(x, reps); }, { x: x }, grad);
  16703. };
  16704. ArrayOps.gather = function (x, indices, axis) {
  16705. if (axis === void 0) { axis = 0; }
  16706. util.assertArgumentsAreTensors({ x: x, indices: indices }, 'gather');
  16707. util.assert(indices.dtype === 'int32', 'Indices must be of dtype `int32`');
  16708. axis = axis_util_1.parseAxisParam(axis, x.shape)[0];
  16709. var grad = function (dy) {
  16710. var derX = function () {
  16711. if (axis === 0) {
  16712. return segment_ops_1.SegmentOps.unsortedSegmentSum(dy, indices, x.shape[axis]);
  16713. }
  16714. var paramsShape = x.shape;
  16715. var indicesSize = indices.size;
  16716. var outerShape = paramsShape.slice(0, axis);
  16717. var outerDims = outerShape.length;
  16718. var innerShape = paramsShape.slice(axis, paramsShape.length).slice(1);
  16719. var innerDims = innerShape.length;
  16720. var outerAxesIndices = arrayRange(0, outerDims);
  16721. var innerAxesIndices = arrayRange(outerDims + 1, outerDims + 1 + innerDims);
  16722. var valuesShape = arrayConcat([outerShape, [indicesSize], innerShape]);
  16723. var values = dy.reshape(valuesShape);
  16724. var reshapedIndices = indices.reshape([indicesSize]);
  16725. var transposeDims = arrayConcat([[outerDims], outerAxesIndices, innerAxesIndices]);
  16726. var valuesTranspose = values.transpose(transposeDims);
  16727. var paramsGrad = segment_ops_1.SegmentOps.unsortedSegmentSum(valuesTranspose, reshapedIndices, x.shape[axis]);
  16728. var invertTransposeDims = axis_util.getUndoAxesPermutation(transposeDims);
  16729. paramsGrad = paramsGrad.transpose(invertTransposeDims);
  16730. return paramsGrad;
  16731. };
  16732. return { x: derX };
  16733. };
  16734. return environment_1.ENV.engine.runKernel(function (backend) { return backend.gather(x, indices, axis); }, { x: x }, grad);
  16735. };
  16736. ArrayOps.pad1d = function (x, paddings, constantValue) {
  16737. if (constantValue === void 0) { constantValue = 0; }
  16738. util.assert(paddings.length === 2, 'Invalid number of paddings. Must be length of 2.');
  16739. return ArrayOps.pad(x, [paddings], constantValue);
  16740. };
  16741. ArrayOps.pad2d = function (x, paddings, constantValue) {
  16742. if (constantValue === void 0) { constantValue = 0; }
  16743. util.assert(paddings.length === 2 && paddings[0].length === 2 &&
  16744. paddings[1].length === 2, 'Invalid number of paddings. Must be length of 2 each.');
  16745. return ArrayOps.pad(x, paddings, constantValue);
  16746. };
  16747. ArrayOps.pad3d = function (x, paddings, constantValue) {
  16748. if (constantValue === void 0) { constantValue = 0; }
  16749. util.assert(paddings.length === 3 && paddings[0].length === 2 &&
  16750. paddings[1].length === 2 && paddings[2].length === 2, 'Invalid number of paddings. Must be length of 2 each.');
  16751. return ArrayOps.pad(x, paddings, constantValue);
  16752. };
  16753. ArrayOps.pad4d = function (x, paddings, constantValue) {
  16754. if (constantValue === void 0) { constantValue = 0; }
  16755. util.assert(paddings.length === 4 && paddings[0].length === 2 &&
  16756. paddings[1].length === 2 && paddings[2].length === 2 &&
  16757. paddings[3].length === 2, 'Invalid number of paddings. Must be length of 2 each.');
  16758. return ArrayOps.pad(x, paddings, constantValue);
  16759. };
  16760. ArrayOps.pad = function (x, paddings, constantValue) {
  16761. if (constantValue === void 0) { constantValue = 0; }
  16762. util.assertArgumentsAreTensors({ x: x }, 'pad');
  16763. if (x.rank === 0) {
  16764. throw new Error('pad(scalar) is not defined. Pass non-scalar to pad');
  16765. }
  16766. var begin = paddings.map(function (p) { return p[0]; });
  16767. var grad = function (dy) {
  16768. return { x: function () { return dy.slice(begin, x.shape); } };
  16769. };
  16770. return environment_1.ENV.engine.runKernel(function (backend) { return backend.pad(x, paddings, constantValue); }, { x: x }, grad);
  16771. };
  16772. ArrayOps.stack = function (tensors, axis) {
  16773. if (axis === void 0) { axis = 0; }
  16774. util.assertArgumentsAreTensors({ tensors: tensors }, 'stack');
  16775. util.assert(tensors.length >= 1, 'Pass at least one tensor to tf.stack');
  16776. if (tensors.length === 1) {
  16777. return tensors[0].expandDims(axis);
  16778. }
  16779. var rank = tensors[0].rank;
  16780. var shape = tensors[0].shape;
  16781. var dtype = tensors[0].dtype;
  16782. util.assert(axis <= rank, 'Axis must be <= rank of the tensor');
  16783. tensors.forEach(function (t) {
  16784. util.assertShapesMatch(shape, t.shape, 'All tensors passed to stack must have matching shapes');
  16785. });
  16786. tensors.forEach(function (t) {
  16787. util.assert(dtype === t.dtype, 'All tensors passed to stack must have matching dtypes');
  16788. });
  16789. var expandedTensors = tensors.map(function (t) { return t.expandDims(axis); });
  16790. return concat_1.ConcatOps.concat(expandedTensors, axis);
  16791. };
  16792. ArrayOps.unstack = function (value, axis) {
  16793. if (axis === void 0) { axis = 0; }
  16794. var num = value.shape[axis];
  16795. var outputShape = Array(value.rank - 1).fill(0);
  16796. var outIndex = 0;
  16797. for (var i = 0; i < value.rank; i++) {
  16798. if (i !== axis) {
  16799. outputShape[outIndex] = value.shape[i];
  16800. outIndex++;
  16801. }
  16802. }
  16803. var splitSizes;
  16804. splitSizes = Array(num).fill(1);
  16805. var begin = Array(value.rank).fill(0);
  16806. var size = value.shape.slice();
  16807. return splitSizes.map(function (s) {
  16808. size[axis] = s;
  16809. var slice = value.slice(begin, size);
  16810. begin[axis] += s;
  16811. return slice.reshape(outputShape);
  16812. });
  16813. };
  16814. ArrayOps.split = function (x, numOrSizeSplits, axis) {
  16815. if (axis === void 0) { axis = 0; }
  16816. util.assertArgumentsAreTensors({ x: x }, 'split');
  16817. axis = axis_util_1.parseAxisParam(axis, x.shape)[0];
  16818. var splitSizes;
  16819. if (typeof (numOrSizeSplits) === 'number') {
  16820. util.assert(x.shape[axis] % numOrSizeSplits === 0, 'Number of splits must evenly divide the axis.');
  16821. splitSizes = Array(numOrSizeSplits).fill(x.shape[axis] / numOrSizeSplits);
  16822. }
  16823. else {
  16824. util.assert(x.shape[axis] === numOrSizeSplits.reduce(function (a, b) { return a + b; }), 'The sum of sizes must match the size of the axis dimension.');
  16825. splitSizes = numOrSizeSplits;
  16826. }
  16827. var begin = Array(x.rank).fill(0);
  16828. var size = x.shape.slice();
  16829. return splitSizes.map(function (s) {
  16830. size[axis] = s;
  16831. var slice = x.slice(begin, size);
  16832. begin[axis] += s;
  16833. return slice;
  16834. });
  16835. };
  16836. ArrayOps.cumsum = function (x, axis, exclusive, reverse) {
  16837. if (axis === void 0) { axis = 0; }
  16838. if (exclusive === void 0) { exclusive = false; }
  16839. if (reverse === void 0) { reverse = false; }
  16840. util.assertArgumentsAreTensors({ x: x }, 'cumsum');
  16841. axis = axis | 0;
  16842. var permutation = axis_util_1.getAxesPermutation([axis], x.rank);
  16843. var permutedX = x;
  16844. if (permutation != null) {
  16845. permutedX = x.transpose(permutation);
  16846. }
  16847. var permutedAxis = axis_util_1.getInnerMostAxes(1, x.rank)[0];
  16848. var grad = function (dy) {
  16849. return { permutedX: function () { return dy.cumsum(axis, exclusive, !reverse); } };
  16850. };
  16851. var value = environment_1.ENV.engine.runKernel(function (backend) { return backend.cumsum(permutedX, permutedAxis, exclusive, reverse); }, { permutedX: permutedX }, grad);
  16852. if (permutation != null) {
  16853. value = value.transpose(permutation);
  16854. }
  16855. return value;
  16856. };
  16857. ArrayOps.expandDims = function (x, axis) {
  16858. if (axis === void 0) { axis = 0; }
  16859. util.assertArgumentsAreTensors({ x: x }, 'expandDims');
  16860. util.assert(axis <= x.rank, 'Axis must be <= rank of the tensor');
  16861. var newShape = x.shape.slice();
  16862. newShape.splice(axis, 0, 1);
  16863. return ArrayOps.reshape(x, newShape);
  16864. };
  16865. ArrayOps.linspace = function (start, stop, num) {
  16866. if (num === 0) {
  16867. throw new Error('Cannot request zero samples');
  16868. }
  16869. var step = (stop - start) / (num - 1);
  16870. var values = makeZerosTypedArray(num, 'float32');
  16871. values[0] = start;
  16872. for (var i = 1; i < values.length; i++) {
  16873. values[i] = values[i - 1] + step;
  16874. }
  16875. return ArrayOps.tensor1d(values, 'float32');
  16876. };
  16877. ArrayOps.range = function (start, stop, step, dtype) {
  16878. if (step === void 0) { step = 1; }
  16879. if (dtype === void 0) { dtype = 'float32'; }
  16880. if (step === 0) {
  16881. throw new Error('Cannot have a step of zero');
  16882. }
  16883. var sameStartStop = start === stop;
  16884. var increasingRangeNegativeStep = start < stop && step < 0;
  16885. var decreasingRangePositiveStep = stop < start && step > 1;
  16886. if (sameStartStop || increasingRangeNegativeStep ||
  16887. decreasingRangePositiveStep) {
  16888. return ArrayOps.zeros([0], dtype);
  16889. }
  16890. var numElements = Math.abs(Math.ceil((stop - start) / step));
  16891. var values = makeZerosTypedArray(numElements, dtype);
  16892. if (stop < start && step === 1) {
  16893. step = -1;
  16894. }
  16895. values[0] = start;
  16896. for (var i = 1; i < values.length; i++) {
  16897. values[i] = values[i - 1] + step;
  16898. }
  16899. return ArrayOps.tensor1d(values, dtype);
  16900. };
  16901. ArrayOps.buffer = function (shape, dtype, values) {
  16902. if (dtype === void 0) { dtype = 'float32'; }
  16903. return new tensor_1.TensorBuffer(shape, dtype, values);
  16904. };
  16905. ArrayOps.print = function (x, verbose) {
  16906. if (verbose === void 0) { verbose = false; }
  16907. console.log(tensor_util.tensorToString(x, verbose));
  16908. };
  16909. __decorate([
  16910. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  16911. ], ArrayOps, "tensor", null);
  16912. __decorate([
  16913. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  16914. ], ArrayOps, "scalar", null);
  16915. __decorate([
  16916. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  16917. ], ArrayOps, "tensor1d", null);
  16918. __decorate([
  16919. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  16920. ], ArrayOps, "tensor2d", null);
  16921. __decorate([
  16922. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  16923. ], ArrayOps, "tensor3d", null);
  16924. __decorate([
  16925. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  16926. ], ArrayOps, "tensor4d", null);
  16927. __decorate([
  16928. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  16929. ], ArrayOps, "tensor5d", null);
  16930. __decorate([
  16931. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  16932. ], ArrayOps, "tensor6d", null);
  16933. __decorate([
  16934. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16935. operation_1.operation
  16936. ], ArrayOps, "ones", null);
  16937. __decorate([
  16938. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16939. operation_1.operation
  16940. ], ArrayOps, "zeros", null);
  16941. __decorate([
  16942. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16943. operation_1.operation
  16944. ], ArrayOps, "fill", null);
  16945. __decorate([
  16946. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16947. operation_1.operation
  16948. ], ArrayOps, "onesLike", null);
  16949. __decorate([
  16950. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16951. operation_1.operation
  16952. ], ArrayOps, "zerosLike", null);
  16953. __decorate([
  16954. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16955. operation_1.operation
  16956. ], ArrayOps, "clone", null);
  16957. __decorate([
  16958. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16959. operation_1.operation
  16960. ], ArrayOps, "eye", null);
  16961. __decorate([
  16962. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16963. operation_1.operation
  16964. ], ArrayOps, "randomNormal", null);
  16965. __decorate([
  16966. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16967. operation_1.operation
  16968. ], ArrayOps, "truncatedNormal", null);
  16969. __decorate([
  16970. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16971. operation_1.operation
  16972. ], ArrayOps, "randomUniform", null);
  16973. __decorate([
  16974. operation_1.operation
  16975. ], ArrayOps, "rand", null);
  16976. __decorate([
  16977. operation_1.operation
  16978. ], ArrayOps, "multinomial", null);
  16979. __decorate([
  16980. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16981. operation_1.operation
  16982. ], ArrayOps, "oneHot", null);
  16983. __decorate([
  16984. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' }),
  16985. operation_1.operation
  16986. ], ArrayOps, "fromPixels", null);
  16987. __decorate([
  16988. doc_1.doc({ heading: 'Visualization' })
  16989. ], ArrayOps, "toPixels", null);
  16990. __decorate([
  16991. doc_1.doc({ heading: 'Tensors', subheading: 'Transformations' }),
  16992. operation_1.operation
  16993. ], ArrayOps, "reshape", null);
  16994. __decorate([
  16995. doc_1.doc({ heading: 'Tensors', subheading: 'Transformations' })
  16996. ], ArrayOps, "squeeze", null);
  16997. __decorate([
  16998. doc_1.doc({ heading: 'Tensors', subheading: 'Transformations' }),
  16999. operation_1.operation
  17000. ], ArrayOps, "cast", null);
  17001. __decorate([
  17002. doc_1.doc({ heading: 'Tensors', subheading: 'Slicing and Joining' }),
  17003. operation_1.operation
  17004. ], ArrayOps, "tile", null);
  17005. __decorate([
  17006. doc_1.doc({ heading: 'Tensors', subheading: 'Slicing and Joining' }),
  17007. operation_1.operation
  17008. ], ArrayOps, "gather", null);
  17009. __decorate([
  17010. doc_1.doc({ heading: 'Tensors', subheading: 'Transformations' }),
  17011. operation_1.operation
  17012. ], ArrayOps, "pad", null);
  17013. __decorate([
  17014. doc_1.doc({ heading: 'Tensors', subheading: 'Slicing and Joining' }),
  17015. operation_1.operation
  17016. ], ArrayOps, "stack", null);
  17017. __decorate([
  17018. doc_1.doc({ heading: 'Tensors', subheading: 'Slicing and Joining' }),
  17019. operation_1.operation
  17020. ], ArrayOps, "unstack", null);
  17021. __decorate([
  17022. doc_1.doc({ heading: 'Tensors', subheading: 'Slicing and Joining' }),
  17023. operation_1.operation
  17024. ], ArrayOps, "split", null);
  17025. __decorate([
  17026. doc_1.doc({ heading: 'Operations', subheading: 'Scan' })
  17027. ], ArrayOps, "cumsum", null);
  17028. __decorate([
  17029. doc_1.doc({ heading: 'Tensors', subheading: 'Transformations' }),
  17030. operation_1.operation
  17031. ], ArrayOps, "expandDims", null);
  17032. __decorate([
  17033. operation_1.operation,
  17034. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  17035. ], ArrayOps, "linspace", null);
  17036. __decorate([
  17037. operation_1.operation,
  17038. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  17039. ], ArrayOps, "range", null);
  17040. __decorate([
  17041. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  17042. ], ArrayOps, "buffer", null);
  17043. __decorate([
  17044. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  17045. ], ArrayOps, "print", null);
  17046. return ArrayOps;
  17047. }());
  17048. exports.ArrayOps = ArrayOps;
  17049. function makeZerosTypedArray(size, dtype) {
  17050. if (dtype == null || dtype === 'float32') {
  17051. return new Float32Array(size);
  17052. }
  17053. else if (dtype === 'int32') {
  17054. return new Int32Array(size);
  17055. }
  17056. else if (dtype === 'bool') {
  17057. return new Uint8Array(size);
  17058. }
  17059. else {
  17060. throw new Error("Unknown data type $ {dtype}");
  17061. }
  17062. }
  17063. function makeOnesTypedArray(size, dtype) {
  17064. var array = makeZerosTypedArray(size, dtype);
  17065. for (var i = 0; i < array.length; i++) {
  17066. array[i] = 1;
  17067. }
  17068. return array;
  17069. }
  17070. function toTypedArray(a, dtype) {
  17071. if (noConversionNeeded(a, dtype)) {
  17072. return a;
  17073. }
  17074. if (Array.isArray(a)) {
  17075. a = util.flatten(a);
  17076. }
  17077. return util.copyTypedArray(a, dtype);
  17078. }
  17079. function noConversionNeeded(a, dtype) {
  17080. return (a instanceof Float32Array && dtype === 'float32') ||
  17081. (a instanceof Int32Array && dtype === 'int32') ||
  17082. (a instanceof Uint8Array && dtype === 'bool');
  17083. }
  17084. function arrayRange(start, stop) {
  17085. var result = [];
  17086. for (var i = start; i < stop; ++i) {
  17087. result.push(i);
  17088. }
  17089. return result;
  17090. }
  17091. function arrayConcat(arrays) {
  17092. var result = [];
  17093. for (var i = 0; i < arrays.length; ++i) {
  17094. for (var j = 0; j < arrays[i].length; ++j) {
  17095. result.push(arrays[i][j]);
  17096. }
  17097. }
  17098. return result;
  17099. }
  17100. },{"../doc":49,"../environment":51,"../tensor":158,"../tensor_util":159,"../util":164,"./axis_util":109,"./concat":114,"./operation":128,"./rand":131,"./segment_ops":135}],109:[function(require,module,exports){
  17101. "use strict";
  17102. Object.defineProperty(exports, "__esModule", { value: true });
  17103. var util = require("../util");
  17104. function axesAreInnerMostDims(axes, rank) {
  17105. for (var i = 0; i < axes.length; ++i) {
  17106. if (axes[axes.length - i - 1] !== rank - 1 - i) {
  17107. return false;
  17108. }
  17109. }
  17110. return true;
  17111. }
  17112. exports.axesAreInnerMostDims = axesAreInnerMostDims;
  17113. function combineLocations(outputLoc, reduceLoc, axes) {
  17114. var rank = outputLoc.length + reduceLoc.length;
  17115. var loc = [];
  17116. var outIdx = 0;
  17117. var reduceIdx = 0;
  17118. for (var dim = 0; dim < rank; dim++) {
  17119. if (axes.indexOf(dim) === -1) {
  17120. loc.push(outputLoc[outIdx++]);
  17121. }
  17122. else {
  17123. loc.push(reduceLoc[reduceIdx++]);
  17124. }
  17125. }
  17126. return loc;
  17127. }
  17128. exports.combineLocations = combineLocations;
  17129. function computeOutAndReduceShapes(aShape, axes) {
  17130. var outShape = [];
  17131. var rank = aShape.length;
  17132. for (var dim = 0; dim < rank; dim++) {
  17133. if (axes.indexOf(dim) === -1) {
  17134. outShape.push(aShape[dim]);
  17135. }
  17136. }
  17137. var reduceShape = axes.map(function (dim) { return aShape[dim]; });
  17138. return [outShape, reduceShape];
  17139. }
  17140. exports.computeOutAndReduceShapes = computeOutAndReduceShapes;
  17141. function expandShapeToKeepDim(shape, axes) {
  17142. var reduceSubShape = axes.map(function (x) { return 1; });
  17143. return combineLocations(shape, reduceSubShape, axes);
  17144. }
  17145. exports.expandShapeToKeepDim = expandShapeToKeepDim;
  17146. function parseAxisParam(axis, shape) {
  17147. var rank = shape.length;
  17148. axis = axis == null ? shape.map(function (s, i) { return i; }) : [].concat(axis);
  17149. util.assert(axis.every(function (ax) { return ax >= -rank && ax < rank; }), "All values in axis param must be in range [-" + rank + ", " + rank + ") but " +
  17150. ("got axis " + axis));
  17151. util.assert(axis.every(function (ax) { return util.isInt(ax); }), "All values in axis param must be integers but " +
  17152. ("got axis " + axis));
  17153. return axis.map(function (a) { return a < 0 ? rank + a : a; });
  17154. }
  17155. exports.parseAxisParam = parseAxisParam;
  17156. function assertAxesAreInnerMostDims(msg, axes, rank) {
  17157. util.assert(axesAreInnerMostDims(axes, rank), msg + " supports only inner-most axes for now. " +
  17158. ("Got axes " + axes + " and rank-" + rank + " input."));
  17159. }
  17160. exports.assertAxesAreInnerMostDims = assertAxesAreInnerMostDims;
  17161. function getAxesPermutation(axes, rank) {
  17162. if (axesAreInnerMostDims(axes, rank)) {
  17163. return null;
  17164. }
  17165. var result = [];
  17166. for (var i = 0; i < rank; ++i) {
  17167. if (axes.indexOf(i) === -1) {
  17168. result.push(i);
  17169. }
  17170. }
  17171. axes.forEach(function (axis) { return result.push(axis); });
  17172. return result;
  17173. }
  17174. exports.getAxesPermutation = getAxesPermutation;
  17175. function getUndoAxesPermutation(axes) {
  17176. return axes.map(function (axis, i) { return [i, axis]; })
  17177. .sort(function (a, b) { return a[1] - b[1]; })
  17178. .map(function (x) { return x[0]; });
  17179. }
  17180. exports.getUndoAxesPermutation = getUndoAxesPermutation;
  17181. function getInnerMostAxes(numAxes, rank) {
  17182. var res = [];
  17183. for (var i = rank - numAxes; i < rank; ++i) {
  17184. res.push(i);
  17185. }
  17186. return res;
  17187. }
  17188. exports.getInnerMostAxes = getInnerMostAxes;
  17189. },{"../util":164}],110:[function(require,module,exports){
  17190. "use strict";
  17191. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17192. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17193. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17194. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  17195. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17196. };
  17197. Object.defineProperty(exports, "__esModule", { value: true });
  17198. var doc_1 = require("../doc");
  17199. var environment_1 = require("../environment");
  17200. var util = require("../util");
  17201. var array_ops_1 = require("./array_ops");
  17202. var broadcast_util_1 = require("./broadcast_util");
  17203. var operation_1 = require("./operation");
  17204. var ops_1 = require("./ops");
  17205. var BatchNormOps = (function () {
  17206. function BatchNormOps() {
  17207. }
  17208. BatchNormOps.batchNormalization2d = function (x, mean, variance, varianceEpsilon, scale, offset) {
  17209. if (varianceEpsilon === void 0) { varianceEpsilon = .001; }
  17210. util.assert(x.rank === 2, "Error in batchNormalization3D: x must be rank 3 but got rank " +
  17211. (x.rank + "."));
  17212. util.assert(mean.rank === 2 || mean.rank === 1, "Error in batchNormalization2D: mean must be rank 2 or rank 1 but " +
  17213. ("got rank " + mean.rank + "."));
  17214. util.assert(variance.rank === 2 || variance.rank === 1, "Error in batchNormalization2D: variance must be rank 2 or rank 1 " +
  17215. ("but got rank " + variance.rank + "."));
  17216. if (scale != null) {
  17217. util.assert(scale.rank === 2 || scale.rank === 1, "Error in batchNormalization2D: scale must be rank 2 or rank 1 " +
  17218. ("but got rank " + scale.rank + "."));
  17219. }
  17220. if (offset != null) {
  17221. util.assert(offset.rank === 2 || offset.rank === 1, "Error in batchNormalization2D: offset must be rank 2 or rank 1 " +
  17222. ("but got rank " + offset.rank + "."));
  17223. }
  17224. return BatchNormOps.batchNormalization(x, mean, variance, varianceEpsilon, scale, offset);
  17225. };
  17226. BatchNormOps.batchNormalization3d = function (x, mean, variance, varianceEpsilon, scale, offset) {
  17227. if (varianceEpsilon === void 0) { varianceEpsilon = .001; }
  17228. util.assert(x.rank === 3, "Error in batchNormalization3D: x must be rank 3 but got rank " +
  17229. (x.rank + "."));
  17230. util.assert(mean.rank === 3 || mean.rank === 1, "Error in batchNormalization3D: mean must be rank 3 or rank 1 but " +
  17231. ("got rank " + mean.rank + "."));
  17232. util.assert(variance.rank === 3 || variance.rank === 1, "Error in batchNormalization3D: variance must be rank 3 or rank 1 " +
  17233. ("but got rank " + variance.rank + "."));
  17234. if (scale != null) {
  17235. util.assert(scale.rank === 3 || scale.rank === 1, "Error in batchNormalization3D: scale must be rank 3 or rank 1 " +
  17236. ("but got rank " + scale.rank + "."));
  17237. }
  17238. if (offset != null) {
  17239. util.assert(offset.rank === 3 || offset.rank === 1, "Error in batchNormalization3D: offset must be rank 3 or rank 1 " +
  17240. ("but got rank " + offset.rank + "."));
  17241. }
  17242. return BatchNormOps.batchNormalization(x, mean, variance, varianceEpsilon, scale, offset);
  17243. };
  17244. BatchNormOps.batchNormalization4d = function (x, mean, variance, varianceEpsilon, scale, offset) {
  17245. if (varianceEpsilon === void 0) { varianceEpsilon = .001; }
  17246. util.assert(x.rank === 4, "Error in batchNormalization4D: x must be rank 4 but got rank " +
  17247. (x.rank + "."));
  17248. util.assert(mean.rank === 4 || mean.rank === 1, "Error in batchNormalization4D: mean must be rank 4 or rank 1 but " +
  17249. ("got rank " + mean.rank + "."));
  17250. util.assert(variance.rank === 4 || variance.rank === 1, "Error in batchNormalization4D: variance must be rank 4 or rank 1 " +
  17251. ("but got rank " + variance.rank + "."));
  17252. if (scale != null) {
  17253. util.assert(scale.rank === 4 || scale.rank === 1, "Error in batchNormalization4D: scale must be rank 4 or rank 1 " +
  17254. ("but got rank " + scale.rank + "."));
  17255. }
  17256. if (offset != null) {
  17257. util.assert(offset.rank === 4 || offset.rank === 1, "Error in batchNormalization4D: offset must be rank 4 or rank 1 " +
  17258. ("but got rank " + offset.rank + "."));
  17259. }
  17260. return BatchNormOps.batchNormalization(x, mean, variance, varianceEpsilon, scale, offset);
  17261. };
  17262. BatchNormOps.batchNormalization = function (x, mean, variance, varianceEpsilon, scale, offset) {
  17263. if (varianceEpsilon === void 0) { varianceEpsilon = .001; }
  17264. util.assertArgumentsAreTensors({ x: x, mean: mean, variance: variance }, 'batchNormalization');
  17265. if (scale != null) {
  17266. util.assertArgumentsAreTensors({ scale: scale }, 'batchNormalization');
  17267. }
  17268. if (offset != null) {
  17269. util.assertArgumentsAreTensors({ offset: offset }, 'batchNormalization');
  17270. }
  17271. util.assert(mean.rank === variance.rank, 'Batch normalization gradient requires mean and variance to have ' +
  17272. 'equal ranks.');
  17273. util.assert(offset == null || mean.rank === offset.rank, 'Batch normalization gradient requires mean and offset to have ' +
  17274. 'equal ranks.');
  17275. util.assert(scale == null || mean.rank === scale.rank, 'Batch normalization gradient requires mean and scale to have ' +
  17276. 'equal ranks.');
  17277. var x4D;
  17278. if (x.rank === 0 || x.rank === 1) {
  17279. x4D = x.as4D(1, 1, 1, x.size);
  17280. }
  17281. else if (x.rank === 2) {
  17282. x4D = x.as4D(1, 1, x.shape[0], x.shape[1]);
  17283. }
  17284. else if (x.rank === 3) {
  17285. x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  17286. }
  17287. else {
  17288. x4D = x;
  17289. }
  17290. var der = function (dy) {
  17291. var scaleValue = scale == null ? array_ops_1.ArrayOps.scalar(1) : scale;
  17292. var reductionAxes = broadcast_util_1.getReductionAxes(mean.shape, x4D.shape);
  17293. var tileShape = [];
  17294. if (mean.rank === 1) {
  17295. for (var i = 0; i < x4D.shape.length - 1; ++i) {
  17296. tileShape.push(x4D.shape[i]);
  17297. }
  17298. tileShape.push(1);
  17299. }
  17300. var xMinusMean = x.sub(mean);
  17301. var dyTimesScaleValue = dy.mul(scaleValue);
  17302. var oneOverSqrtVariance = ops_1.rsqrt(variance.add(array_ops_1.ArrayOps.scalar(varianceEpsilon)));
  17303. var minusHalfRCube = oneOverSqrtVariance.mul(oneOverSqrtVariance)
  17304. .mul(oneOverSqrtVariance)
  17305. .mul(array_ops_1.ArrayOps.scalar(-0.5));
  17306. var derX = function () {
  17307. if (mean.rank === 1) {
  17308. return dy
  17309. .mul(array_ops_1.ArrayOps.tile(oneOverSqrtVariance.as4D(1, 1, 1, mean.shape[0]), tileShape))
  17310. .mul(scaleValue)
  17311. .reshape(x.shape);
  17312. }
  17313. else {
  17314. return dy.mul(oneOverSqrtVariance).mul(scaleValue).reshape(x.shape);
  17315. }
  17316. };
  17317. var derMean = function () {
  17318. var meanDer = oneOverSqrtVariance.mul(array_ops_1.ArrayOps.scalar(-1)).mul(dyTimesScaleValue);
  17319. if (mean.rank === 1) {
  17320. meanDer = meanDer.sum(reductionAxes);
  17321. }
  17322. return meanDer.reshape(mean.shape);
  17323. };
  17324. var derVariance = function () {
  17325. var varianceDer = minusHalfRCube.mul(xMinusMean).mul(dyTimesScaleValue);
  17326. if (mean.rank === 1) {
  17327. varianceDer = varianceDer.sum(reductionAxes);
  17328. }
  17329. return varianceDer.reshape(mean.shape);
  17330. };
  17331. var derScale = function () {
  17332. var xMinusMean2TimesRsqrt = xMinusMean.mul(oneOverSqrtVariance);
  17333. var scaleDer = dy.mul(xMinusMean2TimesRsqrt);
  17334. if (mean.rank === 1) {
  17335. scaleDer = scaleDer.sum(reductionAxes);
  17336. }
  17337. return scaleDer.reshape(mean.shape);
  17338. };
  17339. var derOffset = function () {
  17340. var offsetDer = dy;
  17341. if (mean.rank === 1) {
  17342. offsetDer = offsetDer.sum(reductionAxes);
  17343. }
  17344. return offsetDer.reshape(mean.shape);
  17345. };
  17346. return {
  17347. x: derX,
  17348. mean: derMean,
  17349. variance: derVariance,
  17350. scale: derScale,
  17351. offset: derOffset
  17352. };
  17353. };
  17354. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.batchNormalization(x4D, batchnormReshape4D(mean), batchnormReshape4D(variance), varianceEpsilon, batchnormReshape4D(scale), batchnormReshape4D(offset)); }, { x: x, mean: mean, variance: variance, scale: scale, offset: offset }, der);
  17355. return res.reshape(x.shape);
  17356. };
  17357. __decorate([
  17358. operation_1.operation
  17359. ], BatchNormOps, "batchNormalization2d", null);
  17360. __decorate([
  17361. operation_1.operation
  17362. ], BatchNormOps, "batchNormalization3d", null);
  17363. __decorate([
  17364. operation_1.operation
  17365. ], BatchNormOps, "batchNormalization4d", null);
  17366. __decorate([
  17367. doc_1.doc({ heading: 'Operations', subheading: 'Normalization' })
  17368. ], BatchNormOps, "batchNormalization", null);
  17369. return BatchNormOps;
  17370. }());
  17371. exports.BatchNormOps = BatchNormOps;
  17372. function batchnormReshape4D(x) {
  17373. if (x == null) {
  17374. return null;
  17375. }
  17376. if (x.rank === 0) {
  17377. return x.as1D();
  17378. }
  17379. else if (x.rank === 1) {
  17380. return x;
  17381. }
  17382. else if (x.rank === 2) {
  17383. return x.as4D(1, 1, x.shape[0], x.shape[1]);
  17384. }
  17385. else if (x.rank === 3) {
  17386. return x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  17387. }
  17388. return x;
  17389. }
  17390. },{"../doc":49,"../environment":51,"../util":164,"./array_ops":108,"./broadcast_util":112,"./operation":128,"./ops":129}],111:[function(require,module,exports){
  17391. "use strict";
  17392. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17393. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17394. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17395. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  17396. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17397. };
  17398. Object.defineProperty(exports, "__esModule", { value: true });
  17399. var doc_1 = require("../doc");
  17400. var environment_1 = require("../environment");
  17401. var types_1 = require("../types");
  17402. var util = require("../util");
  17403. var broadcast_util = require("./broadcast_util");
  17404. var operation_1 = require("./operation");
  17405. var ops_1 = require("./ops");
  17406. var BinaryOps = (function () {
  17407. function BinaryOps() {
  17408. }
  17409. BinaryOps.add = function (a, b) {
  17410. util.assertArgumentsAreTensors({ a: a, b: b }, 'add');
  17411. util.assertTypesMatch(a, b);
  17412. var outShape = broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17413. var der = function (dy) {
  17414. var derA = function () {
  17415. var res = dy;
  17416. var reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);
  17417. if (reduceAxes.length > 0) {
  17418. res = res.sum(reduceAxes);
  17419. }
  17420. return res.reshape(a.shape);
  17421. };
  17422. var derB = function () {
  17423. var res = dy;
  17424. var reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);
  17425. if (reduceAxes.length > 0) {
  17426. res = res.sum(reduceAxes);
  17427. }
  17428. return res.reshape(b.shape);
  17429. };
  17430. return { a: derA, b: derB };
  17431. };
  17432. return environment_1.ENV.engine.runKernel(function (backend) { return backend.add(a, b); }, { a: a, b: b }, der);
  17433. };
  17434. BinaryOps.addStrict = function (a, b) {
  17435. util.assertShapesMatch(a.shape, b.shape, 'Error in addStrict: ');
  17436. return a.add(b);
  17437. };
  17438. BinaryOps.sub = function (a, b) {
  17439. util.assertArgumentsAreTensors({ a: a, b: b }, 'sub');
  17440. util.assertTypesMatch(a, b);
  17441. var outShape = broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17442. var der = function (dy) {
  17443. var derA = function () {
  17444. var res = dy;
  17445. var reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);
  17446. if (reduceAxes.length > 0) {
  17447. res = res.sum(reduceAxes);
  17448. }
  17449. return res.reshape(a.shape);
  17450. };
  17451. var derB = function () {
  17452. var res = dy;
  17453. var reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);
  17454. if (reduceAxes.length > 0) {
  17455. res = res.sum(reduceAxes);
  17456. }
  17457. return res.neg().reshape(b.shape);
  17458. };
  17459. return { a: derA, b: derB };
  17460. };
  17461. return environment_1.ENV.engine.runKernel(function (backend) { return backend.subtract(a, b); }, { a: a, b: b }, der);
  17462. };
  17463. BinaryOps.subStrict = function (a, b) {
  17464. util.assertShapesMatch(a.shape, b.shape, 'Error in subStrict: ');
  17465. return a.sub(b);
  17466. };
  17467. BinaryOps.pow = function (base, exp) {
  17468. util.assertArgumentsAreTensors({ base: base, exp: exp }, 'pow');
  17469. var outShape = broadcast_util.assertAndGetBroadcastShape(base.shape, exp.shape);
  17470. base = base.cast(types_1.upcastType(base.dtype, exp.dtype));
  17471. exp = exp.cast(types_1.upcastType(base.dtype, exp.dtype));
  17472. var grad = function (dy, saved) {
  17473. var y = saved[0];
  17474. var derBase = function () {
  17475. var res = dy.mul(exp.toFloat().mul(y.div(base)));
  17476. var reduceAxes = broadcast_util.getReductionAxes(base.shape, outShape);
  17477. if (reduceAxes.length > 0) {
  17478. res = res.sum(reduceAxes);
  17479. }
  17480. return res.reshape(base.shape);
  17481. };
  17482. var derExp = function () {
  17483. var res = dy.mul(y.mul(base.log()).toFloat());
  17484. var reduceAxes = broadcast_util.getReductionAxes(exp.shape, outShape);
  17485. if (reduceAxes.length > 0) {
  17486. res = res.sum(reduceAxes);
  17487. }
  17488. return res.reshape(exp.shape);
  17489. };
  17490. return { base: derBase, exp: derExp };
  17491. };
  17492. return environment_1.ENV.engine.runKernel(function (backend, save) { return save(backend.pow(base, exp)); }, { base: base, exp: exp }, grad);
  17493. };
  17494. BinaryOps.powStrict = function (base, exp) {
  17495. util.assertShapesMatch(base.shape, exp.shape, 'Error in powStrict: ');
  17496. return base.pow(exp);
  17497. };
  17498. BinaryOps.mul = function (a, b) {
  17499. util.assertArgumentsAreTensors({ a: a, b: b }, 'mul');
  17500. util.assertTypesMatch(a, b);
  17501. var outShape = broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17502. var der = function (dy) {
  17503. var derA = function () {
  17504. var res = dy.mul(b.toFloat());
  17505. var reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);
  17506. if (reduceAxes.length > 0) {
  17507. return res.sum(reduceAxes).reshape(a.shape);
  17508. }
  17509. return res;
  17510. };
  17511. var derB = function () {
  17512. var res = dy.mul(a.toFloat());
  17513. var reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);
  17514. if (reduceAxes.length > 0) {
  17515. return res.sum(reduceAxes).reshape(b.shape);
  17516. }
  17517. return res;
  17518. };
  17519. return { a: derA, b: derB };
  17520. };
  17521. return environment_1.ENV.engine.runKernel(function (backend) { return backend.multiply(a, b); }, { a: a, b: b }, der);
  17522. };
  17523. BinaryOps.mulStrict = function (a, b) {
  17524. util.assertShapesMatch(a.shape, b.shape, 'Error in multiplyStrict: ');
  17525. return a.mul(b);
  17526. };
  17527. BinaryOps.div = function (a, b) {
  17528. util.assertArgumentsAreTensors({ a: a, b: b }, 'div');
  17529. util.assertTypesMatch(a, b);
  17530. var forwardFunc;
  17531. if (a.dtype === 'int32' && b.dtype === 'int32') {
  17532. return BinaryOps.floorDiv(a, b);
  17533. }
  17534. else {
  17535. forwardFunc = function (backend) { return backend.realDivide(a, b); };
  17536. }
  17537. var outShape = broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17538. var der = function (dy) {
  17539. var derA = function () {
  17540. var res = dy.div(b.toFloat());
  17541. var reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);
  17542. if (reduceAxes.length > 0) {
  17543. return res.sum(reduceAxes).reshape(a.shape);
  17544. }
  17545. return res;
  17546. };
  17547. var derB = function () {
  17548. var res = dy.mul(a.toFloat());
  17549. var reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);
  17550. if (reduceAxes.length > 0) {
  17551. res = res.sum(reduceAxes).reshape(b.shape);
  17552. }
  17553. var tmp = b.square();
  17554. return res.div(tmp.toFloat()).neg();
  17555. };
  17556. return { a: derA, b: derB };
  17557. };
  17558. return environment_1.ENV.engine.runKernel(forwardFunc, { a: a, b: b }, der);
  17559. };
  17560. BinaryOps.floorDiv = function (a, b) {
  17561. util.assertArgumentsAreTensors({ a: a, b: b }, 'floorDiv');
  17562. util.assertTypesMatch(a, b);
  17563. var forwardFunc = function (backend) { return backend.floorDiv(a, b); };
  17564. var outShape = broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17565. var der = function (dy) {
  17566. var derA = function () {
  17567. var res = dy.div(b.toFloat());
  17568. var reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);
  17569. if (reduceAxes.length > 0) {
  17570. return res.sum(reduceAxes).reshape(a.shape);
  17571. }
  17572. return res;
  17573. };
  17574. var derB = function () {
  17575. var res = dy.mul(a.toFloat());
  17576. var reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);
  17577. if (reduceAxes.length > 0) {
  17578. res = res.sum(reduceAxes).reshape(b.shape);
  17579. }
  17580. var tmp = b.square();
  17581. return res.div(tmp.toFloat()).neg();
  17582. };
  17583. return { a: derA, b: derB };
  17584. };
  17585. return environment_1.ENV.engine.runKernel(forwardFunc, { a: a, b: b }, der);
  17586. };
  17587. BinaryOps.divStrict = function (a, b) {
  17588. util.assertShapesMatch(a.shape, b.shape, 'Error in divideStrict: ');
  17589. return a.div(b);
  17590. };
  17591. BinaryOps.mod = function (a, b) {
  17592. util.assertArgumentsAreTensors({ a: a, b: b }, 'mod');
  17593. util.assertTypesMatch(a, b);
  17594. var outShape = broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17595. var der = function (dy) {
  17596. var derA = function () {
  17597. var reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);
  17598. if (reduceAxes.length > 0) {
  17599. return dy.sum(reduceAxes).reshape(a.shape);
  17600. }
  17601. return dy;
  17602. };
  17603. var derB = function () {
  17604. var res = dy.mul(a.div(b).floor().neg());
  17605. var reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);
  17606. if (reduceAxes.length > 0) {
  17607. return res.sum(reduceAxes).reshape(b.shape);
  17608. }
  17609. return res;
  17610. };
  17611. return { a: derA, b: derB };
  17612. };
  17613. return environment_1.ENV.engine.runKernel(function (backend) { return backend.mod(a, b); }, { a: a, b: b }, der);
  17614. };
  17615. BinaryOps.modStrict = function (a, b) {
  17616. util.assertShapesMatch(a.shape, b.shape, 'Error in modStrict: ');
  17617. return a.mod(b);
  17618. };
  17619. BinaryOps.minimum = function (a, b) {
  17620. util.assertArgumentsAreTensors({ a: a, b: b }, 'minimum');
  17621. util.assertTypesMatch(a, b);
  17622. if (a.dtype === 'bool') {
  17623. a = a.toInt();
  17624. }
  17625. if (b.dtype === 'bool') {
  17626. b = b.toInt();
  17627. }
  17628. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17629. var der = function (dy) {
  17630. var derA = function () { return dy.mul(a.lessEqual(b).toFloat()); };
  17631. var derB = function () { return dy.mul(a.greater(b).toFloat()); };
  17632. return { a: derA, b: derB };
  17633. };
  17634. return environment_1.ENV.engine.runKernel(function (backend) { return backend.minimum(a, b); }, { a: a, b: b }, der);
  17635. };
  17636. BinaryOps.minimumStrict = function (a, b) {
  17637. util.assertShapesMatch(a.shape, b.shape, 'Error in minimumStrict: ');
  17638. return a.minimum(b);
  17639. };
  17640. BinaryOps.maximum = function (a, b) {
  17641. util.assertArgumentsAreTensors({ a: a, b: b }, 'maximum');
  17642. util.assertTypesMatch(a, b);
  17643. if (a.dtype === 'bool') {
  17644. a = a.toInt();
  17645. }
  17646. if (b.dtype === 'bool') {
  17647. b = b.toInt();
  17648. }
  17649. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17650. var der = function (dy) {
  17651. var derA = function () { return dy.mul(a.greaterEqual(b).toFloat()); };
  17652. var derB = function () { return dy.mul(a.less(b).toFloat()); };
  17653. return { a: derA, b: derB };
  17654. };
  17655. return environment_1.ENV.engine.runKernel(function (backend) { return backend.maximum(a, b); }, { a: a, b: b }, der);
  17656. };
  17657. BinaryOps.maximumStrict = function (a, b) {
  17658. util.assertShapesMatch(a.shape, b.shape, 'Error in minimumStrict: ');
  17659. return a.maximum(b);
  17660. };
  17661. BinaryOps.squaredDifference = function (a, b) {
  17662. util.assertArgumentsAreTensors({ a: a, b: b }, 'squaredDifference');
  17663. util.assertTypesMatch(a, b);
  17664. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17665. var der = function (dy) {
  17666. var two = ops_1.scalar(2);
  17667. var derA = function () { return dy.mul(a.sub(b).mul(two)); };
  17668. var derB = function () { return dy.mul(b.sub(a).mul(two)); };
  17669. return { a: derA, b: derB };
  17670. };
  17671. return environment_1.ENV.engine.runKernel(function (backend) { return backend.squaredDifference(a, b); }, { a: a, b: b }, der);
  17672. };
  17673. BinaryOps.squaredDifferenceStrict = function (a, b) {
  17674. util.assertShapesMatch(a.shape, b.shape, 'Error in squaredDifferenceStrict: ');
  17675. return a.squaredDifference(b);
  17676. };
  17677. BinaryOps.atan2 = function (a, b) {
  17678. util.assertArgumentsAreTensors({ a: a, b: b }, 'atan2');
  17679. util.assertTypesMatch(a, b);
  17680. var outShape = broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17681. var der = function (dy) {
  17682. var derA = function () {
  17683. var d = BinaryOps.add(ops_1.square(a), ops_1.square(b));
  17684. var res = dy.mul(b.div(d));
  17685. var reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);
  17686. if (reduceAxes.length > 0) {
  17687. res = res.sum(reduceAxes);
  17688. }
  17689. return res.reshape(a.shape);
  17690. };
  17691. var derB = function () {
  17692. var d = BinaryOps.add(ops_1.square(a), ops_1.square(b));
  17693. var res = ops_1.neg(dy.mul(a.div(d)));
  17694. var reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);
  17695. if (reduceAxes.length > 0) {
  17696. res = res.sum(reduceAxes);
  17697. }
  17698. return res.reshape(b.shape);
  17699. };
  17700. return { a: derA, b: derB };
  17701. };
  17702. return environment_1.ENV.engine.runKernel(function (backend) { return backend.atan2(a, b); }, { a: a, b: b }, der);
  17703. };
  17704. __decorate([
  17705. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17706. operation_1.operation
  17707. ], BinaryOps, "add", null);
  17708. __decorate([
  17709. operation_1.operation
  17710. ], BinaryOps, "addStrict", null);
  17711. __decorate([
  17712. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17713. operation_1.operation
  17714. ], BinaryOps, "sub", null);
  17715. __decorate([
  17716. operation_1.operation
  17717. ], BinaryOps, "subStrict", null);
  17718. __decorate([
  17719. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17720. operation_1.operation
  17721. ], BinaryOps, "pow", null);
  17722. __decorate([
  17723. operation_1.operation
  17724. ], BinaryOps, "powStrict", null);
  17725. __decorate([
  17726. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17727. operation_1.operation
  17728. ], BinaryOps, "mul", null);
  17729. __decorate([
  17730. operation_1.operation
  17731. ], BinaryOps, "mulStrict", null);
  17732. __decorate([
  17733. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17734. operation_1.operation
  17735. ], BinaryOps, "div", null);
  17736. __decorate([
  17737. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17738. operation_1.operation
  17739. ], BinaryOps, "floorDiv", null);
  17740. __decorate([
  17741. operation_1.operation
  17742. ], BinaryOps, "divStrict", null);
  17743. __decorate([
  17744. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17745. operation_1.operation
  17746. ], BinaryOps, "mod", null);
  17747. __decorate([
  17748. operation_1.operation
  17749. ], BinaryOps, "modStrict", null);
  17750. __decorate([
  17751. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17752. operation_1.operation
  17753. ], BinaryOps, "minimum", null);
  17754. __decorate([
  17755. operation_1.operation
  17756. ], BinaryOps, "minimumStrict", null);
  17757. __decorate([
  17758. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17759. operation_1.operation
  17760. ], BinaryOps, "maximum", null);
  17761. __decorate([
  17762. operation_1.operation
  17763. ], BinaryOps, "maximumStrict", null);
  17764. __decorate([
  17765. doc_1.doc({ heading: 'Operations', subheading: 'Arithmetic' }),
  17766. operation_1.operation
  17767. ], BinaryOps, "squaredDifference", null);
  17768. __decorate([
  17769. operation_1.operation
  17770. ], BinaryOps, "squaredDifferenceStrict", null);
  17771. __decorate([
  17772. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  17773. operation_1.operation
  17774. ], BinaryOps, "atan2", null);
  17775. return BinaryOps;
  17776. }());
  17777. exports.BinaryOps = BinaryOps;
  17778. },{"../doc":49,"../environment":51,"../types":163,"../util":164,"./broadcast_util":112,"./operation":128,"./ops":129}],112:[function(require,module,exports){
  17779. "use strict";
  17780. Object.defineProperty(exports, "__esModule", { value: true });
  17781. function getBroadcastDims(inShape, outShape) {
  17782. var inRank = inShape.length;
  17783. var dims = [];
  17784. for (var i = 0; i < inRank; i++) {
  17785. var dim = inRank - 1 - i;
  17786. var a = inShape[dim] || 1;
  17787. var b = outShape[outShape.length - 1 - i] || 1;
  17788. if (b > 1 && a === 1) {
  17789. dims.unshift(dim);
  17790. }
  17791. }
  17792. return dims;
  17793. }
  17794. exports.getBroadcastDims = getBroadcastDims;
  17795. function getReductionAxes(inShape, outShape) {
  17796. var result = [];
  17797. for (var i = 0; i < outShape.length; i++) {
  17798. var inDim = inShape[inShape.length - i - 1];
  17799. var outAxis = outShape.length - i - 1;
  17800. var outDim = outShape[outAxis];
  17801. if (inDim == null || (inDim === 1 && outDim > 1)) {
  17802. result.unshift(outAxis);
  17803. }
  17804. }
  17805. return result;
  17806. }
  17807. exports.getReductionAxes = getReductionAxes;
  17808. function broadcastDimsAreOuter(dims) {
  17809. for (var i = 0; i < dims.length; i++) {
  17810. if (dims[i] !== i) {
  17811. return false;
  17812. }
  17813. }
  17814. return true;
  17815. }
  17816. exports.broadcastDimsAreOuter = broadcastDimsAreOuter;
  17817. function assertAndGetBroadcastShape(shapeA, shapeB) {
  17818. var result = [];
  17819. var errMsg = "Operands could not be broadcast together with shapes " +
  17820. (shapeA + " and " + shapeB + ".");
  17821. var l = Math.max(shapeA.length, shapeB.length);
  17822. for (var i = 0; i < l; i++) {
  17823. var a = shapeA[shapeA.length - i - 1] || 1;
  17824. var b = shapeB[shapeB.length - i - 1] || 1;
  17825. if (a > 1 && b > 1 && a !== b) {
  17826. throw Error(errMsg);
  17827. }
  17828. result.unshift(Math.max(a, b));
  17829. }
  17830. return result;
  17831. }
  17832. exports.assertAndGetBroadcastShape = assertAndGetBroadcastShape;
  17833. },{}],113:[function(require,module,exports){
  17834. "use strict";
  17835. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17836. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17837. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17838. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  17839. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17840. };
  17841. Object.defineProperty(exports, "__esModule", { value: true });
  17842. var doc_1 = require("../doc");
  17843. var environment_1 = require("../environment");
  17844. var util = require("../util");
  17845. var broadcast_util = require("./broadcast_util");
  17846. var operation_1 = require("./operation");
  17847. var CompareOps = (function () {
  17848. function CompareOps() {
  17849. }
  17850. CompareOps.notEqual = function (a, b) {
  17851. util.assertArgumentsAreTensors({ a: a, b: b }, 'notEqual');
  17852. util.assertTypesMatch(a, b);
  17853. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17854. return environment_1.ENV.engine.runKernel(function (backend) { return backend.notEqual(a, b); }, { a: a, b: b });
  17855. };
  17856. CompareOps.notEqualStrict = function (a, b) {
  17857. util.assertShapesMatch(a.shape, b.shape, 'Error in notEqualStrict: ');
  17858. return a.notEqual(b);
  17859. };
  17860. CompareOps.less = function (a, b) {
  17861. util.assertArgumentsAreTensors({ a: a, b: b }, 'less');
  17862. util.assertTypesMatch(a, b);
  17863. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17864. return environment_1.ENV.engine.runKernel(function (backend) { return backend.less(a, b); }, { a: a, b: b });
  17865. };
  17866. CompareOps.lessStrict = function (a, b) {
  17867. util.assertShapesMatch(a.shape, b.shape, 'Error in lessStrict: ');
  17868. return a.less(b);
  17869. };
  17870. CompareOps.equal = function (a, b) {
  17871. util.assertArgumentsAreTensors({ a: a, b: b }, 'equal');
  17872. util.assertTypesMatch(a, b);
  17873. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17874. return environment_1.ENV.engine.runKernel(function (backend) { return backend.equal(a, b); }, { a: a, b: b });
  17875. };
  17876. CompareOps.equalStrict = function (a, b) {
  17877. util.assertShapesMatch(a.shape, b.shape, 'Error in equalStrict: ');
  17878. return a.equal(b);
  17879. };
  17880. CompareOps.lessEqual = function (a, b) {
  17881. util.assertArgumentsAreTensors({ a: a, b: b }, 'lessEqual');
  17882. util.assertTypesMatch(a, b);
  17883. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17884. return environment_1.ENV.engine.runKernel(function (backend) { return backend.lessEqual(a, b); }, { a: a, b: b });
  17885. };
  17886. CompareOps.lessEqualStrict = function (a, b) {
  17887. util.assertShapesMatch(a.shape, b.shape, 'Error in lessEqualStrict: ');
  17888. return a.lessEqual(b);
  17889. };
  17890. CompareOps.greater = function (a, b) {
  17891. util.assertArgumentsAreTensors({ a: a, b: b }, 'greater');
  17892. util.assertTypesMatch(a, b);
  17893. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17894. return environment_1.ENV.engine.runKernel(function (backend) { return backend.greater(a, b); }, { a: a, b: b });
  17895. };
  17896. CompareOps.greaterStrict = function (a, b) {
  17897. util.assertShapesMatch(a.shape, b.shape, 'Error in greaterStrict: ');
  17898. return a.greater(b);
  17899. };
  17900. CompareOps.greaterEqual = function (a, b) {
  17901. util.assertArgumentsAreTensors({ a: a, b: b }, 'greaterEqual');
  17902. util.assertTypesMatch(a, b);
  17903. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  17904. return environment_1.ENV.engine.runKernel(function (backend) { return backend.greaterEqual(a, b); }, { a: a, b: b });
  17905. };
  17906. CompareOps.greaterEqualStrict = function (a, b) {
  17907. util.assertShapesMatch(a.shape, b.shape, 'Error in greaterEqualStrict: ');
  17908. return a.greaterEqual(b);
  17909. };
  17910. __decorate([
  17911. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  17912. operation_1.operation
  17913. ], CompareOps, "notEqual", null);
  17914. __decorate([
  17915. operation_1.operation
  17916. ], CompareOps, "notEqualStrict", null);
  17917. __decorate([
  17918. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  17919. operation_1.operation
  17920. ], CompareOps, "less", null);
  17921. __decorate([
  17922. operation_1.operation
  17923. ], CompareOps, "lessStrict", null);
  17924. __decorate([
  17925. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  17926. operation_1.operation
  17927. ], CompareOps, "equal", null);
  17928. __decorate([
  17929. operation_1.operation
  17930. ], CompareOps, "equalStrict", null);
  17931. __decorate([
  17932. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  17933. operation_1.operation
  17934. ], CompareOps, "lessEqual", null);
  17935. __decorate([
  17936. operation_1.operation
  17937. ], CompareOps, "lessEqualStrict", null);
  17938. __decorate([
  17939. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  17940. operation_1.operation
  17941. ], CompareOps, "greater", null);
  17942. __decorate([
  17943. operation_1.operation
  17944. ], CompareOps, "greaterStrict", null);
  17945. __decorate([
  17946. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  17947. operation_1.operation
  17948. ], CompareOps, "greaterEqual", null);
  17949. __decorate([
  17950. operation_1.operation
  17951. ], CompareOps, "greaterEqualStrict", null);
  17952. return CompareOps;
  17953. }());
  17954. exports.CompareOps = CompareOps;
  17955. },{"../doc":49,"../environment":51,"../util":164,"./broadcast_util":112,"./operation":128}],114:[function(require,module,exports){
  17956. "use strict";
  17957. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17958. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17959. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17960. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  17961. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17962. };
  17963. Object.defineProperty(exports, "__esModule", { value: true });
  17964. var doc_1 = require("../doc");
  17965. var environment_1 = require("../environment");
  17966. var util = require("../util");
  17967. var axis_util_1 = require("./axis_util");
  17968. var concat_util = require("./concat_util");
  17969. var operation_1 = require("./operation");
  17970. var ConcatOps = (function () {
  17971. function ConcatOps() {
  17972. }
  17973. ConcatOps.concat1d = function (tensors) {
  17974. return ConcatOps.concat(tensors, 0);
  17975. };
  17976. ConcatOps.concat2d = function (tensors, axis) {
  17977. return ConcatOps.concat(tensors, axis);
  17978. };
  17979. ConcatOps.concat3d = function (tensors, axis) {
  17980. return ConcatOps.concat(tensors, axis);
  17981. };
  17982. ConcatOps.concat4d = function (tensors, axis) {
  17983. return ConcatOps.concat(tensors, axis);
  17984. };
  17985. ConcatOps.concat = function (tensors, axis) {
  17986. if (axis === void 0) { axis = 0; }
  17987. util.assert(tensors.length >= 1, 'Pass at least one tensor to concat');
  17988. util.assertArgumentsAreTensors({ tensors: tensors }, 'concat');
  17989. var result = tensors[0];
  17990. if (tensors.length === 1) {
  17991. return result;
  17992. }
  17993. var axes = axis_util_1.parseAxisParam(axis, result.shape);
  17994. for (var i = 1; i < tensors.length; ++i) {
  17995. result = concat2Tensors(result, tensors[i], axes[0]);
  17996. }
  17997. return result;
  17998. };
  17999. __decorate([
  18000. doc_1.doc({ heading: 'Tensors', subheading: 'Slicing and Joining' }),
  18001. operation_1.operation
  18002. ], ConcatOps, "concat", null);
  18003. return ConcatOps;
  18004. }());
  18005. exports.ConcatOps = ConcatOps;
  18006. function concat2Tensors(a, b, axis) {
  18007. concat_util.assertParams(a.shape, b.shape, axis);
  18008. var outShape = concat_util.computeOutShape(a.shape, b.shape, axis);
  18009. var a2D = a.as2D(-1, util.sizeFromShape(a.shape.slice(axis)));
  18010. var b2D = b.as2D(-1, util.sizeFromShape(b.shape.slice(axis)));
  18011. var _a = concat_util.computeGradientSliceShapes(a2D.shape, b2D.shape), aBegin = _a.aBegin, aSize = _a.aSize, bBegin = _a.bBegin, bSize = _a.bSize;
  18012. var der = function (dy) {
  18013. return { a: function () { return dy.slice(aBegin, aSize); }, b: function () { return dy.slice(bBegin, bSize); } };
  18014. };
  18015. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.concat(a2D, b2D); }, { a: a2D, b: b2D }, der);
  18016. return res.reshape(outShape);
  18017. }
  18018. },{"../doc":49,"../environment":51,"../util":164,"./axis_util":109,"./concat_util":115,"./operation":128}],115:[function(require,module,exports){
  18019. "use strict";
  18020. Object.defineProperty(exports, "__esModule", { value: true });
  18021. var util = require("../util");
  18022. function assertParams(aShape, bShape, axis) {
  18023. var aRank = aShape.length;
  18024. var bRank = bShape.length;
  18025. util.assert(aShape.length === bShape.length, "Error in concat" + aRank + "D: rank of x1 (" + aRank + ") and x2 (" + bRank + ") " +
  18026. "must be the same.");
  18027. util.assert(axis >= 0 && axis < aRank, "Error in concat" + aRank + "D: axis must be " +
  18028. ("between 0 and " + (aRank - 1) + "."));
  18029. for (var i = 0; i < aRank; i++) {
  18030. util.assert((i === axis) || (aShape[i] === bShape[i]), "Error in concat" + aRank + "D: Shape (" + aShape + ") does not match " +
  18031. ("(" + bShape + ") along the non-concatenated axis " + i + "."));
  18032. }
  18033. }
  18034. exports.assertParams = assertParams;
  18035. function computeOutShape1D(x1Shape, x2Shape) {
  18036. util.assert(x1Shape.length === 1 && x2Shape.length === 1, 'x1 and x2 should be 1d array.');
  18037. var outputShape = x1Shape.slice();
  18038. outputShape[0] += x2Shape[0];
  18039. return outputShape;
  18040. }
  18041. exports.computeOutShape1D = computeOutShape1D;
  18042. function computeOutShape(x1Shape, x2Shape, axis) {
  18043. util.assert(x1Shape.length === x2Shape.length, 'x1 and x2 should have the same rank.');
  18044. var outputShape = x1Shape.slice();
  18045. outputShape[axis] += x2Shape[axis];
  18046. return outputShape;
  18047. }
  18048. exports.computeOutShape = computeOutShape;
  18049. function computeGradientSliceShapes(aShape, bShape) {
  18050. return {
  18051. aBegin: [0, 0],
  18052. aSize: aShape,
  18053. bBegin: [0, aShape[1]],
  18054. bSize: bShape
  18055. };
  18056. }
  18057. exports.computeGradientSliceShapes = computeGradientSliceShapes;
  18058. },{"../util":164}],116:[function(require,module,exports){
  18059. "use strict";
  18060. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18061. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18062. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18063. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18064. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18065. };
  18066. Object.defineProperty(exports, "__esModule", { value: true });
  18067. var doc_1 = require("../doc");
  18068. var environment_1 = require("../environment");
  18069. var util = require("../util");
  18070. var conv_util = require("./conv_util");
  18071. var operation_1 = require("./operation");
  18072. var ConvOps = (function () {
  18073. function ConvOps() {
  18074. }
  18075. ConvOps.conv1d = function (x, filter, stride, pad, dataFormat, dilation, dimRoundingMode) {
  18076. if (dataFormat === void 0) { dataFormat = 'NWC'; }
  18077. if (dilation === void 0) { dilation = 1; }
  18078. util.assertArgumentsAreTensors({ x: x, filter: filter }, 'conv1d');
  18079. var x3D = x;
  18080. var reshapedTo3D = false;
  18081. if (x.rank === 2) {
  18082. reshapedTo3D = true;
  18083. x3D = x.as3D(1, x.shape[0], x.shape[1]);
  18084. }
  18085. util.assert(x3D.rank === 3, "Error in conv1d: input must be rank 3, but got rank " + x3D.rank + ".");
  18086. util.assert(filter.rank === 3, "Error in conv1d: filter must be rank 3, but got rank " +
  18087. (filter.rank + "."));
  18088. if (dimRoundingMode != null) {
  18089. util.assert(util.isInt(pad), "Error in conv1d: pad must be an integer when using, " +
  18090. ("dimRoundingMode " + dimRoundingMode + " but got pad " + pad + "."));
  18091. }
  18092. util.assert(x3D.shape[2] === filter.shape[1], "Error in conv1d: depth of input (" + x3D.shape[2] + ") must match " +
  18093. ("input depth for filter " + filter.shape[1] + "."));
  18094. util.assert(eitherStridesOrDilationsAreOne(stride, dilation), 'Error in conv1D: Either stride or dilation must be 1. ' +
  18095. ("Got stride " + stride + " and dilation '" + dilation + "'"));
  18096. util.assert(dataFormat === 'NWC', "Error in conv1d: got dataFormat of " + dataFormat + " but only NWC is currently supported.");
  18097. var filter4D = filter.as4D(1, filter.shape[0], filter.shape[1], filter.shape[2]);
  18098. var input4D = x3D.as4D(x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]);
  18099. var strides = [1, stride];
  18100. var dilations = [1, dilation];
  18101. var conv2dDataFormat = 'NHWC';
  18102. var res = ConvOps.conv2d(input4D, filter4D, strides, pad, conv2dDataFormat, dilations, dimRoundingMode);
  18103. if (reshapedTo3D) {
  18104. return res.as2D(res.shape[2], res.shape[3]);
  18105. }
  18106. return res.as3D(res.shape[0], res.shape[2], res.shape[3]);
  18107. };
  18108. ConvOps.conv2d = function (x, filter, strides, pad, dataFormat, dilations, dimRoundingMode) {
  18109. if (dataFormat === void 0) { dataFormat = 'NHWC'; }
  18110. if (dilations === void 0) { dilations = [1, 1]; }
  18111. util.assertArgumentsAreTensors({ x: x, filter: filter }, 'conv2d');
  18112. var x4D = x;
  18113. var reshapedTo4D = false;
  18114. if (x.rank === 3) {
  18115. reshapedTo4D = true;
  18116. x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  18117. }
  18118. util.assert(x4D.rank === 4, "Error in conv2d: input must be rank 4, but got rank " + x4D.rank + ".");
  18119. util.assert(filter.rank === 4, "Error in conv2d: filter must be rank 4, but got rank " +
  18120. (filter.rank + "."));
  18121. if (dimRoundingMode != null) {
  18122. util.assert(util.isInt(pad), "Error in conv2d: pad must be an integer when using, " +
  18123. ("dimRoundingMode " + dimRoundingMode + " but got pad " + pad + "."));
  18124. }
  18125. util.assert(x4D.shape[3] === filter.shape[2], "Error in conv2d: depth of input (" + x4D.shape[3] + ") must match " +
  18126. ("input depth for filter " + filter.shape[2] + "."));
  18127. util.assert(eitherStridesOrDilationsAreOne(strides, dilations), 'Error in conv2D: Either strides or dilations must be 1. ' +
  18128. ("Got strides " + strides + " and dilations '" + dilations + "'"));
  18129. util.assert(dataFormat === 'NHWC', "Error in conv2d: got dataFormat of " + dataFormat + " but only NHWC is currently supported.");
  18130. var convInfo = conv_util.computeConv2DInfo(x4D.shape, filter.shape, strides, dilations, pad, dimRoundingMode);
  18131. var grad = function (dy) {
  18132. util.assert(tupleValuesAreOne(dilations), 'Error in gradient of conv2D: dilation rates greater than 1 are not' +
  18133. ("yet supported in gradients. Got dilations '" + dilations + "'"));
  18134. return {
  18135. x: function () { return ConvOps.conv2dDerInput(x4D.shape, dy, filter, strides, pad); },
  18136. filter: function () {
  18137. return ConvOps.conv2dDerFilter(x4D, dy, filter.shape, strides, pad);
  18138. }
  18139. };
  18140. };
  18141. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.conv2d(x4D, filter, convInfo); }, { x: x4D, filter: filter }, grad);
  18142. if (reshapedTo4D) {
  18143. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  18144. }
  18145. return res;
  18146. };
  18147. ConvOps.conv2dDerInput = function (xShape, dy, filter, strides, pad, dimRoundingMode) {
  18148. util.assertArgumentsAreTensors({ dy: dy, filter: filter }, 'conv2dDerInput');
  18149. util.assert(xShape.length === dy.rank, "Length of inShape " +
  18150. ("(" + xShape.length + ") and rank of dy (" + dy.rank + ") must match"));
  18151. var xShape4D = xShape;
  18152. var dy4D = dy;
  18153. var reshapedTo4D = false;
  18154. if (dy.rank === 3) {
  18155. reshapedTo4D = true;
  18156. dy4D = dy.as4D(1, dy.shape[0], dy.shape[1], dy.shape[2]);
  18157. xShape4D = [1, xShape[0], xShape[1], xShape[2]];
  18158. }
  18159. var inDepth = xShape4D[3];
  18160. var outDepth = dy4D.shape[3];
  18161. util.assert(xShape4D.length === 4, "Error in conv2dDerInput: inShape must be length 4, but got length " +
  18162. (xShape4D.length + "."));
  18163. util.assert(dy4D.rank === 4, "Error in conv2dDerInput: dy must be rank 4, but got " +
  18164. ("rank " + dy4D.rank));
  18165. util.assert(filter.rank === 4, "Error in conv2dDerInput: filter must be rank 4, but got " +
  18166. ("rank " + filter.rank));
  18167. util.assert(inDepth === filter.shape[2], "Error in conv2dDerInput: depth of input (" + inDepth + ") must " +
  18168. ("match input depth for filter " + filter.shape[2] + "."));
  18169. util.assert(outDepth === filter.shape[3], "Error in conv2dDerInput: depth of output (" + outDepth + ") must " +
  18170. ("match output depth for filter " + filter.shape[3] + "."));
  18171. if (dimRoundingMode != null) {
  18172. util.assert(util.isInt(pad), "Error in conv2dDerInput: pad must be an integer when using, " +
  18173. ("dimRoundingMode " + dimRoundingMode + " but got pad " + pad + "."));
  18174. }
  18175. var dilations = 1;
  18176. var convInfo = conv_util.computeConv2DInfo(xShape4D, filter.shape, strides, dilations, pad, dimRoundingMode);
  18177. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.conv2dDerInput(dy4D, filter, convInfo); }, { dy4D: dy4D });
  18178. if (reshapedTo4D) {
  18179. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  18180. }
  18181. return res;
  18182. };
  18183. ConvOps.conv2dDerFilter = function (x, dy, filterShape, strides, pad, dimRoundingMode) {
  18184. util.assertArgumentsAreTensors({ x: x, dy: dy }, 'conv2dDerFilter');
  18185. var x4D = x;
  18186. if (x.rank === 3) {
  18187. x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  18188. }
  18189. var dy4D = dy;
  18190. if (dy4D.rank === 3) {
  18191. dy4D = dy.as4D(1, dy.shape[0], dy.shape[1], dy.shape[2]);
  18192. }
  18193. util.assert(x4D.rank === 4, "Error in conv2dDerFilter: input must be rank 4, but got shape " +
  18194. (x4D.shape + "."));
  18195. util.assert(dy4D.rank === 4, "Error in conv2dDerFilter: dy must be rank 4, but got shape " +
  18196. (dy4D.shape + "."));
  18197. util.assert(filterShape.length === 4, "Error in conv2dDerFilter: filterShape must be length 4, but got " +
  18198. (filterShape + "."));
  18199. util.assert(x4D.shape[3] === filterShape[2], "Error in conv2dDerFilter: depth of input " + x4D.shape[3] + ") must " +
  18200. ("match input depth in filter (" + filterShape[2] + "."));
  18201. util.assert(dy4D.shape[3] === filterShape[3], "Error in conv2dDerFilter: depth of dy (" + dy4D.shape[3] + ") must " +
  18202. ("match output depth for filter (" + filterShape[3] + ")."));
  18203. if (dimRoundingMode != null) {
  18204. util.assert(util.isInt(pad), "Error in conv2dDerFilter: pad must be an integer when using, " +
  18205. ("dimRoundingMode " + dimRoundingMode + " but got pad " + pad + "."));
  18206. }
  18207. var dilations = 1;
  18208. var convInfo = conv_util.computeConv2DInfo(x4D.shape, filterShape, strides, dilations, pad, dimRoundingMode);
  18209. return environment_1.ENV.engine.runKernel(function (backend) { return backend.conv2dDerFilter(x4D, dy4D, convInfo); }, { x4D: x4D, dy4D: dy4D });
  18210. };
  18211. ConvOps.conv2dTranspose = function (x, filter, outputShape, strides, pad, dimRoundingMode) {
  18212. util.assertArgumentsAreTensors({ x: x, filter: filter }, 'conv2dTranspose');
  18213. return ConvOps.conv2dDerInput(outputShape, x, filter, strides, pad, dimRoundingMode);
  18214. };
  18215. ConvOps.depthwiseConv2d = function (x, filter, strides, pad, dataFormat, dilations, dimRoundingMode) {
  18216. if (dataFormat === void 0) { dataFormat = 'NHWC'; }
  18217. if (dilations === void 0) { dilations = [1, 1]; }
  18218. util.assertArgumentsAreTensors({ x: x, filter: filter }, 'depthwiseConv2d');
  18219. var x4D = x;
  18220. var reshapedTo4D = false;
  18221. if (x.rank === 3) {
  18222. reshapedTo4D = true;
  18223. x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  18224. }
  18225. util.assert(x4D.rank === 4, "Error in depthwiseConv2d: input must be rank 4, but got " +
  18226. ("rank " + x4D.rank + "."));
  18227. util.assert(filter.rank === 4, "Error in depthwiseConv2d: filter must be rank 4, but got rank " +
  18228. (filter.rank + "."));
  18229. util.assert(x4D.shape[3] === filter.shape[2], "Error in depthwiseConv2d: number of input channels " +
  18230. ("(" + x4D.shape[3] + ") must match the inChannels dimension in ") +
  18231. ("filter " + filter.shape[2] + "."));
  18232. if (dilations == null) {
  18233. dilations = [1, 1];
  18234. }
  18235. util.assert(eitherStridesOrDilationsAreOne(strides, dilations), 'Error in depthwiseConv2d: Either strides or dilations must be 1. ' +
  18236. ("Got strides " + strides + " and dilations '" + dilations + "'"));
  18237. if (dimRoundingMode != null) {
  18238. util.assert(util.isInt(pad), "Error in depthwiseConv2d: pad must be an integer when using, " +
  18239. ("dimRoundingMode " + dimRoundingMode + " but got pad " + pad + "."));
  18240. }
  18241. var convInfo = conv_util.computeConv2DInfo(x4D.shape, filter.shape, strides, dilations, pad, dimRoundingMode, true);
  18242. var grad = function (dy) {
  18243. util.assert(tupleValuesAreOne(dilations), 'Error in gradient of depthwiseConv2d: dilation rates greater than ' +
  18244. ("1 are not yet supported. Got dilations '" + dilations + "'"));
  18245. return {
  18246. x: function () { return depthwiseConv2dDerInput(x4D.shape, dy, filter, convInfo); },
  18247. filter: function () { return depthwiseConv2dDerFilter(x4D, dy, filter.shape, convInfo); },
  18248. };
  18249. };
  18250. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.depthwiseConv2D(x4D, filter, convInfo); }, { x: x4D, filter: filter }, grad);
  18251. if (reshapedTo4D) {
  18252. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  18253. }
  18254. return res;
  18255. };
  18256. ConvOps.separableConv2d = function (x, depthwiseFilter, pointwiseFilter, strides, pad, dilation, dataFormat) {
  18257. if (dilation === void 0) { dilation = [1, 1]; }
  18258. if (dataFormat === void 0) { dataFormat = 'NHWC'; }
  18259. util.assertArgumentsAreTensors({ x: x, depthwiseFilter: depthwiseFilter, pointwiseFilter: pointwiseFilter }, 'separableConv2d');
  18260. var x4D = x;
  18261. var reshapedTo4D = false;
  18262. if (x.rank === 3) {
  18263. reshapedTo4D = true;
  18264. x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  18265. }
  18266. if (dataFormat === 'NCHW') {
  18267. throw new Error('separableConv2d currently does not support dataFormat NCHW; only ' +
  18268. 'NHWC is supported');
  18269. }
  18270. util.assert(x4D.rank === 4, "Error in separableConv2d: input must be rank 4, but got " +
  18271. ("rank " + x4D.rank + "."));
  18272. util.assert(depthwiseFilter.rank === 4, "Error in separableConv2d: depthwise filter must be rank 4, but got " +
  18273. ("rank " + depthwiseFilter.rank + "."));
  18274. util.assert(pointwiseFilter.rank === 4, "Error in separableConv2d: pointwise filter must be rank 4, but got " +
  18275. ("rank " + depthwiseFilter.rank + "."));
  18276. util.assert(pointwiseFilter.shape[0] === 1, "Error in separableConv2d: the first dimension of pointwise filter " +
  18277. (" must be 1, but got " + pointwiseFilter.shape[0] + "."));
  18278. util.assert(pointwiseFilter.shape[1] === 1, "Error in separableConv2d: the second dimension of pointwise filter " +
  18279. (" must be 1, but got " + pointwiseFilter.shape[1] + "."));
  18280. var inChannels = depthwiseFilter.shape[2];
  18281. var channelMultiplier = depthwiseFilter.shape[3];
  18282. util.assert(pointwiseFilter.shape[2] === inChannels * channelMultiplier, "Error in separableConv2d: the third dimension of pointwise filter " +
  18283. ("must be " + inChannels * channelMultiplier + ", ") +
  18284. ("but got " + pointwiseFilter.shape[2] + "."));
  18285. var depthwise = ConvOps.depthwiseConv2d(x4D, depthwiseFilter, strides, pad, dataFormat, dilation);
  18286. var pointwiseStride = 1;
  18287. var res = ConvOps.conv2d(depthwise, pointwiseFilter, pointwiseStride, 'valid', dataFormat);
  18288. if (reshapedTo4D) {
  18289. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  18290. }
  18291. return res;
  18292. };
  18293. __decorate([
  18294. doc_1.doc({ heading: 'Operations', subheading: 'Convolution' }),
  18295. operation_1.operation
  18296. ], ConvOps, "conv1d", null);
  18297. __decorate([
  18298. doc_1.doc({ heading: 'Operations', subheading: 'Convolution' }),
  18299. operation_1.operation
  18300. ], ConvOps, "conv2d", null);
  18301. __decorate([
  18302. operation_1.operation
  18303. ], ConvOps, "conv2dDerInput", null);
  18304. __decorate([
  18305. operation_1.operation
  18306. ], ConvOps, "conv2dDerFilter", null);
  18307. __decorate([
  18308. doc_1.doc({ heading: 'Operations', subheading: 'Convolution' }),
  18309. operation_1.operation
  18310. ], ConvOps, "conv2dTranspose", null);
  18311. __decorate([
  18312. doc_1.doc({ heading: 'Operations', subheading: 'Convolution' }),
  18313. operation_1.operation
  18314. ], ConvOps, "depthwiseConv2d", null);
  18315. __decorate([
  18316. doc_1.doc({ heading: 'Operations', subheading: 'Convolution' }),
  18317. operation_1.operation
  18318. ], ConvOps, "separableConv2d", null);
  18319. return ConvOps;
  18320. }());
  18321. exports.ConvOps = ConvOps;
  18322. function parseTupleParam(param) {
  18323. return typeof param === 'number' ? [param, param] : param;
  18324. }
  18325. function tupleValuesAreOne(param) {
  18326. var _a = parseTupleParam(param), dimA = _a[0], dimB = _a[1];
  18327. return dimA === 1 && dimB === 1;
  18328. }
  18329. function eitherStridesOrDilationsAreOne(strides, dilations) {
  18330. return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);
  18331. }
  18332. function depthwiseConv2dDerInput(xShape, dy, filter, convInfo) {
  18333. var dy4D = dy;
  18334. var reshapedTo4D = false;
  18335. if (dy.rank === 3) {
  18336. reshapedTo4D = true;
  18337. dy4D = dy.as4D(1, dy.shape[0], dy.shape[1], dy.shape[2]);
  18338. }
  18339. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.depthwiseConv2DDerInput(dy4D, filter, convInfo); }, { dy4D: dy4D });
  18340. if (reshapedTo4D) {
  18341. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  18342. }
  18343. return res;
  18344. }
  18345. function depthwiseConv2dDerFilter(x, dy, filterShape, convInfo) {
  18346. var x4D = x;
  18347. if (x.rank === 3) {
  18348. x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  18349. }
  18350. var dy4D = dy;
  18351. if (dy4D.rank === 3) {
  18352. dy4D = dy.as4D(1, dy.shape[0], dy.shape[1], dy.shape[2]);
  18353. }
  18354. return environment_1.ENV.engine.runKernel(function (backend) { return backend.depthwiseConv2DDerFilter(x4D, dy4D, convInfo); }, { x4D: x4D, dy4D: dy4D });
  18355. }
  18356. },{"../doc":49,"../environment":51,"../util":164,"./conv_util":117,"./operation":128}],117:[function(require,module,exports){
  18357. "use strict";
  18358. Object.defineProperty(exports, "__esModule", { value: true });
  18359. var util = require("../util");
  18360. function computePool2DInfo(inShape, filterSize, strides, pad, roundingMode, dataFormat) {
  18361. if (dataFormat === void 0) { dataFormat = 'channelsLast'; }
  18362. var _a = parseTupleParam(filterSize), filterHeight = _a[0], filterWidth = _a[1];
  18363. var filterShape;
  18364. if (dataFormat === 'channelsLast') {
  18365. filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];
  18366. }
  18367. else if (dataFormat === 'channelsFirst') {
  18368. filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];
  18369. }
  18370. else {
  18371. throw new Error("Unknown dataFormat " + dataFormat);
  18372. }
  18373. var dilations = 1;
  18374. return computeConv2DInfo(inShape, filterShape, strides, dilations, pad, roundingMode, false, dataFormat);
  18375. }
  18376. exports.computePool2DInfo = computePool2DInfo;
  18377. function computeConv2DInfo(inShape, filterShape, strides, dilations, pad, roundingMode, depthwise, dataFormat) {
  18378. if (depthwise === void 0) { depthwise = false; }
  18379. if (dataFormat === void 0) { dataFormat = 'channelsLast'; }
  18380. var _a = [-1, -1, -1, -1], batchSize = _a[0], inHeight = _a[1], inWidth = _a[2], inChannels = _a[3];
  18381. if (dataFormat === 'channelsLast') {
  18382. batchSize = inShape[0], inHeight = inShape[1], inWidth = inShape[2], inChannels = inShape[3];
  18383. }
  18384. else if (dataFormat === 'channelsFirst') {
  18385. batchSize = inShape[0], inChannels = inShape[1], inHeight = inShape[2], inWidth = inShape[3];
  18386. }
  18387. else {
  18388. throw new Error("Unknown dataFormat " + dataFormat);
  18389. }
  18390. var filterHeight = filterShape[0], filterWidth = filterShape[1], filterChannels = filterShape[3];
  18391. var _b = parseTupleParam(strides), strideHeight = _b[0], strideWidth = _b[1];
  18392. var _c = parseTupleParam(dilations), dilationHeight = _c[0], dilationWidth = _c[1];
  18393. var effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
  18394. var effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
  18395. var _d = getPadAndOutInfo(pad, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight, effectiveFilterWidth, roundingMode), padInfo = _d.padInfo, outHeight = _d.outHeight, outWidth = _d.outWidth;
  18396. var outChannels = depthwise ? filterChannels * inChannels : filterChannels;
  18397. var outShape;
  18398. if (dataFormat === 'channelsFirst') {
  18399. outShape = [batchSize, outChannels, outHeight, outWidth];
  18400. }
  18401. else if (dataFormat === 'channelsLast') {
  18402. outShape = [batchSize, outHeight, outWidth, outChannels];
  18403. }
  18404. return {
  18405. batchSize: batchSize,
  18406. dataFormat: dataFormat,
  18407. inHeight: inHeight,
  18408. inWidth: inWidth,
  18409. inChannels: inChannels,
  18410. outHeight: outHeight,
  18411. outWidth: outWidth,
  18412. outChannels: outChannels,
  18413. padInfo: padInfo,
  18414. strideHeight: strideHeight,
  18415. strideWidth: strideWidth,
  18416. filterHeight: filterHeight,
  18417. filterWidth: filterWidth,
  18418. dilationHeight: dilationHeight,
  18419. dilationWidth: dilationWidth,
  18420. inShape: inShape,
  18421. outShape: outShape,
  18422. filterShape: filterShape
  18423. };
  18424. }
  18425. exports.computeConv2DInfo = computeConv2DInfo;
  18426. function computeOutputShape3D(inShape, fieldSize, outDepth, stride, zeroPad, roundingMode) {
  18427. if (zeroPad == null) {
  18428. zeroPad = computeDefaultPad(inShape, fieldSize, stride);
  18429. }
  18430. var inputRows = inShape[0];
  18431. var inputCols = inShape[1];
  18432. var outputRows = conditionalRound((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
  18433. util.assert(util.isInt(outputRows), "The output # of rows (" + outputRows + ") must be an integer. Change the " +
  18434. "stride and/or zero pad parameters");
  18435. var outputCols = conditionalRound((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
  18436. util.assert(util.isInt(outputCols), "The output # of columns (" + outputCols + ") must be an integer. Change " +
  18437. "the stride and/or zero pad parameters");
  18438. return [outputRows, outputCols, outDepth];
  18439. }
  18440. function computeDefaultPad(inputShape, fieldSize, stride, dilation) {
  18441. if (dilation === void 0) { dilation = 1; }
  18442. var effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);
  18443. return Math.floor((inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);
  18444. }
  18445. exports.computeDefaultPad = computeDefaultPad;
  18446. function parseTupleParam(param) {
  18447. return typeof param === 'number' ? [param, param] : param;
  18448. }
  18449. function getEffectiveFilterSize(filterSize, dilation) {
  18450. if (dilation <= 1) {
  18451. return filterSize;
  18452. }
  18453. return filterSize + (filterSize - 1) * (dilation - 1);
  18454. }
  18455. function getPadAndOutInfo(pad, inHeight, inWidth, strideHeight, strideWidth, filterHeight, filterWidth, roundingMode) {
  18456. var padInfo;
  18457. var outHeight;
  18458. var outWidth;
  18459. if (typeof pad === 'number') {
  18460. var padType = (pad === 0) ? 'VALID' : 'NUMBER';
  18461. padInfo = { top: pad, bottom: pad, left: pad, right: pad, type: padType };
  18462. var outShape = computeOutputShape3D([inHeight, inWidth, 1], filterHeight, 1, strideHeight, pad, roundingMode);
  18463. outHeight = outShape[0];
  18464. outWidth = outShape[1];
  18465. }
  18466. else if (pad === 'same') {
  18467. outHeight = Math.ceil(inHeight / strideHeight);
  18468. outWidth = Math.ceil(inWidth / strideWidth);
  18469. var padAlongHeight = (outHeight - 1) * strideHeight + filterHeight - inHeight;
  18470. var padAlongWidth = (outWidth - 1) * strideWidth + filterWidth - inWidth;
  18471. var top_1 = Math.floor(padAlongHeight / 2);
  18472. var bottom = padAlongHeight - top_1;
  18473. var left = Math.floor(padAlongWidth / 2);
  18474. var right = padAlongWidth - left;
  18475. padInfo = { top: top_1, bottom: bottom, left: left, right: right, type: 'SAME' };
  18476. }
  18477. else if (pad === 'valid') {
  18478. padInfo = { top: 0, bottom: 0, left: 0, right: 0, type: 'VALID' };
  18479. outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
  18480. outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
  18481. }
  18482. else {
  18483. throw Error("Unknown padding parameter: " + pad);
  18484. }
  18485. return { padInfo: padInfo, outHeight: outHeight, outWidth: outWidth };
  18486. }
  18487. function conditionalRound(value, roundingMode) {
  18488. if (!roundingMode) {
  18489. return value;
  18490. }
  18491. switch (roundingMode) {
  18492. case 'round':
  18493. return Math.round(value);
  18494. case 'ceil':
  18495. return Math.ceil(value);
  18496. case 'floor':
  18497. return Math.floor(value);
  18498. default:
  18499. throw new Error("Unknown roundingMode " + roundingMode);
  18500. }
  18501. }
  18502. },{"../util":164}],118:[function(require,module,exports){
  18503. "use strict";
  18504. Object.defineProperty(exports, "__esModule", { value: true });
  18505. exports.ERF_P = 0.3275911;
  18506. exports.ERF_A1 = 0.254829592;
  18507. exports.ERF_A2 = -0.284496736;
  18508. exports.ERF_A3 = 1.421413741;
  18509. exports.ERF_A4 = -1.453152027;
  18510. exports.ERF_A5 = 1.061405429;
  18511. },{}],119:[function(require,module,exports){
  18512. "use strict";
  18513. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18514. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18515. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18516. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18517. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18518. };
  18519. Object.defineProperty(exports, "__esModule", { value: true });
  18520. var doc_1 = require("../doc");
  18521. var environment_1 = require("../environment");
  18522. var util = require("../util");
  18523. var operation_1 = require("./operation");
  18524. var ImageOps = (function () {
  18525. function ImageOps() {
  18526. }
  18527. ImageOps.resizeBilinear = function (images, size, alignCorners) {
  18528. if (alignCorners === void 0) { alignCorners = false; }
  18529. util.assertArgumentsAreTensors({ images: images }, 'resizeBilinear');
  18530. util.assert(images.rank === 3 || images.rank === 4, "Error in resizeBilinear: x must be rank 3 or 4, but got " +
  18531. ("rank " + images.rank + "."));
  18532. util.assert(size.length === 2, "Error in resizeBilinear: new shape must 2D, but got shape " +
  18533. (size + "."));
  18534. var batchImages = images;
  18535. var reshapedTo4D = false;
  18536. if (images.rank === 3) {
  18537. reshapedTo4D = true;
  18538. batchImages =
  18539. images.as4D(1, images.shape[0], images.shape[1], images.shape[2]);
  18540. }
  18541. var newHeight = size[0], newWidth = size[1];
  18542. var forward = function (backend, save) {
  18543. return backend.resizeBilinear(batchImages, newHeight, newWidth, alignCorners);
  18544. };
  18545. var backward = function (dy, saved) {
  18546. return {
  18547. batchImages: function () { return environment_1.ENV.engine.runKernel(function (backend) {
  18548. return backend.resizeBilinearBackprop(dy, batchImages, alignCorners);
  18549. }, {}); }
  18550. };
  18551. };
  18552. var res = environment_1.ENV.engine.runKernel(forward, { batchImages: batchImages }, backward);
  18553. if (reshapedTo4D) {
  18554. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  18555. }
  18556. return res;
  18557. };
  18558. ImageOps.resizeNearestNeighbor = function (images, size, alignCorners) {
  18559. if (alignCorners === void 0) { alignCorners = false; }
  18560. util.assertArgumentsAreTensors({ images: images }, 'resizeNearestNeighbor');
  18561. util.assert(images.rank === 3 || images.rank === 4, "Error in resizeNearestNeighbor: x must be rank 3 or 4, but got " +
  18562. ("rank " + images.rank + "."));
  18563. util.assert(size.length === 2, "Error in resizeNearestNeighbor: new shape must 2D, but got shape " +
  18564. (size + "."));
  18565. util.assert(images.dtype === 'float32' || images.dtype === 'int32', '`images` must have `int32` or `float32` as dtype');
  18566. var batchImages = images;
  18567. var reshapedTo4D = false;
  18568. if (images.rank === 3) {
  18569. reshapedTo4D = true;
  18570. batchImages =
  18571. images.as4D(1, images.shape[0], images.shape[1], images.shape[2]);
  18572. }
  18573. var newHeight = size[0], newWidth = size[1];
  18574. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.resizeNearestNeighbor(batchImages, newHeight, newWidth, alignCorners); }, { batchImages: batchImages });
  18575. if (reshapedTo4D) {
  18576. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  18577. }
  18578. return res;
  18579. };
  18580. __decorate([
  18581. doc_1.doc({ heading: 'Operations', subheading: 'Images', namespace: 'image' }),
  18582. operation_1.operation
  18583. ], ImageOps, "resizeBilinear", null);
  18584. __decorate([
  18585. doc_1.doc({ heading: 'Operations', subheading: 'Images', namespace: 'image' }),
  18586. operation_1.operation
  18587. ], ImageOps, "resizeNearestNeighbor", null);
  18588. return ImageOps;
  18589. }());
  18590. exports.ImageOps = ImageOps;
  18591. },{"../doc":49,"../environment":51,"../util":164,"./operation":128}],120:[function(require,module,exports){
  18592. "use strict";
  18593. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18594. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18595. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18596. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18597. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18598. };
  18599. Object.defineProperty(exports, "__esModule", { value: true });
  18600. var doc_1 = require("../doc");
  18601. var tracking_1 = require("../tracking");
  18602. var util_1 = require("../util");
  18603. var operation_1 = require("./operation");
  18604. var ops_1 = require("./ops");
  18605. var LinalgOps = (function () {
  18606. function LinalgOps() {
  18607. }
  18608. LinalgOps.gramSchmidt = function (xs) {
  18609. var inputIsTensor2D;
  18610. if (Array.isArray(xs)) {
  18611. inputIsTensor2D = false;
  18612. util_1.assert(xs != null && xs.length > 0, 'Gram-Schmidt process: input must not be null, undefined, or empty');
  18613. var dim = xs[0].shape[0];
  18614. for (var i = 1; i < xs.length; ++i) {
  18615. util_1.assert(xs[i].shape[0] === dim, 'Gram-Schmidt: Non-unique lengths found in the input vectors: ' +
  18616. ("(" + xs[i].shape[0] + " vs. " + dim + ")"));
  18617. }
  18618. }
  18619. else {
  18620. inputIsTensor2D = true;
  18621. xs = ops_1.split(xs, xs.shape[0], 0).map(function (x) { return ops_1.squeeze(x, [0]); });
  18622. }
  18623. util_1.assert(xs.length <= xs[0].shape[0], "Gram-Schmidt: Number of vectors (" + xs.length + ") exceeds " +
  18624. ("number of dimensions (" + xs[0].shape[0] + ")."));
  18625. var ys = [];
  18626. var xs1d = xs;
  18627. var _loop_1 = function (i) {
  18628. ys.push(tracking_1.Tracking.tidy(function () {
  18629. var x = xs1d[i];
  18630. if (i > 0) {
  18631. for (var j = 0; j < i; ++j) {
  18632. var proj = ops_1.sum(ys[j].mulStrict(x)).mul(ys[j]);
  18633. x = x.sub(proj);
  18634. }
  18635. }
  18636. return x.div(ops_1.norm(x, 'euclidean'));
  18637. }));
  18638. };
  18639. for (var i = 0; i < xs.length; ++i) {
  18640. _loop_1(i);
  18641. }
  18642. if (inputIsTensor2D) {
  18643. return ops_1.stack(ys, 0);
  18644. }
  18645. else {
  18646. return ys;
  18647. }
  18648. };
  18649. __decorate([
  18650. doc_1.doc({ heading: 'Operations', subheading: 'Linear Algebra' }),
  18651. operation_1.operation
  18652. ], LinalgOps, "gramSchmidt", null);
  18653. return LinalgOps;
  18654. }());
  18655. exports.LinalgOps = LinalgOps;
  18656. },{"../doc":49,"../tracking":161,"../util":164,"./operation":128,"./ops":129}],121:[function(require,module,exports){
  18657. "use strict";
  18658. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18659. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18660. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18661. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18662. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18663. };
  18664. Object.defineProperty(exports, "__esModule", { value: true });
  18665. var doc_1 = require("../doc");
  18666. var environment_1 = require("../environment");
  18667. var types = require("../types");
  18668. var util = require("../util");
  18669. var broadcast_util = require("./broadcast_util");
  18670. var operation_1 = require("./operation");
  18671. var ops_1 = require("../ops/ops");
  18672. var LogicalOps = (function () {
  18673. function LogicalOps() {
  18674. }
  18675. LogicalOps.logicalNot = function (x) {
  18676. util.assertArgumentsAreTensors({ x: x }, 'logicalNot');
  18677. util.assert(x.dtype === 'bool', 'Error Array must be of type bool.');
  18678. return environment_1.ENV.engine.runKernel(function (backend) { return backend.logicalNot(x); }, { x: x });
  18679. };
  18680. LogicalOps.logicalAnd = function (a, b) {
  18681. util.assertArgumentsAreTensors({ a: a, b: b }, 'logicalAnd');
  18682. util.assert(a.dtype === 'bool' && b.dtype === 'bool', 'Error Array must be of type bool.');
  18683. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  18684. return environment_1.ENV.engine.runKernel(function (backend) { return backend.logicalAnd(a, b); }, { a: a, b: b });
  18685. };
  18686. LogicalOps.logicalOr = function (a, b) {
  18687. util.assertArgumentsAreTensors({ a: a, b: b }, 'logicalOr');
  18688. util.assert(a.dtype === 'bool' && b.dtype === 'bool', 'Error Array must be of type bool.');
  18689. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  18690. return environment_1.ENV.engine.runKernel(function (backend) { return backend.logicalOr(a, b); }, { a: a, b: b });
  18691. };
  18692. LogicalOps.logicalXor = function (a, b) {
  18693. util.assertArgumentsAreTensors({ a: a, b: b }, 'logicalXor');
  18694. util.assert(a.dtype === 'bool' && b.dtype === 'bool', 'Error Array must be of type bool.');
  18695. broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
  18696. return LogicalOps.logicalOr(a, b).logicalAnd(LogicalOps.logicalAnd(a, b).logicalNot());
  18697. };
  18698. LogicalOps.where = function (condition, a, b) {
  18699. util.assertArgumentsAreTensors({ condition: condition, a: a, b: b }, 'where');
  18700. util.assert(condition.dtype === 'bool', 'Error Condition must be of type bool.');
  18701. util.assertShapesMatch(a.shape, b.shape, 'Error in where: ');
  18702. if (condition.rank === 1) {
  18703. util.assert(condition.shape[0] === a.shape[0], 'The first dimension of `a` must match the size of `condition`.');
  18704. }
  18705. else {
  18706. util.assertShapesMatch(condition.shape, b.shape, 'Error in where: ');
  18707. }
  18708. var dtype = types.upcastType(a.dtype, b.dtype);
  18709. var grad = function (dy) { return ({
  18710. condition: function () { return ops_1.zerosLike(condition); },
  18711. a: function () { return dy.mul(condition.cast(a.dtype)); },
  18712. b: function () { return dy.mul(condition.logicalNot().cast(b.dtype)); }
  18713. }); };
  18714. return environment_1.ENV.engine.runKernel(function (backend) { return backend.where(condition, a, b, dtype); }, { condition: condition, a: a, b: b }, grad);
  18715. };
  18716. __decorate([
  18717. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  18718. operation_1.operation
  18719. ], LogicalOps, "logicalNot", null);
  18720. __decorate([
  18721. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  18722. operation_1.operation
  18723. ], LogicalOps, "logicalAnd", null);
  18724. __decorate([
  18725. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  18726. operation_1.operation
  18727. ], LogicalOps, "logicalOr", null);
  18728. __decorate([
  18729. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  18730. operation_1.operation
  18731. ], LogicalOps, "logicalXor", null);
  18732. __decorate([
  18733. doc_1.doc({ heading: 'Operations', subheading: 'Logical' }),
  18734. operation_1.operation
  18735. ], LogicalOps, "where", null);
  18736. return LogicalOps;
  18737. }());
  18738. exports.LogicalOps = LogicalOps;
  18739. },{"../doc":49,"../environment":51,"../ops/ops":129,"../types":163,"../util":164,"./broadcast_util":112,"./operation":128}],122:[function(require,module,exports){
  18740. "use strict";
  18741. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18742. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18743. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18744. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18745. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18746. };
  18747. Object.defineProperty(exports, "__esModule", { value: true });
  18748. var doc_1 = require("../doc");
  18749. var util = require("../util");
  18750. var operation_1 = require("./operation");
  18751. var ops = require("./ops");
  18752. var Reduction;
  18753. (function (Reduction) {
  18754. Reduction[Reduction["NONE"] = 0] = "NONE";
  18755. Reduction[Reduction["MEAN"] = 1] = "MEAN";
  18756. Reduction[Reduction["SUM"] = 2] = "SUM";
  18757. Reduction[Reduction["SUM_BY_NONZERO_WEIGHTS"] = 3] = "SUM_BY_NONZERO_WEIGHTS";
  18758. })(Reduction = exports.Reduction || (exports.Reduction = {}));
  18759. var LossOps = (function () {
  18760. function LossOps() {
  18761. }
  18762. LossOps.computeWeightedLoss = function (losses, weights, reduction) {
  18763. if (reduction === void 0) { reduction = Reduction.SUM_BY_NONZERO_WEIGHTS; }
  18764. util.assertArgumentsAreTensors({ losses: losses }, 'computeWeightedLoss');
  18765. if (weights != null) {
  18766. util.assertArgumentsAreTensors({ weights: weights }, 'computeWeightedLoss');
  18767. }
  18768. var weightedLoss = (weights == null) ? losses : losses.mul(weights);
  18769. if (reduction === Reduction.NONE) {
  18770. return weightedLoss;
  18771. }
  18772. if (reduction === Reduction.SUM) {
  18773. return weightedLoss.sum();
  18774. }
  18775. if (reduction === Reduction.MEAN) {
  18776. return (weights == null) ? weightedLoss.mean() :
  18777. weightedLoss.sum().div(weights.sum());
  18778. }
  18779. if (reduction === Reduction.SUM_BY_NONZERO_WEIGHTS) {
  18780. if (weights == null) {
  18781. return weightedLoss.sum().div(ops.scalar(losses.size));
  18782. }
  18783. else {
  18784. var numNonZeros = weights.notEqual(ops.scalar(0)).sum().toFloat();
  18785. return weightedLoss.sum().div(numNonZeros);
  18786. }
  18787. }
  18788. throw Error("Unknown reduction: " + reduction);
  18789. };
  18790. LossOps.absoluteDifference = function (labels, predictions, weights, reduction) {
  18791. if (reduction === void 0) { reduction = Reduction.SUM_BY_NONZERO_WEIGHTS; }
  18792. util.assertArgumentsAreTensors({ labels: labels, predictions: predictions }, 'absoluteDifference');
  18793. if (weights != null) {
  18794. util.assertArgumentsAreTensors({ weights: weights }, 'absoluteDifference');
  18795. }
  18796. util.assertShapesMatch(labels.shape, predictions.shape, 'Error in absoluteDifference: ');
  18797. var losses = labels.sub(predictions).abs();
  18798. return LossOps.computeWeightedLoss(losses, weights, reduction);
  18799. };
  18800. LossOps.meanSquaredError = function (labels, predictions, weights, reduction) {
  18801. if (reduction === void 0) { reduction = Reduction.SUM_BY_NONZERO_WEIGHTS; }
  18802. util.assertArgumentsAreTensors({ labels: labels, predictions: predictions }, 'meanSquaredError');
  18803. if (weights != null) {
  18804. util.assertArgumentsAreTensors({ weights: weights }, 'meanSquaredError');
  18805. }
  18806. util.assertShapesMatch(labels.shape, predictions.shape, 'Error in meanSquaredError: ');
  18807. var losses = labels.squaredDifference(predictions);
  18808. return LossOps.computeWeightedLoss(losses, weights, reduction);
  18809. };
  18810. LossOps.cosineDistance = function (labels, predictions, axis, weights, reduction) {
  18811. if (reduction === void 0) { reduction = Reduction.SUM_BY_NONZERO_WEIGHTS; }
  18812. util.assertArgumentsAreTensors({ labels: labels, predictions: predictions }, 'cosineDistance');
  18813. if (weights != null) {
  18814. util.assertArgumentsAreTensors({ weights: weights }, 'cosineDistance');
  18815. }
  18816. util.assertShapesMatch(labels.shape, predictions.shape, 'Error in cosineDistance: ');
  18817. var one = ops.scalar(1);
  18818. var losses = one.sub(labels.mul(predictions).sum(axis, true));
  18819. return LossOps.computeWeightedLoss(losses, weights, reduction);
  18820. };
  18821. LossOps.hingeLoss = function (labels, predictions, weights, reduction) {
  18822. if (reduction === void 0) { reduction = Reduction.SUM_BY_NONZERO_WEIGHTS; }
  18823. util.assertArgumentsAreTensors({ labels: labels, predictions: predictions }, 'hingeLoss');
  18824. if (weights != null) {
  18825. util.assertArgumentsAreTensors({ weights: weights }, 'hingeLoss');
  18826. }
  18827. util.assertShapesMatch(labels.shape, predictions.shape, 'Error in hingeLoss: ');
  18828. var one = ops.scalar(1);
  18829. labels = ops.scalar(2).mul(labels).sub(one);
  18830. var losses = one.sub(labels.mul(predictions)).relu();
  18831. return LossOps.computeWeightedLoss(losses, weights, reduction);
  18832. };
  18833. LossOps.logLoss = function (labels, predictions, weights, epsilon, reduction) {
  18834. if (epsilon === void 0) { epsilon = 1e-7; }
  18835. if (reduction === void 0) { reduction = Reduction.SUM_BY_NONZERO_WEIGHTS; }
  18836. util.assertArgumentsAreTensors({ labels: labels, predictions: predictions }, 'logLoss');
  18837. if (weights != null) {
  18838. util.assertArgumentsAreTensors({ weights: weights }, 'logLoss');
  18839. }
  18840. util.assertShapesMatch(labels.shape, predictions.shape, 'Error in logLoss: ');
  18841. var one = ops.scalar(1);
  18842. var epsilonScalar = ops.scalar(epsilon);
  18843. var losses = labels.mul(predictions.add(epsilonScalar).log())
  18844. .neg()
  18845. .sub(one.sub(labels).mul(one.sub(predictions).add(epsilonScalar).log()));
  18846. return LossOps.computeWeightedLoss(losses, weights, reduction);
  18847. };
  18848. LossOps.huberLoss = function (labels, predictions, weights, delta, reduction) {
  18849. if (delta === void 0) { delta = 1.0; }
  18850. if (reduction === void 0) { reduction = Reduction.SUM_BY_NONZERO_WEIGHTS; }
  18851. util.assertArgumentsAreTensors({ labels: labels, predictions: predictions }, 'huberLoss');
  18852. if (weights != null) {
  18853. util.assertArgumentsAreTensors({ weights: weights }, 'huberLoss');
  18854. }
  18855. util.assertShapesMatch(labels.shape, predictions.shape, 'Error in huberLoss: ');
  18856. var deltaScalar = ops.scalar(delta);
  18857. var error = predictions.sub(labels).abs();
  18858. var quadratic = ops.minimum(error, deltaScalar);
  18859. var linear = error.sub(quadratic);
  18860. var losses = ops.scalar(0.5).mul(quadratic.square()).add(deltaScalar.mul(linear));
  18861. return LossOps.computeWeightedLoss(losses, weights, reduction);
  18862. };
  18863. __decorate([
  18864. doc_1.doc({ heading: 'Training', subheading: 'Losses', namespace: 'losses' }),
  18865. operation_1.operation
  18866. ], LossOps, "computeWeightedLoss", null);
  18867. __decorate([
  18868. doc_1.doc({ heading: 'Training', subheading: 'Losses', namespace: 'losses' }),
  18869. operation_1.operation
  18870. ], LossOps, "absoluteDifference", null);
  18871. __decorate([
  18872. doc_1.doc({ heading: 'Training', subheading: 'Losses', namespace: 'losses' }),
  18873. operation_1.operation
  18874. ], LossOps, "meanSquaredError", null);
  18875. __decorate([
  18876. doc_1.doc({ heading: 'Training', subheading: 'Losses', namespace: 'losses' }),
  18877. operation_1.operation
  18878. ], LossOps, "cosineDistance", null);
  18879. __decorate([
  18880. doc_1.doc({ heading: 'Training', subheading: 'Losses', namespace: 'losses' }),
  18881. operation_1.operation
  18882. ], LossOps, "hingeLoss", null);
  18883. __decorate([
  18884. doc_1.doc({ heading: 'Training', subheading: 'Losses', namespace: 'losses' }),
  18885. operation_1.operation
  18886. ], LossOps, "logLoss", null);
  18887. __decorate([
  18888. doc_1.doc({ heading: 'Training', subheading: 'Losses', namespace: 'losses' }),
  18889. operation_1.operation
  18890. ], LossOps, "huberLoss", null);
  18891. return LossOps;
  18892. }());
  18893. exports.LossOps = LossOps;
  18894. },{"../doc":49,"../util":164,"./operation":128,"./ops":129}],123:[function(require,module,exports){
  18895. "use strict";
  18896. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18897. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18898. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18899. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18900. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18901. };
  18902. Object.defineProperty(exports, "__esModule", { value: true });
  18903. var doc_1 = require("../doc");
  18904. var environment_1 = require("../environment");
  18905. var util = require("../util");
  18906. var operation_1 = require("./operation");
  18907. var LRNOps = (function () {
  18908. function LRNOps() {
  18909. }
  18910. LRNOps.localResponseNormalization = function (x, depthRadius, bias, alpha, beta) {
  18911. if (depthRadius === void 0) { depthRadius = 5; }
  18912. if (bias === void 0) { bias = 1; }
  18913. if (alpha === void 0) { alpha = 1; }
  18914. if (beta === void 0) { beta = 0.5; }
  18915. util.assertArgumentsAreTensors({ x: x }, 'localResponseNormalization');
  18916. util.assert(x.rank === 4 || x.rank === 3, "Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank " + x.rank + ".");
  18917. util.assert(util.isInt(depthRadius), "Error in localResponseNormalization: depthRadius must be an integer\n but got depthRadius " + depthRadius + ".");
  18918. var x4D = x;
  18919. var reshapedTo4D = false;
  18920. if (x.rank === 3) {
  18921. reshapedTo4D = true;
  18922. x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  18923. }
  18924. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.localResponseNormalization4D(x4D, depthRadius, bias, alpha, beta); }, { x4D: x4D });
  18925. if (reshapedTo4D) {
  18926. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  18927. }
  18928. else {
  18929. return res;
  18930. }
  18931. };
  18932. __decorate([
  18933. doc_1.doc({ heading: 'Operations', subheading: 'Normalization' }),
  18934. operation_1.operation
  18935. ], LRNOps, "localResponseNormalization", null);
  18936. return LRNOps;
  18937. }());
  18938. exports.LRNOps = LRNOps;
  18939. },{"../doc":49,"../environment":51,"../util":164,"./operation":128}],124:[function(require,module,exports){
  18940. "use strict";
  18941. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18942. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18943. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18944. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18945. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18946. };
  18947. Object.defineProperty(exports, "__esModule", { value: true });
  18948. var doc_1 = require("../doc");
  18949. var util = require("../util");
  18950. var operation_1 = require("./operation");
  18951. var LSTMOps = (function () {
  18952. function LSTMOps() {
  18953. }
  18954. LSTMOps.multiRNNCell = function (lstmCells, data, c, h) {
  18955. util.assertArgumentsAreTensors({ data: data, c: c, h: h }, 'multiRNNCell');
  18956. var input = data;
  18957. var newStates = [];
  18958. for (var i = 0; i < lstmCells.length; i++) {
  18959. var output = lstmCells[i](input, c[i], h[i]);
  18960. newStates.push(output[0]);
  18961. newStates.push(output[1]);
  18962. input = output[1];
  18963. }
  18964. var newC = [];
  18965. var newH = [];
  18966. for (var i = 0; i < newStates.length; i += 2) {
  18967. newC.push(newStates[i]);
  18968. newH.push(newStates[i + 1]);
  18969. }
  18970. return [newC, newH];
  18971. };
  18972. LSTMOps.basicLSTMCell = function (forgetBias, lstmKernel, lstmBias, data, c, h) {
  18973. util.assertArgumentsAreTensors({ forgetBias: forgetBias, lstmKernel: lstmKernel, lstmBias: lstmBias, data: data, c: c, h: h }, 'basicLSTMCell');
  18974. var combined = data.concat(h, 1);
  18975. var weighted = combined.matMul(lstmKernel);
  18976. var res = weighted.add(lstmBias);
  18977. var batchSize = res.shape[0];
  18978. var sliceCols = res.shape[1] / 4;
  18979. var sliceSize = [batchSize, sliceCols];
  18980. var i = res.slice([0, 0], sliceSize);
  18981. var j = res.slice([0, sliceCols], sliceSize);
  18982. var f = res.slice([0, sliceCols * 2], sliceSize);
  18983. var o = res.slice([0, sliceCols * 3], sliceSize);
  18984. var newC = i.sigmoid().mulStrict(j.tanh()).addStrict(c.mulStrict(forgetBias.add(f).sigmoid()));
  18985. var newH = newC.tanh().mulStrict(o.sigmoid());
  18986. return [newC, newH];
  18987. };
  18988. __decorate([
  18989. doc_1.doc({ heading: 'Operations', subheading: 'RNN' }),
  18990. operation_1.operation
  18991. ], LSTMOps, "multiRNNCell", null);
  18992. __decorate([
  18993. doc_1.doc({ heading: 'Operations', subheading: 'RNN' }),
  18994. operation_1.operation
  18995. ], LSTMOps, "basicLSTMCell", null);
  18996. return LSTMOps;
  18997. }());
  18998. exports.LSTMOps = LSTMOps;
  18999. },{"../doc":49,"../util":164,"./operation":128}],125:[function(require,module,exports){
  19000. "use strict";
  19001. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19002. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19003. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19004. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19005. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19006. };
  19007. Object.defineProperty(exports, "__esModule", { value: true });
  19008. var doc_1 = require("../doc");
  19009. var environment_1 = require("../environment");
  19010. var util = require("../util");
  19011. var operation_1 = require("./operation");
  19012. var MatmulOps = (function () {
  19013. function MatmulOps() {
  19014. }
  19015. MatmulOps.matMul = function (a, b, transposeA, transposeB) {
  19016. if (transposeA === void 0) { transposeA = false; }
  19017. if (transposeB === void 0) { transposeB = false; }
  19018. util.assertArgumentsAreTensors({ a: a, b: b }, 'matMul');
  19019. var innerShapeA = transposeA ? a.shape[0] : a.shape[1];
  19020. var innerShapeB = transposeB ? b.shape[1] : b.shape[0];
  19021. util.assert(a.rank === 2 && b.rank === 2, "Error in matMul: inputs must be rank 2, got ranks " + a.rank +
  19022. (" and " + b.rank + "."));
  19023. util.assert(innerShapeA === innerShapeB, "Error in matMul: inner shapes (" + innerShapeA + ") and (" +
  19024. (innerShapeB + ") of Tensors with shapes " + a.shape + " and ") +
  19025. (b.shape + " and transposeA=" + transposeA) +
  19026. (" and transposeB=" + transposeB + " must match."));
  19027. var grad = function (dy) {
  19028. if (!transposeA && !transposeB) {
  19029. return {
  19030. a: function () { return dy.matMul(b.toFloat(), false, true); },
  19031. b: function () { return a.toFloat().matMul(dy, true, false); }
  19032. };
  19033. }
  19034. else if (!transposeA && transposeB) {
  19035. return {
  19036. a: function () { return dy.matMul(b.toFloat(), false, false); },
  19037. b: function () { return dy.matMul(a.toFloat(), true, false); }
  19038. };
  19039. }
  19040. else if (transposeA && !transposeB) {
  19041. return {
  19042. a: function () { return b.toFloat().matMul(dy, false, true); },
  19043. b: function () { return a.toFloat().matMul(dy, false, false); }
  19044. };
  19045. }
  19046. else {
  19047. return {
  19048. a: function () { return b.toFloat().matMul(dy, true, true); },
  19049. b: function () { return dy.matMul(a.toFloat(), true, true); }
  19050. };
  19051. }
  19052. };
  19053. return environment_1.ENV.engine.runKernel(function (backend) { return backend.matMul(a, b, transposeA, transposeB); }, { a: a, b: b }, grad);
  19054. };
  19055. MatmulOps.vectorTimesMatrix = function (v, matrix) {
  19056. util.assert(v.rank === 1, "Error in vectorTimesMatrix: first input must be rank 1, but got " +
  19057. ("rank " + v.rank + "."));
  19058. util.assert(matrix.rank === 2, "Error in vectorTimesMatrix: second input must be rank 2, but got " +
  19059. ("rank " + matrix.rank + "."));
  19060. util.assert(v.size === matrix.shape[0], "Error in vectorTimesMatrix: size of vector (" + v.size + ") " +
  19061. ("must match first dimension of matrix (" + matrix.shape[0] + ")"));
  19062. return v.as2D(1, -1).matMul(matrix).as1D();
  19063. };
  19064. MatmulOps.matrixTimesVector = function (matrix, v) {
  19065. util.assert(v.rank === 1, "Error in matrixTimesVector: second input must rank 1, but got " +
  19066. ("rank " + v.rank + "."));
  19067. util.assert(matrix.rank === 2, "Error in matrixTimesVector: first input must be a rank 2, but got " +
  19068. ("rank " + matrix.rank + "."));
  19069. util.assert(v.size === matrix.shape[1], "Error in matrixTimesVector: size of first rank 1 input " + v.size + " " +
  19070. "must match inner dimension of second rank 2 input, but got " +
  19071. ("shape " + matrix.shape + "."));
  19072. return matrix.matMul(v.as2D(-1, 1)).as1D();
  19073. };
  19074. MatmulOps.dotProduct = function (v1, v2) {
  19075. util.assert(v1.rank === 1 && v2.rank === 1, "Error in dotProduct: inputs must be rank 1, but got ranks " +
  19076. (v1.rank + " and " + v2.rank + "."));
  19077. util.assert(v1.size === v2.size, "Error in dotProduct: size of inputs (" + v1.size + ") and (" +
  19078. (v2.size + ") must match."));
  19079. return v1.as2D(1, -1).matMul(v2.as2D(-1, 1)).asScalar();
  19080. };
  19081. MatmulOps.outerProduct = function (v1, v2) {
  19082. util.assert(v1.rank === 1 && v2.rank === 1, "Error in outerProduct: inputs must be rank 1, but got ranks " +
  19083. (v1.rank + " and " + v2.rank + "."));
  19084. return v1.as2D(-1, 1).matMul(v2.as2D(1, -1));
  19085. };
  19086. MatmulOps.dot = function (t1, t2) {
  19087. util.assert((t1.rank === 1 || t1.rank === 2) && (t2.rank === 1 || t2.rank === 2), "Error in dot: inputs must all be rank 1 or 2, but got ranks " +
  19088. (t1.rank + " and " + t2.rank + "."));
  19089. var t1Inner = (t1.rank === 1 ? t1.size : t1.shape[1]);
  19090. var t2Inner = (t2.rank === 1 ? t2.size : t2.shape[0]);
  19091. util.assert(t1Inner === t2Inner, "Error in dot: inner dimensions of inputs must match, but got " +
  19092. (t1Inner + " and " + t2Inner + "."));
  19093. if (t1.rank === 1 && t2.rank === 1) {
  19094. return t1.as2D(1, -1).matMul(t2.as2D(-1, 1)).asScalar();
  19095. }
  19096. else if (t1.rank === 1 && t2.rank === 2) {
  19097. return t1.as2D(1, -1).matMul(t2.as2D(t2.shape[0], t2.shape[1])).as1D();
  19098. }
  19099. else if (t1.rank === 2 && t2.rank === 1) {
  19100. return t1.matMul(t2.as2D(-1, 1)).as1D();
  19101. }
  19102. else {
  19103. return t1.matMul(t2.as2D(t2.shape[0], t2.shape[1]));
  19104. }
  19105. };
  19106. __decorate([
  19107. doc_1.doc({ heading: 'Operations', subheading: 'Matrices' }),
  19108. operation_1.operation
  19109. ], MatmulOps, "matMul", null);
  19110. __decorate([
  19111. operation_1.operation
  19112. ], MatmulOps, "vectorTimesMatrix", null);
  19113. __decorate([
  19114. operation_1.operation
  19115. ], MatmulOps, "matrixTimesVector", null);
  19116. __decorate([
  19117. operation_1.operation
  19118. ], MatmulOps, "dotProduct", null);
  19119. __decorate([
  19120. doc_1.doc({ heading: 'Operations', subheading: 'Matrices' }),
  19121. operation_1.operation
  19122. ], MatmulOps, "outerProduct", null);
  19123. __decorate([
  19124. doc_1.doc({ heading: 'Operations', subheading: 'Matrices' }),
  19125. operation_1.operation
  19126. ], MatmulOps, "dot", null);
  19127. return MatmulOps;
  19128. }());
  19129. exports.MatmulOps = MatmulOps;
  19130. },{"../doc":49,"../environment":51,"../util":164,"./operation":128}],126:[function(require,module,exports){
  19131. "use strict";
  19132. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19133. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19134. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19135. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19136. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19137. };
  19138. Object.defineProperty(exports, "__esModule", { value: true });
  19139. var doc_1 = require("../doc");
  19140. var util = require("../util");
  19141. var array_ops_1 = require("./array_ops");
  19142. var binary_ops_1 = require("./binary_ops");
  19143. var operation_1 = require("./operation");
  19144. var MovingAverageOps = (function () {
  19145. function MovingAverageOps() {
  19146. }
  19147. MovingAverageOps.movingAverage = function (v, x, decay, step, zeroDebias) {
  19148. if (zeroDebias === void 0) { zeroDebias = true; }
  19149. util.assertArgumentsAreTensors({ v: v, x: x }, 'movingAverage');
  19150. util.assertTypesMatch(v, x);
  19151. util.assert(util.arraysEqual(v.shape, x.shape), 'Shape mismatch in v and x');
  19152. var one = array_ops_1.ArrayOps.scalar(1);
  19153. decay = typeof decay === 'number' ? array_ops_1.ArrayOps.scalar(decay) : decay;
  19154. var oneMinusDecay = one.sub(decay);
  19155. var update = x.sub(v).mul(oneMinusDecay);
  19156. if (zeroDebias) {
  19157. util.assert(step != null, 'When using zeroDebias: true, step is required.');
  19158. step = typeof step === 'number' ? array_ops_1.ArrayOps.scalar(step) : step;
  19159. update = update.div(one.sub(binary_ops_1.BinaryOps.pow(decay, step)));
  19160. }
  19161. return v.add(update);
  19162. };
  19163. __decorate([
  19164. doc_1.doc({ heading: 'Operations', subheading: 'Moving Average' }),
  19165. operation_1.operation
  19166. ], MovingAverageOps, "movingAverage", null);
  19167. return MovingAverageOps;
  19168. }());
  19169. exports.MovingAverageOps = MovingAverageOps;
  19170. },{"../doc":49,"../util":164,"./array_ops":108,"./binary_ops":111,"./operation":128}],127:[function(require,module,exports){
  19171. "use strict";
  19172. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19173. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19174. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19175. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19176. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19177. };
  19178. Object.defineProperty(exports, "__esModule", { value: true });
  19179. var doc_1 = require("../doc");
  19180. var util = require("../util");
  19181. var axis_util = require("./axis_util");
  19182. var operation_1 = require("./operation");
  19183. var ops = require("./ops");
  19184. var NormOps = (function () {
  19185. function NormOps() {
  19186. }
  19187. NormOps.norm = function (x, ord, axis, keepDims) {
  19188. if (ord === void 0) { ord = 'euclidean'; }
  19189. if (axis === void 0) { axis = null; }
  19190. if (keepDims === void 0) { keepDims = false; }
  19191. util.assertArgumentsAreTensors({ x: x }, 'norm');
  19192. var norm = normImpl(x, ord, axis);
  19193. var keepDimsShape = norm.shape;
  19194. if (keepDims) {
  19195. var axes = axis_util.parseAxisParam(axis, x.shape);
  19196. keepDimsShape = axis_util.expandShapeToKeepDim(norm.shape, axes);
  19197. }
  19198. return norm.reshape(keepDimsShape);
  19199. };
  19200. __decorate([
  19201. doc_1.doc({ heading: 'Operations', subheading: 'Matrices' }),
  19202. operation_1.operation
  19203. ], NormOps, "norm", null);
  19204. return NormOps;
  19205. }());
  19206. exports.NormOps = NormOps;
  19207. function normImpl(x, p, axis) {
  19208. if (axis === void 0) { axis = null; }
  19209. if (x.rank === 0) {
  19210. return x.abs();
  19211. }
  19212. if (x.rank !== 1 && axis === null) {
  19213. return normImpl(x.reshape([-1]), p, axis);
  19214. }
  19215. if (x.rank === 1 || typeof axis === 'number' ||
  19216. axis instanceof Array && axis.length === 1) {
  19217. if (p === 1) {
  19218. return x.abs().sum(axis);
  19219. }
  19220. if (p === Infinity) {
  19221. return x.abs().max(axis);
  19222. }
  19223. if (p === -Infinity) {
  19224. return x.abs().min(axis);
  19225. }
  19226. if (p === 'euclidean' || p === 2) {
  19227. return x.abs().pow(ops.scalar(2, 'int32')).sum(axis).sqrt();
  19228. }
  19229. throw new Error("Error in norm: invalid ord value: " + p);
  19230. }
  19231. if (axis instanceof Array && axis.length === 2) {
  19232. if (p === 1) {
  19233. return x.abs().sum(axis[0]).max(axis[1] - 1);
  19234. }
  19235. if (p === Infinity) {
  19236. return x.abs().sum(axis[1]).max(axis[0]);
  19237. }
  19238. if (p === -Infinity) {
  19239. return x.abs().sum(axis[1]).min(axis[0]);
  19240. }
  19241. if (p === 'fro' || p === 'euclidean') {
  19242. return x.square().sum(axis).sqrt();
  19243. }
  19244. throw new Error("Error in norm: invalid ord value: " + p);
  19245. }
  19246. throw new Error("Error in norm: invalid axis: " + axis);
  19247. }
  19248. },{"../doc":49,"../util":164,"./axis_util":109,"./operation":128,"./ops":129}],128:[function(require,module,exports){
  19249. "use strict";
  19250. Object.defineProperty(exports, "__esModule", { value: true });
  19251. var globals_1 = require("../globals");
  19252. function operation(target, name, descriptor) {
  19253. var fn = descriptor.value;
  19254. descriptor.value = function () {
  19255. var args = [];
  19256. for (var _i = 0; _i < arguments.length; _i++) {
  19257. args[_i] = arguments[_i];
  19258. }
  19259. return globals_1.tidy(name, function () { return fn.apply(void 0, args); });
  19260. };
  19261. return descriptor;
  19262. }
  19263. exports.operation = operation;
  19264. },{"../globals":52}],129:[function(require,module,exports){
  19265. "use strict";
  19266. Object.defineProperty(exports, "__esModule", { value: true });
  19267. var array_ops_1 = require("./array_ops");
  19268. var batchnorm_1 = require("./batchnorm");
  19269. var binary_ops_1 = require("./binary_ops");
  19270. var compare_1 = require("./compare");
  19271. var concat_1 = require("./concat");
  19272. var conv_1 = require("./conv");
  19273. var image_ops_1 = require("./image_ops");
  19274. var linalg_ops_1 = require("./linalg_ops");
  19275. var logical_ops_1 = require("./logical_ops");
  19276. var loss_ops_1 = require("./loss_ops");
  19277. var lrn_1 = require("./lrn");
  19278. var lstm_1 = require("./lstm");
  19279. var matmul_1 = require("./matmul");
  19280. var moving_average_1 = require("./moving_average");
  19281. var norm_1 = require("./norm");
  19282. var pool_1 = require("./pool");
  19283. var reduction_ops_1 = require("./reduction_ops");
  19284. var reverse_1 = require("./reverse");
  19285. var segment_ops_1 = require("./segment_ops");
  19286. var sigmoid_cross_entropy_1 = require("./sigmoid_cross_entropy");
  19287. var slice_1 = require("./slice");
  19288. var softmax_1 = require("./softmax");
  19289. var strided_slice_1 = require("./strided_slice");
  19290. var transpose_1 = require("./transpose");
  19291. var unary_ops_1 = require("./unary_ops");
  19292. exports.batchNormalization = batchnorm_1.BatchNormOps.batchNormalization;
  19293. exports.batchNormalization2d = batchnorm_1.BatchNormOps.batchNormalization2d;
  19294. exports.batchNormalization3d = batchnorm_1.BatchNormOps.batchNormalization3d;
  19295. exports.batchNormalization4d = batchnorm_1.BatchNormOps.batchNormalization4d;
  19296. exports.concat = concat_1.ConcatOps.concat;
  19297. exports.concat1d = concat_1.ConcatOps.concat1d;
  19298. exports.concat2d = concat_1.ConcatOps.concat2d;
  19299. exports.concat3d = concat_1.ConcatOps.concat3d;
  19300. exports.concat4d = concat_1.ConcatOps.concat4d;
  19301. exports.conv1d = conv_1.ConvOps.conv1d;
  19302. exports.conv2d = conv_1.ConvOps.conv2d;
  19303. exports.conv2dTranspose = conv_1.ConvOps.conv2dTranspose;
  19304. exports.depthwiseConv2d = conv_1.ConvOps.depthwiseConv2d;
  19305. exports.separableConv2d = conv_1.ConvOps.separableConv2d;
  19306. exports.matMul = matmul_1.MatmulOps.matMul;
  19307. exports.matrixTimesVector = matmul_1.MatmulOps.matrixTimesVector;
  19308. exports.outerProduct = matmul_1.MatmulOps.outerProduct;
  19309. exports.vectorTimesMatrix = matmul_1.MatmulOps.vectorTimesMatrix;
  19310. exports.dot = matmul_1.MatmulOps.dot;
  19311. exports.avgPool = pool_1.PoolOps.avgPool;
  19312. exports.maxPool = pool_1.PoolOps.maxPool;
  19313. exports.transpose = transpose_1.TransposeOps.transpose;
  19314. exports.reverse = reverse_1.ReverseOps.reverse;
  19315. exports.reverse1d = reverse_1.ReverseOps.reverse1d;
  19316. exports.reverse2d = reverse_1.ReverseOps.reverse2d;
  19317. exports.reverse3d = reverse_1.ReverseOps.reverse3d;
  19318. exports.reverse4d = reverse_1.ReverseOps.reverse4d;
  19319. exports.slice = slice_1.SliceOps.slice;
  19320. exports.slice1d = slice_1.SliceOps.slice1d;
  19321. exports.slice2d = slice_1.SliceOps.slice2d;
  19322. exports.slice3d = slice_1.SliceOps.slice3d;
  19323. exports.slice4d = slice_1.SliceOps.slice4d;
  19324. exports.stridedSlice = strided_slice_1.StridedSliceOps.stridedSlice;
  19325. exports.argMax = reduction_ops_1.ReductionOps.argMax;
  19326. exports.argMin = reduction_ops_1.ReductionOps.argMin;
  19327. exports.logSumExp = reduction_ops_1.ReductionOps.logSumExp;
  19328. exports.max = reduction_ops_1.ReductionOps.max;
  19329. exports.mean = reduction_ops_1.ReductionOps.mean;
  19330. exports.min = reduction_ops_1.ReductionOps.min;
  19331. exports.all = reduction_ops_1.ReductionOps.all;
  19332. exports.moments = reduction_ops_1.ReductionOps.moments;
  19333. exports.sum = reduction_ops_1.ReductionOps.sum;
  19334. exports.unsortedSegmentSum = segment_ops_1.SegmentOps.unsortedSegmentSum;
  19335. exports.equal = compare_1.CompareOps.equal;
  19336. exports.equalStrict = compare_1.CompareOps.equalStrict;
  19337. exports.greater = compare_1.CompareOps.greater;
  19338. exports.greaterStrict = compare_1.CompareOps.greaterStrict;
  19339. exports.greaterEqual = compare_1.CompareOps.greaterEqual;
  19340. exports.greaterEqualStrict = compare_1.CompareOps.greaterEqualStrict;
  19341. exports.less = compare_1.CompareOps.less;
  19342. exports.lessStrict = compare_1.CompareOps.lessStrict;
  19343. exports.lessEqual = compare_1.CompareOps.lessEqual;
  19344. exports.lessEqualStrict = compare_1.CompareOps.lessEqualStrict;
  19345. exports.notEqual = compare_1.CompareOps.notEqual;
  19346. exports.notEqualStrict = compare_1.CompareOps.notEqualStrict;
  19347. exports.logicalNot = logical_ops_1.LogicalOps.logicalNot;
  19348. exports.logicalAnd = logical_ops_1.LogicalOps.logicalAnd;
  19349. exports.logicalOr = logical_ops_1.LogicalOps.logicalOr;
  19350. exports.logicalXor = logical_ops_1.LogicalOps.logicalXor;
  19351. exports.where = logical_ops_1.LogicalOps.where;
  19352. exports.abs = unary_ops_1.UnaryOps.abs;
  19353. exports.acos = unary_ops_1.UnaryOps.acos;
  19354. exports.acosh = unary_ops_1.UnaryOps.acosh;
  19355. exports.asin = unary_ops_1.UnaryOps.asin;
  19356. exports.asinh = unary_ops_1.UnaryOps.asinh;
  19357. exports.atan = unary_ops_1.UnaryOps.atan;
  19358. exports.atanh = unary_ops_1.UnaryOps.atanh;
  19359. exports.ceil = unary_ops_1.UnaryOps.ceil;
  19360. exports.clipByValue = unary_ops_1.UnaryOps.clipByValue;
  19361. exports.cos = unary_ops_1.UnaryOps.cos;
  19362. exports.cosh = unary_ops_1.UnaryOps.cosh;
  19363. exports.elu = unary_ops_1.UnaryOps.elu;
  19364. exports.exp = unary_ops_1.UnaryOps.exp;
  19365. exports.expm1 = unary_ops_1.UnaryOps.expm1;
  19366. exports.floor = unary_ops_1.UnaryOps.floor;
  19367. exports.sign = unary_ops_1.UnaryOps.sign;
  19368. exports.leakyRelu = unary_ops_1.UnaryOps.leakyRelu;
  19369. exports.log = unary_ops_1.UnaryOps.log;
  19370. exports.log1p = unary_ops_1.UnaryOps.log1p;
  19371. exports.logSigmoid = unary_ops_1.UnaryOps.logSigmoid;
  19372. exports.neg = unary_ops_1.UnaryOps.neg;
  19373. exports.prelu = unary_ops_1.UnaryOps.prelu;
  19374. exports.relu = unary_ops_1.UnaryOps.relu;
  19375. exports.reciprocal = unary_ops_1.UnaryOps.reciprocal;
  19376. exports.round = unary_ops_1.UnaryOps.round;
  19377. exports.selu = unary_ops_1.UnaryOps.selu;
  19378. exports.sigmoid = unary_ops_1.UnaryOps.sigmoid;
  19379. exports.sin = unary_ops_1.UnaryOps.sin;
  19380. exports.sinh = unary_ops_1.UnaryOps.sinh;
  19381. exports.softplus = unary_ops_1.UnaryOps.softplus;
  19382. exports.sqrt = unary_ops_1.UnaryOps.sqrt;
  19383. exports.rsqrt = unary_ops_1.UnaryOps.rsqrt;
  19384. exports.square = unary_ops_1.UnaryOps.square;
  19385. exports.step = unary_ops_1.UnaryOps.step;
  19386. exports.tan = unary_ops_1.UnaryOps.tan;
  19387. exports.tanh = unary_ops_1.UnaryOps.tanh;
  19388. exports.erf = unary_ops_1.UnaryOps.erf;
  19389. exports.add = binary_ops_1.BinaryOps.add;
  19390. exports.addStrict = binary_ops_1.BinaryOps.addStrict;
  19391. exports.atan2 = binary_ops_1.BinaryOps.atan2;
  19392. exports.div = binary_ops_1.BinaryOps.div;
  19393. exports.floorDiv = binary_ops_1.BinaryOps.floorDiv;
  19394. exports.divStrict = binary_ops_1.BinaryOps.divStrict;
  19395. exports.maximum = binary_ops_1.BinaryOps.maximum;
  19396. exports.maximumStrict = binary_ops_1.BinaryOps.maximumStrict;
  19397. exports.minimum = binary_ops_1.BinaryOps.minimum;
  19398. exports.minimumStrict = binary_ops_1.BinaryOps.minimumStrict;
  19399. exports.mod = binary_ops_1.BinaryOps.mod;
  19400. exports.modStrict = binary_ops_1.BinaryOps.modStrict;
  19401. exports.mul = binary_ops_1.BinaryOps.mul;
  19402. exports.mulStrict = binary_ops_1.BinaryOps.mulStrict;
  19403. exports.pow = binary_ops_1.BinaryOps.pow;
  19404. exports.powStrict = binary_ops_1.BinaryOps.powStrict;
  19405. exports.sub = binary_ops_1.BinaryOps.sub;
  19406. exports.subStrict = binary_ops_1.BinaryOps.subStrict;
  19407. exports.squaredDifference = binary_ops_1.BinaryOps.squaredDifference;
  19408. exports.squaredDifferenceStrict = binary_ops_1.BinaryOps.squaredDifferenceStrict;
  19409. exports.norm = norm_1.NormOps.norm;
  19410. exports.cast = array_ops_1.ArrayOps.cast;
  19411. exports.clone = array_ops_1.ArrayOps.clone;
  19412. exports.fromPixels = array_ops_1.ArrayOps.fromPixels;
  19413. exports.toPixels = array_ops_1.ArrayOps.toPixels;
  19414. exports.ones = array_ops_1.ArrayOps.ones;
  19415. exports.onesLike = array_ops_1.ArrayOps.onesLike;
  19416. exports.zeros = array_ops_1.ArrayOps.zeros;
  19417. exports.zerosLike = array_ops_1.ArrayOps.zerosLike;
  19418. exports.eye = array_ops_1.ArrayOps.eye;
  19419. exports.rand = array_ops_1.ArrayOps.rand;
  19420. exports.randomNormal = array_ops_1.ArrayOps.randomNormal;
  19421. exports.truncatedNormal = array_ops_1.ArrayOps.truncatedNormal;
  19422. exports.randomUniform = array_ops_1.ArrayOps.randomUniform;
  19423. exports.multinomial = array_ops_1.ArrayOps.multinomial;
  19424. exports.reshape = array_ops_1.ArrayOps.reshape;
  19425. exports.squeeze = array_ops_1.ArrayOps.squeeze;
  19426. exports.tile = array_ops_1.ArrayOps.tile;
  19427. exports.gather = array_ops_1.ArrayOps.gather;
  19428. exports.oneHot = array_ops_1.ArrayOps.oneHot;
  19429. exports.linspace = array_ops_1.ArrayOps.linspace;
  19430. exports.range = array_ops_1.ArrayOps.range;
  19431. exports.buffer = array_ops_1.ArrayOps.buffer;
  19432. exports.fill = array_ops_1.ArrayOps.fill;
  19433. exports.tensor = array_ops_1.ArrayOps.tensor;
  19434. exports.scalar = array_ops_1.ArrayOps.scalar;
  19435. exports.tensor1d = array_ops_1.ArrayOps.tensor1d;
  19436. exports.tensor2d = array_ops_1.ArrayOps.tensor2d;
  19437. exports.tensor3d = array_ops_1.ArrayOps.tensor3d;
  19438. exports.tensor4d = array_ops_1.ArrayOps.tensor4d;
  19439. exports.tensor5d = array_ops_1.ArrayOps.tensor5d;
  19440. exports.tensor6d = array_ops_1.ArrayOps.tensor6d;
  19441. exports.print = array_ops_1.ArrayOps.print;
  19442. exports.expandDims = array_ops_1.ArrayOps.expandDims;
  19443. exports.stack = array_ops_1.ArrayOps.stack;
  19444. exports.unstack = array_ops_1.ArrayOps.unstack;
  19445. exports.split = array_ops_1.ArrayOps.split;
  19446. exports.cumsum = array_ops_1.ArrayOps.cumsum;
  19447. exports.pad = array_ops_1.ArrayOps.pad;
  19448. exports.pad1d = array_ops_1.ArrayOps.pad1d;
  19449. exports.pad2d = array_ops_1.ArrayOps.pad2d;
  19450. exports.pad3d = array_ops_1.ArrayOps.pad3d;
  19451. exports.pad4d = array_ops_1.ArrayOps.pad4d;
  19452. exports.movingAverage = moving_average_1.MovingAverageOps.movingAverage;
  19453. exports.basicLSTMCell = lstm_1.LSTMOps.basicLSTMCell;
  19454. exports.multiRNNCell = lstm_1.LSTMOps.multiRNNCell;
  19455. exports.softmax = softmax_1.SoftmaxOps.softmax;
  19456. exports.sigmoidCrossEntropyWithLogits = sigmoid_cross_entropy_1.SigmoidCrossEntropyOps.sigmoidCrossEntropyWithLogits;
  19457. exports.localResponseNormalization = lrn_1.LRNOps.localResponseNormalization;
  19458. exports.linalg = linalg_ops_1.LinalgOps;
  19459. var operation_1 = require("./operation");
  19460. exports.operation = operation_1.operation;
  19461. var tensor_1 = require("../tensor");
  19462. var types_1 = require("../types");
  19463. [tensor_1.Tensor, types_1.Rank];
  19464. [loss_ops_1.Reduction];
  19465. exports.losses = {
  19466. absoluteDifference: loss_ops_1.LossOps.absoluteDifference,
  19467. computeWeightedLoss: loss_ops_1.LossOps.computeWeightedLoss,
  19468. cosineDistance: loss_ops_1.LossOps.cosineDistance,
  19469. hingeLoss: loss_ops_1.LossOps.hingeLoss,
  19470. huberLoss: loss_ops_1.LossOps.huberLoss,
  19471. logLoss: loss_ops_1.LossOps.logLoss,
  19472. meanSquaredError: loss_ops_1.LossOps.meanSquaredError,
  19473. softmaxCrossEntropy: softmax_1.SoftmaxOps.softmaxCrossEntropy
  19474. };
  19475. exports.image = {
  19476. resizeBilinear: image_ops_1.ImageOps.resizeBilinear,
  19477. resizeNearestNeighbor: image_ops_1.ImageOps.resizeNearestNeighbor,
  19478. };
  19479. },{"../tensor":158,"../types":163,"./array_ops":108,"./batchnorm":110,"./binary_ops":111,"./compare":113,"./concat":114,"./conv":116,"./image_ops":119,"./linalg_ops":120,"./logical_ops":121,"./loss_ops":122,"./lrn":123,"./lstm":124,"./matmul":125,"./moving_average":126,"./norm":127,"./operation":128,"./pool":130,"./reduction_ops":133,"./reverse":134,"./segment_ops":135,"./sigmoid_cross_entropy":138,"./slice":139,"./softmax":141,"./strided_slice":142,"./transpose":143,"./unary_ops":144}],130:[function(require,module,exports){
  19480. "use strict";
  19481. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19482. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19483. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19484. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19485. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19486. };
  19487. Object.defineProperty(exports, "__esModule", { value: true });
  19488. var doc_1 = require("../doc");
  19489. var environment_1 = require("../environment");
  19490. var util = require("../util");
  19491. var conv_util = require("./conv_util");
  19492. var operation_1 = require("./operation");
  19493. var PoolOps = (function () {
  19494. function PoolOps() {
  19495. }
  19496. PoolOps.maxPool = function (x, filterSize, strides, pad, dimRoundingMode) {
  19497. util.assertArgumentsAreTensors({ x: x }, 'maxPool');
  19498. var x4D = x;
  19499. var reshapedTo4D = false;
  19500. if (x.rank === 3) {
  19501. reshapedTo4D = true;
  19502. x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  19503. }
  19504. util.assert(x4D.rank === 4, "Error in maxPool: input must be rank 4 but got rank " + x4D.rank + ".");
  19505. if (dimRoundingMode != null) {
  19506. util.assert(util.isInt(pad), "Error in maxPool: pad must be an integer when using, " +
  19507. ("dimRoundingMode " + dimRoundingMode + " but got pad " + pad + "."));
  19508. }
  19509. var convInfo = conv_util.computePool2DInfo(x4D.shape, filterSize, strides, pad, dimRoundingMode);
  19510. var grad = function (dy, saved) {
  19511. var y4D = saved[0];
  19512. return {
  19513. x: function () { return PoolOps.maxPoolBackprop(dy, x4D, y4D, filterSize, strides, pad); }
  19514. };
  19515. };
  19516. var res = environment_1.ENV.engine.runKernel(function (backend, save) { return save(backend.maxPool(x4D, convInfo)); }, { x: x4D }, grad);
  19517. if (reshapedTo4D) {
  19518. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  19519. }
  19520. return res;
  19521. };
  19522. PoolOps.maxPoolBackprop = function (dy, input, output, filterSize, strides, pad, dimRoundingMode) {
  19523. util.assertArgumentsAreTensors({ dy: dy, input: input, output: output }, 'maxPoolBackprop');
  19524. util.assert(input.rank === dy.rank, "Rank of input (" + input.rank + ") does not match rank of dy (" + dy.rank + ")");
  19525. util.assert(dy.rank === 4, "Error in maxPoolBackprop: dy must be rank 4 but got rank " +
  19526. (dy.rank + "."));
  19527. util.assert(input.rank === 4, "Error in maxPoolBackprop: input must be rank 4 but got rank " +
  19528. (input.rank + "."));
  19529. if (dimRoundingMode != null) {
  19530. util.assert(util.isInt(pad), "Error in maxPoolBackprop: pad must be an integer when using, " +
  19531. ("dimRoundingMode " + dimRoundingMode + " but got pad " + pad + "."));
  19532. }
  19533. var convInfo = conv_util.computePool2DInfo(input.shape, filterSize, strides, pad, dimRoundingMode);
  19534. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.maxPoolBackprop(dy, input, output, convInfo); }, { dy: dy, input: input });
  19535. return res;
  19536. };
  19537. PoolOps.avgPool = function (x, filterSize, strides, pad, dimRoundingMode) {
  19538. util.assertArgumentsAreTensors({ x: x }, 'avgPool');
  19539. util.assert(x.dtype === 'float32', 'The input dtype to avgPool must be float32');
  19540. var x4D = x;
  19541. var reshapedTo4D = false;
  19542. if (x.rank === 3) {
  19543. reshapedTo4D = true;
  19544. x4D = x.as4D(1, x.shape[0], x.shape[1], x.shape[2]);
  19545. }
  19546. util.assert(x4D.rank === 4, "Error in avgPool: x must be rank 4 but got rank " + x4D.rank + ".");
  19547. if (dimRoundingMode != null) {
  19548. util.assert(util.isInt(pad), "Error in avgPool: pad must be an integer when using, " +
  19549. ("dimRoundingMode " + dimRoundingMode + " but got pad " + pad + "."));
  19550. }
  19551. var convInfo = conv_util.computePool2DInfo(x4D.shape, filterSize, strides, pad);
  19552. var grad = function (dy) {
  19553. return {
  19554. x: function () { return PoolOps.avgPoolBackprop(dy, x4D, filterSize, strides, pad); }
  19555. };
  19556. };
  19557. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.avgPool(x4D, convInfo); }, { x: x4D }, grad);
  19558. res = res.cast(x.dtype);
  19559. if (reshapedTo4D) {
  19560. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  19561. }
  19562. return res;
  19563. };
  19564. PoolOps.avgPoolBackprop = function (dy, input, filterSize, strides, pad) {
  19565. util.assertArgumentsAreTensors({ dy: dy, input: input }, 'avgPoolBackprop');
  19566. util.assert(input.rank === dy.rank, "Rank of input (" + input.rank + ") does not match rank of dy (" + dy.rank + ")");
  19567. var input4D = input;
  19568. var dy4D = dy;
  19569. var reshapedTo4D = false;
  19570. if (input.rank === 3) {
  19571. reshapedTo4D = true;
  19572. input4D = input.as4D(1, input.shape[0], input.shape[1], input.shape[2]);
  19573. dy4D = dy.as4D(1, dy.shape[0], dy.shape[1], dy.shape[2]);
  19574. }
  19575. util.assert(dy4D.rank === 4, "Error in avgPoolBackprop: dy must be rank 4 but got rank " +
  19576. (dy4D.rank + "."));
  19577. util.assert(input4D.rank === 4, "Error in avgPoolBackprop: input must be rank 4 but got rank " +
  19578. (input4D.rank + "."));
  19579. var convInfo = conv_util.computePool2DInfo(input4D.shape, filterSize, strides, pad);
  19580. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.avgPoolBackprop(dy4D, input4D, convInfo); }, { dy4D: dy4D, input4D: input4D });
  19581. if (reshapedTo4D) {
  19582. return res.as3D(res.shape[1], res.shape[2], res.shape[3]);
  19583. }
  19584. return res;
  19585. };
  19586. __decorate([
  19587. doc_1.doc({ heading: 'Operations', subheading: 'Convolution' }),
  19588. operation_1.operation
  19589. ], PoolOps, "maxPool", null);
  19590. __decorate([
  19591. operation_1.operation
  19592. ], PoolOps, "maxPoolBackprop", null);
  19593. __decorate([
  19594. doc_1.doc({ heading: 'Operations', subheading: 'Convolution' }),
  19595. operation_1.operation
  19596. ], PoolOps, "avgPool", null);
  19597. __decorate([
  19598. operation_1.operation
  19599. ], PoolOps, "avgPoolBackprop", null);
  19600. return PoolOps;
  19601. }());
  19602. exports.PoolOps = PoolOps;
  19603. },{"../doc":49,"../environment":51,"../util":164,"./conv_util":117,"./operation":128}],131:[function(require,module,exports){
  19604. "use strict";
  19605. Object.defineProperty(exports, "__esModule", { value: true });
  19606. var seedrandom = require("seedrandom");
  19607. var MPRandGauss = (function () {
  19608. function MPRandGauss(mean, stdDeviation, dtype, truncated, seed) {
  19609. this.mean = mean;
  19610. this.stdDev = stdDeviation;
  19611. this.dtype = dtype;
  19612. this.nextVal = NaN;
  19613. this.truncated = truncated;
  19614. if (this.truncated) {
  19615. this.upper = this.mean + this.stdDev * 2;
  19616. this.lower = this.mean - this.stdDev * 2;
  19617. }
  19618. var seedValue = seed ? seed : Math.random();
  19619. this.random = seedrandom.alea(seedValue.toString());
  19620. }
  19621. MPRandGauss.prototype.nextValue = function () {
  19622. if (!isNaN(this.nextVal)) {
  19623. var value = this.nextVal;
  19624. this.nextVal = NaN;
  19625. return value;
  19626. }
  19627. var resultX, resultY;
  19628. var isValid = false;
  19629. while (!isValid) {
  19630. var v1 = void 0, v2 = void 0, s = void 0;
  19631. do {
  19632. v1 = 2 * this.random() - 1;
  19633. v2 = 2 * this.random() - 1;
  19634. s = v1 * v1 + v2 * v2;
  19635. } while (s >= 1 || s === 0);
  19636. var mul = Math.sqrt(-2.0 * Math.log(s) / s);
  19637. resultX = this.mean + this.stdDev * v1 * mul;
  19638. resultY = this.mean + this.stdDev * v2 * mul;
  19639. if (!this.truncated || this.isValidTruncated(resultX)) {
  19640. isValid = true;
  19641. }
  19642. }
  19643. if (!this.truncated || this.isValidTruncated(resultY)) {
  19644. this.nextVal = this.convertValue(resultY);
  19645. }
  19646. return this.convertValue(resultX);
  19647. };
  19648. MPRandGauss.prototype.convertValue = function (value) {
  19649. if (this.dtype == null || this.dtype === 'float32') {
  19650. return value;
  19651. }
  19652. return Math.round(value);
  19653. };
  19654. MPRandGauss.prototype.isValidTruncated = function (value) {
  19655. return value <= this.upper && value >= this.lower;
  19656. };
  19657. return MPRandGauss;
  19658. }());
  19659. exports.MPRandGauss = MPRandGauss;
  19660. },{"seedrandom":231}],132:[function(require,module,exports){
  19661. "use strict";
  19662. Object.defineProperty(exports, "__esModule", { value: true });
  19663. var util_1 = require("../util");
  19664. exports.PARALLELIZE_THRESHOLD = 30;
  19665. function computeOptimalWindowSize(inSize) {
  19666. if (inSize <= exports.PARALLELIZE_THRESHOLD) {
  19667. return inSize;
  19668. }
  19669. return util_1.nearestDivisor(inSize, Math.floor(Math.sqrt(inSize)));
  19670. }
  19671. exports.computeOptimalWindowSize = computeOptimalWindowSize;
  19672. },{"../util":164}],133:[function(require,module,exports){
  19673. "use strict";
  19674. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19675. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19676. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19677. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19678. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19679. };
  19680. Object.defineProperty(exports, "__esModule", { value: true });
  19681. var doc_1 = require("../doc");
  19682. var environment_1 = require("../environment");
  19683. var globals_1 = require("../globals");
  19684. var util = require("../util");
  19685. var axis_util = require("./axis_util");
  19686. var operation_1 = require("./operation");
  19687. var ops = require("./ops");
  19688. var ReductionOps = (function () {
  19689. function ReductionOps() {
  19690. }
  19691. ReductionOps.logSumExp = function (x, axis, keepDims) {
  19692. if (axis === void 0) { axis = null; }
  19693. if (keepDims === void 0) { keepDims = false; }
  19694. util.assertArgumentsAreTensors({ x: x }, 'logSumExp');
  19695. var axes = axis_util.parseAxisParam(axis, x.shape);
  19696. var xMax = x.max(axes, true);
  19697. var a = x.sub(xMax);
  19698. var b = a.exp();
  19699. var c = b.sum(axes);
  19700. var d = c.log();
  19701. var res = xMax.reshape(d.shape).add(d);
  19702. if (keepDims) {
  19703. var newShape = axis_util.expandShapeToKeepDim(res.shape, axes);
  19704. return res.reshape(newShape);
  19705. }
  19706. return res;
  19707. };
  19708. ReductionOps.sum = function (x, axis, keepDims) {
  19709. if (axis === void 0) { axis = null; }
  19710. if (keepDims === void 0) { keepDims = false; }
  19711. util.assertArgumentsAreTensors({ x: x }, 'sum');
  19712. if (x.dtype === 'bool') {
  19713. x = x.toInt();
  19714. }
  19715. var axes = axis_util.parseAxisParam(axis, x.shape);
  19716. var customOp = globals_1.customGrad(function (x) {
  19717. var permutation = axis_util.getAxesPermutation(axes, x.rank);
  19718. var reductionAxes = axes;
  19719. var permutedX = x;
  19720. if (permutation != null) {
  19721. permutedX = x.transpose(permutation);
  19722. reductionAxes =
  19723. axis_util.getInnerMostAxes(reductionAxes.length, x.rank);
  19724. }
  19725. var value = environment_1.ENV.engine.runKernel(function (backend) { return backend.sum(permutedX, reductionAxes); }, { permutedX: permutedX });
  19726. if (keepDims) {
  19727. var newShape = axis_util.expandShapeToKeepDim(value.shape, axes);
  19728. value = value.reshape(newShape);
  19729. }
  19730. var gradFunc = function (dy) {
  19731. var expandedDyShape = x.shape.slice();
  19732. axes.forEach(function (axis) {
  19733. expandedDyShape[axis] = 1;
  19734. });
  19735. var expandedDy = dy.reshape(expandedDyShape);
  19736. var derX = expandedDy.mul(ops.ones(x.shape, 'float32'));
  19737. return derX;
  19738. };
  19739. return { value: value, gradFunc: gradFunc };
  19740. });
  19741. return customOp(x);
  19742. };
  19743. ReductionOps.mean = function (x, axis, keepDims) {
  19744. if (axis === void 0) { axis = null; }
  19745. if (keepDims === void 0) { keepDims = false; }
  19746. util.assertArgumentsAreTensors({ x: x }, 'mean');
  19747. var axes = axis_util.parseAxisParam(axis, x.shape);
  19748. var shapes = axis_util.computeOutAndReduceShapes(x.shape, axes);
  19749. var reduceShape = shapes[1];
  19750. var reduceSize = util.sizeFromShape(reduceShape);
  19751. var customOp = globals_1.customGrad(function (x) {
  19752. var reduceSizeScalar = ops.scalar(reduceSize);
  19753. var xReduce = reduceSizeScalar.dtype === x.dtype ?
  19754. x :
  19755. x.cast(reduceSizeScalar.dtype);
  19756. var res = xReduce.div(reduceSizeScalar);
  19757. var value = res.sum(axis, keepDims);
  19758. var gradFunc = function (dy) {
  19759. var expandedDyShape = x.shape.slice();
  19760. axes.forEach(function (axis) {
  19761. expandedDyShape[axis] = 1;
  19762. });
  19763. var expandedDy = dy.reshape(expandedDyShape);
  19764. var derX = expandedDy.mul(ops.ones(x.shape, 'float32')).div(reduceSizeScalar);
  19765. return derX;
  19766. };
  19767. return { value: value, gradFunc: gradFunc };
  19768. });
  19769. return customOp(x);
  19770. };
  19771. ReductionOps.min = function (x, axis, keepDims) {
  19772. if (axis === void 0) { axis = null; }
  19773. if (keepDims === void 0) { keepDims = false; }
  19774. util.assertArgumentsAreTensors({ x: x }, 'min');
  19775. var origAxes = axis_util.parseAxisParam(axis, x.shape);
  19776. var axes = origAxes;
  19777. var permutedAxes = axis_util.getAxesPermutation(axes, x.rank);
  19778. if (permutedAxes != null) {
  19779. x = x.transpose(permutedAxes);
  19780. axes = axis_util.getInnerMostAxes(axes.length, x.rank);
  19781. }
  19782. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.min(x, axes); }, { x: x });
  19783. if (keepDims) {
  19784. var newShape = axis_util.expandShapeToKeepDim(res.shape, origAxes);
  19785. return res.reshape(newShape);
  19786. }
  19787. return res;
  19788. };
  19789. ReductionOps.max = function (x, axis, keepDims) {
  19790. if (axis === void 0) { axis = null; }
  19791. if (keepDims === void 0) { keepDims = false; }
  19792. util.assertArgumentsAreTensors({ x: x }, 'max');
  19793. var origAxes = axis_util.parseAxisParam(axis, x.shape);
  19794. var axes = origAxes;
  19795. var permutedAxes = axis_util.getAxesPermutation(axes, x.rank);
  19796. if (permutedAxes != null) {
  19797. x = x.transpose(permutedAxes);
  19798. axes = axis_util.getInnerMostAxes(axes.length, x.rank);
  19799. }
  19800. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.max(x, axes); }, { x: x });
  19801. if (keepDims) {
  19802. var newShape = axis_util.expandShapeToKeepDim(res.shape, origAxes);
  19803. return res.reshape(newShape);
  19804. }
  19805. return res;
  19806. };
  19807. ReductionOps.argMin = function (x, axis) {
  19808. if (axis === void 0) { axis = 0; }
  19809. util.assertArgumentsAreTensors({ x: x }, 'argMin');
  19810. if (axis == null) {
  19811. axis = 0;
  19812. }
  19813. var axes = axis_util.parseAxisParam(axis, x.shape);
  19814. var permutedAxes = axis_util.getAxesPermutation(axes, x.rank);
  19815. if (permutedAxes != null) {
  19816. x = x.transpose(permutedAxes);
  19817. axes = axis_util.getInnerMostAxes(axes.length, x.rank);
  19818. }
  19819. return environment_1.ENV.engine.runKernel(function (backend) { return backend.argMin(x, axes[0]); }, { x: x });
  19820. };
  19821. ReductionOps.argMax = function (x, axis) {
  19822. if (axis === void 0) { axis = 0; }
  19823. util.assertArgumentsAreTensors({ x: x }, 'argMax');
  19824. if (axis == null) {
  19825. axis = 0;
  19826. }
  19827. var axes = axis_util.parseAxisParam(axis, x.shape);
  19828. var permutedAxes = axis_util.getAxesPermutation(axes, x.rank);
  19829. if (permutedAxes != null) {
  19830. x = x.transpose(permutedAxes);
  19831. axes = axis_util.getInnerMostAxes(axes.length, x.rank);
  19832. }
  19833. return environment_1.ENV.engine.runKernel(function (backend) { return backend.argMax(x, axes[0]); }, { x: x });
  19834. };
  19835. ReductionOps.all = function (x, axis, keepDims) {
  19836. if (axis === void 0) { axis = null; }
  19837. if (keepDims === void 0) { keepDims = false; }
  19838. util.assertArgumentsAreTensors({ x: x }, 'all');
  19839. util.assert(x.dtype === 'bool', 'Error Array must be of type bool.');
  19840. var origAxes = axis_util.parseAxisParam(axis, x.shape);
  19841. var axes = origAxes;
  19842. var permutedAxes = axis_util.getAxesPermutation(axes, x.rank);
  19843. if (permutedAxes != null) {
  19844. x = x.transpose(permutedAxes);
  19845. axes = axis_util.getInnerMostAxes(axes.length, x.rank);
  19846. }
  19847. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.all(x, axes); }, { x: x });
  19848. if (keepDims) {
  19849. var newShape = axis_util.expandShapeToKeepDim(res.shape, origAxes);
  19850. return res.reshape(newShape);
  19851. }
  19852. return res;
  19853. };
  19854. ReductionOps.moments = function (x, axis, keepDims) {
  19855. if (axis === void 0) { axis = null; }
  19856. if (keepDims === void 0) { keepDims = false; }
  19857. util.assertArgumentsAreTensors({ x: x }, 'moments');
  19858. var axes = axis_util.parseAxisParam(axis, x.shape);
  19859. var mean = x.mean(axes, keepDims);
  19860. var keepDimsShape = mean.shape;
  19861. if (!keepDims) {
  19862. keepDimsShape = axis_util.expandShapeToKeepDim(mean.shape, axes);
  19863. }
  19864. var devSquared = x.toFloat().sub(mean.reshape(keepDimsShape)).square();
  19865. var variance = devSquared.mean(axes, keepDims);
  19866. return { mean: mean, variance: variance };
  19867. };
  19868. __decorate([
  19869. doc_1.doc({ heading: 'Operations', subheading: 'Reduction' }),
  19870. operation_1.operation
  19871. ], ReductionOps, "logSumExp", null);
  19872. __decorate([
  19873. doc_1.doc({ heading: 'Operations', subheading: 'Reduction' }),
  19874. operation_1.operation
  19875. ], ReductionOps, "sum", null);
  19876. __decorate([
  19877. doc_1.doc({ heading: 'Operations', subheading: 'Reduction' }),
  19878. operation_1.operation
  19879. ], ReductionOps, "mean", null);
  19880. __decorate([
  19881. doc_1.doc({ heading: 'Operations', subheading: 'Reduction' }),
  19882. operation_1.operation
  19883. ], ReductionOps, "min", null);
  19884. __decorate([
  19885. doc_1.doc({ heading: 'Operations', subheading: 'Reduction' }),
  19886. operation_1.operation
  19887. ], ReductionOps, "max", null);
  19888. __decorate([
  19889. doc_1.doc({ heading: 'Operations', subheading: 'Reduction' }),
  19890. operation_1.operation
  19891. ], ReductionOps, "argMin", null);
  19892. __decorate([
  19893. doc_1.doc({ heading: 'Operations', subheading: 'Reduction' }),
  19894. operation_1.operation
  19895. ], ReductionOps, "argMax", null);
  19896. __decorate([
  19897. doc_1.doc({ heading: 'Operations', subheading: 'Reduction' }),
  19898. operation_1.operation
  19899. ], ReductionOps, "all", null);
  19900. __decorate([
  19901. doc_1.doc({ heading: 'Operations', subheading: 'Normalization' }),
  19902. operation_1.operation
  19903. ], ReductionOps, "moments", null);
  19904. return ReductionOps;
  19905. }());
  19906. exports.ReductionOps = ReductionOps;
  19907. },{"../doc":49,"../environment":51,"../globals":52,"../util":164,"./axis_util":109,"./operation":128,"./ops":129}],134:[function(require,module,exports){
  19908. "use strict";
  19909. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19910. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19911. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19912. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19913. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19914. };
  19915. Object.defineProperty(exports, "__esModule", { value: true });
  19916. var doc_1 = require("../doc");
  19917. var environment_1 = require("../environment");
  19918. var util = require("../util");
  19919. var axis_util_1 = require("./axis_util");
  19920. var operation_1 = require("./operation");
  19921. var ReverseOps = (function () {
  19922. function ReverseOps() {
  19923. }
  19924. ReverseOps.reverse1d = function (x) {
  19925. util.assert(x.rank === 1, "Error in reverse1D: x must be rank 1 but got\n rank " + x.rank + ".");
  19926. return ReverseOps.reverse(x, 0);
  19927. };
  19928. ReverseOps.reverse2d = function (x, axis) {
  19929. util.assert(x.rank === 2, "Error in reverse2D: x must be rank 2 but got\n rank " + x.rank + ".");
  19930. return ReverseOps.reverse(x, axis);
  19931. };
  19932. ReverseOps.reverse3d = function (x, axis) {
  19933. util.assert(x.rank === 3, "Error in reverse3D: x must be rank 3 but got\n rank " + x.rank + ".");
  19934. return ReverseOps.reverse(x, axis);
  19935. };
  19936. ReverseOps.reverse4d = function (x, axis) {
  19937. util.assert(x.rank === 4, "Error in reverse4D: x must be rank 4 but got\n rank " + x.rank + ".");
  19938. return ReverseOps.reverse(x, axis);
  19939. };
  19940. ReverseOps.reverse = function (x, axis) {
  19941. util.assertArgumentsAreTensors({ x: x }, 'reverse');
  19942. if (x.rank === 0) {
  19943. return x.clone();
  19944. }
  19945. var axes = axis_util_1.parseAxisParam(axis, x.shape);
  19946. var grad = function (dy) {
  19947. return { x: function () { return dy.reverse(axes); } };
  19948. };
  19949. var res = environment_1.ENV.engine.runKernel(function (backend) { return backend.reverse(x, axes); }, { x: x }, grad);
  19950. return res.reshapeAs(x);
  19951. };
  19952. __decorate([
  19953. doc_1.doc({ heading: 'Tensors', subheading: 'Slicing and Joining' }),
  19954. operation_1.operation
  19955. ], ReverseOps, "reverse", null);
  19956. return ReverseOps;
  19957. }());
  19958. exports.ReverseOps = ReverseOps;
  19959. },{"../doc":49,"../environment":51,"../util":164,"./axis_util":109,"./operation":128}],135:[function(require,module,exports){
  19960. "use strict";
  19961. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19962. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19963. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19964. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19965. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19966. };
  19967. Object.defineProperty(exports, "__esModule", { value: true });
  19968. var doc_1 = require("../doc");
  19969. var environment_1 = require("../environment");
  19970. var util = require("../util");
  19971. var array_ops_1 = require("./array_ops");
  19972. var binary_ops_1 = require("./binary_ops");
  19973. var compare_1 = require("./compare");
  19974. var logical_ops_1 = require("./logical_ops");
  19975. var operation_1 = require("./operation");
  19976. var SegmentOps = (function () {
  19977. function SegmentOps() {
  19978. }
  19979. SegmentOps.unsortedSegmentSum = function (x, segmentIds, numSegments) {
  19980. util.assertArgumentsAreTensors({ x: x, segmentIds: segmentIds }, 'unsortedSegmentSum');
  19981. util.assert(segmentIds.dtype === 'int32', 'segmentIds must be of dtype `int32`');
  19982. util.assert(util.isInt(numSegments), 'numSegments must be of dtype int');
  19983. var gradFunc = function (dy) {
  19984. var derX = function () {
  19985. return gatherDropNegatives(dy, segmentIds);
  19986. };
  19987. return { x: derX };
  19988. };
  19989. return environment_1.ENV.engine.runKernel(function (backend) {
  19990. return backend.unsortedSegmentSum(x, segmentIds, numSegments);
  19991. }, { x: x }, gradFunc);
  19992. };
  19993. __decorate([
  19994. doc_1.doc({ heading: 'Operations', subheading: 'Segment' }),
  19995. operation_1.operation
  19996. ], SegmentOps, "unsortedSegmentSum", null);
  19997. return SegmentOps;
  19998. }());
  19999. exports.SegmentOps = SegmentOps;
  20000. function gatherDropNegatives(x, indices) {
  20001. var zeroClippedIndices = binary_ops_1.BinaryOps.maximum(indices, array_ops_1.ArrayOps.zerosLike(indices));
  20002. var gathered = array_ops_1.ArrayOps.gather(x, zeroClippedIndices);
  20003. var isPositive = compare_1.CompareOps.greaterEqual(indices, array_ops_1.ArrayOps.scalar(0, 'int32'));
  20004. var numIters = gathered.rank - isPositive.rank;
  20005. for (var i = 0; i < numIters; ++i) {
  20006. isPositive = array_ops_1.ArrayOps.expandDims(isPositive, i + 1);
  20007. }
  20008. isPositive =
  20009. logical_ops_1.LogicalOps.logicalAnd(isPositive, array_ops_1.ArrayOps.ones(gathered.shape, 'bool'));
  20010. var zeroSlice = array_ops_1.ArrayOps.zerosLike(gathered);
  20011. return logical_ops_1.LogicalOps.where(isPositive, gathered, zeroSlice);
  20012. }
  20013. },{"../doc":49,"../environment":51,"../util":164,"./array_ops":108,"./binary_ops":111,"./compare":113,"./logical_ops":121,"./operation":128}],136:[function(require,module,exports){
  20014. "use strict";
  20015. Object.defineProperty(exports, "__esModule", { value: true });
  20016. var util_1 = require("../util");
  20017. var reduce_util_1 = require("./reduce_util");
  20018. function segOpComputeOptimalWindowSize(inSize, numSegments) {
  20019. var done = false;
  20020. var res;
  20021. if (inSize <= reduce_util_1.PARALLELIZE_THRESHOLD) {
  20022. res = inSize;
  20023. done = true;
  20024. }
  20025. else {
  20026. res = util_1.nearestDivisor(inSize, Math.floor(Math.sqrt(inSize)));
  20027. }
  20028. while (!done) {
  20029. if (res > numSegments || res === inSize) {
  20030. done = true;
  20031. break;
  20032. }
  20033. else {
  20034. res = util_1.nearestDivisor(inSize, res + 1);
  20035. }
  20036. }
  20037. return res;
  20038. }
  20039. exports.segOpComputeOptimalWindowSize = segOpComputeOptimalWindowSize;
  20040. function computeOutShape(aShape, axis, numSegments) {
  20041. var outShape = [];
  20042. var rank = aShape.length;
  20043. for (var dim = 0; dim < rank; dim++) {
  20044. if (dim !== axis) {
  20045. outShape.push(aShape[dim]);
  20046. }
  20047. else {
  20048. outShape.push(numSegments);
  20049. }
  20050. }
  20051. return outShape;
  20052. }
  20053. exports.computeOutShape = computeOutShape;
  20054. },{"../util":164,"./reduce_util":132}],137:[function(require,module,exports){
  20055. "use strict";
  20056. Object.defineProperty(exports, "__esModule", { value: true });
  20057. exports.SELU_SCALEALPHA = 1.7580993408473768599402175208123;
  20058. exports.SELU_SCALE = 1.0507009873554804934193349852946;
  20059. },{}],138:[function(require,module,exports){
  20060. "use strict";
  20061. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  20062. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  20063. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  20064. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  20065. return c > 3 && r && Object.defineProperty(target, key, r), r;
  20066. };
  20067. Object.defineProperty(exports, "__esModule", { value: true });
  20068. var doc_1 = require("../doc");
  20069. var util = require("../util");
  20070. var operation_1 = require("./operation");
  20071. var SigmoidCrossEntropyOps = (function () {
  20072. function SigmoidCrossEntropyOps() {
  20073. }
  20074. SigmoidCrossEntropyOps.sigmoidCrossEntropyWithLogits = function (labels, logits) {
  20075. util.assertArgumentsAreTensors({ labels: labels, logits: logits }, 'sigmoidCrossEntropyWithLogits');
  20076. util.assertShapesMatch(labels.shape, logits.shape, 'Error in sigmoidCrossEntropyWithLogits: ');
  20077. var maxOutput = logits.relu();
  20078. var outputXTarget = logits.mul(labels);
  20079. var sigmoidOutput = logits.abs().neg().exp().log1p();
  20080. return maxOutput.sub(outputXTarget).add(sigmoidOutput);
  20081. };
  20082. __decorate([
  20083. doc_1.doc({ heading: 'Operations', subheading: 'Cross Entropy' }),
  20084. operation_1.operation
  20085. ], SigmoidCrossEntropyOps, "sigmoidCrossEntropyWithLogits", null);
  20086. return SigmoidCrossEntropyOps;
  20087. }());
  20088. exports.SigmoidCrossEntropyOps = SigmoidCrossEntropyOps;
  20089. },{"../doc":49,"../util":164,"./operation":128}],139:[function(require,module,exports){
  20090. "use strict";
  20091. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  20092. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  20093. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  20094. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  20095. return c > 3 && r && Object.defineProperty(target, key, r), r;
  20096. };
  20097. Object.defineProperty(exports, "__esModule", { value: true });
  20098. var doc_1 = require("../doc");
  20099. var environment_1 = require("../environment");
  20100. var util = require("../util");
  20101. var operation_1 = require("./operation");
  20102. var slice_util = require("./slice_util");
  20103. var SliceOps = (function () {
  20104. function SliceOps() {
  20105. }
  20106. SliceOps.slice1d = function (x, begin, size) {
  20107. util.assert(x.rank === 1, "slice1d expects a rank-1 tensor, but got a rank-" + x.rank + " tensor");
  20108. return SliceOps.slice(x, [begin], [size]);
  20109. };
  20110. SliceOps.slice2d = function (x, begin, size) {
  20111. util.assert(x.rank === 2, "slice1d expects a rank-2 tensor, but got a rank-" + x.rank + " tensor");
  20112. return SliceOps.slice(x, begin, size);
  20113. };
  20114. SliceOps.slice3d = function (x, begin, size) {
  20115. util.assert(x.rank === 3, "slice1d expects a rank-3 tensor, but got a rank-" + x.rank + " tensor");
  20116. return SliceOps.slice(x, begin, size);
  20117. };
  20118. SliceOps.slice4d = function (x, begin, size) {
  20119. util.assert(x.rank === 4, "slice1d expects a rank-4 tensor, but got a rank-" + x.rank + " tensor");
  20120. return SliceOps.slice(x, begin, size);
  20121. };
  20122. SliceOps.slice = function (x, begin, size) {
  20123. util.assertArgumentsAreTensors({ x: x }, 'slice');
  20124. if (x.rank === 0) {
  20125. throw new Error('Slicing scalar is not possible');
  20126. }
  20127. var begin_;
  20128. if (typeof begin === 'number') {
  20129. begin_ = [begin].concat(new Array(x.rank - 1).fill(0));
  20130. }
  20131. else if (begin.length < x.rank) {
  20132. begin_ = begin.concat(new Array(x.rank - begin.length).fill(0));
  20133. }
  20134. else {
  20135. begin_ = begin;
  20136. }
  20137. var size_;
  20138. if (size == null) {
  20139. size_ = new Array(x.rank).fill(-1);
  20140. }
  20141. else if (typeof size === 'number') {
  20142. size_ = [size].concat(new Array(x.rank - 1).fill(-1));
  20143. }
  20144. else if (size.length < x.rank) {
  20145. size_ = size.concat(new Array(x.rank - size.length).fill(-1));
  20146. }
  20147. else {
  20148. size_ = size;
  20149. }
  20150. size_ = size_.map(function (d, i) {
  20151. if (d >= 0) {
  20152. return d;
  20153. }
  20154. else {
  20155. util.assert(d === -1, 'Bad value in size');
  20156. return x.shape[i] - begin_[i];
  20157. }
  20158. });
  20159. slice_util.assertParamsValid(x, begin_, size_);
  20160. var inputShape = x.shape;
  20161. var grad = function (dy) {
  20162. var paddings = [];
  20163. for (var i = 0; i < dy.rank; i++) {
  20164. paddings.push([begin_[i], inputShape[i] - begin_[i] - size_[i]]);
  20165. }
  20166. return { x: function () { return dy.pad(paddings); } };
  20167. };
  20168. return environment_1.ENV.engine.runKernel(function (backend) { return backend.slice(x, begin_, size_); }, { x: x }, grad);
  20169. };
  20170. __decorate([
  20171. doc_1.doc({ heading: 'Tensors', subheading: 'Slicing and Joining' }),
  20172. operation_1.operation
  20173. ], SliceOps, "slice", null);
  20174. return SliceOps;
  20175. }());
  20176. exports.SliceOps = SliceOps;
  20177. },{"../doc":49,"../environment":51,"../util":164,"./operation":128,"./slice_util":140}],140:[function(require,module,exports){
  20178. "use strict";
  20179. Object.defineProperty(exports, "__esModule", { value: true });
  20180. var util = require("../util");
  20181. function assertParamsValid(input, begin, size) {
  20182. util.assert(input.rank === begin.length, "Error in slice" + input.rank + "D: Length of begin " + begin + " must " +
  20183. ("match the rank of the array (" + input.rank + ")."));
  20184. util.assert(input.rank === size.length, "Error in slice" + input.rank + "D: Length of size " + size + " must " +
  20185. ("match the rank of the array (" + input.rank + ")."));
  20186. for (var i = 0; i < input.rank; ++i) {
  20187. util.assert(begin[i] + size[i] <= input.shape[i], "Error in slice" + input.rank + "D: begin[" + i + "] + size[" + i + "] " +
  20188. ("(" + (begin[i] + size[i]) + ") would overflow input.shape[" + i + "] (" + input.shape[i] + ")"));
  20189. }
  20190. }
  20191. exports.assertParamsValid = assertParamsValid;
  20192. function getStridedSlicedInfo(shape, begin, end, strides, beginMask, endMask) {
  20193. if (beginMask === void 0) { beginMask = 0; }
  20194. if (endMask === void 0) { endMask = 0; }
  20195. var startIndex = [];
  20196. var endIndex = [];
  20197. for (var i = 0; i < shape.length; i++) {
  20198. startIndex[i] = startForAxis(beginMask, begin, strides, shape, i);
  20199. endIndex[i] = stopForAxis(endMask, end, strides, shape, i);
  20200. }
  20201. var size = new Array(shape.length).fill(0);
  20202. size = size.map(function (d, i) {
  20203. var count = 0;
  20204. for (var start = startIndex[i]; !(strides[i] > 0 ? start >= endIndex[i] : start <= endIndex[i]); start += strides[i]) {
  20205. count += 1;
  20206. }
  20207. return count;
  20208. });
  20209. return [startIndex, size];
  20210. }
  20211. exports.getStridedSlicedInfo = getStridedSlicedInfo;
  20212. function startForAxis(beginMask, startIndices, strides, inputShape, axis) {
  20213. var start = startIndices[axis];
  20214. if (beginMask & 1 << axis) {
  20215. if (strides[axis] > 0) {
  20216. start = Number.MIN_SAFE_INTEGER;
  20217. }
  20218. else {
  20219. start = Number.MAX_SAFE_INTEGER;
  20220. }
  20221. }
  20222. var axisSize = inputShape[axis];
  20223. if (start < 0) {
  20224. start += axisSize;
  20225. }
  20226. start = util.clamp(0, start, axisSize - 1);
  20227. return start;
  20228. }
  20229. exports.startForAxis = startForAxis;
  20230. function stopForAxis(endMask, stopIndices, strides, inputShape, axis) {
  20231. var stop = stopIndices[axis];
  20232. if (endMask & (1 << axis)) {
  20233. if (strides[axis] > 0) {
  20234. stop = Number.MAX_SAFE_INTEGER;
  20235. }
  20236. else {
  20237. stop = Number.MIN_SAFE_INTEGER;
  20238. }
  20239. }
  20240. var axisSize = inputShape[axis];
  20241. if (stop < 0) {
  20242. stop += axisSize;
  20243. }
  20244. if (strides[axis] > 0) {
  20245. stop = util.clamp(0, stop, axisSize);
  20246. }
  20247. else {
  20248. stop = util.clamp(-1, stop, axisSize - 1);
  20249. }
  20250. return stop;
  20251. }
  20252. exports.stopForAxis = stopForAxis;
  20253. },{"../util":164}],141:[function(require,module,exports){
  20254. "use strict";
  20255. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  20256. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  20257. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  20258. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  20259. return c > 3 && r && Object.defineProperty(target, key, r), r;
  20260. };
  20261. Object.defineProperty(exports, "__esModule", { value: true });
  20262. var doc_1 = require("../doc");
  20263. var globals_1 = require("../globals");
  20264. var util = require("../util");
  20265. var axis_util = require("./axis_util");
  20266. var operation_1 = require("./operation");
  20267. var ops = require("./ops");
  20268. var SoftmaxOps = (function () {
  20269. function SoftmaxOps() {
  20270. }
  20271. SoftmaxOps.softmax = function (logits, dim) {
  20272. if (dim === void 0) { dim = -1; }
  20273. util.assertArgumentsAreTensors({ logits: logits }, 'softmax');
  20274. if (dim === -1) {
  20275. dim = logits.rank - 1;
  20276. }
  20277. if (dim !== logits.rank - 1) {
  20278. throw Error('Softmax along a non-last dimension is not yet supported. ' +
  20279. ("Logits was rank " + logits.rank + " and dim was " + dim));
  20280. }
  20281. var customOp = globals_1.customGrad(function (logits) {
  20282. var keepDims = true;
  20283. var lse = logits.logSumExp([dim], keepDims);
  20284. var logResult = logits.toFloat().sub(lse);
  20285. var y = logResult.exp();
  20286. var gradFunc = function (dy) {
  20287. var dyTimesY = dy.mul(y);
  20288. var keepDims = true;
  20289. return dyTimesY.sub(dyTimesY.sum([dim], keepDims).mul(y));
  20290. };
  20291. return { value: y, gradFunc: gradFunc };
  20292. });
  20293. return customOp(logits);
  20294. };
  20295. SoftmaxOps.softmaxCrossEntropy = function (labels, logits, dim) {
  20296. if (dim === void 0) { dim = -1; }
  20297. util.assertArgumentsAreTensors({ labels: labels, logits: logits }, 'softmaxCrossEntropy');
  20298. util.assertShapesMatch(labels.shape, logits.shape, 'Error in softmaxCrossEntropy: ');
  20299. if (dim === -1) {
  20300. dim = logits.rank - 1;
  20301. }
  20302. if (dim !== logits.rank - 1) {
  20303. throw Error("Softmax cross entropy along a non-last dimension is not yet " +
  20304. ("supported. Labels / logits was rank " + logits.rank + " ") +
  20305. ("and dim was " + dim));
  20306. }
  20307. var customOp = globals_1.customGrad(function (labels, logits) {
  20308. var predictedProbs = logits.softmax(dim);
  20309. var costVector = ops.scalar(1e-5).add(predictedProbs).log().mul(labels).neg();
  20310. var value = costVector.sum([dim]);
  20311. var gradFunc = function (dy) {
  20312. var dyShape = axis_util.expandShapeToKeepDim(dy.shape, [dim]);
  20313. return [
  20314. dy.reshape(dyShape).mul(labels.toFloat().sub(predictedProbs)),
  20315. dy.reshape(dyShape).mul(predictedProbs.sub(labels.toFloat())),
  20316. ];
  20317. };
  20318. return { value: value, gradFunc: gradFunc };
  20319. });
  20320. return customOp(labels, logits);
  20321. };
  20322. __decorate([
  20323. doc_1.doc({ heading: 'Operations', subheading: 'Normalization' }),
  20324. operation_1.operation
  20325. ], SoftmaxOps, "softmax", null);
  20326. __decorate([
  20327. doc_1.doc({ heading: 'Training', subheading: 'Losses', namespace: 'losses' }),
  20328. operation_1.operation
  20329. ], SoftmaxOps, "softmaxCrossEntropy", null);
  20330. return SoftmaxOps;
  20331. }());
  20332. exports.SoftmaxOps = SoftmaxOps;
  20333. },{"../doc":49,"../globals":52,"../util":164,"./axis_util":109,"./operation":128,"./ops":129}],142:[function(require,module,exports){
  20334. "use strict";
  20335. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  20336. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  20337. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  20338. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  20339. return c > 3 && r && Object.defineProperty(target, key, r), r;
  20340. };
  20341. Object.defineProperty(exports, "__esModule", { value: true });
  20342. var doc_1 = require("../doc");
  20343. var environment_1 = require("../environment");
  20344. var util = require("../util");
  20345. var operation_1 = require("./operation");
  20346. var StridedSliceOps = (function () {
  20347. function StridedSliceOps() {
  20348. }
  20349. StridedSliceOps.stridedSlice = function (x, begin, end, strides, beginMask, endMask) {
  20350. if (beginMask === void 0) { beginMask = 0; }
  20351. if (endMask === void 0) { endMask = 0; }
  20352. util.assertArgumentsAreTensors({ x: x }, 'stridedSlice');
  20353. return environment_1.ENV.engine.runKernel(function (backend) { return backend.stridedSlice(x, begin, end, strides, beginMask, endMask); }, { x: x });
  20354. };
  20355. __decorate([
  20356. doc_1.doc({ heading: 'Operations', subheading: 'Slicing and Joining' }),
  20357. operation_1.operation
  20358. ], StridedSliceOps, "stridedSlice", null);
  20359. return StridedSliceOps;
  20360. }());
  20361. exports.StridedSliceOps = StridedSliceOps;
  20362. },{"../doc":49,"../environment":51,"../util":164,"./operation":128}],143:[function(require,module,exports){
  20363. "use strict";
  20364. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  20365. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  20366. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  20367. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  20368. return c > 3 && r && Object.defineProperty(target, key, r), r;
  20369. };
  20370. Object.defineProperty(exports, "__esModule", { value: true });
  20371. var doc_1 = require("../doc");
  20372. var environment_1 = require("../environment");
  20373. var util = require("../util");
  20374. var axis_util = require("./axis_util");
  20375. var operation_1 = require("./operation");
  20376. var TransposeOps = (function () {
  20377. function TransposeOps() {
  20378. }
  20379. TransposeOps.transpose = function (x, perm) {
  20380. util.assertArgumentsAreTensors({ x: x }, 'transpose');
  20381. if (perm == null) {
  20382. perm = x.shape.map(function (s, i) { return i; }).reverse();
  20383. }
  20384. util.assert(x.rank === perm.length, "Error in transpose: rank of input " + x.rank + " " +
  20385. ("must match length of perm " + perm + "."));
  20386. perm.forEach(function (axis) {
  20387. util.assert(axis >= 0 && axis < x.rank, "All entries in 'perm' must be between 0 and " + (x.rank - 1) +
  20388. (" but got " + perm));
  20389. });
  20390. if (x.rank <= 1) {
  20391. return x.clone();
  20392. }
  20393. var der = function (dy) {
  20394. var undoPerm = axis_util.getUndoAxesPermutation(perm);
  20395. return { x: function () { return dy.transpose(undoPerm); } };
  20396. };
  20397. return environment_1.ENV.engine.runKernel(function (backend) { return backend.transpose(x, perm); }, { x: x }, der);
  20398. };
  20399. __decorate([
  20400. doc_1.doc({ heading: 'Operations', subheading: 'Matrices' }),
  20401. operation_1.operation
  20402. ], TransposeOps, "transpose", null);
  20403. return TransposeOps;
  20404. }());
  20405. exports.TransposeOps = TransposeOps;
  20406. },{"../doc":49,"../environment":51,"../util":164,"./axis_util":109,"./operation":128}],144:[function(require,module,exports){
  20407. "use strict";
  20408. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  20409. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  20410. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  20411. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  20412. return c > 3 && r && Object.defineProperty(target, key, r), r;
  20413. };
  20414. Object.defineProperty(exports, "__esModule", { value: true });
  20415. var doc_1 = require("../doc");
  20416. var environment_1 = require("../environment");
  20417. var util = require("../util");
  20418. var operation_1 = require("./operation");
  20419. var ops = require("./ops");
  20420. var ops_1 = require("./ops");
  20421. var selu_util = require("./selu_util");
  20422. var UnaryOps = (function () {
  20423. function UnaryOps() {
  20424. }
  20425. UnaryOps.neg = function (x) {
  20426. util.assertArgumentsAreTensors({ x: x }, 'neg');
  20427. var grad = function (dy) {
  20428. return { x: function () { return dy.neg(); } };
  20429. };
  20430. return environment_1.ENV.engine.runKernel(function (backend) { return backend.neg(x); }, { x: x }, grad);
  20431. };
  20432. UnaryOps.ceil = function (x) {
  20433. util.assertArgumentsAreTensors({ x: x }, 'ceil');
  20434. var grad = function (dy) {
  20435. return { x: function () { return ops.zerosLike(dy); } };
  20436. };
  20437. return environment_1.ENV.engine.runKernel(function (backend) { return backend.ceil(x); }, { x: x }, grad);
  20438. };
  20439. UnaryOps.floor = function (x) {
  20440. util.assertArgumentsAreTensors({ x: x }, 'floor');
  20441. var grad = function (dy) {
  20442. return { x: function () { return ops.zerosLike(dy); } };
  20443. };
  20444. return environment_1.ENV.engine.runKernel(function (backend) { return backend.floor(x); }, { x: x }, grad);
  20445. };
  20446. UnaryOps.sign = function (x) {
  20447. util.assertArgumentsAreTensors({ x: x }, 'sign');
  20448. var grad = function (dy) {
  20449. return { x: function () { return ops.zerosLike(dy); } };
  20450. };
  20451. return environment_1.ENV.engine.runKernel(function (backend) { return backend.sign(x); }, { x: x }, grad);
  20452. };
  20453. UnaryOps.round = function (x) {
  20454. util.assertArgumentsAreTensors({ x: x }, 'round');
  20455. var grad = function (dy) {
  20456. return { x: function () { return ops.zerosLike(dy); } };
  20457. };
  20458. return environment_1.ENV.engine.runKernel(function (backend) { return backend.round(x); }, { x: x }, grad);
  20459. };
  20460. UnaryOps.exp = function (x) {
  20461. util.assertArgumentsAreTensors({ x: x }, 'exp');
  20462. var bck = function (dy, saved) {
  20463. var y = saved[0];
  20464. return { x: function () { return dy.mulStrict(y); } };
  20465. };
  20466. return environment_1.ENV.engine.runKernel(function (backend, save) { return save(backend.exp(x)); }, { x: x }, bck);
  20467. };
  20468. UnaryOps.expm1 = function (x) {
  20469. util.assertArgumentsAreTensors({ x: x }, 'expm1');
  20470. var grad = function (dy) {
  20471. return { x: function () { return dy.mulStrict(x.exp()); } };
  20472. };
  20473. return environment_1.ENV.engine.runKernel(function (backend) { return backend.expm1(x); }, { x: x }, grad);
  20474. };
  20475. UnaryOps.log = function (x) {
  20476. util.assertArgumentsAreTensors({ x: x }, 'log');
  20477. var grad = function (dy) {
  20478. return { x: function () { return dy.divStrict(x.toFloat()); } };
  20479. };
  20480. return environment_1.ENV.engine.runKernel(function (backend) { return backend.log(x); }, { x: x }, grad);
  20481. };
  20482. UnaryOps.log1p = function (x) {
  20483. util.assertArgumentsAreTensors({ x: x }, 'log1p');
  20484. var grad = function (dy) {
  20485. return { x: function () { return dy.divStrict(x.add(ops.scalar(1))); } };
  20486. };
  20487. return environment_1.ENV.engine.runKernel(function (backend) { return backend.log1p(x); }, { x: x }, grad);
  20488. };
  20489. UnaryOps.sqrt = function (x) {
  20490. util.assertArgumentsAreTensors({ x: x }, 'sqrt');
  20491. var grad = function (dy) {
  20492. return { x: function () { return dy.divStrict(x.toFloat().sqrt().mul(ops.scalar(2))); } };
  20493. };
  20494. return environment_1.ENV.engine.runKernel(function (backend) { return backend.sqrt(x); }, { x: x }, grad);
  20495. };
  20496. UnaryOps.rsqrt = function (x) {
  20497. util.assertArgumentsAreTensors({ x: x }, 'rsqrt');
  20498. var grad = function (dy) {
  20499. return {
  20500. x: function () { return dy.divStrict(x.pow(ops.scalar(1.5)).mul(ops.scalar(2))).neg(); }
  20501. };
  20502. };
  20503. return environment_1.ENV.engine.runKernel(function (backend) { return backend.rsqrt(x); }, { x: x }, grad);
  20504. };
  20505. UnaryOps.square = function (x) {
  20506. util.assertArgumentsAreTensors({ x: x }, 'square');
  20507. var grad = function (dy) {
  20508. return { x: function () { return dy.mulStrict(x.toFloat().mul(ops.scalar(2))); } };
  20509. };
  20510. return environment_1.ENV.engine.runKernel(function (backend) { return backend.square(x); }, { x: x }, grad);
  20511. };
  20512. UnaryOps.reciprocal = function (x) {
  20513. util.assertArgumentsAreTensors({ x: x }, 'reciprocal');
  20514. var grad = function (dy) {
  20515. return { x: function () { return dy.divStrict(x.square().neg()); } };
  20516. };
  20517. return environment_1.ENV.engine.runKernel(function (backend) { return backend.reciprocal(x); }, { x: x }, grad);
  20518. };
  20519. UnaryOps.abs = function (x) {
  20520. util.assertArgumentsAreTensors({ x: x }, 'abs');
  20521. var grad = function (dy) {
  20522. return { x: function () { return dy.mulStrict(x.toFloat().step(-1)); } };
  20523. };
  20524. return environment_1.ENV.engine.runKernel(function (backend) { return backend.abs(x); }, { x: x }, grad);
  20525. };
  20526. UnaryOps.clipByValue = function (x, clipValueMin, clipValueMax) {
  20527. util.assertArgumentsAreTensors({ x: x }, 'clipByValue');
  20528. util.assert((clipValueMin <= clipValueMax), "Error in clip: min (" + clipValueMin + ") must be " +
  20529. ("less than or equal to max (" + clipValueMax + ")."));
  20530. var grad = function (dy) {
  20531. return {
  20532. x: function () { return dy.where(x.greaterEqual(ops.scalar(clipValueMin))
  20533. .logicalAnd(x.lessEqual(ops.scalar(clipValueMax))), ops_1.zerosLike(dy)); },
  20534. };
  20535. };
  20536. return environment_1.ENV.engine.runKernel(function (backend) { return backend.clip(x, clipValueMin, clipValueMax); }, { x: x }, grad);
  20537. };
  20538. UnaryOps.relu = function (x) {
  20539. util.assertArgumentsAreTensors({ x: x }, 'relu');
  20540. if (x.dtype === 'bool') {
  20541. return x.toInt();
  20542. }
  20543. var grad = function (dy) {
  20544. var stepRes = x.step();
  20545. return { x: function () { return dy.mulStrict(stepRes.toFloat()); } };
  20546. };
  20547. return environment_1.ENV.engine.runKernel(function (backend) { return backend.relu(x); }, { x: x }, grad);
  20548. };
  20549. UnaryOps.elu = function (x) {
  20550. util.assertArgumentsAreTensors({ x: x }, 'elu');
  20551. var grad = function (dy, saved) {
  20552. var y = saved[0];
  20553. return {
  20554. x: function () {
  20555. return environment_1.ENV.engine.runKernel(function (backend) { return backend.eluDer(dy, y); }, { dy: dy, y: y });
  20556. }
  20557. };
  20558. };
  20559. return environment_1.ENV.engine.runKernel(function (backend, save) { return save(backend.elu(x)); }, { x: x }, grad);
  20560. };
  20561. UnaryOps.selu = function (x) {
  20562. util.assertArgumentsAreTensors({ x: x }, 'selu');
  20563. var grad = function (dy) {
  20564. return {
  20565. x: function () {
  20566. var mask = x.greater(ops.scalar(0));
  20567. var scaleAlpha = ops.scalar(selu_util.SELU_SCALEALPHA);
  20568. var scale = ops.scalar(selu_util.SELU_SCALE);
  20569. var greaterThanZeroDer = dy.mul(scale);
  20570. var lessEqualZeroDer = dy.mul(scaleAlpha).mul(x.toFloat().exp());
  20571. return ops.where(mask, greaterThanZeroDer, lessEqualZeroDer);
  20572. }
  20573. };
  20574. };
  20575. return environment_1.ENV.engine.runKernel(function (backend) { return backend.selu(x); }, { x: x }, grad);
  20576. };
  20577. UnaryOps.leakyRelu = function (x, alpha) {
  20578. if (alpha === void 0) { alpha = 0.2; }
  20579. util.assertArgumentsAreTensors({ x: x }, 'leakyRelu');
  20580. return ops.maximum(ops.scalar(alpha).mul(x), x);
  20581. };
  20582. UnaryOps.prelu = function (x, alpha) {
  20583. util.assertArgumentsAreTensors({ x: x, alpha: alpha }, 'prelu');
  20584. var zero = ops.scalar(0);
  20585. return ops.maximum(zero, x).add(alpha.mul(ops.minimum(zero, x)));
  20586. };
  20587. UnaryOps.sigmoid = function (x) {
  20588. util.assertArgumentsAreTensors({ x: x }, 'sigmoid');
  20589. var grad = function (dy, saved) {
  20590. var y = saved[0];
  20591. return { x: function () { return dy.mulStrict(y.mul(ops.scalar(1).sub(y))); } };
  20592. };
  20593. return environment_1.ENV.engine.runKernel(function (backend, save) { return save(backend.sigmoid(x)); }, { x: x }, grad);
  20594. };
  20595. UnaryOps.logSigmoid = function (x) {
  20596. util.assertArgumentsAreTensors({ x: x }, 'logSigmoid');
  20597. var grad = function (dy) {
  20598. return { x: function () { return dy.mulStrict(x.neg().sigmoid()); } };
  20599. };
  20600. return environment_1.ENV.engine.runKernel(function (backend) { return backend.softplus(x.neg()).neg(); }, { x: x }, grad);
  20601. };
  20602. UnaryOps.softplus = function (x) {
  20603. util.assertArgumentsAreTensors({ x: x }, 'softplus');
  20604. var grad = function (dy) {
  20605. return { x: function () { return dy.mulStrict(x.sigmoid()); } };
  20606. };
  20607. return environment_1.ENV.engine.runKernel(function (backend) { return backend.softplus(x); }, { x: x }, grad);
  20608. };
  20609. UnaryOps.sin = function (x) {
  20610. util.assertArgumentsAreTensors({ x: x }, 'sin');
  20611. var grad = function (dy) {
  20612. return { x: function () { return x.toFloat().cos().mulStrict(dy); } };
  20613. };
  20614. return environment_1.ENV.engine.runKernel(function (backend) { return backend.sin(x); }, { x: x }, grad);
  20615. };
  20616. UnaryOps.cos = function (x) {
  20617. util.assertArgumentsAreTensors({ x: x }, 'cos');
  20618. var grad = function (dy) {
  20619. return { x: function () { return x.toFloat().sin().neg().mulStrict(dy); } };
  20620. };
  20621. return environment_1.ENV.engine.runKernel(function (backend) { return backend.cos(x); }, { x: x }, grad);
  20622. };
  20623. UnaryOps.tan = function (x) {
  20624. util.assertArgumentsAreTensors({ x: x }, 'tan');
  20625. var grad = function (dy) {
  20626. return { x: function () { return dy.divStrict(x.cos().square()); } };
  20627. };
  20628. return environment_1.ENV.engine.runKernel(function (backend) { return backend.tan(x); }, { x: x }, grad);
  20629. };
  20630. UnaryOps.asin = function (x) {
  20631. util.assertArgumentsAreTensors({ x: x }, 'asin');
  20632. var grad = function (dy) {
  20633. return {
  20634. x: function () {
  20635. return dy.divStrict(UnaryOps.sqrt(ops.scalar(1).sub(x.toFloat().square())));
  20636. }
  20637. };
  20638. };
  20639. return environment_1.ENV.engine.runKernel(function (backend) { return backend.asin(x); }, { x: x }, grad);
  20640. };
  20641. UnaryOps.acos = function (x) {
  20642. util.assertArgumentsAreTensors({ x: x }, 'acos');
  20643. var grad = function (dy) {
  20644. return {
  20645. x: function () {
  20646. return dy.divStrict(UnaryOps.sqrt(ops.scalar(1).sub(x.toFloat().square())))
  20647. .neg();
  20648. }
  20649. };
  20650. };
  20651. return environment_1.ENV.engine.runKernel(function (backend) { return backend.acos(x); }, { x: x }, grad);
  20652. };
  20653. UnaryOps.atan = function (x) {
  20654. util.assertArgumentsAreTensors({ x: x }, 'atan');
  20655. var grad = function (dy) {
  20656. return { x: function () { return dy.divStrict(ops.scalar(1).add(x.toFloat().square())); } };
  20657. };
  20658. return environment_1.ENV.engine.runKernel(function (backend) { return backend.atan(x); }, { x: x }, grad);
  20659. };
  20660. UnaryOps.sinh = function (x) {
  20661. util.assertArgumentsAreTensors({ x: x }, 'sinh');
  20662. var grad = function (dy) {
  20663. return { x: function () { return x.toFloat().cosh().mulStrict(dy); } };
  20664. };
  20665. return environment_1.ENV.engine.runKernel(function (backend) { return backend.sinh(x); }, { x: x }, grad);
  20666. };
  20667. UnaryOps.cosh = function (x) {
  20668. util.assertArgumentsAreTensors({ x: x }, 'cosh');
  20669. var grad = function (dy) {
  20670. return { x: function () { return x.toFloat().sinh().mulStrict(dy); } };
  20671. };
  20672. return environment_1.ENV.engine.runKernel(function (backend) { return backend.cosh(x); }, { x: x }, grad);
  20673. };
  20674. UnaryOps.tanh = function (x) {
  20675. util.assertArgumentsAreTensors({ x: x }, 'tanh');
  20676. var grad = function (dy, saved) {
  20677. var y = saved[0];
  20678. return { x: function () { return ops.scalar(1).sub(y.square()).mulStrict(dy); } };
  20679. };
  20680. return environment_1.ENV.engine.runKernel(function (backend, save) { return save(backend.tanh(x)); }, { x: x }, grad);
  20681. };
  20682. UnaryOps.asinh = function (x) {
  20683. util.assertArgumentsAreTensors({ x: x }, 'asinh');
  20684. var grad = function (dy) {
  20685. return {
  20686. x: function () {
  20687. return dy.divStrict(UnaryOps.sqrt(ops.scalar(1).add(x.toFloat().square())));
  20688. }
  20689. };
  20690. };
  20691. return environment_1.ENV.engine.runKernel(function (backend) { return backend.asinh(x); }, { x: x }, grad);
  20692. };
  20693. UnaryOps.acosh = function (x) {
  20694. util.assertArgumentsAreTensors({ x: x }, 'acosh');
  20695. var grad = function (dy) {
  20696. return {
  20697. x: function () {
  20698. return dy.divStrict(UnaryOps.sqrt(x.toFloat().square().sub(ops.scalar(1))));
  20699. }
  20700. };
  20701. };
  20702. return environment_1.ENV.engine.runKernel(function (backend) { return backend.acosh(x); }, { x: x }, grad);
  20703. };
  20704. UnaryOps.atanh = function (x) {
  20705. util.assertArgumentsAreTensors({ x: x }, 'atanh');
  20706. var grad = function (dy) {
  20707. return { x: function () { return dy.divStrict(ops.scalar(1).sub(x.toFloat().square())); } };
  20708. };
  20709. return environment_1.ENV.engine.runKernel(function (backend) { return backend.atanh(x); }, { x: x }, grad);
  20710. };
  20711. UnaryOps.erf = function (x) {
  20712. util.assert(x.dtype === 'int32' || x.dtype === 'float32', 'Input dtype must be `int32` or `float32`.');
  20713. if (x.dtype === 'int32') {
  20714. x = x.toFloat();
  20715. }
  20716. var grad = function (dy) {
  20717. return {
  20718. x: function () {
  20719. return dy.mulStrict(ops.scalar(2 / Math.sqrt(Math.PI))
  20720. .mul(x.square().neg().exp()));
  20721. }
  20722. };
  20723. };
  20724. return environment_1.ENV.engine.runKernel(function (backend) { return backend.erf(x); }, { x: x }, grad);
  20725. };
  20726. UnaryOps.step = function (x, alpha) {
  20727. if (alpha === void 0) { alpha = 0.0; }
  20728. util.assertArgumentsAreTensors({ x: x }, 'step');
  20729. var grad = function (dy) {
  20730. return { x: function () { return ops.zerosLike(dy); } };
  20731. };
  20732. return environment_1.ENV.engine.runKernel(function (backend) { return backend.step(x, alpha); }, { x: x }, grad);
  20733. };
  20734. __decorate([
  20735. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20736. operation_1.operation
  20737. ], UnaryOps, "neg", null);
  20738. __decorate([
  20739. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20740. operation_1.operation
  20741. ], UnaryOps, "ceil", null);
  20742. __decorate([
  20743. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20744. operation_1.operation
  20745. ], UnaryOps, "floor", null);
  20746. __decorate([
  20747. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20748. operation_1.operation
  20749. ], UnaryOps, "sign", null);
  20750. __decorate([
  20751. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20752. operation_1.operation
  20753. ], UnaryOps, "round", null);
  20754. __decorate([
  20755. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20756. operation_1.operation
  20757. ], UnaryOps, "exp", null);
  20758. __decorate([
  20759. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20760. operation_1.operation
  20761. ], UnaryOps, "expm1", null);
  20762. __decorate([
  20763. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20764. operation_1.operation
  20765. ], UnaryOps, "log", null);
  20766. __decorate([
  20767. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20768. operation_1.operation
  20769. ], UnaryOps, "log1p", null);
  20770. __decorate([
  20771. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20772. operation_1.operation
  20773. ], UnaryOps, "sqrt", null);
  20774. __decorate([
  20775. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20776. operation_1.operation
  20777. ], UnaryOps, "rsqrt", null);
  20778. __decorate([
  20779. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20780. operation_1.operation
  20781. ], UnaryOps, "square", null);
  20782. __decorate([
  20783. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20784. operation_1.operation
  20785. ], UnaryOps, "reciprocal", null);
  20786. __decorate([
  20787. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20788. operation_1.operation
  20789. ], UnaryOps, "abs", null);
  20790. __decorate([
  20791. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20792. operation_1.operation
  20793. ], UnaryOps, "clipByValue", null);
  20794. __decorate([
  20795. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20796. operation_1.operation
  20797. ], UnaryOps, "relu", null);
  20798. __decorate([
  20799. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20800. operation_1.operation
  20801. ], UnaryOps, "elu", null);
  20802. __decorate([
  20803. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20804. operation_1.operation
  20805. ], UnaryOps, "selu", null);
  20806. __decorate([
  20807. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20808. operation_1.operation
  20809. ], UnaryOps, "leakyRelu", null);
  20810. __decorate([
  20811. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20812. operation_1.operation
  20813. ], UnaryOps, "prelu", null);
  20814. __decorate([
  20815. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20816. operation_1.operation
  20817. ], UnaryOps, "sigmoid", null);
  20818. __decorate([
  20819. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20820. operation_1.operation
  20821. ], UnaryOps, "logSigmoid", null);
  20822. __decorate([
  20823. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20824. operation_1.operation
  20825. ], UnaryOps, "softplus", null);
  20826. __decorate([
  20827. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20828. operation_1.operation
  20829. ], UnaryOps, "sin", null);
  20830. __decorate([
  20831. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20832. operation_1.operation
  20833. ], UnaryOps, "cos", null);
  20834. __decorate([
  20835. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20836. operation_1.operation
  20837. ], UnaryOps, "tan", null);
  20838. __decorate([
  20839. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20840. operation_1.operation
  20841. ], UnaryOps, "asin", null);
  20842. __decorate([
  20843. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20844. operation_1.operation
  20845. ], UnaryOps, "acos", null);
  20846. __decorate([
  20847. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20848. operation_1.operation
  20849. ], UnaryOps, "atan", null);
  20850. __decorate([
  20851. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20852. operation_1.operation
  20853. ], UnaryOps, "sinh", null);
  20854. __decorate([
  20855. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20856. operation_1.operation
  20857. ], UnaryOps, "cosh", null);
  20858. __decorate([
  20859. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20860. operation_1.operation
  20861. ], UnaryOps, "tanh", null);
  20862. __decorate([
  20863. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20864. operation_1.operation
  20865. ], UnaryOps, "asinh", null);
  20866. __decorate([
  20867. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20868. operation_1.operation
  20869. ], UnaryOps, "acosh", null);
  20870. __decorate([
  20871. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20872. operation_1.operation
  20873. ], UnaryOps, "atanh", null);
  20874. __decorate([
  20875. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20876. operation_1.operation
  20877. ], UnaryOps, "erf", null);
  20878. __decorate([
  20879. doc_1.doc({ heading: 'Operations', subheading: 'Basic math' }),
  20880. operation_1.operation
  20881. ], UnaryOps, "step", null);
  20882. return UnaryOps;
  20883. }());
  20884. exports.UnaryOps = UnaryOps;
  20885. },{"../doc":49,"../environment":51,"../util":164,"./operation":128,"./ops":129,"./selu_util":137}],145:[function(require,module,exports){
  20886. "use strict";
  20887. var __extends = (this && this.__extends) || (function () {
  20888. var extendStatics = Object.setPrototypeOf ||
  20889. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  20890. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  20891. return function (d, b) {
  20892. extendStatics(d, b);
  20893. function __() { this.constructor = d; }
  20894. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  20895. };
  20896. })();
  20897. Object.defineProperty(exports, "__esModule", { value: true });
  20898. var environment_1 = require("../environment");
  20899. var globals_1 = require("../globals");
  20900. var ops_1 = require("../ops/ops");
  20901. var serialization_1 = require("../serialization");
  20902. var optimizer_1 = require("./optimizer");
  20903. var optimizer_utils = require("./optimizer_utils");
  20904. var AdadeltaOptimizer = (function (_super) {
  20905. __extends(AdadeltaOptimizer, _super);
  20906. function AdadeltaOptimizer(learningRate, rho, epsilon) {
  20907. if (epsilon === void 0) { epsilon = null; }
  20908. var _this = _super.call(this) || this;
  20909. _this.learningRate = learningRate;
  20910. _this.rho = rho;
  20911. _this.epsilon = epsilon;
  20912. _this.accumulatedGrads = {};
  20913. _this.accumulatedUpdates = {};
  20914. _this.c = globals_1.keep(ops_1.scalar(-learningRate));
  20915. _this.rhoScalar = globals_1.keep(ops_1.scalar(rho));
  20916. _this.oneMinusRho = globals_1.keep(ops_1.scalar(1 - rho));
  20917. if (epsilon === null) {
  20918. epsilon = optimizer_utils.getOptimizerDefaultEpsilonValue();
  20919. }
  20920. _this.epsilonScalar = globals_1.keep(ops_1.scalar(epsilon));
  20921. return _this;
  20922. }
  20923. AdadeltaOptimizer.prototype.applyGradients = function (variableGradients) {
  20924. var _this = this;
  20925. var _loop_1 = function (variableName) {
  20926. var value = environment_1.ENV.engine.registeredVariables[variableName];
  20927. if (this_1.accumulatedGrads[variableName] == null) {
  20928. var trainable_1 = false;
  20929. globals_1.tidy(function () {
  20930. _this.accumulatedGrads[variableName] =
  20931. ops_1.zerosLike(value).variable(trainable_1);
  20932. });
  20933. }
  20934. if (this_1.accumulatedUpdates[variableName] == null) {
  20935. var trainable_2 = false;
  20936. globals_1.tidy(function () {
  20937. _this.accumulatedUpdates[variableName] =
  20938. ops_1.zerosLike(value).variable(trainable_2);
  20939. });
  20940. }
  20941. var gradient = variableGradients[variableName];
  20942. var accumulatedGrad = this_1.accumulatedGrads[variableName];
  20943. var accumulatedUpdate = this_1.accumulatedUpdates[variableName];
  20944. globals_1.tidy(function () {
  20945. var newAccumulatedGrad = _this.rhoScalar.mul(accumulatedGrad)
  20946. .add(_this.oneMinusRho.mul(gradient.square()));
  20947. var updates = accumulatedUpdate.add(_this.epsilonScalar)
  20948. .sqrt()
  20949. .div(accumulatedGrad.add(_this.epsilonScalar).sqrt())
  20950. .mul(gradient);
  20951. var newAccumulatedUpdate = _this.rhoScalar.mul(accumulatedUpdate)
  20952. .add(_this.oneMinusRho.mul(updates.square()));
  20953. _this.accumulatedGrads[variableName].assign(newAccumulatedGrad);
  20954. _this.accumulatedUpdates[variableName].assign(newAccumulatedUpdate);
  20955. var newValue = _this.c.mul(updates).add(value);
  20956. value.assign(newValue);
  20957. });
  20958. };
  20959. var this_1 = this;
  20960. for (var variableName in variableGradients) {
  20961. _loop_1(variableName);
  20962. }
  20963. };
  20964. AdadeltaOptimizer.prototype.dispose = function () {
  20965. var _this = this;
  20966. this.c.dispose();
  20967. this.epsilonScalar.dispose();
  20968. this.rhoScalar.dispose();
  20969. this.oneMinusRho.dispose();
  20970. if (this.accumulatedUpdates != null) {
  20971. Object.keys(this.accumulatedUpdates)
  20972. .forEach(function (name) { return _this.accumulatedUpdates[name].dispose(); });
  20973. Object.keys(this.accumulatedGrads)
  20974. .forEach(function (name) { return _this.accumulatedGrads[name].dispose(); });
  20975. }
  20976. };
  20977. AdadeltaOptimizer.prototype.getConfig = function () {
  20978. return {
  20979. learningRate: this.learningRate,
  20980. rho: this.rho,
  20981. epsilon: this.epsilon
  20982. };
  20983. };
  20984. AdadeltaOptimizer.fromConfig = function (cls, config) {
  20985. return new cls(config.learningRate, config.rho, config.epsilon);
  20986. };
  20987. AdadeltaOptimizer.className = 'AdadeltaOptimizer';
  20988. return AdadeltaOptimizer;
  20989. }(optimizer_1.Optimizer));
  20990. exports.AdadeltaOptimizer = AdadeltaOptimizer;
  20991. serialization_1.SerializationMap.register(AdadeltaOptimizer);
  20992. },{"../environment":51,"../globals":52,"../ops/ops":129,"../serialization":156,"./optimizer":150,"./optimizer_utils":152}],146:[function(require,module,exports){
  20993. "use strict";
  20994. var __extends = (this && this.__extends) || (function () {
  20995. var extendStatics = Object.setPrototypeOf ||
  20996. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  20997. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  20998. return function (d, b) {
  20999. extendStatics(d, b);
  21000. function __() { this.constructor = d; }
  21001. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  21002. };
  21003. })();
  21004. Object.defineProperty(exports, "__esModule", { value: true });
  21005. var environment_1 = require("../environment");
  21006. var globals_1 = require("../globals");
  21007. var ops_1 = require("../ops/ops");
  21008. var serialization_1 = require("../serialization");
  21009. var optimizer_1 = require("./optimizer");
  21010. var optimizer_utils = require("./optimizer_utils");
  21011. var AdagradOptimizer = (function (_super) {
  21012. __extends(AdagradOptimizer, _super);
  21013. function AdagradOptimizer(learningRate, initialAccumulatorValue) {
  21014. if (initialAccumulatorValue === void 0) { initialAccumulatorValue = 0.1; }
  21015. var _this = _super.call(this) || this;
  21016. _this.learningRate = learningRate;
  21017. _this.initialAccumulatorValue = initialAccumulatorValue;
  21018. _this.accumulatedGrads = {};
  21019. _this.c = globals_1.keep(ops_1.scalar(-learningRate));
  21020. var epsilon = optimizer_utils.getOptimizerDefaultEpsilonValue();
  21021. _this.epsilon = globals_1.keep(ops_1.scalar(epsilon));
  21022. return _this;
  21023. }
  21024. AdagradOptimizer.prototype.applyGradients = function (variableGradients) {
  21025. var _this = this;
  21026. var _loop_1 = function (variableName) {
  21027. var value = environment_1.ENV.engine.registeredVariables[variableName];
  21028. if (this_1.accumulatedGrads[variableName] == null) {
  21029. var trainable_1 = false;
  21030. globals_1.tidy(function () {
  21031. _this.accumulatedGrads[variableName] =
  21032. ops_1.fill(value.shape, _this.initialAccumulatorValue)
  21033. .variable(trainable_1);
  21034. });
  21035. }
  21036. var gradient = variableGradients[variableName];
  21037. var accumulatedGrad = this_1.accumulatedGrads[variableName];
  21038. globals_1.tidy(function () {
  21039. var newAccumulatedGrad = accumulatedGrad.add(gradient.square());
  21040. _this.accumulatedGrads[variableName].assign(newAccumulatedGrad);
  21041. var newValue = _this.c
  21042. .mul(gradient.div(newAccumulatedGrad.add(_this.epsilon).sqrt()))
  21043. .add(value);
  21044. value.assign(newValue);
  21045. });
  21046. };
  21047. var this_1 = this;
  21048. for (var variableName in variableGradients) {
  21049. _loop_1(variableName);
  21050. }
  21051. };
  21052. AdagradOptimizer.prototype.dispose = function () {
  21053. var _this = this;
  21054. this.epsilon.dispose();
  21055. this.c.dispose();
  21056. if (this.accumulatedGrads != null) {
  21057. Object.keys(this.accumulatedGrads)
  21058. .forEach(function (name) { return _this.accumulatedGrads[name].dispose(); });
  21059. }
  21060. };
  21061. AdagradOptimizer.prototype.getConfig = function () {
  21062. return {
  21063. learningRate: this.learningRate,
  21064. initialAccumulatorValue: this.initialAccumulatorValue,
  21065. };
  21066. };
  21067. AdagradOptimizer.fromConfig = function (cls, config) {
  21068. return new cls(config.learningRate, config.initialAccumulatorValue);
  21069. };
  21070. AdagradOptimizer.className = 'AdagradOptimizer';
  21071. return AdagradOptimizer;
  21072. }(optimizer_1.Optimizer));
  21073. exports.AdagradOptimizer = AdagradOptimizer;
  21074. serialization_1.SerializationMap.register(AdagradOptimizer);
  21075. },{"../environment":51,"../globals":52,"../ops/ops":129,"../serialization":156,"./optimizer":150,"./optimizer_utils":152}],147:[function(require,module,exports){
  21076. "use strict";
  21077. var __extends = (this && this.__extends) || (function () {
  21078. var extendStatics = Object.setPrototypeOf ||
  21079. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  21080. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  21081. return function (d, b) {
  21082. extendStatics(d, b);
  21083. function __() { this.constructor = d; }
  21084. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  21085. };
  21086. })();
  21087. Object.defineProperty(exports, "__esModule", { value: true });
  21088. var environment_1 = require("../environment");
  21089. var globals_1 = require("../globals");
  21090. var ops_1 = require("../ops/ops");
  21091. var serialization_1 = require("../serialization");
  21092. var optimizer_1 = require("./optimizer");
  21093. var optimizer_utils = require("./optimizer_utils");
  21094. var AdamOptimizer = (function (_super) {
  21095. __extends(AdamOptimizer, _super);
  21096. function AdamOptimizer(learningRate, beta1, beta2, epsilon) {
  21097. if (epsilon === void 0) { epsilon = null; }
  21098. var _this = _super.call(this) || this;
  21099. _this.learningRate = learningRate;
  21100. _this.beta1 = beta1;
  21101. _this.beta2 = beta2;
  21102. _this.epsilon = epsilon;
  21103. _this.accumulatedFirstMoment = {};
  21104. _this.accumulatedSecondMoment = {};
  21105. _this.c = globals_1.keep(ops_1.scalar(-learningRate));
  21106. _this.beta1Scalar = globals_1.keep(ops_1.scalar(beta1));
  21107. _this.beta2Scalar = globals_1.keep(ops_1.scalar(beta2));
  21108. globals_1.tidy(function () {
  21109. _this.accBeta1 = ops_1.scalar(beta1).variable();
  21110. _this.accBeta2 = ops_1.scalar(beta2).variable();
  21111. });
  21112. _this.oneMinusBeta1 = globals_1.keep(ops_1.scalar(1 - beta1));
  21113. _this.oneMinusBeta2 = globals_1.keep(ops_1.scalar(1 - beta2));
  21114. _this.one = globals_1.keep(ops_1.scalar(1));
  21115. if (epsilon === null) {
  21116. epsilon = optimizer_utils.getOptimizerDefaultEpsilonValue();
  21117. }
  21118. _this.epsScalar = globals_1.keep(ops_1.scalar(epsilon));
  21119. return _this;
  21120. }
  21121. AdamOptimizer.prototype.applyGradients = function (variableGradients) {
  21122. var _this = this;
  21123. globals_1.tidy(function () {
  21124. var oneMinusAccBeta1 = _this.one.sub(_this.accBeta1);
  21125. var oneMinusAccBeta2 = _this.one.sub(_this.accBeta2);
  21126. for (var variableName in variableGradients) {
  21127. var value = environment_1.ENV.engine.registeredVariables[variableName];
  21128. if (_this.accumulatedFirstMoment[variableName] == null) {
  21129. var trainable = false;
  21130. _this.accumulatedFirstMoment[variableName] =
  21131. ops_1.zerosLike(value).variable(trainable);
  21132. }
  21133. if (_this.accumulatedSecondMoment[variableName] == null) {
  21134. var trainable = false;
  21135. _this.accumulatedSecondMoment[variableName] =
  21136. ops_1.zerosLike(value).variable(trainable);
  21137. }
  21138. var gradient = variableGradients[variableName];
  21139. var firstMoment = _this.accumulatedFirstMoment[variableName];
  21140. var secondMoment = _this.accumulatedSecondMoment[variableName];
  21141. var newFirstMoment = _this.beta1Scalar.mul(firstMoment)
  21142. .add(_this.oneMinusBeta1.mul(gradient));
  21143. var newSecondMoment = _this.beta2Scalar.mul(secondMoment)
  21144. .add(_this.oneMinusBeta2.mul(gradient.square()));
  21145. var biasCorrectedFirstMoment = newFirstMoment.div(oneMinusAccBeta1);
  21146. var biasCorrectedSecondMoment = newSecondMoment.div(oneMinusAccBeta2);
  21147. _this.accumulatedFirstMoment[variableName].assign(newFirstMoment);
  21148. _this.accumulatedSecondMoment[variableName].assign(newSecondMoment);
  21149. var newValue = _this.c
  21150. .mul(biasCorrectedFirstMoment.div(_this.epsScalar.add(biasCorrectedSecondMoment.sqrt())))
  21151. .add(value);
  21152. value.assign(newValue);
  21153. }
  21154. _this.accBeta1.assign(_this.accBeta1.mul(_this.beta1Scalar));
  21155. _this.accBeta2.assign(_this.accBeta2.mul(_this.beta2Scalar));
  21156. });
  21157. };
  21158. AdamOptimizer.prototype.dispose = function () {
  21159. var _this = this;
  21160. this.c.dispose();
  21161. this.epsScalar.dispose();
  21162. this.beta1Scalar.dispose();
  21163. this.beta2Scalar.dispose();
  21164. this.accBeta1.dispose();
  21165. this.accBeta2.dispose();
  21166. this.oneMinusBeta1.dispose();
  21167. this.oneMinusBeta2.dispose();
  21168. this.one.dispose();
  21169. if (this.accumulatedFirstMoment != null) {
  21170. Object.keys(this.accumulatedFirstMoment)
  21171. .forEach(function (name) { return _this.accumulatedFirstMoment[name].dispose(); });
  21172. }
  21173. if (this.accumulatedSecondMoment != null) {
  21174. Object.keys(this.accumulatedSecondMoment)
  21175. .forEach(function (name) { return _this.accumulatedSecondMoment[name].dispose(); });
  21176. }
  21177. };
  21178. AdamOptimizer.prototype.getConfig = function () {
  21179. return {
  21180. learningRate: this.learningRate,
  21181. beta1: this.beta1,
  21182. beta2: this.beta2,
  21183. epsilon: this.epsilon,
  21184. };
  21185. };
  21186. AdamOptimizer.fromConfig = function (cls, config) {
  21187. return new cls(config.learningRate, config.beta1, config.beta2, config.epsilon);
  21188. };
  21189. AdamOptimizer.className = 'AdamOptimizer';
  21190. return AdamOptimizer;
  21191. }(optimizer_1.Optimizer));
  21192. exports.AdamOptimizer = AdamOptimizer;
  21193. serialization_1.SerializationMap.register(AdamOptimizer);
  21194. },{"../environment":51,"../globals":52,"../ops/ops":129,"../serialization":156,"./optimizer":150,"./optimizer_utils":152}],148:[function(require,module,exports){
  21195. "use strict";
  21196. var __extends = (this && this.__extends) || (function () {
  21197. var extendStatics = Object.setPrototypeOf ||
  21198. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  21199. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  21200. return function (d, b) {
  21201. extendStatics(d, b);
  21202. function __() { this.constructor = d; }
  21203. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  21204. };
  21205. })();
  21206. Object.defineProperty(exports, "__esModule", { value: true });
  21207. var environment_1 = require("../environment");
  21208. var globals_1 = require("../globals");
  21209. var ops_1 = require("../ops/ops");
  21210. var serialization_1 = require("../serialization");
  21211. var optimizer_1 = require("./optimizer");
  21212. var optimizer_utils = require("./optimizer_utils");
  21213. var AdamaxOptimizer = (function (_super) {
  21214. __extends(AdamaxOptimizer, _super);
  21215. function AdamaxOptimizer(learningRate, beta1, beta2, epsilon, decay) {
  21216. if (epsilon === void 0) { epsilon = null; }
  21217. if (decay === void 0) { decay = 0.0; }
  21218. var _this = _super.call(this) || this;
  21219. _this.learningRate = learningRate;
  21220. _this.beta1 = beta1;
  21221. _this.beta2 = beta2;
  21222. _this.epsilon = epsilon;
  21223. _this.decay = decay;
  21224. _this.accumulatedFirstMoment = {};
  21225. _this.accumulatedWeightedInfNorm = {};
  21226. _this.c = globals_1.keep(ops_1.scalar(-learningRate));
  21227. _this.beta1Scalar = globals_1.keep(ops_1.scalar(beta1));
  21228. _this.beta2Scalar = globals_1.keep(ops_1.scalar(beta2));
  21229. _this.decayScalar = globals_1.keep(ops_1.scalar(decay));
  21230. globals_1.tidy(function () {
  21231. _this.iteration = ops_1.scalar(0).variable();
  21232. _this.accBeta1 = ops_1.scalar(beta1).variable();
  21233. });
  21234. _this.oneMinusBeta1 = globals_1.keep(ops_1.scalar(1 - beta1));
  21235. _this.one = globals_1.keep(ops_1.scalar(1));
  21236. if (epsilon === null) {
  21237. epsilon = optimizer_utils.getOptimizerDefaultEpsilonValue();
  21238. }
  21239. _this.epsScalar = globals_1.keep(ops_1.scalar(epsilon));
  21240. return _this;
  21241. }
  21242. AdamaxOptimizer.prototype.applyGradients = function (variableGradients) {
  21243. var _this = this;
  21244. globals_1.tidy(function () {
  21245. var oneMinusAccBeta1 = _this.one.sub(_this.accBeta1);
  21246. var lr = _this.c.div(_this.one.add(_this.decayScalar.mul(_this.iteration)));
  21247. for (var variableName in variableGradients) {
  21248. var value = environment_1.ENV.engine.registeredVariables[variableName];
  21249. if (_this.accumulatedFirstMoment[variableName] == null) {
  21250. var trainable = false;
  21251. _this.accumulatedFirstMoment[variableName] =
  21252. ops_1.zerosLike(value).variable(trainable);
  21253. }
  21254. if (_this.accumulatedWeightedInfNorm[variableName] == null) {
  21255. var trainable = false;
  21256. _this.accumulatedWeightedInfNorm[variableName] =
  21257. ops_1.zerosLike(value).variable(trainable);
  21258. }
  21259. var gradient = variableGradients[variableName];
  21260. var firstMoment = _this.accumulatedFirstMoment[variableName];
  21261. var weightedInfNorm = _this.accumulatedWeightedInfNorm[variableName];
  21262. var newFirstMoment = _this.beta1Scalar.mul(firstMoment)
  21263. .add(_this.oneMinusBeta1.mul(gradient));
  21264. var ut0 = _this.beta2Scalar.mul(weightedInfNorm);
  21265. var ut1 = gradient.abs();
  21266. var newWeightedInfNorm = ut0.maximum(ut1);
  21267. _this.accumulatedFirstMoment[variableName].assign(newFirstMoment);
  21268. _this.accumulatedWeightedInfNorm[variableName].assign(newWeightedInfNorm);
  21269. var newValue = lr.div(oneMinusAccBeta1)
  21270. .mul(newFirstMoment.div(_this.epsScalar.add(newWeightedInfNorm)))
  21271. .add(value);
  21272. value.assign(newValue);
  21273. }
  21274. _this.iteration.assign(_this.iteration.add(_this.one));
  21275. _this.accBeta1.assign(_this.accBeta1.mul(_this.beta1Scalar));
  21276. });
  21277. };
  21278. AdamaxOptimizer.prototype.dispose = function () {
  21279. var _this = this;
  21280. this.c.dispose();
  21281. this.epsScalar.dispose();
  21282. this.accBeta1.dispose();
  21283. this.beta1Scalar.dispose();
  21284. this.beta2Scalar.dispose();
  21285. this.oneMinusBeta1.dispose();
  21286. this.decayScalar.dispose();
  21287. this.iteration.dispose();
  21288. this.one.dispose();
  21289. if (this.accumulatedFirstMoment != null) {
  21290. Object.keys(this.accumulatedFirstMoment)
  21291. .forEach(function (name) { return _this.accumulatedFirstMoment[name].dispose(); });
  21292. }
  21293. if (this.accumulatedWeightedInfNorm != null) {
  21294. Object.keys(this.accumulatedWeightedInfNorm)
  21295. .forEach(function (name) { return _this.accumulatedWeightedInfNorm[name].dispose(); });
  21296. }
  21297. };
  21298. AdamaxOptimizer.prototype.getConfig = function () {
  21299. return {
  21300. learningRate: this.learningRate,
  21301. beta1: this.beta1,
  21302. beta2: this.beta2,
  21303. epsilon: this.epsilon,
  21304. decay: this.decay
  21305. };
  21306. };
  21307. AdamaxOptimizer.fromConfig = function (cls, config) {
  21308. return new cls(config.learningRate, config.beta1, config.beta2, config.epsilon, config.decay);
  21309. };
  21310. AdamaxOptimizer.className = 'AdamaxOptimizer';
  21311. return AdamaxOptimizer;
  21312. }(optimizer_1.Optimizer));
  21313. exports.AdamaxOptimizer = AdamaxOptimizer;
  21314. serialization_1.SerializationMap.register(AdamaxOptimizer);
  21315. },{"../environment":51,"../globals":52,"../ops/ops":129,"../serialization":156,"./optimizer":150,"./optimizer_utils":152}],149:[function(require,module,exports){
  21316. "use strict";
  21317. var __extends = (this && this.__extends) || (function () {
  21318. var extendStatics = Object.setPrototypeOf ||
  21319. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  21320. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  21321. return function (d, b) {
  21322. extendStatics(d, b);
  21323. function __() { this.constructor = d; }
  21324. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  21325. };
  21326. })();
  21327. Object.defineProperty(exports, "__esModule", { value: true });
  21328. var environment_1 = require("../environment");
  21329. var globals_1 = require("../globals");
  21330. var ops_1 = require("../ops/ops");
  21331. var serialization_1 = require("../serialization");
  21332. var sgd_optimizer_1 = require("./sgd_optimizer");
  21333. var MomentumOptimizer = (function (_super) {
  21334. __extends(MomentumOptimizer, _super);
  21335. function MomentumOptimizer(learningRate, momentum, useNesterov) {
  21336. if (useNesterov === void 0) { useNesterov = false; }
  21337. var _this = _super.call(this, learningRate) || this;
  21338. _this.learningRate = learningRate;
  21339. _this.momentum = momentum;
  21340. _this.useNesterov = useNesterov;
  21341. _this.m = ops_1.scalar(_this.momentum);
  21342. _this.accumulations = {};
  21343. return _this;
  21344. }
  21345. MomentumOptimizer.prototype.applyGradients = function (variableGradients) {
  21346. var _this = this;
  21347. var _loop_1 = function (variableName) {
  21348. var value = environment_1.ENV.engine.registeredVariables[variableName];
  21349. if (this_1.accumulations[variableName] == null) {
  21350. var trainable_1 = false;
  21351. globals_1.tidy(function () {
  21352. _this.accumulations[variableName] =
  21353. ops_1.zerosLike(value).variable(trainable_1);
  21354. });
  21355. }
  21356. var accumulation = this_1.accumulations[variableName];
  21357. var gradient = variableGradients[variableName];
  21358. globals_1.tidy(function () {
  21359. var newValue;
  21360. var newAccumulation = _this.m.mul(accumulation).add(gradient);
  21361. if (_this.useNesterov) {
  21362. newValue =
  21363. _this.c.mul(gradient.add(newAccumulation.mul(_this.m))).add(value);
  21364. }
  21365. else {
  21366. newValue = _this.c.mul(newAccumulation).add(value);
  21367. }
  21368. _this.accumulations[variableName].assign(newAccumulation);
  21369. value.assign(newValue);
  21370. });
  21371. };
  21372. var this_1 = this;
  21373. for (var variableName in variableGradients) {
  21374. _loop_1(variableName);
  21375. }
  21376. };
  21377. MomentumOptimizer.prototype.dispose = function () {
  21378. _super.prototype.dispose.call(this);
  21379. this.m.dispose();
  21380. if (this.accumulations != null) {
  21381. for (var variableName in this.accumulations) {
  21382. this.accumulations[variableName].dispose();
  21383. }
  21384. }
  21385. };
  21386. MomentumOptimizer.prototype.setMomentum = function (momentum) {
  21387. this.momentum = momentum;
  21388. };
  21389. MomentumOptimizer.prototype.getConfig = function () {
  21390. return {
  21391. learningRate: this.learningRate,
  21392. momentum: this.momentum,
  21393. useNesterov: this.useNesterov
  21394. };
  21395. };
  21396. MomentumOptimizer.fromConfig = function (cls, config) {
  21397. return new cls(config.learningRate, config.momentum, config.useNesterov);
  21398. };
  21399. MomentumOptimizer.className = 'MomentumOptimizer';
  21400. return MomentumOptimizer;
  21401. }(sgd_optimizer_1.SGDOptimizer));
  21402. exports.MomentumOptimizer = MomentumOptimizer;
  21403. serialization_1.SerializationMap.register(MomentumOptimizer);
  21404. },{"../environment":51,"../globals":52,"../ops/ops":129,"../serialization":156,"./sgd_optimizer":154}],150:[function(require,module,exports){
  21405. "use strict";
  21406. var __extends = (this && this.__extends) || (function () {
  21407. var extendStatics = Object.setPrototypeOf ||
  21408. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  21409. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  21410. return function (d, b) {
  21411. extendStatics(d, b);
  21412. function __() { this.constructor = d; }
  21413. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  21414. };
  21415. })();
  21416. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  21417. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  21418. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  21419. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  21420. return c > 3 && r && Object.defineProperty(target, key, r), r;
  21421. };
  21422. Object.defineProperty(exports, "__esModule", { value: true });
  21423. var doc_1 = require("../doc");
  21424. var globals_1 = require("../globals");
  21425. var serialization_1 = require("../serialization");
  21426. var Optimizer = (function (_super) {
  21427. __extends(Optimizer, _super);
  21428. function Optimizer() {
  21429. return _super !== null && _super.apply(this, arguments) || this;
  21430. }
  21431. Optimizer.prototype.minimize = function (f, returnCost, varList) {
  21432. if (returnCost === void 0) { returnCost = false; }
  21433. var _a = this.computeGradients(f, varList), value = _a.value, grads = _a.grads;
  21434. this.applyGradients(grads);
  21435. var varNames = Object.keys(grads);
  21436. varNames.forEach(function (varName) { return grads[varName].dispose(); });
  21437. if (returnCost) {
  21438. return value;
  21439. }
  21440. else {
  21441. value.dispose();
  21442. return null;
  21443. }
  21444. };
  21445. Optimizer.prototype.computeGradients = function (f, varList) {
  21446. return globals_1.variableGrads(f, varList);
  21447. };
  21448. __decorate([
  21449. doc_1.doc({ heading: 'Training', subheading: 'Optimizers' })
  21450. ], Optimizer.prototype, "minimize", null);
  21451. Optimizer = __decorate([
  21452. doc_1.doc({ heading: 'Training', subheading: 'Classes', namespace: 'train' })
  21453. ], Optimizer);
  21454. return Optimizer;
  21455. }(serialization_1.Serializable));
  21456. exports.Optimizer = Optimizer;
  21457. },{"../doc":49,"../globals":52,"../serialization":156}],151:[function(require,module,exports){
  21458. "use strict";
  21459. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  21460. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  21461. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  21462. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  21463. return c > 3 && r && Object.defineProperty(target, key, r), r;
  21464. };
  21465. Object.defineProperty(exports, "__esModule", { value: true });
  21466. var doc_1 = require("../doc");
  21467. var adadelta_optimizer_1 = require("./adadelta_optimizer");
  21468. var adagrad_optimizer_1 = require("./adagrad_optimizer");
  21469. var adam_optimizer_1 = require("./adam_optimizer");
  21470. var adamax_optimizer_1 = require("./adamax_optimizer");
  21471. var momentum_optimizer_1 = require("./momentum_optimizer");
  21472. var rmsprop_optimizer_1 = require("./rmsprop_optimizer");
  21473. var sgd_optimizer_1 = require("./sgd_optimizer");
  21474. var OptimizerConstructors = (function () {
  21475. function OptimizerConstructors() {
  21476. }
  21477. OptimizerConstructors.sgd = function (learningRate) {
  21478. return new sgd_optimizer_1.SGDOptimizer(learningRate);
  21479. };
  21480. OptimizerConstructors.momentum = function (learningRate, momentum, useNesterov) {
  21481. if (useNesterov === void 0) { useNesterov = false; }
  21482. return new momentum_optimizer_1.MomentumOptimizer(learningRate, momentum, useNesterov);
  21483. };
  21484. OptimizerConstructors.rmsprop = function (learningRate, decay, momentum, epsilon, centered) {
  21485. if (decay === void 0) { decay = .9; }
  21486. if (momentum === void 0) { momentum = 0.0; }
  21487. if (epsilon === void 0) { epsilon = null; }
  21488. if (centered === void 0) { centered = false; }
  21489. return new rmsprop_optimizer_1.RMSPropOptimizer(learningRate, decay, momentum, epsilon, centered);
  21490. };
  21491. OptimizerConstructors.adam = function (learningRate, beta1, beta2, epsilon) {
  21492. if (learningRate === void 0) { learningRate = 0.001; }
  21493. if (beta1 === void 0) { beta1 = 0.9; }
  21494. if (beta2 === void 0) { beta2 = 0.999; }
  21495. if (epsilon === void 0) { epsilon = null; }
  21496. return new adam_optimizer_1.AdamOptimizer(learningRate, beta1, beta2, epsilon);
  21497. };
  21498. OptimizerConstructors.adadelta = function (learningRate, rho, epsilon) {
  21499. if (learningRate === void 0) { learningRate = .001; }
  21500. if (rho === void 0) { rho = .95; }
  21501. if (epsilon === void 0) { epsilon = null; }
  21502. return new adadelta_optimizer_1.AdadeltaOptimizer(learningRate, rho, epsilon);
  21503. };
  21504. OptimizerConstructors.adamax = function (learningRate, beta1, beta2, epsilon, decay) {
  21505. if (learningRate === void 0) { learningRate = 0.002; }
  21506. if (beta1 === void 0) { beta1 = 0.9; }
  21507. if (beta2 === void 0) { beta2 = 0.999; }
  21508. if (epsilon === void 0) { epsilon = null; }
  21509. if (decay === void 0) { decay = 0.0; }
  21510. return new adamax_optimizer_1.AdamaxOptimizer(learningRate, beta1, beta2, epsilon, decay);
  21511. };
  21512. OptimizerConstructors.adagrad = function (learningRate, initialAccumulatorValue) {
  21513. if (initialAccumulatorValue === void 0) { initialAccumulatorValue = 0.1; }
  21514. return new adagrad_optimizer_1.AdagradOptimizer(learningRate, initialAccumulatorValue);
  21515. };
  21516. __decorate([
  21517. doc_1.doc({ heading: 'Training', subheading: 'Optimizers', namespace: 'train' })
  21518. ], OptimizerConstructors, "sgd", null);
  21519. __decorate([
  21520. doc_1.doc({ heading: 'Training', subheading: 'Optimizers', namespace: 'train' })
  21521. ], OptimizerConstructors, "momentum", null);
  21522. __decorate([
  21523. doc_1.doc({ heading: 'Training', subheading: 'Optimizers', namespace: 'train' })
  21524. ], OptimizerConstructors, "rmsprop", null);
  21525. __decorate([
  21526. doc_1.doc({ heading: 'Training', subheading: 'Optimizers', namespace: 'train' })
  21527. ], OptimizerConstructors, "adam", null);
  21528. __decorate([
  21529. doc_1.doc({ heading: 'Training', subheading: 'Optimizers', namespace: 'train' })
  21530. ], OptimizerConstructors, "adadelta", null);
  21531. __decorate([
  21532. doc_1.doc({ heading: 'Training', subheading: 'Optimizers', namespace: 'train' })
  21533. ], OptimizerConstructors, "adamax", null);
  21534. __decorate([
  21535. doc_1.doc({ heading: 'Training', subheading: 'Optimizers', namespace: 'train' })
  21536. ], OptimizerConstructors, "adagrad", null);
  21537. return OptimizerConstructors;
  21538. }());
  21539. exports.OptimizerConstructors = OptimizerConstructors;
  21540. },{"../doc":49,"./adadelta_optimizer":145,"./adagrad_optimizer":146,"./adam_optimizer":147,"./adamax_optimizer":148,"./momentum_optimizer":149,"./rmsprop_optimizer":153,"./sgd_optimizer":154}],152:[function(require,module,exports){
  21541. "use strict";
  21542. Object.defineProperty(exports, "__esModule", { value: true });
  21543. var environment_1 = require("../environment");
  21544. var DEFAULT_FLOAT32_EPSILON = 1e-8;
  21545. var DEFAULT_FLOAT16_EPSILON = 1e-4;
  21546. function getOptimizerDefaultEpsilonValue() {
  21547. if (environment_1.ENV.get('WEBGL_RENDER_FLOAT32_ENABLED')) {
  21548. return DEFAULT_FLOAT32_EPSILON;
  21549. }
  21550. return DEFAULT_FLOAT16_EPSILON;
  21551. }
  21552. exports.getOptimizerDefaultEpsilonValue = getOptimizerDefaultEpsilonValue;
  21553. },{"../environment":51}],153:[function(require,module,exports){
  21554. "use strict";
  21555. var __extends = (this && this.__extends) || (function () {
  21556. var extendStatics = Object.setPrototypeOf ||
  21557. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  21558. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  21559. return function (d, b) {
  21560. extendStatics(d, b);
  21561. function __() { this.constructor = d; }
  21562. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  21563. };
  21564. })();
  21565. Object.defineProperty(exports, "__esModule", { value: true });
  21566. var environment_1 = require("../environment");
  21567. var globals_1 = require("../globals");
  21568. var ops_1 = require("../ops/ops");
  21569. var serialization_1 = require("../serialization");
  21570. var optimizer_1 = require("./optimizer");
  21571. var optimizer_utils = require("./optimizer_utils");
  21572. var RMSPropOptimizer = (function (_super) {
  21573. __extends(RMSPropOptimizer, _super);
  21574. function RMSPropOptimizer(learningRate, decay, momentum, epsilon, centered) {
  21575. if (decay === void 0) { decay = 0.9; }
  21576. if (momentum === void 0) { momentum = 0.0; }
  21577. if (epsilon === void 0) { epsilon = null; }
  21578. if (centered === void 0) { centered = false; }
  21579. var _this = _super.call(this) || this;
  21580. _this.learningRate = learningRate;
  21581. _this.decay = decay;
  21582. _this.momentum = momentum;
  21583. _this.epsilon = epsilon;
  21584. _this.accumulatedMeanSquares = {};
  21585. _this.accumulatedMeanGrads = {};
  21586. _this.accumulatedMoments = {};
  21587. _this.c = globals_1.keep(ops_1.scalar(learningRate));
  21588. _this.decayScalar = globals_1.keep(ops_1.scalar(decay));
  21589. _this.momentumScalar = globals_1.keep(ops_1.scalar(momentum));
  21590. _this.oneMinusDecay = globals_1.keep(ops_1.scalar(1 - decay));
  21591. _this.centered = centered;
  21592. if (epsilon === null) {
  21593. epsilon = optimizer_utils.getOptimizerDefaultEpsilonValue();
  21594. }
  21595. _this.epsilonScalar = globals_1.keep(ops_1.scalar(epsilon));
  21596. return _this;
  21597. }
  21598. RMSPropOptimizer.prototype.applyGradients = function (variableGradients) {
  21599. var _this = this;
  21600. var _loop_1 = function (variableName) {
  21601. var value = environment_1.ENV.engine.registeredVariables[variableName];
  21602. if (this_1.accumulatedMeanSquares[variableName] == null) {
  21603. var trainable_1 = false;
  21604. globals_1.tidy(function () {
  21605. _this.accumulatedMeanSquares[variableName] =
  21606. ops_1.zerosLike(value).variable(trainable_1);
  21607. });
  21608. }
  21609. if (this_1.accumulatedMeanGrads[variableName] == null && this_1.centered) {
  21610. var trainable_2 = false;
  21611. globals_1.tidy(function () {
  21612. _this.accumulatedMeanGrads[variableName] =
  21613. ops_1.zerosLike(value).variable(trainable_2);
  21614. });
  21615. }
  21616. if (this_1.accumulatedMoments[variableName] == null) {
  21617. var trainable_3 = false;
  21618. globals_1.tidy(function () {
  21619. _this.accumulatedMoments[variableName] =
  21620. ops_1.zerosLike(value).variable(trainable_3);
  21621. });
  21622. }
  21623. var accumulatedMeanSquare = this_1.accumulatedMeanSquares[variableName];
  21624. var accumulatedMeanGrad = this_1.accumulatedMeanGrads[variableName];
  21625. var accumulatedMoments = this_1.accumulatedMoments[variableName];
  21626. var gradient = variableGradients[variableName];
  21627. globals_1.tidy(function () {
  21628. var newAccumulatedMeanSquare = _this.decayScalar.mul(accumulatedMeanSquare)
  21629. .add(_this.oneMinusDecay.mul(gradient.square()));
  21630. if (_this.centered) {
  21631. var newAccumulatedMeanGrad = _this.decayScalar.mul(accumulatedMeanGrad)
  21632. .add(_this.oneMinusDecay.mul(gradient));
  21633. var newAccumulatedMoments = _this.momentumScalar.mul(accumulatedMoments)
  21634. .add(_this.c.mul(gradient).div(newAccumulatedMeanSquare
  21635. .sub(newAccumulatedMeanGrad.square().add(_this.epsilonScalar))
  21636. .sqrt()));
  21637. _this.accumulatedMeanSquares[variableName].assign(newAccumulatedMeanSquare);
  21638. _this.accumulatedMeanGrads[variableName].assign(newAccumulatedMeanGrad);
  21639. _this.accumulatedMoments[variableName].assign(newAccumulatedMoments);
  21640. var newValue = value.sub(newAccumulatedMoments);
  21641. value.assign(newValue);
  21642. }
  21643. else {
  21644. var newAccumulatedMeanSquare_1 = _this.decayScalar.mul(accumulatedMeanSquare)
  21645. .add(_this.oneMinusDecay.mul(gradient.square()));
  21646. var newAccumulatedMoments = _this.momentumScalar.mul(accumulatedMoments)
  21647. .add(_this.c.mul(gradient).div(newAccumulatedMeanSquare_1.add(_this.epsilonScalar).sqrt()));
  21648. _this.accumulatedMeanSquares[variableName].assign(newAccumulatedMeanSquare_1);
  21649. _this.accumulatedMoments[variableName].assign(newAccumulatedMoments);
  21650. var newValue = value.sub(newAccumulatedMoments);
  21651. value.assign(newValue);
  21652. }
  21653. });
  21654. };
  21655. var this_1 = this;
  21656. for (var variableName in variableGradients) {
  21657. _loop_1(variableName);
  21658. }
  21659. };
  21660. RMSPropOptimizer.prototype.dispose = function () {
  21661. var _this = this;
  21662. this.c.dispose();
  21663. this.epsilonScalar.dispose();
  21664. this.decayScalar.dispose();
  21665. this.momentumScalar.dispose();
  21666. this.oneMinusDecay.dispose();
  21667. if (this.accumulatedMeanSquares != null) {
  21668. Object.keys(this.accumulatedMeanSquares)
  21669. .forEach(function (name) { return _this.accumulatedMeanSquares[name].dispose(); });
  21670. }
  21671. if (this.accumulatedMeanGrads != null && this.centered) {
  21672. Object.keys(this.accumulatedMeanGrads)
  21673. .forEach(function (name) { return _this.accumulatedMeanGrads[name].dispose(); });
  21674. }
  21675. if (this.accumulatedMoments != null) {
  21676. Object.keys(this.accumulatedMoments)
  21677. .forEach(function (name) { return _this.accumulatedMoments[name].dispose(); });
  21678. }
  21679. };
  21680. RMSPropOptimizer.prototype.getConfig = function () {
  21681. return {
  21682. learningRate: this.learningRate,
  21683. decay: this.decay,
  21684. momentum: this.momentum,
  21685. epsilon: this.epsilon,
  21686. centered: this.centered
  21687. };
  21688. };
  21689. RMSPropOptimizer.fromConfig = function (cls, config) {
  21690. return new cls(config.learningRate, config.decay, config.momentum, config.epsilon, config.centered);
  21691. };
  21692. RMSPropOptimizer.className = 'RMSPropOptimizer';
  21693. return RMSPropOptimizer;
  21694. }(optimizer_1.Optimizer));
  21695. exports.RMSPropOptimizer = RMSPropOptimizer;
  21696. serialization_1.SerializationMap.register(RMSPropOptimizer);
  21697. },{"../environment":51,"../globals":52,"../ops/ops":129,"../serialization":156,"./optimizer":150,"./optimizer_utils":152}],154:[function(require,module,exports){
  21698. "use strict";
  21699. var __extends = (this && this.__extends) || (function () {
  21700. var extendStatics = Object.setPrototypeOf ||
  21701. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  21702. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  21703. return function (d, b) {
  21704. extendStatics(d, b);
  21705. function __() { this.constructor = d; }
  21706. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  21707. };
  21708. })();
  21709. Object.defineProperty(exports, "__esModule", { value: true });
  21710. var environment_1 = require("../environment");
  21711. var globals_1 = require("../globals");
  21712. var ops_1 = require("../ops/ops");
  21713. var serialization_1 = require("../serialization");
  21714. var optimizer_1 = require("./optimizer");
  21715. var SGDOptimizer = (function (_super) {
  21716. __extends(SGDOptimizer, _super);
  21717. function SGDOptimizer(learningRate) {
  21718. var _this = _super.call(this) || this;
  21719. _this.learningRate = learningRate;
  21720. _this.setLearningRate(learningRate);
  21721. return _this;
  21722. }
  21723. SGDOptimizer.prototype.applyGradients = function (variableGradients) {
  21724. var _this = this;
  21725. var varNames = Object.keys(variableGradients);
  21726. varNames.forEach(function (varName) {
  21727. var gradient = variableGradients[varName];
  21728. var value = environment_1.ENV.engine.registeredVariables[varName];
  21729. globals_1.tidy(function () {
  21730. var newValue = _this.c.mul(gradient).add(value);
  21731. value.assign(newValue);
  21732. });
  21733. });
  21734. };
  21735. SGDOptimizer.prototype.setLearningRate = function (learningRate) {
  21736. this.learningRate = learningRate;
  21737. if (this.c != null) {
  21738. this.c.dispose();
  21739. }
  21740. this.c = globals_1.keep(ops_1.scalar(-learningRate));
  21741. };
  21742. SGDOptimizer.prototype.dispose = function () {
  21743. this.c.dispose();
  21744. };
  21745. SGDOptimizer.prototype.getConfig = function () {
  21746. return { learningRate: this.learningRate };
  21747. };
  21748. SGDOptimizer.fromConfig = function (cls, config) {
  21749. return new cls(config.learningRate);
  21750. };
  21751. SGDOptimizer.className = 'SGDOptimizer';
  21752. return SGDOptimizer;
  21753. }(optimizer_1.Optimizer));
  21754. exports.SGDOptimizer = SGDOptimizer;
  21755. serialization_1.SerializationMap.register(SGDOptimizer);
  21756. },{"../environment":51,"../globals":52,"../ops/ops":129,"../serialization":156,"./optimizer":150}],155:[function(require,module,exports){
  21757. "use strict";
  21758. Object.defineProperty(exports, "__esModule", { value: true });
  21759. var util = require("./util");
  21760. var Profiler = (function () {
  21761. function Profiler(backendTimer, logger) {
  21762. this.backendTimer = backendTimer;
  21763. this.logger = logger;
  21764. if (logger == null) {
  21765. this.logger = new Logger();
  21766. }
  21767. }
  21768. Profiler.prototype.profileKernel = function (name, f) {
  21769. var _this = this;
  21770. var result;
  21771. var holdResultWrapperFn = function () {
  21772. result = f();
  21773. };
  21774. var timer = this.backendTimer.time(holdResultWrapperFn);
  21775. var vals = result.dataSync();
  21776. util.checkForNaN(vals, result.dtype, name);
  21777. timer.then(function (timing) {
  21778. _this.logger.logKernelProfile(name, result, vals, timing.kernelMs);
  21779. });
  21780. return result;
  21781. };
  21782. return Profiler;
  21783. }());
  21784. exports.Profiler = Profiler;
  21785. var Logger = (function () {
  21786. function Logger() {
  21787. }
  21788. Logger.prototype.logKernelProfile = function (name, result, vals, timeMs) {
  21789. var time = util.rightPad(timeMs + "ms", 9);
  21790. var paddedName = util.rightPad(name, 25);
  21791. var rank = result.rank;
  21792. var size = result.size;
  21793. var shape = util.rightPad(result.shape.toString(), 14);
  21794. console.log("%c" + paddedName + "\t%c" + time + "\t%c" + rank + "D " + shape + "\t%c" + size, 'font-weight:bold', 'color:red', 'color:blue', 'color: orange');
  21795. };
  21796. return Logger;
  21797. }());
  21798. exports.Logger = Logger;
  21799. },{"./util":164}],156:[function(require,module,exports){
  21800. "use strict";
  21801. Object.defineProperty(exports, "__esModule", { value: true });
  21802. var Serializable = (function () {
  21803. function Serializable() {
  21804. }
  21805. Serializable.prototype.getClassName = function () {
  21806. return this.constructor
  21807. .className;
  21808. };
  21809. Serializable.fromConfig = function (cls, config) {
  21810. return new cls(config);
  21811. };
  21812. return Serializable;
  21813. }());
  21814. exports.Serializable = Serializable;
  21815. var SerializationMap = (function () {
  21816. function SerializationMap() {
  21817. this.classNameMap = {};
  21818. }
  21819. SerializationMap.getMap = function () {
  21820. if (SerializationMap.instance == null) {
  21821. SerializationMap.instance = new SerializationMap();
  21822. }
  21823. return SerializationMap.instance;
  21824. };
  21825. SerializationMap.register = function (cls) {
  21826. this.getMap().classNameMap[cls.className] = [cls, cls.fromConfig];
  21827. };
  21828. return SerializationMap;
  21829. }());
  21830. exports.SerializationMap = SerializationMap;
  21831. },{}],157:[function(require,module,exports){
  21832. "use strict";
  21833. Object.defineProperty(exports, "__esModule", { value: true });
  21834. var util = require("./util");
  21835. function getFilteredNodesXToY(tape, xs, y) {
  21836. var tensorsFromX = {};
  21837. var nodesFromX = {};
  21838. for (var i = 0; i < xs.length; i++) {
  21839. tensorsFromX[xs[i].id] = true;
  21840. }
  21841. for (var i = 0; i < tape.length; i++) {
  21842. var node = tape[i];
  21843. var nodeInputs = node.inputs;
  21844. for (var inputName in nodeInputs) {
  21845. var input = nodeInputs[inputName];
  21846. var anyInputFromX = false;
  21847. for (var j = 0; j < xs.length; j++) {
  21848. if (tensorsFromX[input.id]) {
  21849. tensorsFromX[node.output.id] = true;
  21850. anyInputFromX = true;
  21851. nodesFromX[node.id] = true;
  21852. break;
  21853. }
  21854. }
  21855. if (anyInputFromX) {
  21856. break;
  21857. }
  21858. }
  21859. }
  21860. var tensorsLeadToY = {};
  21861. tensorsLeadToY[y.id] = true;
  21862. var nodesToY = {};
  21863. for (var i = tape.length - 1; i >= 0; i--) {
  21864. var node = tape[i];
  21865. var nodeInputs = node.inputs;
  21866. var outputs = [];
  21867. outputs.push(node.output);
  21868. for (var j = 0; j < outputs.length; j++) {
  21869. if (tensorsLeadToY[outputs[j].id]) {
  21870. for (var inputName in nodeInputs) {
  21871. tensorsLeadToY[nodeInputs[inputName].id] = true;
  21872. nodesToY[node.id] = true;
  21873. }
  21874. break;
  21875. }
  21876. }
  21877. }
  21878. var filteredTape = [];
  21879. for (var i = 0; i < tape.length; i++) {
  21880. var node = tape[i];
  21881. if (nodesFromX[node.id] && nodesToY[node.id]) {
  21882. var prunedInputs = {};
  21883. for (var inputName in node.inputs) {
  21884. var nodeInput = node.inputs[inputName];
  21885. if (tensorsFromX[nodeInput.id]) {
  21886. prunedInputs[inputName] = nodeInput;
  21887. }
  21888. }
  21889. var prunedNode = Object.assign({}, node);
  21890. prunedNode.inputs = prunedInputs;
  21891. prunedNode.output = node.output;
  21892. filteredTape.push(prunedNode);
  21893. }
  21894. }
  21895. return filteredTape;
  21896. }
  21897. exports.getFilteredNodesXToY = getFilteredNodesXToY;
  21898. function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape) {
  21899. for (var i = filteredTape.length - 1; i >= 0; i--) {
  21900. var node = filteredTape[i];
  21901. var dy = tensorAccumulatedGradientMap[node.output.id];
  21902. if (node.gradient == null) {
  21903. throw new Error("Cannot compute gradient: gradient function not found " +
  21904. ("for " + node.name + "."));
  21905. }
  21906. var inputGradients = node.gradient(dy);
  21907. for (var inputName in node.inputs) {
  21908. if (!(inputName in inputGradients)) {
  21909. throw new Error("Cannot backprop through input " + inputName + ". " +
  21910. ("Available gradients found: " + Object.keys(inputGradients) + "."));
  21911. }
  21912. var dx = inputGradients[inputName]();
  21913. var x = node.inputs[inputName];
  21914. if (!util.arraysEqual(dx.shape, x.shape)) {
  21915. throw new Error("Error in gradient for op " + node.name + ". The gradient of input " +
  21916. ("'" + inputName + "' has shape '" + dx.shape + "', which does not match ") +
  21917. ("the shape of the input '" + x.shape + "'"));
  21918. }
  21919. if (tensorAccumulatedGradientMap[x.id] == null) {
  21920. tensorAccumulatedGradientMap[x.id] = dx;
  21921. }
  21922. else {
  21923. var curGradient = tensorAccumulatedGradientMap[x.id];
  21924. tensorAccumulatedGradientMap[x.id] = curGradient.add(dx);
  21925. curGradient.dispose();
  21926. }
  21927. }
  21928. }
  21929. }
  21930. exports.backpropagateGradients = backpropagateGradients;
  21931. },{"./util":164}],158:[function(require,module,exports){
  21932. "use strict";
  21933. var __extends = (this && this.__extends) || (function () {
  21934. var extendStatics = Object.setPrototypeOf ||
  21935. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  21936. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  21937. return function (d, b) {
  21938. extendStatics(d, b);
  21939. function __() { this.constructor = d; }
  21940. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  21941. };
  21942. })();
  21943. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  21944. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  21945. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  21946. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  21947. return c > 3 && r && Object.defineProperty(target, key, r), r;
  21948. };
  21949. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  21950. return new (P || (P = Promise))(function (resolve, reject) {
  21951. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  21952. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  21953. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  21954. step((generator = generator.apply(thisArg, _arguments || [])).next());
  21955. });
  21956. };
  21957. var __generator = (this && this.__generator) || function (thisArg, body) {
  21958. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  21959. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  21960. function verb(n) { return function (v) { return step([n, v]); }; }
  21961. function step(op) {
  21962. if (f) throw new TypeError("Generator is already executing.");
  21963. while (_) try {
  21964. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  21965. if (y = 0, t) op = [0, t.value];
  21966. switch (op[0]) {
  21967. case 0: case 1: t = op; break;
  21968. case 4: _.label++; return { value: op[1], done: false };
  21969. case 5: _.label++; y = op[1]; op = [0]; continue;
  21970. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  21971. default:
  21972. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  21973. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  21974. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  21975. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  21976. if (t[2]) _.ops.pop();
  21977. _.trys.pop(); continue;
  21978. }
  21979. op = body.call(thisArg, _);
  21980. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  21981. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  21982. }
  21983. };
  21984. Object.defineProperty(exports, "__esModule", { value: true });
  21985. var doc_1 = require("./doc");
  21986. var environment_1 = require("./environment");
  21987. var ops = require("./ops/ops");
  21988. var tensor_util = require("./tensor_util");
  21989. var util = require("./util");
  21990. var TensorBuffer = (function () {
  21991. function TensorBuffer(shape, dtype, values) {
  21992. this.dtype = dtype;
  21993. if (values != null) {
  21994. var n = values.length;
  21995. var size = util.sizeFromShape(shape);
  21996. util.assert(n === size, "Length of values '" + n + "' does not match the size " +
  21997. ("inferred by the shape '" + size + "'"));
  21998. }
  21999. this.shape = shape.slice();
  22000. this.values =
  22001. values || util.getTypedArrayFromDType(dtype, util.sizeFromShape(shape));
  22002. this.strides = computeStrides(shape);
  22003. this.size = util.sizeFromShape(shape);
  22004. }
  22005. TensorBuffer.prototype.set = function (value) {
  22006. var locs = [];
  22007. for (var _i = 1; _i < arguments.length; _i++) {
  22008. locs[_i - 1] = arguments[_i];
  22009. }
  22010. if (locs.length === 0) {
  22011. locs = [0];
  22012. }
  22013. util.assert(locs.length === this.rank, "The number of provided coordinates (" + locs.length + ") must " +
  22014. ("match the rank (" + this.rank + ")"));
  22015. var index = this.locToIndex(locs);
  22016. this.values[index] = value;
  22017. };
  22018. TensorBuffer.prototype.get = function () {
  22019. var locs = [];
  22020. for (var _i = 0; _i < arguments.length; _i++) {
  22021. locs[_i] = arguments[_i];
  22022. }
  22023. if (locs.length === 0) {
  22024. locs = [0];
  22025. }
  22026. var index = locs[locs.length - 1];
  22027. for (var i = 0; i < locs.length - 1; ++i) {
  22028. index += this.strides[i] * locs[i];
  22029. }
  22030. return this.values[index];
  22031. };
  22032. TensorBuffer.prototype.locToIndex = function (locs) {
  22033. if (this.rank === 0) {
  22034. return 0;
  22035. }
  22036. else if (this.rank === 1) {
  22037. return locs[0];
  22038. }
  22039. var index = locs[locs.length - 1];
  22040. for (var i = 0; i < locs.length - 1; ++i) {
  22041. index += this.strides[i] * locs[i];
  22042. }
  22043. return index;
  22044. };
  22045. TensorBuffer.prototype.indexToLoc = function (index) {
  22046. if (this.rank === 0) {
  22047. return [];
  22048. }
  22049. else if (this.rank === 1) {
  22050. return [index];
  22051. }
  22052. var locs = new Array(this.shape.length);
  22053. for (var i = 0; i < locs.length - 1; ++i) {
  22054. locs[i] = Math.floor(index / this.strides[i]);
  22055. index -= locs[i] * this.strides[i];
  22056. }
  22057. locs[locs.length - 1] = index;
  22058. return locs;
  22059. };
  22060. Object.defineProperty(TensorBuffer.prototype, "rank", {
  22061. get: function () {
  22062. return this.shape.length;
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. TensorBuffer.prototype.toTensor = function () {
  22068. return Tensor.make(this.shape, { values: this.values }, this.dtype);
  22069. };
  22070. __decorate([
  22071. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  22072. ], TensorBuffer.prototype, "set", null);
  22073. __decorate([
  22074. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  22075. ], TensorBuffer.prototype, "get", null);
  22076. __decorate([
  22077. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  22078. ], TensorBuffer.prototype, "toTensor", null);
  22079. TensorBuffer = __decorate([
  22080. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22081. ], TensorBuffer);
  22082. return TensorBuffer;
  22083. }());
  22084. exports.TensorBuffer = TensorBuffer;
  22085. var Tensor = (function () {
  22086. function Tensor(shape, dtype, values, dataId) {
  22087. this.isDisposedInternal = false;
  22088. this.size = util.sizeFromShape(shape);
  22089. if (values != null) {
  22090. util.assert(this.size === values.length, "Constructing tensor of shape (" + this.size + ") should match the " +
  22091. ("length of values (" + values.length + ")"));
  22092. }
  22093. this.shape = shape.slice();
  22094. this.dtype = dtype || 'float32';
  22095. this.strides = computeStrides(shape);
  22096. this.dataId = dataId != null ? dataId : {};
  22097. this.id = Tensor_1.nextId++;
  22098. this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher');
  22099. environment_1.ENV.engine.registerTensor(this);
  22100. if (values != null) {
  22101. environment_1.ENV.engine.write(this.dataId, values);
  22102. }
  22103. }
  22104. Tensor_1 = Tensor;
  22105. Tensor.make = function (shape, data, dtype) {
  22106. return new Tensor_1(shape, dtype, data.values, data.dataId);
  22107. };
  22108. Tensor.prototype.flatten = function () {
  22109. this.throwIfDisposed();
  22110. return this.as1D();
  22111. };
  22112. Tensor.prototype.asScalar = function () {
  22113. this.throwIfDisposed();
  22114. util.assert(this.size === 1, 'The array must have only 1 element.');
  22115. return this.reshape([]);
  22116. };
  22117. Tensor.prototype.as1D = function () {
  22118. this.throwIfDisposed();
  22119. return this.reshape([this.size]);
  22120. };
  22121. Tensor.prototype.as2D = function (rows, columns) {
  22122. this.throwIfDisposed();
  22123. return this.reshape([rows, columns]);
  22124. };
  22125. Tensor.prototype.as3D = function (rows, columns, depth) {
  22126. this.throwIfDisposed();
  22127. return this.reshape([rows, columns, depth]);
  22128. };
  22129. Tensor.prototype.as4D = function (rows, columns, depth, depth2) {
  22130. this.throwIfDisposed();
  22131. return this.reshape([rows, columns, depth, depth2]);
  22132. };
  22133. Tensor.prototype.asType = function (dtype) {
  22134. this.throwIfDisposed();
  22135. return ops.cast(this, dtype);
  22136. };
  22137. Object.defineProperty(Tensor.prototype, "rank", {
  22138. get: function () {
  22139. return this.shape.length;
  22140. },
  22141. enumerable: true,
  22142. configurable: true
  22143. });
  22144. Tensor.prototype.get = function () {
  22145. var locs = [];
  22146. for (var _i = 0; _i < arguments.length; _i++) {
  22147. locs[_i] = arguments[_i];
  22148. }
  22149. util.assert(locs.length === this.rank, 'Number of coordinates in get() must match the rank of the tensor');
  22150. this.throwIfDisposed();
  22151. if (locs.length === 0) {
  22152. locs = [0];
  22153. }
  22154. var index = locs[locs.length - 1];
  22155. for (var i = 0; i < locs.length - 1; ++i) {
  22156. index += this.strides[i] * locs[i];
  22157. }
  22158. return this.dataSync()[index];
  22159. };
  22160. Tensor.prototype.buffer = function () {
  22161. return ops.buffer(this.shape, this.dtype, this.dataSync());
  22162. };
  22163. Tensor.prototype.data = function () {
  22164. return __awaiter(this, void 0, void 0, function () {
  22165. return __generator(this, function (_a) {
  22166. this.throwIfDisposed();
  22167. return [2, environment_1.ENV.engine.read(this.dataId)];
  22168. });
  22169. });
  22170. };
  22171. Tensor.prototype.dataSync = function () {
  22172. this.throwIfDisposed();
  22173. return environment_1.ENV.engine.readSync(this.dataId);
  22174. };
  22175. Tensor.prototype.dispose = function () {
  22176. if (this.isDisposed) {
  22177. return;
  22178. }
  22179. environment_1.ENV.engine.disposeTensor(this);
  22180. this.isDisposedInternal = true;
  22181. };
  22182. Object.defineProperty(Tensor.prototype, "isDisposed", {
  22183. get: function () {
  22184. return this.isDisposedInternal;
  22185. },
  22186. enumerable: true,
  22187. configurable: true
  22188. });
  22189. Tensor.prototype.throwIfDisposed = function () {
  22190. if (this.isDisposed) {
  22191. throw new Error("Tensor is disposed.");
  22192. }
  22193. };
  22194. Tensor.prototype.toFloat = function () {
  22195. return this.asType('float32');
  22196. };
  22197. Tensor.prototype.toInt = function () {
  22198. return this.asType('int32');
  22199. };
  22200. Tensor.prototype.toBool = function () {
  22201. return this.asType('bool');
  22202. };
  22203. Tensor.prototype.print = function (verbose) {
  22204. if (verbose === void 0) { verbose = false; }
  22205. return ops.print(this, verbose);
  22206. };
  22207. Tensor.prototype.reshape = function (newShape) {
  22208. this.throwIfDisposed();
  22209. return ops.reshape(this, newShape);
  22210. };
  22211. Tensor.prototype.reshapeAs = function (x) {
  22212. this.throwIfDisposed();
  22213. return this.reshape(x.shape);
  22214. };
  22215. Tensor.prototype.expandDims = function (axis) {
  22216. if (axis === void 0) { axis = 0; }
  22217. return ops.expandDims(this, axis);
  22218. };
  22219. Tensor.prototype.cumsum = function (axis, exclusive, reverse) {
  22220. if (axis === void 0) { axis = 0; }
  22221. if (exclusive === void 0) { exclusive = false; }
  22222. if (reverse === void 0) { reverse = false; }
  22223. return ops.cumsum(this, axis, exclusive, reverse);
  22224. };
  22225. Tensor.prototype.squeeze = function (axis) {
  22226. this.throwIfDisposed();
  22227. return ops.squeeze(this, axis);
  22228. };
  22229. Tensor.prototype.clone = function () {
  22230. this.throwIfDisposed();
  22231. return ops.clone(this);
  22232. };
  22233. Tensor.prototype.toString = function (verbose) {
  22234. if (verbose === void 0) { verbose = false; }
  22235. return tensor_util.tensorToString(this, verbose);
  22236. };
  22237. Tensor.prototype.tile = function (reps) {
  22238. this.throwIfDisposed();
  22239. return ops.tile(this, reps);
  22240. };
  22241. Tensor.prototype.gather = function (indices, axis) {
  22242. if (axis === void 0) { axis = 0; }
  22243. this.throwIfDisposed();
  22244. return ops.gather(this, indices, axis);
  22245. };
  22246. Tensor.prototype.matMul = function (b, transposeA, transposeB) {
  22247. if (transposeA === void 0) { transposeA = false; }
  22248. if (transposeB === void 0) { transposeB = false; }
  22249. this.throwIfDisposed();
  22250. return ops.matMul(this, b, transposeA, transposeB);
  22251. };
  22252. Tensor.prototype.dot = function (b) {
  22253. this.throwIfDisposed();
  22254. return ops.dot(this, b);
  22255. };
  22256. Tensor.prototype.norm = function (ord, axis, keepDims) {
  22257. if (ord === void 0) { ord = 'euclidean'; }
  22258. if (axis === void 0) { axis = null; }
  22259. if (keepDims === void 0) { keepDims = false; }
  22260. this.throwIfDisposed();
  22261. return ops.norm(this, ord, axis, keepDims);
  22262. };
  22263. Tensor.prototype.slice = function (begin, size) {
  22264. this.throwIfDisposed();
  22265. return ops.slice(this, begin, size);
  22266. };
  22267. Tensor.prototype.reverse = function (axis) {
  22268. this.throwIfDisposed();
  22269. return ops.reverse(this, axis);
  22270. };
  22271. Tensor.prototype.concat = function (x, axis) {
  22272. if (axis === void 0) { axis = 0; }
  22273. this.throwIfDisposed();
  22274. return ops.concat([this, x], axis);
  22275. };
  22276. Tensor.prototype.stack = function (x, axis) {
  22277. if (axis === void 0) { axis = 0; }
  22278. return ops.stack([this, x], axis);
  22279. };
  22280. Tensor.prototype.unstack = function (x, axis) {
  22281. if (axis === void 0) { axis = 0; }
  22282. return ops.unstack(this, axis);
  22283. };
  22284. Tensor.prototype.pad = function (paddings, constantValue) {
  22285. if (constantValue === void 0) { constantValue = 0; }
  22286. return ops.pad(this, paddings, constantValue);
  22287. };
  22288. Tensor.prototype.batchNormalization = function (mean, variance, varianceEpsilon, scale, offset) {
  22289. if (varianceEpsilon === void 0) { varianceEpsilon = .001; }
  22290. this.throwIfDisposed();
  22291. return ops.batchNormalization(this, mean, variance, varianceEpsilon, scale, offset);
  22292. };
  22293. Tensor.prototype.all = function (axis, keepDims) {
  22294. if (axis === void 0) { axis = null; }
  22295. if (keepDims === void 0) { keepDims = false; }
  22296. this.throwIfDisposed();
  22297. return ops.all(this, axis, keepDims);
  22298. };
  22299. Tensor.prototype.logSumExp = function (axis, keepDims) {
  22300. if (axis === void 0) { axis = null; }
  22301. if (keepDims === void 0) { keepDims = false; }
  22302. this.throwIfDisposed();
  22303. return ops.logSumExp(this, axis, keepDims);
  22304. };
  22305. Tensor.prototype.sum = function (axis, keepDims) {
  22306. if (axis === void 0) { axis = null; }
  22307. if (keepDims === void 0) { keepDims = false; }
  22308. this.throwIfDisposed();
  22309. return ops.sum(this, axis, keepDims);
  22310. };
  22311. Tensor.prototype.mean = function (axis, keepDims) {
  22312. if (axis === void 0) { axis = null; }
  22313. if (keepDims === void 0) { keepDims = false; }
  22314. this.throwIfDisposed();
  22315. return ops.mean(this, axis, keepDims);
  22316. };
  22317. Tensor.prototype.min = function (axis, keepDims) {
  22318. if (axis === void 0) { axis = null; }
  22319. if (keepDims === void 0) { keepDims = false; }
  22320. this.throwIfDisposed();
  22321. return ops.min(this, axis, keepDims);
  22322. };
  22323. Tensor.prototype.max = function (axis, keepDims) {
  22324. if (axis === void 0) { axis = null; }
  22325. if (keepDims === void 0) { keepDims = false; }
  22326. this.throwIfDisposed();
  22327. return ops.max(this, axis, keepDims);
  22328. };
  22329. Tensor.prototype.argMin = function (axis) {
  22330. if (axis === void 0) { axis = null; }
  22331. this.throwIfDisposed();
  22332. return ops.argMin(this, axis);
  22333. };
  22334. Tensor.prototype.argMax = function (axis) {
  22335. if (axis === void 0) { axis = null; }
  22336. this.throwIfDisposed();
  22337. return ops.argMax(this, axis);
  22338. };
  22339. Tensor.prototype.cast = function (dtype) {
  22340. this.throwIfDisposed();
  22341. return ops.cast(this, dtype);
  22342. };
  22343. Tensor.prototype.add = function (x) {
  22344. this.throwIfDisposed();
  22345. return ops.add(this, x);
  22346. };
  22347. Tensor.prototype.addStrict = function (x) {
  22348. this.throwIfDisposed();
  22349. return ops.addStrict(this, x);
  22350. };
  22351. Tensor.prototype.sub = function (x) {
  22352. this.throwIfDisposed();
  22353. return ops.sub(this, x);
  22354. };
  22355. Tensor.prototype.subStrict = function (x) {
  22356. this.throwIfDisposed();
  22357. return ops.subStrict(this, x);
  22358. };
  22359. Tensor.prototype.pow = function (exp) {
  22360. this.throwIfDisposed();
  22361. return ops.pow(this, exp);
  22362. };
  22363. Tensor.prototype.powStrict = function (exp) {
  22364. this.throwIfDisposed();
  22365. return ops.powStrict(this, exp);
  22366. };
  22367. Tensor.prototype.mul = function (x) {
  22368. this.throwIfDisposed();
  22369. return ops.mul(this, x);
  22370. };
  22371. Tensor.prototype.mulStrict = function (x) {
  22372. this.throwIfDisposed();
  22373. return ops.mulStrict(this, x);
  22374. };
  22375. Tensor.prototype.div = function (x) {
  22376. this.throwIfDisposed();
  22377. return ops.div(this, x);
  22378. };
  22379. Tensor.prototype.floorDiv = function (x) {
  22380. this.throwIfDisposed();
  22381. return ops.floorDiv(this, x);
  22382. };
  22383. Tensor.prototype.divStrict = function (x) {
  22384. this.throwIfDisposed();
  22385. return ops.divStrict(this, x);
  22386. };
  22387. Tensor.prototype.minimum = function (x) {
  22388. this.throwIfDisposed();
  22389. return ops.minimum(this, x);
  22390. };
  22391. Tensor.prototype.minimumStrict = function (x) {
  22392. this.throwIfDisposed();
  22393. return ops.minimumStrict(this, x);
  22394. };
  22395. Tensor.prototype.maximum = function (x) {
  22396. this.throwIfDisposed();
  22397. return ops.maximum(this, x);
  22398. };
  22399. Tensor.prototype.maximumStrict = function (x) {
  22400. this.throwIfDisposed();
  22401. return ops.maximumStrict(this, x);
  22402. };
  22403. Tensor.prototype.mod = function (x) {
  22404. this.throwIfDisposed();
  22405. return ops.mod(this, x);
  22406. };
  22407. Tensor.prototype.modStrict = function (x) {
  22408. this.throwIfDisposed();
  22409. return ops.modStrict(this, x);
  22410. };
  22411. Tensor.prototype.squaredDifference = function (x) {
  22412. this.throwIfDisposed();
  22413. return ops.squaredDifference(this, x);
  22414. };
  22415. Tensor.prototype.squaredDifferenceStrict = function (x) {
  22416. this.throwIfDisposed();
  22417. return ops.squaredDifferenceStrict(this, x);
  22418. };
  22419. Tensor.prototype.transpose = function (perm) {
  22420. this.throwIfDisposed();
  22421. return ops.transpose(this, perm);
  22422. };
  22423. Tensor.prototype.notEqual = function (x) {
  22424. this.throwIfDisposed();
  22425. return ops.notEqual(this, x);
  22426. };
  22427. Tensor.prototype.notEqualStrict = function (x) {
  22428. this.throwIfDisposed();
  22429. return ops.notEqualStrict(this, x);
  22430. };
  22431. Tensor.prototype.less = function (x) {
  22432. this.throwIfDisposed();
  22433. return ops.less(this, x);
  22434. };
  22435. Tensor.prototype.lessStrict = function (x) {
  22436. this.throwIfDisposed();
  22437. return ops.lessStrict(this, x);
  22438. };
  22439. Tensor.prototype.equal = function (x) {
  22440. this.throwIfDisposed();
  22441. return ops.equal(this, x);
  22442. };
  22443. Tensor.prototype.equalStrict = function (x) {
  22444. this.throwIfDisposed();
  22445. return ops.equalStrict(this, x);
  22446. };
  22447. Tensor.prototype.lessEqual = function (x) {
  22448. this.throwIfDisposed();
  22449. return ops.lessEqual(this, x);
  22450. };
  22451. Tensor.prototype.lessEqualStrict = function (x) {
  22452. this.throwIfDisposed();
  22453. return ops.lessEqualStrict(this, x);
  22454. };
  22455. Tensor.prototype.greater = function (x) {
  22456. this.throwIfDisposed();
  22457. return ops.greater(this, x);
  22458. };
  22459. Tensor.prototype.greaterStrict = function (x) {
  22460. this.throwIfDisposed();
  22461. return ops.greaterStrict(this, x);
  22462. };
  22463. Tensor.prototype.greaterEqual = function (x) {
  22464. this.throwIfDisposed();
  22465. return ops.greaterEqual(this, x);
  22466. };
  22467. Tensor.prototype.greaterEqualStrict = function (x) {
  22468. this.throwIfDisposed();
  22469. return ops.greaterEqualStrict(this, x);
  22470. };
  22471. Tensor.prototype.logicalAnd = function (x) {
  22472. this.throwIfDisposed();
  22473. return ops.logicalAnd(this, x);
  22474. };
  22475. Tensor.prototype.logicalOr = function (x) {
  22476. this.throwIfDisposed();
  22477. return ops.logicalOr(this, x);
  22478. };
  22479. Tensor.prototype.logicalNot = function () {
  22480. this.throwIfDisposed();
  22481. return ops.logicalNot(this);
  22482. };
  22483. Tensor.prototype.logicalXor = function (x) {
  22484. this.throwIfDisposed();
  22485. return ops.logicalXor(this, x);
  22486. };
  22487. Tensor.prototype.where = function (condition, x) {
  22488. this.throwIfDisposed();
  22489. return ops.where(condition, this, x);
  22490. };
  22491. Tensor.prototype.neg = function () {
  22492. this.throwIfDisposed();
  22493. return ops.neg(this);
  22494. };
  22495. Tensor.prototype.ceil = function () {
  22496. this.throwIfDisposed();
  22497. return ops.ceil(this);
  22498. };
  22499. Tensor.prototype.floor = function () {
  22500. this.throwIfDisposed();
  22501. return ops.floor(this);
  22502. };
  22503. Tensor.prototype.sign = function () {
  22504. this.throwIfDisposed();
  22505. return ops.sign(this);
  22506. };
  22507. Tensor.prototype.exp = function () {
  22508. this.throwIfDisposed();
  22509. return ops.exp(this);
  22510. };
  22511. Tensor.prototype.expm1 = function () {
  22512. this.throwIfDisposed();
  22513. return ops.expm1(this);
  22514. };
  22515. Tensor.prototype.log = function () {
  22516. this.throwIfDisposed();
  22517. return ops.log(this);
  22518. };
  22519. Tensor.prototype.log1p = function () {
  22520. this.throwIfDisposed();
  22521. return ops.log1p(this);
  22522. };
  22523. Tensor.prototype.sqrt = function () {
  22524. this.throwIfDisposed();
  22525. return ops.sqrt(this);
  22526. };
  22527. Tensor.prototype.rsqrt = function () {
  22528. this.throwIfDisposed();
  22529. return ops.rsqrt(this);
  22530. };
  22531. Tensor.prototype.square = function () {
  22532. this.throwIfDisposed();
  22533. return ops.square(this);
  22534. };
  22535. Tensor.prototype.reciprocal = function () {
  22536. this.throwIfDisposed();
  22537. return ops.reciprocal(this);
  22538. };
  22539. Tensor.prototype.abs = function () {
  22540. this.throwIfDisposed();
  22541. return ops.abs(this);
  22542. };
  22543. Tensor.prototype.clipByValue = function (min, max) {
  22544. this.throwIfDisposed();
  22545. return ops.clipByValue(this, min, max);
  22546. };
  22547. Tensor.prototype.relu = function () {
  22548. this.throwIfDisposed();
  22549. return ops.relu(this);
  22550. };
  22551. Tensor.prototype.elu = function () {
  22552. this.throwIfDisposed();
  22553. return ops.elu(this);
  22554. };
  22555. Tensor.prototype.selu = function () {
  22556. this.throwIfDisposed();
  22557. return ops.selu(this);
  22558. };
  22559. Tensor.prototype.leakyRelu = function (alpha) {
  22560. if (alpha === void 0) { alpha = 0.2; }
  22561. this.throwIfDisposed();
  22562. return ops.leakyRelu(this, alpha);
  22563. };
  22564. Tensor.prototype.prelu = function (alpha) {
  22565. this.throwIfDisposed();
  22566. return ops.prelu(this, alpha);
  22567. };
  22568. Tensor.prototype.sigmoid = function () {
  22569. this.throwIfDisposed();
  22570. return ops.sigmoid(this);
  22571. };
  22572. Tensor.prototype.logSigmoid = function () {
  22573. this.throwIfDisposed();
  22574. return ops.logSigmoid(this);
  22575. };
  22576. Tensor.prototype.softplus = function () {
  22577. this.throwIfDisposed();
  22578. return ops.softplus(this);
  22579. };
  22580. Tensor.prototype.sin = function () {
  22581. this.throwIfDisposed();
  22582. return ops.sin(this);
  22583. };
  22584. Tensor.prototype.cos = function () {
  22585. this.throwIfDisposed();
  22586. return ops.cos(this);
  22587. };
  22588. Tensor.prototype.tan = function () {
  22589. this.throwIfDisposed();
  22590. return ops.tan(this);
  22591. };
  22592. Tensor.prototype.asin = function () {
  22593. this.throwIfDisposed();
  22594. return ops.asin(this);
  22595. };
  22596. Tensor.prototype.acos = function () {
  22597. this.throwIfDisposed();
  22598. return ops.acos(this);
  22599. };
  22600. Tensor.prototype.atan = function () {
  22601. this.throwIfDisposed();
  22602. return ops.atan(this);
  22603. };
  22604. Tensor.prototype.sinh = function () {
  22605. this.throwIfDisposed();
  22606. return ops.sinh(this);
  22607. };
  22608. Tensor.prototype.cosh = function () {
  22609. this.throwIfDisposed();
  22610. return ops.cosh(this);
  22611. };
  22612. Tensor.prototype.tanh = function () {
  22613. this.throwIfDisposed();
  22614. return ops.tanh(this);
  22615. };
  22616. Tensor.prototype.asinh = function () {
  22617. this.throwIfDisposed();
  22618. return ops.asinh(this);
  22619. };
  22620. Tensor.prototype.acosh = function () {
  22621. this.throwIfDisposed();
  22622. return ops.acosh(this);
  22623. };
  22624. Tensor.prototype.atanh = function () {
  22625. this.throwIfDisposed();
  22626. return ops.atanh(this);
  22627. };
  22628. Tensor.prototype.erf = function () {
  22629. this.throwIfDisposed();
  22630. return ops.erf(this);
  22631. };
  22632. Tensor.prototype.round = function () {
  22633. this.throwIfDisposed();
  22634. return ops.round(this);
  22635. };
  22636. Tensor.prototype.step = function (alpha) {
  22637. if (alpha === void 0) { alpha = 0.0; }
  22638. this.throwIfDisposed();
  22639. return ops.step(this, alpha);
  22640. };
  22641. Tensor.prototype.softmax = function (dim) {
  22642. if (dim === void 0) { dim = -1; }
  22643. this.throwIfDisposed();
  22644. return ops.softmax(this, dim);
  22645. };
  22646. Tensor.prototype.resizeBilinear = function (newShape2D, alignCorners) {
  22647. if (alignCorners === void 0) { alignCorners = false; }
  22648. this.throwIfDisposed();
  22649. return ops.image.resizeBilinear(this, newShape2D, alignCorners);
  22650. };
  22651. Tensor.prototype.resizeNearestNeighbor = function (newShape2D, alignCorners) {
  22652. if (alignCorners === void 0) { alignCorners = false; }
  22653. this.throwIfDisposed();
  22654. return ops.image.resizeNearestNeighbor(this, newShape2D, alignCorners);
  22655. };
  22656. Tensor.prototype.conv1d = function (filter, stride, pad, dataFormat, dilation, dimRoundingMode) {
  22657. if (dataFormat === void 0) { dataFormat = 'NWC'; }
  22658. if (dilation === void 0) { dilation = 1; }
  22659. this.throwIfDisposed();
  22660. return ops.conv1d(this, filter, stride, pad, dataFormat, dilation, dimRoundingMode);
  22661. };
  22662. Tensor.prototype.conv2d = function (filter, strides, pad, dataFormat, dilations, dimRoundingMode) {
  22663. if (dataFormat === void 0) { dataFormat = 'NHWC'; }
  22664. if (dilations === void 0) { dilations = [1, 1]; }
  22665. this.throwIfDisposed();
  22666. return ops.conv2d(this, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
  22667. };
  22668. Tensor.prototype.conv2dTranspose = function (filter, outputShape, strides, pad, dimRoundingMode) {
  22669. this.throwIfDisposed();
  22670. return ops.conv2dTranspose(this, filter, outputShape, strides, pad, dimRoundingMode);
  22671. };
  22672. Tensor.prototype.depthwiseConv2D = function (filter, strides, pad, dataFormat, dilations, dimRoundingMode) {
  22673. if (dataFormat === void 0) { dataFormat = 'NHWC'; }
  22674. if (dilations === void 0) { dilations = [1, 1]; }
  22675. this.throwIfDisposed();
  22676. return ops.depthwiseConv2d(this, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
  22677. };
  22678. Tensor.prototype.avgPool = function (filterSize, strides, pad, dimRoundingMode) {
  22679. this.throwIfDisposed();
  22680. return ops.avgPool(this, filterSize, strides, pad, dimRoundingMode);
  22681. };
  22682. Tensor.prototype.maxPool = function (filterSize, strides, pad, dimRoundingMode) {
  22683. this.throwIfDisposed();
  22684. return ops.maxPool(this, filterSize, strides, pad, dimRoundingMode);
  22685. };
  22686. Tensor.prototype.localResponseNormalization = function (radius, bias, alpha, beta) {
  22687. if (radius === void 0) { radius = 5; }
  22688. if (bias === void 0) { bias = 1; }
  22689. if (alpha === void 0) { alpha = 1; }
  22690. if (beta === void 0) { beta = 0.5; }
  22691. return ops.localResponseNormalization(this, radius, bias, alpha, beta);
  22692. };
  22693. Tensor.prototype.variable = function (trainable, name, dtype) {
  22694. if (trainable === void 0) { trainable = true; }
  22695. this.throwIfDisposed();
  22696. return Variable.variable(this, trainable, name, dtype);
  22697. };
  22698. Tensor.prototype.unsortedSegmentSum = function (segmentIds, numSegments) {
  22699. this.throwIfDisposed();
  22700. return ops.unsortedSegmentSum(this, segmentIds, numSegments);
  22701. };
  22702. Tensor.nextId = 0;
  22703. __decorate([
  22704. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22705. ], Tensor.prototype, "flatten", null);
  22706. __decorate([
  22707. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22708. ], Tensor.prototype, "asScalar", null);
  22709. __decorate([
  22710. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22711. ], Tensor.prototype, "as1D", null);
  22712. __decorate([
  22713. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22714. ], Tensor.prototype, "as2D", null);
  22715. __decorate([
  22716. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22717. ], Tensor.prototype, "as3D", null);
  22718. __decorate([
  22719. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22720. ], Tensor.prototype, "as4D", null);
  22721. __decorate([
  22722. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22723. ], Tensor.prototype, "asType", null);
  22724. __decorate([
  22725. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22726. ], Tensor.prototype, "buffer", null);
  22727. __decorate([
  22728. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22729. ], Tensor.prototype, "data", null);
  22730. __decorate([
  22731. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22732. ], Tensor.prototype, "dataSync", null);
  22733. __decorate([
  22734. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22735. ], Tensor.prototype, "dispose", null);
  22736. __decorate([
  22737. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22738. ], Tensor.prototype, "toFloat", null);
  22739. __decorate([
  22740. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22741. ], Tensor.prototype, "toInt", null);
  22742. __decorate([
  22743. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22744. ], Tensor.prototype, "toBool", null);
  22745. __decorate([
  22746. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22747. ], Tensor.prototype, "print", null);
  22748. __decorate([
  22749. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22750. ], Tensor.prototype, "reshape", null);
  22751. __decorate([
  22752. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22753. ], Tensor.prototype, "reshapeAs", null);
  22754. __decorate([
  22755. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22756. ], Tensor.prototype, "expandDims", null);
  22757. __decorate([
  22758. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22759. ], Tensor.prototype, "cumsum", null);
  22760. __decorate([
  22761. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22762. ], Tensor.prototype, "squeeze", null);
  22763. __decorate([
  22764. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22765. ], Tensor.prototype, "clone", null);
  22766. __decorate([
  22767. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22768. ], Tensor.prototype, "toString", null);
  22769. Tensor = Tensor_1 = __decorate([
  22770. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22771. ], Tensor);
  22772. return Tensor;
  22773. var Tensor_1;
  22774. }());
  22775. exports.Tensor = Tensor;
  22776. var Variable = (function (_super) {
  22777. __extends(Variable, _super);
  22778. function Variable(initialValue, trainable, name) {
  22779. if (trainable === void 0) { trainable = true; }
  22780. var _this = _super.call(this, initialValue.shape, initialValue.dtype, null, initialValue.dataId) || this;
  22781. _this.trainable = trainable;
  22782. _this.name = name;
  22783. if (_this.name == null) {
  22784. _this.name = Variable_1.nextVarId.toString();
  22785. Variable_1.nextVarId++;
  22786. }
  22787. environment_1.ENV.engine.registerVariable(_this);
  22788. return _this;
  22789. }
  22790. Variable_1 = Variable;
  22791. Variable.variable = function (initialValue, trainable, name, dtype) {
  22792. if (trainable === void 0) { trainable = true; }
  22793. if (dtype != null && dtype !== initialValue.dtype) {
  22794. initialValue = initialValue.asType(dtype);
  22795. }
  22796. return new Variable_1(initialValue, trainable, name);
  22797. };
  22798. Variable.prototype.assign = function (newValue) {
  22799. if (newValue.dtype !== this.dtype) {
  22800. throw new Error("dtype of the new value (" + newValue.dtype + ") and " +
  22801. ("previous value (" + this.dtype + ") must match"));
  22802. }
  22803. if (!util.arraysEqual(newValue.shape, this.shape)) {
  22804. throw new Error("shape of the new value (" + newValue.shape + ") and " +
  22805. ("previous value (" + this.shape + ") must match"));
  22806. }
  22807. environment_1.ENV.engine.disposeTensor(this);
  22808. this.dataId = newValue.dataId;
  22809. environment_1.ENV.engine.registerTensor(this);
  22810. };
  22811. Variable.nextVarId = 0;
  22812. __decorate([
  22813. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22814. ], Variable.prototype, "assign", null);
  22815. __decorate([
  22816. doc_1.doc({ heading: 'Tensors', subheading: 'Creation' })
  22817. ], Variable, "variable", null);
  22818. Variable = Variable_1 = __decorate([
  22819. doc_1.doc({ heading: 'Tensors', subheading: 'Classes' })
  22820. ], Variable);
  22821. return Variable;
  22822. var Variable_1;
  22823. }(Tensor));
  22824. exports.Variable = Variable;
  22825. var variable = Variable.variable;
  22826. exports.variable = variable;
  22827. function computeStrides(shape) {
  22828. var rank = shape.length;
  22829. if (rank < 2) {
  22830. return [];
  22831. }
  22832. var strides = new Array(rank - 1);
  22833. strides[rank - 2] = shape[rank - 1];
  22834. for (var i = rank - 3; i >= 0; --i) {
  22835. strides[i] = strides[i + 1] * shape[i + 1];
  22836. }
  22837. return strides;
  22838. }
  22839. },{"./doc":49,"./environment":51,"./ops/ops":129,"./tensor_util":159,"./util":164}],159:[function(require,module,exports){
  22840. "use strict";
  22841. Object.defineProperty(exports, "__esModule", { value: true });
  22842. var util = require("./util");
  22843. var FORMAT_LIMIT_NUM_VALS = 20;
  22844. var FORMAT_NUM_FIRST_LAST_VALS = 3;
  22845. var FORMAT_NUM_SIG_DIGITS = 7;
  22846. function tensorToString(t, verbose) {
  22847. var vals = t.dataSync();
  22848. var padPerCol = computeMaxSizePerColumn(t);
  22849. var valsLines = subTensorToString(vals, t.shape, t.strides, padPerCol);
  22850. var lines = ['Tensor'];
  22851. if (verbose) {
  22852. lines.push(" dtype: " + t.dtype);
  22853. lines.push(" rank: " + t.rank);
  22854. lines.push(" shape: [" + t.shape + "]");
  22855. lines.push(" values:");
  22856. }
  22857. lines.push(valsLines.map(function (l) { return ' ' + l; }).join('\n'));
  22858. return lines.join('\n');
  22859. }
  22860. exports.tensorToString = tensorToString;
  22861. function computeMaxSizePerColumn(t) {
  22862. var vals = t.dataSync();
  22863. var n = t.size;
  22864. var numCols = t.strides[t.strides.length - 1];
  22865. var padPerCol = new Array(numCols).fill(0);
  22866. if (t.rank > 1) {
  22867. for (var row = 0; row < n / numCols; row++) {
  22868. var offset = row * numCols;
  22869. for (var j = 0; j < numCols; j++) {
  22870. padPerCol[j] =
  22871. Math.max(padPerCol[j], valToString(vals[offset + j], 0).length);
  22872. }
  22873. }
  22874. }
  22875. return padPerCol;
  22876. }
  22877. function valToString(val, pad) {
  22878. return util.rightPad(parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString(), pad);
  22879. }
  22880. function subTensorToString(vals, shape, strides, padPerCol, isLast) {
  22881. if (isLast === void 0) { isLast = true; }
  22882. var size = shape[0];
  22883. var rank = shape.length;
  22884. if (rank === 0) {
  22885. return [vals[0].toString()];
  22886. }
  22887. if (rank === 1) {
  22888. if (size > FORMAT_LIMIT_NUM_VALS) {
  22889. var firstVals = Array.from(vals.subarray(0, FORMAT_NUM_FIRST_LAST_VALS));
  22890. var lastVals = Array.from(vals.subarray(size - FORMAT_NUM_FIRST_LAST_VALS, size));
  22891. return [
  22892. '[' + firstVals.map(function (x, i) { return valToString(x, padPerCol[i]); }).join(', ') +
  22893. ', ..., ' +
  22894. lastVals
  22895. .map(function (x, i) { return valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i]); })
  22896. .join(', ') +
  22897. ']'
  22898. ];
  22899. }
  22900. return [
  22901. '[' +
  22902. Array.from(vals).map(function (x, i) { return valToString(x, padPerCol[i]); }).join(', ') +
  22903. ']'
  22904. ];
  22905. }
  22906. var subshape = shape.slice(1);
  22907. var substrides = strides.slice(1);
  22908. var stride = strides[0];
  22909. var lines = [];
  22910. if (size > FORMAT_LIMIT_NUM_VALS) {
  22911. for (var i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {
  22912. var start = i * stride;
  22913. var end = start + stride;
  22914. lines.push.apply(lines, subTensorToString(vals.subarray(start, end), subshape, substrides, padPerCol, false));
  22915. }
  22916. lines.push('...');
  22917. for (var i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {
  22918. var start = i * stride;
  22919. var end = start + stride;
  22920. lines.push.apply(lines, subTensorToString(vals.subarray(start, end), subshape, substrides, padPerCol, i === size - 1));
  22921. }
  22922. }
  22923. else {
  22924. for (var i = 0; i < size; i++) {
  22925. var start = i * stride;
  22926. var end = start + stride;
  22927. lines.push.apply(lines, subTensorToString(vals.subarray(start, end), subshape, substrides, padPerCol, i === size - 1));
  22928. }
  22929. }
  22930. var sep = rank === 2 ? ',' : '';
  22931. lines[0] = '[' + lines[0] + sep;
  22932. for (var i = 1; i < lines.length - 1; i++) {
  22933. lines[i] = ' ' + lines[i] + sep;
  22934. }
  22935. var newLineSep = ',\n';
  22936. for (var i = 2; i < rank; i++) {
  22937. newLineSep += '\n';
  22938. }
  22939. lines[lines.length - 1] =
  22940. ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);
  22941. return lines;
  22942. }
  22943. },{"./util":164}],160:[function(require,module,exports){
  22944. "use strict";
  22945. Object.defineProperty(exports, "__esModule", { value: true });
  22946. var environment_1 = require("./environment");
  22947. var tensor_1 = require("./tensor");
  22948. var util = require("./util");
  22949. exports.WEBGL_ENVS = [
  22950. {
  22951. 'BACKEND': 'test-webgl',
  22952. 'WEBGL_RENDER_FLOAT32_ENABLED': true,
  22953. 'WEBGL_DOWNLOAD_FLOAT_ENABLED': true,
  22954. 'WEBGL_VERSION': 1
  22955. },
  22956. {
  22957. 'BACKEND': 'test-webgl',
  22958. 'WEBGL_RENDER_FLOAT32_ENABLED': true,
  22959. 'WEBGL_DOWNLOAD_FLOAT_ENABLED': true,
  22960. 'WEBGL_VERSION': 2
  22961. }
  22962. ];
  22963. exports.CPU_ENVS = [{ 'BACKEND': 'test-cpu' }];
  22964. exports.CHROME_CPU_ENVS = [{ 'BACKEND': 'test-cpu', 'IS_CHROME': true }];
  22965. exports.NATIVE_ENV = {};
  22966. exports.BROWSER_ENVS = exports.WEBGL_ENVS.concat(exports.CPU_ENVS);
  22967. exports.ALL_ENVS = [exports.NATIVE_ENV].concat(exports.BROWSER_ENVS);
  22968. function expectArraysClose(actual, expected, epsilon) {
  22969. if (epsilon == null) {
  22970. epsilon = environment_1.ENV.get('TEST_EPSILON');
  22971. }
  22972. if (!(actual instanceof tensor_1.Tensor) && !(expected instanceof tensor_1.Tensor)) {
  22973. var aType = actual.constructor.name;
  22974. var bType = expected.constructor.name;
  22975. if (aType !== bType) {
  22976. throw new Error("Arrays are of different type actual: " + aType + " " +
  22977. ("vs expected: " + bType));
  22978. }
  22979. }
  22980. else if (actual instanceof tensor_1.Tensor && expected instanceof tensor_1.Tensor) {
  22981. if (actual.dtype !== expected.dtype) {
  22982. throw new Error("Arrays are of different type actual: " + actual.dtype + " " +
  22983. ("vs expected: " + expected.dtype + "."));
  22984. }
  22985. if (!util.arraysEqual(actual.shape, expected.shape)) {
  22986. throw new Error("Arrays are of different shape actual: " + actual.shape + " " +
  22987. ("vs expected: " + expected.shape + "."));
  22988. }
  22989. }
  22990. var actualValues;
  22991. var expectedValues;
  22992. if (actual instanceof tensor_1.Tensor) {
  22993. actualValues = actual.dataSync();
  22994. }
  22995. else {
  22996. actualValues = actual;
  22997. }
  22998. if (expected instanceof tensor_1.Tensor) {
  22999. expectedValues = expected.dataSync();
  23000. }
  23001. else {
  23002. expectedValues = expected;
  23003. }
  23004. if (actualValues.length !== expectedValues.length) {
  23005. throw new Error("Arrays have different lengths actual: " + actualValues.length + " vs " +
  23006. ("expected: " + expectedValues.length + ".\n") +
  23007. ("Actual: " + actualValues + ".\n") +
  23008. ("Expected: " + expectedValues + "."));
  23009. }
  23010. for (var i = 0; i < expectedValues.length; ++i) {
  23011. var a = actualValues[i];
  23012. var e = expectedValues[i];
  23013. if (!areClose(a, Number(e), epsilon)) {
  23014. throw new Error("Arrays differ: actual[" + i + "] = " + a + ", expected[" + i + "] = " + e + ".\n" +
  23015. ("Actual: " + actualValues + ".\n") +
  23016. ("Expected: " + expectedValues + "."));
  23017. }
  23018. }
  23019. }
  23020. exports.expectArraysClose = expectArraysClose;
  23021. function expectPromiseToFail(fn, done) {
  23022. fn().then(function () { return done.fail(); }, function () { return done(); });
  23023. }
  23024. exports.expectPromiseToFail = expectPromiseToFail;
  23025. function expectArraysEqual(actual, expected) {
  23026. return expectArraysClose(actual, expected, 0);
  23027. }
  23028. exports.expectArraysEqual = expectArraysEqual;
  23029. function expectNumbersClose(a, e, epsilon) {
  23030. if (epsilon == null) {
  23031. epsilon = environment_1.ENV.get('TEST_EPSILON');
  23032. }
  23033. if (!areClose(a, e, epsilon)) {
  23034. throw new Error("Numbers differ: actual === " + a + ", expected === " + e);
  23035. }
  23036. }
  23037. exports.expectNumbersClose = expectNumbersClose;
  23038. function areClose(a, e, epsilon) {
  23039. if (isNaN(a) && isNaN(e)) {
  23040. return true;
  23041. }
  23042. if (isNaN(a) || isNaN(e) || Math.abs(a - e) > epsilon) {
  23043. return false;
  23044. }
  23045. return true;
  23046. }
  23047. function expectValuesInRange(actual, low, high) {
  23048. var actualVals;
  23049. if (actual instanceof tensor_1.Tensor) {
  23050. actualVals = actual.dataSync();
  23051. }
  23052. else {
  23053. actualVals = actual;
  23054. }
  23055. for (var i = 0; i < actualVals.length; i++) {
  23056. if (actualVals[i] < low || actualVals[i] > high) {
  23057. throw new Error("Value out of range:" + actualVals[i] + " low: " + low + ", high: " + high);
  23058. }
  23059. }
  23060. }
  23061. exports.expectValuesInRange = expectValuesInRange;
  23062. function expectArrayBuffersEqual(actual, expected) {
  23063. expect(new Float32Array(actual)).toEqual(new Float32Array(expected));
  23064. }
  23065. exports.expectArrayBuffersEqual = expectArrayBuffersEqual;
  23066. },{"./environment":51,"./tensor":158,"./util":164}],161:[function(require,module,exports){
  23067. "use strict";
  23068. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  23069. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  23070. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  23071. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  23072. return c > 3 && r && Object.defineProperty(target, key, r), r;
  23073. };
  23074. Object.defineProperty(exports, "__esModule", { value: true });
  23075. var doc_1 = require("./doc");
  23076. var environment_1 = require("./environment");
  23077. var util_1 = require("./util");
  23078. var Tracking = (function () {
  23079. function Tracking() {
  23080. }
  23081. Tracking.tidy = function (nameOrFn, fn, gradMode) {
  23082. if (gradMode === void 0) { gradMode = false; }
  23083. var name = null;
  23084. if (fn == null) {
  23085. if (typeof nameOrFn !== 'function') {
  23086. throw new Error('Please provide a function to tidy()');
  23087. }
  23088. fn = nameOrFn;
  23089. }
  23090. else {
  23091. if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {
  23092. throw new Error('When calling with two arguments, the first argument ' +
  23093. 'to tidy() must be a string');
  23094. }
  23095. if (typeof fn !== 'function') {
  23096. throw new Error('When calling with two arguments, the 2nd argument ' +
  23097. 'to tidy() must be a function');
  23098. }
  23099. name = nameOrFn;
  23100. }
  23101. environment_1.ENV.engine.startScope(name, gradMode);
  23102. var result = fn();
  23103. if (result instanceof Promise) {
  23104. console.error('Cannot return a Promise inside of tidy.');
  23105. }
  23106. environment_1.ENV.engine.endScope(result, gradMode);
  23107. return result;
  23108. };
  23109. Tracking.dispose = function (container) {
  23110. var tensors = util_1.getTensorsInContainer(container);
  23111. tensors.forEach(function (tensor) { return tensor.dispose(); });
  23112. };
  23113. Tracking.keep = function (result) {
  23114. return environment_1.ENV.engine.keep(result);
  23115. };
  23116. Tracking.time = function (f) {
  23117. return environment_1.ENV.engine.time(f);
  23118. };
  23119. __decorate([
  23120. doc_1.doc({ heading: 'Performance', subheading: 'Memory' })
  23121. ], Tracking, "tidy", null);
  23122. __decorate([
  23123. doc_1.doc({ heading: 'Performance', subheading: 'Memory' })
  23124. ], Tracking, "dispose", null);
  23125. __decorate([
  23126. doc_1.doc({ heading: 'Performance', subheading: 'Memory' })
  23127. ], Tracking, "keep", null);
  23128. __decorate([
  23129. doc_1.doc({ heading: 'Performance', subheading: 'Timing' })
  23130. ], Tracking, "time", null);
  23131. return Tracking;
  23132. }());
  23133. exports.Tracking = Tracking;
  23134. },{"./doc":49,"./environment":51,"./util":164}],162:[function(require,module,exports){
  23135. "use strict";
  23136. Object.defineProperty(exports, "__esModule", { value: true });
  23137. var adadelta_optimizer_1 = require("./optimizers/adadelta_optimizer");
  23138. var adagrad_optimizer_1 = require("./optimizers/adagrad_optimizer");
  23139. var adam_optimizer_1 = require("./optimizers/adam_optimizer");
  23140. var adamax_optimizer_1 = require("./optimizers/adamax_optimizer");
  23141. var momentum_optimizer_1 = require("./optimizers/momentum_optimizer");
  23142. var optimizer_constructors_1 = require("./optimizers/optimizer_constructors");
  23143. var rmsprop_optimizer_1 = require("./optimizers/rmsprop_optimizer");
  23144. var sgd_optimizer_1 = require("./optimizers/sgd_optimizer");
  23145. [momentum_optimizer_1.MomentumOptimizer, sgd_optimizer_1.SGDOptimizer, adadelta_optimizer_1.AdadeltaOptimizer, adagrad_optimizer_1.AdagradOptimizer,
  23146. rmsprop_optimizer_1.RMSPropOptimizer, adamax_optimizer_1.AdamaxOptimizer, adam_optimizer_1.AdamOptimizer];
  23147. exports.train = {
  23148. sgd: optimizer_constructors_1.OptimizerConstructors.sgd,
  23149. momentum: optimizer_constructors_1.OptimizerConstructors.momentum,
  23150. adadelta: optimizer_constructors_1.OptimizerConstructors.adadelta,
  23151. adagrad: optimizer_constructors_1.OptimizerConstructors.adagrad,
  23152. rmsprop: optimizer_constructors_1.OptimizerConstructors.rmsprop,
  23153. adamax: optimizer_constructors_1.OptimizerConstructors.adamax,
  23154. adam: optimizer_constructors_1.OptimizerConstructors.adam
  23155. };
  23156. },{"./optimizers/adadelta_optimizer":145,"./optimizers/adagrad_optimizer":146,"./optimizers/adam_optimizer":147,"./optimizers/adamax_optimizer":148,"./optimizers/momentum_optimizer":149,"./optimizers/optimizer_constructors":151,"./optimizers/rmsprop_optimizer":153,"./optimizers/sgd_optimizer":154}],163:[function(require,module,exports){
  23157. "use strict";
  23158. Object.defineProperty(exports, "__esModule", { value: true });
  23159. var DType;
  23160. (function (DType) {
  23161. DType["float32"] = "float32";
  23162. DType["int32"] = "int32";
  23163. DType["bool"] = "bool";
  23164. })(DType = exports.DType || (exports.DType = {}));
  23165. var Rank;
  23166. (function (Rank) {
  23167. Rank["R0"] = "R0";
  23168. Rank["R1"] = "R1";
  23169. Rank["R2"] = "R2";
  23170. Rank["R3"] = "R3";
  23171. Rank["R4"] = "R4";
  23172. Rank["R5"] = "R5";
  23173. Rank["R6"] = "R6";
  23174. })(Rank = exports.Rank || (exports.Rank = {}));
  23175. var UpcastInt32AndMap;
  23176. (function (UpcastInt32AndMap) {
  23177. UpcastInt32AndMap["float32"] = "float32";
  23178. UpcastInt32AndMap["int32"] = "int32";
  23179. UpcastInt32AndMap["bool"] = "int32";
  23180. })(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
  23181. var UpcastBoolAndMap;
  23182. (function (UpcastBoolAndMap) {
  23183. UpcastBoolAndMap["float32"] = "float32";
  23184. UpcastBoolAndMap["int32"] = "int32";
  23185. UpcastBoolAndMap["bool"] = "bool";
  23186. })(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
  23187. var UpcastFloat32AndMap;
  23188. (function (UpcastFloat32AndMap) {
  23189. UpcastFloat32AndMap["float32"] = "float32";
  23190. UpcastFloat32AndMap["int32"] = "float32";
  23191. UpcastFloat32AndMap["bool"] = "float32";
  23192. })(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
  23193. var upcastTypeMap = {
  23194. float32: UpcastFloat32AndMap,
  23195. int32: UpcastInt32AndMap,
  23196. bool: UpcastBoolAndMap
  23197. };
  23198. function upcastType(typeA, typeB) {
  23199. return upcastTypeMap[typeA][typeB];
  23200. }
  23201. exports.upcastType = upcastType;
  23202. function sumOutType(type) {
  23203. return upcastType(type, 'int32');
  23204. }
  23205. exports.sumOutType = sumOutType;
  23206. },{}],164:[function(require,module,exports){
  23207. "use strict";
  23208. Object.defineProperty(exports, "__esModule", { value: true });
  23209. var tensor_1 = require("./tensor");
  23210. function assertArgumentIsTensor(x, argName, functionName) {
  23211. assert(x instanceof tensor_1.Tensor, "Argument '" + argName + "' passed to '" + functionName + "' must be a Tensor, " +
  23212. ("but got " + typeof x + "."));
  23213. }
  23214. function assertArgumentsAreTensors(args, functionName) {
  23215. var _loop_1 = function (argName) {
  23216. var arg = args[argName];
  23217. if (Array.isArray(arg)) {
  23218. arg.forEach(function (t, i) {
  23219. assertArgumentIsTensor(t, argName + "[" + i + "]", functionName);
  23220. });
  23221. }
  23222. else {
  23223. assertArgumentIsTensor(arg, argName, functionName);
  23224. }
  23225. };
  23226. for (var argName in args) {
  23227. _loop_1(argName);
  23228. }
  23229. }
  23230. exports.assertArgumentsAreTensors = assertArgumentsAreTensors;
  23231. function shuffle(array) {
  23232. var counter = array.length;
  23233. var temp = 0;
  23234. var index = 0;
  23235. while (counter > 0) {
  23236. index = (Math.random() * counter) | 0;
  23237. counter--;
  23238. temp = array[counter];
  23239. array[counter] = array[index];
  23240. array[index] = temp;
  23241. }
  23242. }
  23243. exports.shuffle = shuffle;
  23244. function clamp(min, x, max) {
  23245. return Math.max(min, Math.min(x, max));
  23246. }
  23247. exports.clamp = clamp;
  23248. function randUniform(a, b) {
  23249. return Math.random() * (b - a) + a;
  23250. }
  23251. exports.randUniform = randUniform;
  23252. function distSquared(a, b) {
  23253. var result = 0;
  23254. for (var i = 0; i < a.length; i++) {
  23255. var diff = Number(a[i]) - Number(b[i]);
  23256. result += diff * diff;
  23257. }
  23258. return result;
  23259. }
  23260. exports.distSquared = distSquared;
  23261. function assert(expr, msg) {
  23262. if (!expr) {
  23263. throw new Error(msg);
  23264. }
  23265. }
  23266. exports.assert = assert;
  23267. function assertShapesMatch(shapeA, shapeB, errorMessagePrefix) {
  23268. if (errorMessagePrefix === void 0) { errorMessagePrefix = ''; }
  23269. assert(arraysEqual(shapeA, shapeB), errorMessagePrefix + (" Shapes " + shapeA + " and " + shapeB + " must match"));
  23270. }
  23271. exports.assertShapesMatch = assertShapesMatch;
  23272. function assertTypesMatch(a, b) {
  23273. assert(a.dtype === b.dtype, " The dtypes of the first(" + a.dtype + ") and" +
  23274. (" second(" + b.dtype + ") input must match"));
  23275. }
  23276. exports.assertTypesMatch = assertTypesMatch;
  23277. function flatten(arr, ret) {
  23278. if (ret === void 0) { ret = []; }
  23279. if (Array.isArray(arr)) {
  23280. for (var i = 0; i < arr.length; ++i) {
  23281. flatten(arr[i], ret);
  23282. }
  23283. }
  23284. else {
  23285. ret.push(arr);
  23286. }
  23287. return ret;
  23288. }
  23289. exports.flatten = flatten;
  23290. function inferShape(val) {
  23291. if (isTypedArray(val)) {
  23292. return [val.length];
  23293. }
  23294. if (!Array.isArray(val)) {
  23295. return [];
  23296. }
  23297. var shape = [];
  23298. while (val instanceof Array) {
  23299. shape.push(val.length);
  23300. val = val[0];
  23301. }
  23302. return shape;
  23303. }
  23304. exports.inferShape = inferShape;
  23305. function sizeFromShape(shape) {
  23306. if (shape.length === 0) {
  23307. return 1;
  23308. }
  23309. var size = shape[0];
  23310. for (var i = 1; i < shape.length; i++) {
  23311. size *= shape[i];
  23312. }
  23313. return size;
  23314. }
  23315. exports.sizeFromShape = sizeFromShape;
  23316. function isScalarShape(shape) {
  23317. return shape.length === 0;
  23318. }
  23319. exports.isScalarShape = isScalarShape;
  23320. function arraysEqual(n1, n2) {
  23321. if (n1.length !== n2.length) {
  23322. return false;
  23323. }
  23324. for (var i = 0; i < n1.length; i++) {
  23325. if (n1[i] !== n2[i]) {
  23326. return false;
  23327. }
  23328. }
  23329. return true;
  23330. }
  23331. exports.arraysEqual = arraysEqual;
  23332. function isInt(a) {
  23333. return a % 1 === 0;
  23334. }
  23335. exports.isInt = isInt;
  23336. function tanh(x) {
  23337. if (Math.tanh != null) {
  23338. return Math.tanh(x);
  23339. }
  23340. if (x === Infinity) {
  23341. return 1;
  23342. }
  23343. else if (x === -Infinity) {
  23344. return -1;
  23345. }
  23346. else {
  23347. var e2x = Math.exp(2 * x);
  23348. return (e2x - 1) / (e2x + 1);
  23349. }
  23350. }
  23351. exports.tanh = tanh;
  23352. function sizeToSquarishShape(size) {
  23353. for (var a = Math.floor(Math.sqrt(size)); a > 1; --a) {
  23354. if (size % a === 0) {
  23355. return [a, size / a];
  23356. }
  23357. }
  23358. return [1, size];
  23359. }
  23360. exports.sizeToSquarishShape = sizeToSquarishShape;
  23361. function createShuffledIndices(n) {
  23362. var shuffledIndices = new Uint32Array(n);
  23363. for (var i = 0; i < n; ++i) {
  23364. shuffledIndices[i] = i;
  23365. }
  23366. shuffle(shuffledIndices);
  23367. return shuffledIndices;
  23368. }
  23369. exports.createShuffledIndices = createShuffledIndices;
  23370. function rightPad(a, size) {
  23371. if (size <= a.length) {
  23372. return a;
  23373. }
  23374. return a + ' '.repeat(size - a.length);
  23375. }
  23376. exports.rightPad = rightPad;
  23377. function repeatedTry(checkFn, delayFn, maxCounter) {
  23378. if (delayFn === void 0) { delayFn = function (counter) { return 0; }; }
  23379. return new Promise(function (resolve, reject) {
  23380. var tryCount = 0;
  23381. var tryFn = function () {
  23382. if (checkFn()) {
  23383. resolve();
  23384. return;
  23385. }
  23386. tryCount++;
  23387. var nextBackoff = delayFn(tryCount);
  23388. if (maxCounter != null && tryCount >= maxCounter) {
  23389. reject();
  23390. return;
  23391. }
  23392. setTimeout(tryFn, nextBackoff);
  23393. };
  23394. tryFn();
  23395. });
  23396. }
  23397. exports.repeatedTry = repeatedTry;
  23398. function getQueryParams(queryString) {
  23399. var params = {};
  23400. queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, function (s) {
  23401. var t = [];
  23402. for (var _i = 1; _i < arguments.length; _i++) {
  23403. t[_i - 1] = arguments[_i];
  23404. }
  23405. decodeParam(params, t[0], t[1]);
  23406. return t.join('=');
  23407. });
  23408. return params;
  23409. }
  23410. exports.getQueryParams = getQueryParams;
  23411. function decodeParam(params, name, value) {
  23412. params[decodeURIComponent(name)] = decodeURIComponent(value || '');
  23413. }
  23414. function inferFromImplicitShape(shape, size) {
  23415. var shapeProd = 1;
  23416. var implicitIdx = -1;
  23417. for (var i = 0; i < shape.length; ++i) {
  23418. if (shape[i] > 0) {
  23419. shapeProd *= shape[i];
  23420. }
  23421. else if (shape[i] === -1) {
  23422. if (implicitIdx !== -1) {
  23423. throw Error("Shapes can only have 1 implicit size. " +
  23424. ("Found - 1 at dim " + implicitIdx + " and dim " + i));
  23425. }
  23426. implicitIdx = i;
  23427. }
  23428. else if (shape[i] <= 0) {
  23429. throw Error("Shapes can not be <= 0. Found " + shape[i] + " at dim " + i);
  23430. }
  23431. }
  23432. if (implicitIdx === -1) {
  23433. if (size > 0 && size !== shapeProd) {
  23434. throw Error("Size(" + size + ") must match the product of shape " + shape);
  23435. }
  23436. return shape;
  23437. }
  23438. if (size % shapeProd !== 0) {
  23439. throw Error("The implicit shape can't be a fractional number. " +
  23440. ("Got " + size + " / " + shapeProd));
  23441. }
  23442. var newShape = shape.slice();
  23443. newShape[implicitIdx] = size / shapeProd;
  23444. return newShape;
  23445. }
  23446. exports.inferFromImplicitShape = inferFromImplicitShape;
  23447. function squeezeShape(shape, axis) {
  23448. var newShape = [];
  23449. var keptDims = [];
  23450. var j = 0;
  23451. for (var i = 0; i < shape.length; ++i) {
  23452. if (axis != null) {
  23453. if (axis[j] === i && shape[i] > 1) {
  23454. throw new Error("Can't squeeze axis " + i + " since its dim '" + shape[i] + "' is not 1");
  23455. }
  23456. if ((axis[j] == null || axis[j] > i) && shape[i] === 1) {
  23457. newShape.push(shape[i]);
  23458. keptDims.push(i);
  23459. }
  23460. if (axis[j] <= i) {
  23461. j++;
  23462. }
  23463. }
  23464. if (shape[i] > 1) {
  23465. newShape.push(shape[i]);
  23466. keptDims.push(i);
  23467. }
  23468. }
  23469. return { newShape: newShape, keptDims: keptDims };
  23470. }
  23471. exports.squeezeShape = squeezeShape;
  23472. function getTypedArrayFromDType(dtype, size) {
  23473. var values = null;
  23474. if (dtype == null || dtype === 'float32') {
  23475. values = new Float32Array(size);
  23476. }
  23477. else if (dtype === 'int32') {
  23478. values = new Int32Array(size);
  23479. }
  23480. else if (dtype === 'bool') {
  23481. values = new Uint8Array(size);
  23482. }
  23483. else {
  23484. throw new Error("Unknown data type " + dtype);
  23485. }
  23486. return values;
  23487. }
  23488. exports.getTypedArrayFromDType = getTypedArrayFromDType;
  23489. function isTensorInList(tensor, tensorList) {
  23490. for (var i = 0; i < tensorList.length; i++) {
  23491. if (tensorList[i].id === tensor.id) {
  23492. return true;
  23493. }
  23494. }
  23495. return false;
  23496. }
  23497. exports.isTensorInList = isTensorInList;
  23498. function checkForNaN(vals, dtype, name) {
  23499. if (dtype !== 'float32') {
  23500. return;
  23501. }
  23502. for (var i = 0; i < vals.length; i++) {
  23503. if (isNaN(vals[i])) {
  23504. throw Error("The result of the '" + name + "' has NaNs.");
  23505. }
  23506. }
  23507. }
  23508. exports.checkForNaN = checkForNaN;
  23509. function flattenNameArrayMap(nameArrayMap, keys) {
  23510. var xs = [];
  23511. if (nameArrayMap instanceof tensor_1.Tensor) {
  23512. xs.push(nameArrayMap);
  23513. }
  23514. else {
  23515. var xMap = nameArrayMap;
  23516. for (var i = 0; i < keys.length; i++) {
  23517. xs.push(xMap[keys[i]]);
  23518. }
  23519. }
  23520. return xs;
  23521. }
  23522. exports.flattenNameArrayMap = flattenNameArrayMap;
  23523. function unflattenToNameArrayMap(keys, flatArrays) {
  23524. if (keys.length !== flatArrays.length) {
  23525. throw new Error("Cannot unflatten Tensor[], keys and arrays are not of same length.");
  23526. }
  23527. var result = {};
  23528. for (var i = 0; i < keys.length; i++) {
  23529. result[keys[i]] = flatArrays[i];
  23530. }
  23531. return result;
  23532. }
  23533. exports.unflattenToNameArrayMap = unflattenToNameArrayMap;
  23534. function hasEncodingLoss(oldType, newType) {
  23535. if (newType === 'float32') {
  23536. return false;
  23537. }
  23538. if (newType === 'int32' && oldType !== 'float32') {
  23539. return false;
  23540. }
  23541. if (newType === 'bool' && oldType === 'bool') {
  23542. return false;
  23543. }
  23544. return true;
  23545. }
  23546. exports.hasEncodingLoss = hasEncodingLoss;
  23547. function copyTypedArray(array, dtype) {
  23548. if (dtype == null || dtype === 'float32') {
  23549. return new Float32Array(array);
  23550. }
  23551. else if (dtype === 'int32') {
  23552. return new Int32Array(array);
  23553. }
  23554. else if (dtype === 'bool') {
  23555. var bool = new Uint8Array(array.length);
  23556. for (var i = 0; i < bool.length; ++i) {
  23557. if (Math.round(array[i]) !== 0) {
  23558. bool[i] = 1;
  23559. }
  23560. }
  23561. return bool;
  23562. }
  23563. else {
  23564. throw new Error("Unknown data type " + dtype);
  23565. }
  23566. }
  23567. exports.copyTypedArray = copyTypedArray;
  23568. function isTypedArray(a) {
  23569. return a instanceof Float32Array || a instanceof Int32Array ||
  23570. a instanceof Uint8Array;
  23571. }
  23572. exports.isTypedArray = isTypedArray;
  23573. function bytesPerElement(dtype) {
  23574. if (dtype === 'float32' || dtype === 'int32') {
  23575. return 4;
  23576. }
  23577. else if (dtype === 'bool') {
  23578. return 1;
  23579. }
  23580. else {
  23581. throw new Error("Unknown dtype " + dtype);
  23582. }
  23583. }
  23584. exports.bytesPerElement = bytesPerElement;
  23585. function isFunction(f) {
  23586. return !!(f && f.constructor && f.call && f.apply);
  23587. }
  23588. exports.isFunction = isFunction;
  23589. function getTensorsInContainer(result) {
  23590. var list = [];
  23591. var seen = new Set();
  23592. walkTensorContainer(result, list, seen);
  23593. return list;
  23594. }
  23595. exports.getTensorsInContainer = getTensorsInContainer;
  23596. function walkTensorContainer(container, list, seen) {
  23597. if (container == null) {
  23598. return;
  23599. }
  23600. if (container instanceof tensor_1.Tensor) {
  23601. list.push(container);
  23602. return;
  23603. }
  23604. if (!isIterable(container)) {
  23605. return;
  23606. }
  23607. var iterable = container;
  23608. for (var k in iterable) {
  23609. var val = iterable[k];
  23610. if (!seen.has(val)) {
  23611. seen.add(val);
  23612. walkTensorContainer(val, list, seen);
  23613. }
  23614. }
  23615. }
  23616. function nearestDivisor(size, start) {
  23617. for (var i = start; i < size; ++i) {
  23618. if (size % i === 0) {
  23619. return i;
  23620. }
  23621. }
  23622. return size;
  23623. }
  23624. exports.nearestDivisor = nearestDivisor;
  23625. function isIterable(obj) {
  23626. return Array.isArray(obj) || typeof obj === 'object';
  23627. }
  23628. },{"./tensor":158}],165:[function(require,module,exports){
  23629. "use strict";
  23630. Object.defineProperty(exports, "__esModule", { value: true });
  23631. var version = '0.11.9';
  23632. exports.version = version;
  23633. },{}],166:[function(require,module,exports){
  23634. "use strict";
  23635. Object.defineProperty(exports, "__esModule", { value: true });
  23636. var gpgpu_util = require("./kernels/webgl/gpgpu_util");
  23637. exports.gpgpu_util = gpgpu_util;
  23638. var webgl_util = require("./kernels/webgl/webgl_util");
  23639. exports.webgl_util = webgl_util;
  23640. var backend_webgl_1 = require("./kernels/backend_webgl");
  23641. exports.MathBackendWebGL = backend_webgl_1.MathBackendWebGL;
  23642. var gpgpu_context_1 = require("./kernels/webgl/gpgpu_context");
  23643. exports.GPGPUContext = gpgpu_context_1.GPGPUContext;
  23644. },{"./kernels/backend_webgl":67,"./kernels/webgl/gpgpu_context":82,"./kernels/webgl/gpgpu_util":84,"./kernels/webgl/webgl_util":107}],167:[function(require,module,exports){
  23645. "use strict";
  23646. var __extends = (this && this.__extends) || (function () {
  23647. var extendStatics = Object.setPrototypeOf ||
  23648. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  23649. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  23650. return function (d, b) {
  23651. extendStatics(d, b);
  23652. function __() { this.constructor = d; }
  23653. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  23654. };
  23655. })();
  23656. Object.defineProperty(exports, "__esModule", { value: true });
  23657. var tfc = require("@tensorflow/tfjs-core");
  23658. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  23659. var K = require("./backend/tfjs_backend");
  23660. var generic_utils_1 = require("./utils/generic_utils");
  23661. var Activation = (function (_super) {
  23662. __extends(Activation, _super);
  23663. function Activation() {
  23664. return _super !== null && _super.apply(this, arguments) || this;
  23665. }
  23666. Activation.prototype.getConfig = function () {
  23667. return {};
  23668. };
  23669. return Activation;
  23670. }(tfjs_core_1.serialization.Serializable));
  23671. exports.Activation = Activation;
  23672. var Elu = (function (_super) {
  23673. __extends(Elu, _super);
  23674. function Elu() {
  23675. return _super !== null && _super.apply(this, arguments) || this;
  23676. }
  23677. Elu.prototype.apply = function (x, alpha) {
  23678. if (alpha === void 0) { alpha = 1; }
  23679. return K.elu(x, alpha);
  23680. };
  23681. Elu.className = 'elu';
  23682. return Elu;
  23683. }(Activation));
  23684. exports.Elu = Elu;
  23685. tfjs_core_1.serialization.SerializationMap.register(Elu);
  23686. var Selu = (function (_super) {
  23687. __extends(Selu, _super);
  23688. function Selu() {
  23689. return _super !== null && _super.apply(this, arguments) || this;
  23690. }
  23691. Selu.prototype.apply = function (x) {
  23692. return tfc.selu(x);
  23693. };
  23694. Selu.className = 'selu';
  23695. return Selu;
  23696. }(Activation));
  23697. exports.Selu = Selu;
  23698. tfjs_core_1.serialization.SerializationMap.register(Selu);
  23699. var Relu = (function (_super) {
  23700. __extends(Relu, _super);
  23701. function Relu() {
  23702. return _super !== null && _super.apply(this, arguments) || this;
  23703. }
  23704. Relu.prototype.apply = function (x) {
  23705. return tfc.relu(x);
  23706. };
  23707. Relu.className = 'relu';
  23708. return Relu;
  23709. }(Activation));
  23710. exports.Relu = Relu;
  23711. tfjs_core_1.serialization.SerializationMap.register(Relu);
  23712. var Relu6 = (function (_super) {
  23713. __extends(Relu6, _super);
  23714. function Relu6() {
  23715. return _super !== null && _super.apply(this, arguments) || this;
  23716. }
  23717. Relu6.prototype.apply = function (x) {
  23718. return tfjs_core_1.tidy(function () { return tfc.minimum(K.getScalar(6.0), tfc.relu(x)); });
  23719. };
  23720. Relu6.className = 'relu6';
  23721. return Relu6;
  23722. }(Activation));
  23723. exports.Relu6 = Relu6;
  23724. tfjs_core_1.serialization.SerializationMap.register(Relu6);
  23725. var Linear = (function (_super) {
  23726. __extends(Linear, _super);
  23727. function Linear() {
  23728. return _super !== null && _super.apply(this, arguments) || this;
  23729. }
  23730. Linear.prototype.apply = function (x) {
  23731. return x;
  23732. };
  23733. Linear.className = 'linear';
  23734. return Linear;
  23735. }(Activation));
  23736. exports.Linear = Linear;
  23737. tfjs_core_1.serialization.SerializationMap.register(Linear);
  23738. var Sigmoid = (function (_super) {
  23739. __extends(Sigmoid, _super);
  23740. function Sigmoid() {
  23741. return _super !== null && _super.apply(this, arguments) || this;
  23742. }
  23743. Sigmoid.prototype.apply = function (x) {
  23744. return tfc.sigmoid(x);
  23745. };
  23746. Sigmoid.className = 'sigmoid';
  23747. return Sigmoid;
  23748. }(Activation));
  23749. exports.Sigmoid = Sigmoid;
  23750. tfjs_core_1.serialization.SerializationMap.register(Sigmoid);
  23751. var HardSigmoid = (function (_super) {
  23752. __extends(HardSigmoid, _super);
  23753. function HardSigmoid() {
  23754. return _super !== null && _super.apply(this, arguments) || this;
  23755. }
  23756. HardSigmoid.prototype.apply = function (x) {
  23757. return K.hardSigmoid(x);
  23758. };
  23759. HardSigmoid.className = 'hardSigmoid';
  23760. return HardSigmoid;
  23761. }(Activation));
  23762. exports.HardSigmoid = HardSigmoid;
  23763. tfjs_core_1.serialization.SerializationMap.register(HardSigmoid);
  23764. var Softplus = (function (_super) {
  23765. __extends(Softplus, _super);
  23766. function Softplus() {
  23767. return _super !== null && _super.apply(this, arguments) || this;
  23768. }
  23769. Softplus.prototype.apply = function (x) {
  23770. return tfc.softplus(x);
  23771. };
  23772. Softplus.className = 'softplus';
  23773. return Softplus;
  23774. }(Activation));
  23775. exports.Softplus = Softplus;
  23776. tfjs_core_1.serialization.SerializationMap.register(Softplus);
  23777. var Softsign = (function (_super) {
  23778. __extends(Softsign, _super);
  23779. function Softsign() {
  23780. return _super !== null && _super.apply(this, arguments) || this;
  23781. }
  23782. Softsign.prototype.apply = function (x) {
  23783. return K.softsign(x);
  23784. };
  23785. Softsign.className = 'softsign';
  23786. return Softsign;
  23787. }(Activation));
  23788. exports.Softsign = Softsign;
  23789. tfjs_core_1.serialization.SerializationMap.register(Softsign);
  23790. var Tanh = (function (_super) {
  23791. __extends(Tanh, _super);
  23792. function Tanh() {
  23793. return _super !== null && _super.apply(this, arguments) || this;
  23794. }
  23795. Tanh.prototype.apply = function (x) {
  23796. return tfc.tanh(x);
  23797. };
  23798. Tanh.className = 'tanh';
  23799. return Tanh;
  23800. }(Activation));
  23801. exports.Tanh = Tanh;
  23802. tfjs_core_1.serialization.SerializationMap.register(Tanh);
  23803. var Softmax = (function (_super) {
  23804. __extends(Softmax, _super);
  23805. function Softmax() {
  23806. return _super !== null && _super.apply(this, arguments) || this;
  23807. }
  23808. Softmax.prototype.apply = function (x, axis) {
  23809. if (axis === void 0) { axis = (-1); }
  23810. return tfc.softmax(x, axis);
  23811. };
  23812. Softmax.className = 'softmax';
  23813. return Softmax;
  23814. }(Activation));
  23815. exports.Softmax = Softmax;
  23816. tfjs_core_1.serialization.SerializationMap.register(Softmax);
  23817. function serializeActivation(activation) {
  23818. return activation.getClassName();
  23819. }
  23820. exports.serializeActivation = serializeActivation;
  23821. function deserializeActivation(config, customObjects) {
  23822. if (customObjects === void 0) { customObjects = {}; }
  23823. return generic_utils_1.deserializeKerasObject(config, tfjs_core_1.serialization.SerializationMap.getMap().classNameMap, customObjects, 'activation');
  23824. }
  23825. exports.deserializeActivation = deserializeActivation;
  23826. function getActivation(identifier) {
  23827. if (identifier == null) {
  23828. var config = { className: 'linear', config: {} };
  23829. return deserializeActivation(config);
  23830. }
  23831. if (typeof identifier === 'string') {
  23832. var config = { className: identifier, config: {} };
  23833. return deserializeActivation(config);
  23834. }
  23835. else if (identifier instanceof Activation) {
  23836. return identifier;
  23837. }
  23838. else {
  23839. return deserializeActivation(identifier);
  23840. }
  23841. }
  23842. exports.getActivation = getActivation;
  23843. },{"./backend/tfjs_backend":169,"./utils/generic_utils":199,"@tensorflow/tfjs-core":54}],168:[function(require,module,exports){
  23844. "use strict";
  23845. Object.defineProperty(exports, "__esModule", { value: true });
  23846. var _epsilon = 1e-7;
  23847. function epsilon() {
  23848. return _epsilon;
  23849. }
  23850. exports.epsilon = epsilon;
  23851. function setEpsilon(e) {
  23852. _epsilon = e;
  23853. }
  23854. exports.setEpsilon = setEpsilon;
  23855. function imageDataFormat() {
  23856. return 'channelsLast';
  23857. }
  23858. exports.imageDataFormat = imageDataFormat;
  23859. },{}],169:[function(require,module,exports){
  23860. "use strict";
  23861. Object.defineProperty(exports, "__esModule", { value: true });
  23862. var tfc = require("@tensorflow/tfjs-core");
  23863. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  23864. var common_1 = require("../common");
  23865. var errors_1 = require("../errors");
  23866. var math_utils = require("../utils/math_utils");
  23867. var variables_1 = require("../variables");
  23868. var common_2 = require("./common");
  23869. var common_3 = require("./common");
  23870. var backend = 'webgl';
  23871. var DEFAULT_DTYPE = 'float32';
  23872. function disposeScalarCache() {
  23873. for (var typeKey in scalarCache) {
  23874. for (var key in scalarCache[typeKey]) {
  23875. scalarCache[typeKey][key].dispose();
  23876. delete scalarCache[typeKey][key];
  23877. }
  23878. }
  23879. }
  23880. exports.disposeScalarCache = disposeScalarCache;
  23881. function setBackend(requestedBackend) {
  23882. tfc.setBackend(requestedBackend);
  23883. backend = requestedBackend;
  23884. disposeScalarCache();
  23885. }
  23886. exports.setBackend = setBackend;
  23887. function getBackend() {
  23888. return backend;
  23889. }
  23890. exports.getBackend = getBackend;
  23891. var scalarCache = {
  23892. float32: {},
  23893. int32: {}
  23894. };
  23895. function getScalar(value, dtype) {
  23896. if (dtype === undefined) {
  23897. dtype = DEFAULT_DTYPE;
  23898. }
  23899. if (scalarCache[dtype][value] == null) {
  23900. scalarCache[dtype][value] = tfjs_core_1.scalar(value, dtype);
  23901. tfc.keep(scalarCache[dtype][value]);
  23902. }
  23903. return scalarCache[dtype][value];
  23904. }
  23905. exports.getScalar = getScalar;
  23906. exports.epsilon = common_2.epsilon;
  23907. function isBackendSymbolic() {
  23908. return false;
  23909. }
  23910. exports.isBackendSymbolic = isBackendSymbolic;
  23911. function shape(x) {
  23912. return x.shape;
  23913. }
  23914. exports.shape = shape;
  23915. function intShape(x) {
  23916. return x.shape;
  23917. }
  23918. exports.intShape = intShape;
  23919. function dtype(x) {
  23920. return (x instanceof tfjs_core_1.Tensor) ? DEFAULT_DTYPE : x.dtype;
  23921. }
  23922. exports.dtype = dtype;
  23923. function countParams(x) {
  23924. var shape = x.shape;
  23925. if (shape.length > 0) {
  23926. return shape.reduce(function (a, b) { return a * b; });
  23927. }
  23928. else {
  23929. return 1;
  23930. }
  23931. }
  23932. exports.countParams = countParams;
  23933. function cast(x, dtype) {
  23934. return x.asType(dtype);
  23935. }
  23936. exports.cast = cast;
  23937. function expandDims(x, axis) {
  23938. if (axis === void 0) { axis = -1; }
  23939. var outShape = shape(x).slice();
  23940. if (axis < 0) {
  23941. axis = outShape.length + axis + 1;
  23942. }
  23943. outShape.splice(axis, 0, 1);
  23944. return x.reshape(outShape);
  23945. }
  23946. exports.expandDims = expandDims;
  23947. function repeat(x, n) {
  23948. return tfjs_core_1.tidy(function () {
  23949. if (x.shape.length !== 2) {
  23950. throw new errors_1.ValueError("repeat() expects a rank-2 tensor, but received a " +
  23951. ("rank-" + x.shape.length + " tensor."));
  23952. }
  23953. var y = expandDims(x, 1);
  23954. return tile(y, [1, n, 1]);
  23955. });
  23956. }
  23957. exports.repeat = repeat;
  23958. function flatten(x) {
  23959. var newShape = [math_utils.arrayProd(x.shape)];
  23960. return x.reshape(newShape);
  23961. }
  23962. exports.flatten = flatten;
  23963. function batchFlatten(x) {
  23964. if (x.rank <= 1) {
  23965. throw new errors_1.ValueError("batchFlatten requires a minimum rank of 2. Got rank: " + x.rank + ".");
  23966. }
  23967. var newShape = [x.shape[0], math_utils.arrayProd(x.shape, 1)];
  23968. return x.reshape(newShape);
  23969. }
  23970. exports.batchFlatten = batchFlatten;
  23971. function sliceAlongFirstAxis(array, start, size) {
  23972. return tfjs_core_1.tidy(function () {
  23973. switch (array.rank) {
  23974. case 1:
  23975. return tfc.slice1d(array, start, size);
  23976. case 2:
  23977. return tfc.slice2d(array, [start, 0], [size, array.shape[1]]);
  23978. case 3:
  23979. return tfc.slice3d(array, [start, 0, 0], [size, array.shape[1], array.shape[2]]);
  23980. case 4:
  23981. return tfc.slice4d(array, [start, 0, 0, 0], [size, array.shape[1], array.shape[2], array.shape[3]]);
  23982. default:
  23983. throw new errors_1.ValueError("sliceAlongFirstAxis() received an unsupported tensor rank: " +
  23984. ("" + array.rank));
  23985. }
  23986. });
  23987. }
  23988. exports.sliceAlongFirstAxis = sliceAlongFirstAxis;
  23989. function sliceAlongLastAxis(array, start, size) {
  23990. return tfjs_core_1.tidy(function () {
  23991. switch (array.rank) {
  23992. case 1:
  23993. return tfc.slice1d(array, start, size);
  23994. case 2:
  23995. return tfc.slice2d(array, [0, start], [array.shape[0], size]);
  23996. case 3:
  23997. return tfc.slice3d(array, [0, 0, start], [array.shape[0], array.shape[1], size]);
  23998. case 4:
  23999. return tfc.slice4d(array, [0, 0, 0, start], [array.shape[0], array.shape[1], array.shape[2], size]);
  24000. default:
  24001. throw new errors_1.ValueError("sliceAlongLastAxis() received an unsupported tensor rank: " +
  24002. ("" + array.rank));
  24003. }
  24004. });
  24005. }
  24006. exports.sliceAlongLastAxis = sliceAlongLastAxis;
  24007. function sliceAlongAxis(array, start, size, axis) {
  24008. return tfjs_core_1.tidy(function () {
  24009. switch (array.rank) {
  24010. case 1:
  24011. return tfc.slice1d(array, start, size);
  24012. case 2:
  24013. switch (axis) {
  24014. case 1:
  24015. return sliceAlongFirstAxis(array, start, size);
  24016. case 2:
  24017. return sliceAlongLastAxis(array, start, size);
  24018. default:
  24019. throw new errors_1.ValueError("The axis is not within the rank of the tensor " +
  24020. ("" + axis));
  24021. }
  24022. case 3:
  24023. switch (axis) {
  24024. case 1:
  24025. return sliceAlongFirstAxis(array, start, size);
  24026. case 2:
  24027. return tfc.slice3d(array, [0, start, 0], [array.shape[0], size, array.shape[2]]);
  24028. case 3:
  24029. return sliceAlongLastAxis(array, start, size);
  24030. default:
  24031. throw new errors_1.ValueError("The axis is not within the rank of the tensor " +
  24032. ("" + axis));
  24033. }
  24034. case 4:
  24035. switch (axis) {
  24036. case 1:
  24037. return sliceAlongFirstAxis(array, start, size);
  24038. case 2:
  24039. return tfc.slice4d(array, [0, start, 0, 0], [array.shape[0], size, array.shape[2], array.shape[3]]);
  24040. case 3:
  24041. return tfc.slice4d(array, [0, 0, start, 0], [array.shape[0], array.shape[1], size, array.shape[3]]);
  24042. case 4:
  24043. return sliceAlongLastAxis(array, start, size);
  24044. default:
  24045. throw new errors_1.ValueError("The axis is not within the rank of the tensor " +
  24046. ("" + axis));
  24047. }
  24048. default:
  24049. throw new errors_1.ValueError("sliceAlongLastAxis() received an unsupported tensor rank: " +
  24050. ("" + array.rank));
  24051. }
  24052. });
  24053. }
  24054. exports.sliceAlongAxis = sliceAlongAxis;
  24055. function concatenate(tensors, axis) {
  24056. if (axis === void 0) { axis = -1; }
  24057. var rank;
  24058. if (axis < 0) {
  24059. rank = tensors[0].rank;
  24060. if (rank !== 0) {
  24061. axis = rank;
  24062. }
  24063. else {
  24064. axis = 0;
  24065. }
  24066. }
  24067. if (axis === tensors[0].rank) {
  24068. axis = -1;
  24069. }
  24070. return tfc.concat(tensors, axis);
  24071. }
  24072. exports.concatenate = concatenate;
  24073. function concatAlongFirstAxis(a, b) {
  24074. switch (a.rank) {
  24075. case 1:
  24076. return tfc.concat1d([a, b]);
  24077. case 2:
  24078. return tfc.concat2d([a, b], 0);
  24079. case 3:
  24080. return tfc.concat3d([a, b], 0);
  24081. case 4:
  24082. return tfc.concat4d([a, b], 0);
  24083. default:
  24084. throw new errors_1.ValueError('concatAlongFirstAxis() received an unsupported tensor rank: ' +
  24085. a.rank);
  24086. }
  24087. }
  24088. exports.concatAlongFirstAxis = concatAlongFirstAxis;
  24089. function tile(x, n) {
  24090. if (!Array.isArray(n)) {
  24091. n = [n];
  24092. }
  24093. if (x.rank !== n.length) {
  24094. throw new errors_1.ValueError("The length of input n (" + n.length + ") does not match " +
  24095. ("the number of dimensions in input x (" + x.rank + ")"));
  24096. }
  24097. return tfc.tile(x, n);
  24098. }
  24099. exports.tile = tile;
  24100. function identity(x) {
  24101. return x.clone();
  24102. }
  24103. exports.identity = identity;
  24104. function eyeVariable(size, dtype, name) {
  24105. return new variables_1.LayerVariable(tfc.eye(size, size, null, dtype), dtype, name);
  24106. }
  24107. exports.eyeVariable = eyeVariable;
  24108. function scalarTimesArray(c, x) {
  24109. return tfc.mul(c, x);
  24110. }
  24111. exports.scalarTimesArray = scalarTimesArray;
  24112. function scalarPlusArray(c, x) {
  24113. return tfc.add(c, x);
  24114. }
  24115. exports.scalarPlusArray = scalarPlusArray;
  24116. function randomNormal(shape, mean, stddev, dtype, seed) {
  24117. if (mean === void 0) { mean = 0.0; }
  24118. if (stddev === void 0) { stddev = 1.0; }
  24119. return tfc.randomNormal(shape, mean, stddev, dtype, seed);
  24120. }
  24121. exports.randomNormal = randomNormal;
  24122. function dot(x, y) {
  24123. if (y.rank !== 2) {
  24124. throw new errors_1.NotImplementedError("dot support for y other than rank 2 is not yet implemented: " +
  24125. ("y shape = " + shape));
  24126. }
  24127. else {
  24128. if (x.rank === 2) {
  24129. return tfc.matMul(x, y);
  24130. }
  24131. else if (x.rank === 3) {
  24132. var xShape0 = x.shape[0];
  24133. var xShape1 = x.shape[1];
  24134. var xShape2 = x.shape[2];
  24135. x = x.reshape([xShape0 * xShape1, xShape2]);
  24136. return tfc.matMul(x, y).reshape([
  24137. xShape0, xShape1, y.shape[1]
  24138. ]);
  24139. }
  24140. else {
  24141. throw new errors_1.NotImplementedError("dot support for x of rank " + x.rank + " is not yet implemented: " +
  24142. ("x shape = " + shape));
  24143. }
  24144. }
  24145. }
  24146. exports.dot = dot;
  24147. function sign(x) {
  24148. return tfjs_core_1.tidy(function () {
  24149. var zerosLikeX = tfjs_core_1.zerosLike(x);
  24150. var onesLikeX = tfjs_core_1.onesLike(x);
  24151. return tfjs_core_1.where(tfc.equal(x, zerosLikeX), zerosLikeX, tfjs_core_1.where(tfc.greater(x, tfjs_core_1.zerosLike(x)), onesLikeX, scalarTimesArray(getScalar(-1), onesLikeX)));
  24152. });
  24153. }
  24154. exports.sign = sign;
  24155. function qr(x) {
  24156. var _a = tfjs_core_1.tidy(function () {
  24157. if (x.shape.length !== 2) {
  24158. throw new errors_1.ValueError("qr() requires a 2D Tensor, but got a " + x.shape.length + "D Tensor.");
  24159. }
  24160. if (x.shape[0] < x.shape[1]) {
  24161. throw new errors_1.ValueError("qr() requires x.shape[0] >= x.shape[1], but got shape: [" + x.shape + "]");
  24162. }
  24163. var m = x.shape[0];
  24164. var n = x.shape[1];
  24165. var q = tfc.eye(m);
  24166. var r = x.clone();
  24167. var one2D = tfjs_core_1.tensor2d([[1]], [1, 1]);
  24168. var w = one2D.clone();
  24169. var _loop_1 = function (j) {
  24170. var rTemp = r;
  24171. var wTemp = w;
  24172. var qTemp = q;
  24173. _a = tfjs_core_1.tidy(function () {
  24174. var rjEnd1 = r.slice([j, j], [m - j, 1]);
  24175. var normX = tfc.norm(rjEnd1);
  24176. var rjj = r.slice([j, j], [1, 1]);
  24177. var s = tfc.neg(sign(rjj));
  24178. var u1 = rjj.sub(tfc.mul(s, normX));
  24179. var wPre = tfc.div(rjEnd1, u1);
  24180. if (wPre.shape[0] === 1) {
  24181. w = one2D.clone();
  24182. }
  24183. else {
  24184. w = one2D.concat(wPre.slice([1, 0], [wPre.shape[0] - 1, wPre.shape[1]]), 0);
  24185. }
  24186. var tau = tfc.neg(tfc.div(tfc.matMul(s, u1), normX));
  24187. var rjEndAll = r.slice([j, 0], [m - j, n]);
  24188. var tauTimesW = tau.mul(w);
  24189. if (j === 0) {
  24190. r = rjEndAll.sub(tauTimesW.matMul(w.transpose().matMul(rjEndAll)));
  24191. }
  24192. else {
  24193. r = r.slice([0, 0], [j, n])
  24194. .concat(rjEndAll.sub(tauTimesW.matMul(w.transpose().matMul(rjEndAll))), 0);
  24195. }
  24196. var qAllJEnd = q.slice([0, j], [m, q.shape[1] - j]);
  24197. if (j === 0) {
  24198. q = qAllJEnd.sub(qAllJEnd.matMul(w).matMul(tauTimesW.transpose()));
  24199. }
  24200. else {
  24201. q = q.slice([0, 0], [m, j])
  24202. .concat(qAllJEnd.sub(qAllJEnd.matMul(w).matMul(tauTimesW.transpose())), 1);
  24203. }
  24204. return [w, r, q];
  24205. }), w = _a[0], r = _a[1], q = _a[2];
  24206. tfjs_core_1.dispose([rTemp, wTemp, qTemp]);
  24207. var _a;
  24208. };
  24209. for (var j = 0; j < n; ++j) {
  24210. _loop_1(j);
  24211. }
  24212. return [q, r];
  24213. }), qOuter = _a[0], rOuter = _a[1];
  24214. return [qOuter, rOuter];
  24215. }
  24216. exports.qr = qr;
  24217. function oneHot(indices, numClasses) {
  24218. return tfjs_core_1.tidy(function () {
  24219. if (indices.rank !== 1) {
  24220. throw new Error('Only 1D one-hot tensors are supported in the ' +
  24221. 'deeplearn backend, at present.');
  24222. }
  24223. indices = indices.toInt();
  24224. return tfc.oneHot(indices, numClasses).toFloat();
  24225. });
  24226. }
  24227. exports.oneHot = oneHot;
  24228. function gather(reference, indices, axis) {
  24229. return tfjs_core_1.tidy(function () {
  24230. if (Array.isArray(indices)) {
  24231. indices = tfjs_core_1.tensor1d(indices, 'int32');
  24232. }
  24233. else {
  24234. indices = indices.toInt();
  24235. }
  24236. return tfc.gather(reference, indices, axis);
  24237. });
  24238. }
  24239. exports.gather = gather;
  24240. function square(x) {
  24241. return tfc.mulStrict(x, x);
  24242. }
  24243. exports.square = square;
  24244. function pow(x, a) {
  24245. return tfjs_core_1.tidy(function () {
  24246. if (typeof (a) === 'number') {
  24247. a = tfjs_core_1.scalar(Math.round(a), 'int32');
  24248. }
  24249. if (a.dtype !== 'int32') {
  24250. throw new errors_1.NotImplementedError("Non-int32 dtype (" + a.dtype + ") is not supported by pow() yet");
  24251. }
  24252. return tfc.pow(x, a);
  24253. });
  24254. }
  24255. exports.pow = pow;
  24256. function biasAdd(x, bias, dataFormat) {
  24257. return tfjs_core_1.tidy(function () {
  24258. if (dataFormat == null) {
  24259. dataFormat = common_3.imageDataFormat();
  24260. }
  24261. common_1.checkDataFormat(dataFormat);
  24262. if (bias.rank !== 1 && bias.rank !== x.rank) {
  24263. throw new errors_1.ValueError('Unexpected bias dimensions: ' + bias.rank +
  24264. '; expected it to be 1 or ' + x.rank);
  24265. }
  24266. var biasShape = bias.shape;
  24267. var y;
  24268. if (x.rank === 5) {
  24269. if (dataFormat === 'channelsFirst') {
  24270. if (biasShape.length === 1) {
  24271. y = x.add(bias.reshape([1, biasShape[0], 1, 1, 1]));
  24272. }
  24273. else {
  24274. y = x.add(bias.reshape([1, biasShape[3], biasShape[0], biasShape[1], biasShape[2]]));
  24275. }
  24276. }
  24277. else if (dataFormat === 'channelsLast') {
  24278. if (biasShape.length === 1) {
  24279. y = x.add(bias.reshape([1, 1, 1, 1, biasShape[0]]));
  24280. }
  24281. else {
  24282. y = x.add(bias.reshape([1].concat(biasShape)));
  24283. }
  24284. }
  24285. }
  24286. else if (x.rank === 4) {
  24287. if (dataFormat === 'channelsFirst') {
  24288. if (biasShape.length === 1) {
  24289. y = x.add(bias.reshape([1, biasShape[0], 1, 1]));
  24290. }
  24291. else {
  24292. y = x.add(bias.reshape([1, biasShape[2], biasShape[0], biasShape[1]]));
  24293. }
  24294. }
  24295. else if (dataFormat === 'channelsLast') {
  24296. if (biasShape.length === 1) {
  24297. y = x.add(bias.reshape([1, 1, 1, biasShape[0]]));
  24298. }
  24299. else {
  24300. y = x.add(bias.reshape([1].concat(biasShape)));
  24301. }
  24302. }
  24303. }
  24304. else if (x.rank === 3) {
  24305. if (dataFormat === 'channelsFirst') {
  24306. if (biasShape.length === 1) {
  24307. y = x.add(bias.reshape([1, biasShape[0], 1]));
  24308. }
  24309. else {
  24310. y = x.add(bias.reshape([1, biasShape[1], biasShape[0]]));
  24311. }
  24312. }
  24313. else if (dataFormat === 'channelsLast') {
  24314. if (biasShape.length === 1) {
  24315. y = x.add(bias.reshape([1, 1, biasShape[0]]));
  24316. }
  24317. else {
  24318. y = x.add(bias.reshape([1].concat(biasShape)));
  24319. }
  24320. }
  24321. }
  24322. else if (x.rank < 3) {
  24323. y = x.add(bias);
  24324. }
  24325. else {
  24326. throw new errors_1.ValueError("Unsupported input rank by biasAdd: " + x.rank);
  24327. }
  24328. return y;
  24329. });
  24330. }
  24331. exports.biasAdd = biasAdd;
  24332. function elu(x, alpha) {
  24333. if (alpha === void 0) { alpha = 1; }
  24334. if (alpha !== 1) {
  24335. throw new errors_1.NotImplementedError("Support for alpha values other than 1 (" + alpha + ") is not implemented " +
  24336. "yet.");
  24337. }
  24338. return tfc.elu(x);
  24339. }
  24340. exports.elu = elu;
  24341. function softsign(x) {
  24342. return tfjs_core_1.tidy(function () { return tfc.div(x, tfc.add(getScalar(1), tfc.abs(x))); });
  24343. }
  24344. exports.softsign = softsign;
  24345. function dropout(x, level, noiseShape, seed) {
  24346. return tfjs_core_1.tidy(function () {
  24347. if (noiseShape != null && !tfjs_core_1.util.arraysEqual(x.shape, noiseShape)) {
  24348. throw new errors_1.NotImplementedError('Non-default noise shape is not implemented yet: ' +
  24349. JSON.stringify(noiseShape));
  24350. }
  24351. if (seed != null) {
  24352. throw new errors_1.NotImplementedError('seed is not implemented for dropout yet.');
  24353. }
  24354. var multiplier = tfc.step(tfc.add(tfc.neg(level), tfc.randomUniform(x.shape, 0, 1, 'float32')));
  24355. multiplier = tfc.mul(tfc.div(getScalar(1), tfc.sub(getScalar(1), level)), multiplier);
  24356. return tfc.mul(x, multiplier);
  24357. });
  24358. }
  24359. exports.dropout = dropout;
  24360. function nameScope(name, fn) {
  24361. return common_1.nameScope(name, fn);
  24362. }
  24363. exports.nameScope = nameScope;
  24364. function floatx() {
  24365. return 'float32';
  24366. }
  24367. exports.floatx = floatx;
  24368. var _uidPrefixes = {};
  24369. function getUid(prefix) {
  24370. if (prefix === void 0) { prefix = ''; }
  24371. if (!(prefix in _uidPrefixes)) {
  24372. _uidPrefixes[prefix] = 0;
  24373. }
  24374. _uidPrefixes[prefix] += 1;
  24375. return prefix + _uidPrefixes[prefix].toString();
  24376. }
  24377. exports.getUid = getUid;
  24378. function hardSigmoid(x) {
  24379. return tfjs_core_1.tidy(function () {
  24380. var y = scalarPlusArray(getScalar(0.5), scalarTimesArray(getScalar(0.2), x));
  24381. return tfc.clipByValue(y, 0, 1);
  24382. });
  24383. }
  24384. exports.hardSigmoid = hardSigmoid;
  24385. function inTrainPhase(x, alt, training) {
  24386. if (training === void 0) { training = false; }
  24387. return training ? x() : alt();
  24388. }
  24389. exports.inTrainPhase = inTrainPhase;
  24390. function gradients(lossFn, variables) {
  24391. var variableList = variables.map(function (variable) { return variable.read(); });
  24392. var valudAndGrads = tfjs_core_1.variableGrads(lossFn, variableList);
  24393. return variables.map(function (variable) { return valudAndGrads.grads[variable.name]; });
  24394. }
  24395. exports.gradients = gradients;
  24396. },{"../common":171,"../errors":176,"../utils/math_utils":201,"../variables":203,"./common":168,"@tensorflow/tfjs-core":54}],170:[function(require,module,exports){
  24397. "use strict";
  24398. var __extends = (this && this.__extends) || (function () {
  24399. var extendStatics = Object.setPrototypeOf ||
  24400. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  24401. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  24402. return function (d, b) {
  24403. extendStatics(d, b);
  24404. function __() { this.constructor = d; }
  24405. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  24406. };
  24407. })();
  24408. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  24409. return new (P || (P = Promise))(function (resolve, reject) {
  24410. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  24411. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  24412. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  24413. step((generator = generator.apply(thisArg, _arguments || [])).next());
  24414. });
  24415. };
  24416. var __generator = (this && this.__generator) || function (thisArg, body) {
  24417. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  24418. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  24419. function verb(n) { return function (v) { return step([n, v]); }; }
  24420. function step(op) {
  24421. if (f) throw new TypeError("Generator is already executing.");
  24422. while (_) try {
  24423. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  24424. if (y = 0, t) op = [0, t.value];
  24425. switch (op[0]) {
  24426. case 0: case 1: t = op; break;
  24427. case 4: _.label++; return { value: op[1], done: false };
  24428. case 5: _.label++; y = op[1]; op = [0]; continue;
  24429. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  24430. default:
  24431. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  24432. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  24433. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  24434. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  24435. if (t[2]) _.ops.pop();
  24436. _.trys.pop(); continue;
  24437. }
  24438. op = body.call(thisArg, _);
  24439. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  24440. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  24441. }
  24442. };
  24443. Object.defineProperty(exports, "__esModule", { value: true });
  24444. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  24445. var K = require("./backend/tfjs_backend");
  24446. var generic_utils = require("./utils/generic_utils");
  24447. var Callback = (function () {
  24448. function Callback() {
  24449. this.validationData = null;
  24450. this.model = null;
  24451. }
  24452. Callback.prototype.setParams = function (params) {
  24453. this.params = params;
  24454. };
  24455. Callback.prototype.setModel = function (model) {
  24456. this.model = model;
  24457. };
  24458. Callback.prototype.onEpochBegin = function (epoch, logs) {
  24459. return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
  24460. return [2];
  24461. }); });
  24462. };
  24463. Callback.prototype.onEpochEnd = function (epoch, logs) {
  24464. return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
  24465. return [2];
  24466. }); });
  24467. };
  24468. Callback.prototype.onBatchBegin = function (batch, logs) {
  24469. return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
  24470. return [2];
  24471. }); });
  24472. };
  24473. Callback.prototype.onBatchEnd = function (batch, logs) {
  24474. return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
  24475. return [2];
  24476. }); });
  24477. };
  24478. Callback.prototype.onTrainBegin = function (logs) {
  24479. return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
  24480. return [2];
  24481. }); });
  24482. };
  24483. Callback.prototype.onTrainEnd = function (logs) {
  24484. return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
  24485. return [2];
  24486. }); });
  24487. };
  24488. return Callback;
  24489. }());
  24490. exports.Callback = Callback;
  24491. var CallbackList = (function () {
  24492. function CallbackList(callbacks, queueLength) {
  24493. if (queueLength === void 0) { queueLength = 10; }
  24494. if (callbacks == null) {
  24495. callbacks = [];
  24496. }
  24497. this.callbacks = callbacks;
  24498. this.queueLength = queueLength;
  24499. }
  24500. CallbackList.prototype.append = function (callback) {
  24501. this.callbacks.push(callback);
  24502. };
  24503. CallbackList.prototype.setParams = function (params) {
  24504. for (var _i = 0, _a = this.callbacks; _i < _a.length; _i++) {
  24505. var callback = _a[_i];
  24506. callback.setParams(params);
  24507. }
  24508. };
  24509. CallbackList.prototype.setModel = function (model) {
  24510. for (var _i = 0, _a = this.callbacks; _i < _a.length; _i++) {
  24511. var callback = _a[_i];
  24512. callback.setModel(model);
  24513. }
  24514. };
  24515. CallbackList.prototype.onEpochBegin = function (epoch, logs) {
  24516. return __awaiter(this, void 0, void 0, function () {
  24517. var _i, _a, callback;
  24518. return __generator(this, function (_b) {
  24519. switch (_b.label) {
  24520. case 0:
  24521. if (logs == null) {
  24522. logs = {};
  24523. }
  24524. _i = 0, _a = this.callbacks;
  24525. _b.label = 1;
  24526. case 1:
  24527. if (!(_i < _a.length)) return [3, 4];
  24528. callback = _a[_i];
  24529. return [4, callback.onEpochBegin(epoch, logs)];
  24530. case 2:
  24531. _b.sent();
  24532. _b.label = 3;
  24533. case 3:
  24534. _i++;
  24535. return [3, 1];
  24536. case 4: return [2];
  24537. }
  24538. });
  24539. });
  24540. };
  24541. CallbackList.prototype.onEpochEnd = function (epoch, logs) {
  24542. return __awaiter(this, void 0, void 0, function () {
  24543. var _i, _a, callback;
  24544. return __generator(this, function (_b) {
  24545. switch (_b.label) {
  24546. case 0:
  24547. if (logs == null) {
  24548. logs = {};
  24549. }
  24550. _i = 0, _a = this.callbacks;
  24551. _b.label = 1;
  24552. case 1:
  24553. if (!(_i < _a.length)) return [3, 4];
  24554. callback = _a[_i];
  24555. return [4, callback.onEpochEnd(epoch, logs)];
  24556. case 2:
  24557. _b.sent();
  24558. _b.label = 3;
  24559. case 3:
  24560. _i++;
  24561. return [3, 1];
  24562. case 4: return [2];
  24563. }
  24564. });
  24565. });
  24566. };
  24567. CallbackList.prototype.onBatchBegin = function (batch, logs) {
  24568. return __awaiter(this, void 0, void 0, function () {
  24569. var _i, _a, callback;
  24570. return __generator(this, function (_b) {
  24571. switch (_b.label) {
  24572. case 0:
  24573. if (logs == null) {
  24574. logs = {};
  24575. }
  24576. _i = 0, _a = this.callbacks;
  24577. _b.label = 1;
  24578. case 1:
  24579. if (!(_i < _a.length)) return [3, 4];
  24580. callback = _a[_i];
  24581. return [4, callback.onBatchBegin(batch, logs)];
  24582. case 2:
  24583. _b.sent();
  24584. _b.label = 3;
  24585. case 3:
  24586. _i++;
  24587. return [3, 1];
  24588. case 4: return [2];
  24589. }
  24590. });
  24591. });
  24592. };
  24593. CallbackList.prototype.onBatchEnd = function (batch, logs) {
  24594. return __awaiter(this, void 0, void 0, function () {
  24595. var _i, _a, callback;
  24596. return __generator(this, function (_b) {
  24597. switch (_b.label) {
  24598. case 0:
  24599. if (logs == null) {
  24600. logs = {};
  24601. }
  24602. _i = 0, _a = this.callbacks;
  24603. _b.label = 1;
  24604. case 1:
  24605. if (!(_i < _a.length)) return [3, 4];
  24606. callback = _a[_i];
  24607. return [4, callback.onBatchEnd(batch, logs)];
  24608. case 2:
  24609. _b.sent();
  24610. _b.label = 3;
  24611. case 3:
  24612. _i++;
  24613. return [3, 1];
  24614. case 4: return [2];
  24615. }
  24616. });
  24617. });
  24618. };
  24619. CallbackList.prototype.onTrainBegin = function (logs) {
  24620. return __awaiter(this, void 0, void 0, function () {
  24621. var _i, _a, callback;
  24622. return __generator(this, function (_b) {
  24623. switch (_b.label) {
  24624. case 0:
  24625. if (logs == null) {
  24626. logs = {};
  24627. }
  24628. _i = 0, _a = this.callbacks;
  24629. _b.label = 1;
  24630. case 1:
  24631. if (!(_i < _a.length)) return [3, 4];
  24632. callback = _a[_i];
  24633. return [4, callback.onTrainBegin(logs)];
  24634. case 2:
  24635. _b.sent();
  24636. _b.label = 3;
  24637. case 3:
  24638. _i++;
  24639. return [3, 1];
  24640. case 4: return [2];
  24641. }
  24642. });
  24643. });
  24644. };
  24645. CallbackList.prototype.onTrainEnd = function (logs) {
  24646. return __awaiter(this, void 0, void 0, function () {
  24647. var _i, _a, callback;
  24648. return __generator(this, function (_b) {
  24649. switch (_b.label) {
  24650. case 0:
  24651. if (logs == null) {
  24652. logs = {};
  24653. }
  24654. _i = 0, _a = this.callbacks;
  24655. _b.label = 1;
  24656. case 1:
  24657. if (!(_i < _a.length)) return [3, 4];
  24658. callback = _a[_i];
  24659. return [4, callback.onTrainEnd(logs)];
  24660. case 2:
  24661. _b.sent();
  24662. _b.label = 3;
  24663. case 3:
  24664. _i++;
  24665. return [3, 1];
  24666. case 4: return [2];
  24667. }
  24668. });
  24669. });
  24670. };
  24671. return CallbackList;
  24672. }());
  24673. exports.CallbackList = CallbackList;
  24674. var BaseLogger = (function (_super) {
  24675. __extends(BaseLogger, _super);
  24676. function BaseLogger() {
  24677. return _super.call(this) || this;
  24678. }
  24679. BaseLogger.prototype.onEpochBegin = function (epoch, logs) {
  24680. return __awaiter(this, void 0, void 0, function () {
  24681. return __generator(this, function (_a) {
  24682. this.seen = 0;
  24683. this.totals = {};
  24684. return [2];
  24685. });
  24686. });
  24687. };
  24688. BaseLogger.prototype.onBatchEnd = function (batch, logs) {
  24689. return __awaiter(this, void 0, void 0, function () {
  24690. var _this = this;
  24691. var batchSize, _loop_1, this_1, key;
  24692. return __generator(this, function (_a) {
  24693. if (logs == null) {
  24694. logs = {};
  24695. }
  24696. batchSize = logs['size'] == null ? 0 : logs['size'];
  24697. this.seen += batchSize;
  24698. _loop_1 = function (key) {
  24699. var value = logs[key];
  24700. if (typeof value === 'number') {
  24701. if (!this_1.totals.hasOwnProperty(key)) {
  24702. this_1.totals[key] = 0;
  24703. }
  24704. this_1.totals[key] = this_1.totals[key] + value * batchSize;
  24705. }
  24706. else {
  24707. var oldTotalsToDispose = void 0;
  24708. if (key in this_1.totals) {
  24709. oldTotalsToDispose = this_1.totals[key];
  24710. }
  24711. else {
  24712. this_1.totals[key] = K.getScalar(0);
  24713. }
  24714. this_1.totals[key] = tfjs_core_1.tidy(function () { return K.scalarPlusArray(_this.totals[key], tfjs_core_1.mul(value, K.getScalar(batchSize))); });
  24715. if (oldTotalsToDispose != null) {
  24716. oldTotalsToDispose.dispose();
  24717. }
  24718. }
  24719. };
  24720. this_1 = this;
  24721. for (key in logs) {
  24722. _loop_1(key);
  24723. }
  24724. return [2];
  24725. });
  24726. });
  24727. };
  24728. BaseLogger.prototype.onEpochEnd = function (epoch, logs) {
  24729. return __awaiter(this, void 0, void 0, function () {
  24730. var _this = this;
  24731. var _loop_2, this_2, _i, _a, key;
  24732. return __generator(this, function (_b) {
  24733. if (logs != null) {
  24734. _loop_2 = function (key) {
  24735. if (this_2.totals[key] == null) {
  24736. return "continue";
  24737. }
  24738. if (typeof this_2.totals[key] === 'number') {
  24739. logs[key] = this_2.totals[key] / this_2.seen;
  24740. }
  24741. else {
  24742. tfjs_core_1.tidy(function () {
  24743. logs[key] =
  24744. K.scalarTimesArray(tfjs_core_1.div(K.getScalar(1), K.getScalar(_this.seen)), _this.totals[key]);
  24745. _this.totals[key].dispose();
  24746. tfjs_core_1.keep(logs[key]);
  24747. });
  24748. }
  24749. };
  24750. this_2 = this;
  24751. for (_i = 0, _a = this.params['metrics']; _i < _a.length; _i++) {
  24752. key = _a[_i];
  24753. _loop_2(key);
  24754. }
  24755. }
  24756. return [2];
  24757. });
  24758. });
  24759. };
  24760. return BaseLogger;
  24761. }(Callback));
  24762. exports.BaseLogger = BaseLogger;
  24763. function resolveScalarsInLogs(logs) {
  24764. return __awaiter(this, void 0, void 0, function () {
  24765. var promises, keys, key, value, valueScalar, values, i;
  24766. return __generator(this, function (_a) {
  24767. switch (_a.label) {
  24768. case 0:
  24769. if (logs == null) {
  24770. return [2];
  24771. }
  24772. promises = [];
  24773. keys = [];
  24774. for (key in logs) {
  24775. value = logs[key];
  24776. if (typeof value !== 'number') {
  24777. valueScalar = value;
  24778. promises.push(valueScalar.data());
  24779. keys.push(key);
  24780. }
  24781. }
  24782. return [4, Promise.all(promises)];
  24783. case 1:
  24784. values = _a.sent();
  24785. for (i = 0; i < values.length; ++i) {
  24786. logs[keys[i]] = values[i][0];
  24787. }
  24788. return [2];
  24789. }
  24790. });
  24791. });
  24792. }
  24793. exports.resolveScalarsInLogs = resolveScalarsInLogs;
  24794. function disposeTensorsInLogs(logs) {
  24795. if (logs == null) {
  24796. return;
  24797. }
  24798. for (var key in logs) {
  24799. var value = logs[key];
  24800. if (typeof value !== 'number') {
  24801. value.dispose();
  24802. }
  24803. }
  24804. }
  24805. exports.disposeTensorsInLogs = disposeTensorsInLogs;
  24806. var History = (function (_super) {
  24807. __extends(History, _super);
  24808. function History() {
  24809. return _super !== null && _super.apply(this, arguments) || this;
  24810. }
  24811. History.prototype.onTrainBegin = function (logs) {
  24812. return __awaiter(this, void 0, void 0, function () {
  24813. return __generator(this, function (_a) {
  24814. this.epoch = [];
  24815. this.history = {};
  24816. return [2];
  24817. });
  24818. });
  24819. };
  24820. History.prototype.onEpochEnd = function (epoch, logs) {
  24821. return __awaiter(this, void 0, void 0, function () {
  24822. var key;
  24823. return __generator(this, function (_a) {
  24824. if (logs == null) {
  24825. logs = {};
  24826. }
  24827. this.epoch.push(epoch);
  24828. for (key in logs) {
  24829. if (this.history[key] == null) {
  24830. this.history[key] = [];
  24831. }
  24832. this.history[key].push(logs[key]);
  24833. }
  24834. return [2];
  24835. });
  24836. });
  24837. };
  24838. History.prototype.syncData = function () {
  24839. return __awaiter(this, void 0, void 0, function () {
  24840. var promises, keys, indices, key, valueArray, i, valueScalar, values, n;
  24841. return __generator(this, function (_a) {
  24842. switch (_a.label) {
  24843. case 0:
  24844. promises = [];
  24845. keys = [];
  24846. indices = [];
  24847. for (key in this.history) {
  24848. valueArray = this.history[key];
  24849. for (i = 0; i < valueArray.length; ++i) {
  24850. if (typeof valueArray[i] !== 'number') {
  24851. valueScalar = valueArray[i];
  24852. promises.push(valueScalar.data());
  24853. keys.push(key);
  24854. indices.push(i);
  24855. }
  24856. }
  24857. }
  24858. return [4, Promise.all(promises)];
  24859. case 1:
  24860. values = _a.sent();
  24861. for (n = 0; n < values.length; ++n) {
  24862. this.history[keys[n]][indices[n]].dispose();
  24863. this.history[keys[n]][indices[n]] = values[n][0];
  24864. }
  24865. return [2];
  24866. }
  24867. });
  24868. });
  24869. };
  24870. return History;
  24871. }(Callback));
  24872. exports.History = History;
  24873. var CustomCallback = (function (_super) {
  24874. __extends(CustomCallback, _super);
  24875. function CustomCallback(config) {
  24876. var _this = _super.call(this) || this;
  24877. _this.trainBegin = config.onTrainBegin;
  24878. _this.trainEnd = config.onTrainEnd;
  24879. _this.epochBegin = config.onEpochBegin;
  24880. _this.epochEnd = config.onEpochEnd;
  24881. _this.batchBegin = config.onBatchBegin;
  24882. _this.batchEnd = config.onBatchEnd;
  24883. return _this;
  24884. }
  24885. CustomCallback.prototype.onEpochBegin = function (epoch, logs) {
  24886. return __awaiter(this, void 0, void 0, function () {
  24887. return __generator(this, function (_a) {
  24888. switch (_a.label) {
  24889. case 0:
  24890. if (!(this.epochBegin != null)) return [3, 3];
  24891. return [4, resolveScalarsInLogs(logs)];
  24892. case 1:
  24893. _a.sent();
  24894. return [4, this.epochBegin(epoch, logs)];
  24895. case 2:
  24896. _a.sent();
  24897. _a.label = 3;
  24898. case 3: return [2];
  24899. }
  24900. });
  24901. });
  24902. };
  24903. CustomCallback.prototype.onEpochEnd = function (epoch, logs) {
  24904. return __awaiter(this, void 0, void 0, function () {
  24905. return __generator(this, function (_a) {
  24906. switch (_a.label) {
  24907. case 0:
  24908. if (!(this.epochEnd != null)) return [3, 3];
  24909. return [4, resolveScalarsInLogs(logs)];
  24910. case 1:
  24911. _a.sent();
  24912. return [4, this.epochEnd(epoch, logs)];
  24913. case 2:
  24914. _a.sent();
  24915. _a.label = 3;
  24916. case 3: return [2];
  24917. }
  24918. });
  24919. });
  24920. };
  24921. CustomCallback.prototype.onBatchBegin = function (batch, logs) {
  24922. return __awaiter(this, void 0, void 0, function () {
  24923. return __generator(this, function (_a) {
  24924. switch (_a.label) {
  24925. case 0:
  24926. if (!(this.batchBegin != null)) return [3, 3];
  24927. return [4, resolveScalarsInLogs(logs)];
  24928. case 1:
  24929. _a.sent();
  24930. return [4, this.batchBegin(batch, logs)];
  24931. case 2:
  24932. _a.sent();
  24933. _a.label = 3;
  24934. case 3: return [2];
  24935. }
  24936. });
  24937. });
  24938. };
  24939. CustomCallback.prototype.onBatchEnd = function (batch, logs) {
  24940. return __awaiter(this, void 0, void 0, function () {
  24941. return __generator(this, function (_a) {
  24942. switch (_a.label) {
  24943. case 0:
  24944. if (!(this.batchEnd != null)) return [3, 3];
  24945. return [4, resolveScalarsInLogs(logs)];
  24946. case 1:
  24947. _a.sent();
  24948. return [4, this.batchEnd(batch, logs)];
  24949. case 2:
  24950. _a.sent();
  24951. _a.label = 3;
  24952. case 3: return [2];
  24953. }
  24954. });
  24955. });
  24956. };
  24957. CustomCallback.prototype.onTrainBegin = function (logs) {
  24958. return __awaiter(this, void 0, void 0, function () {
  24959. return __generator(this, function (_a) {
  24960. switch (_a.label) {
  24961. case 0:
  24962. if (!(this.trainBegin != null)) return [3, 3];
  24963. return [4, resolveScalarsInLogs(logs)];
  24964. case 1:
  24965. _a.sent();
  24966. return [4, this.trainBegin(logs)];
  24967. case 2:
  24968. _a.sent();
  24969. _a.label = 3;
  24970. case 3: return [2];
  24971. }
  24972. });
  24973. });
  24974. };
  24975. CustomCallback.prototype.onTrainEnd = function (logs) {
  24976. return __awaiter(this, void 0, void 0, function () {
  24977. return __generator(this, function (_a) {
  24978. switch (_a.label) {
  24979. case 0:
  24980. if (!(this.trainEnd != null)) return [3, 3];
  24981. return [4, resolveScalarsInLogs(logs)];
  24982. case 1:
  24983. _a.sent();
  24984. return [4, this.trainEnd(logs)];
  24985. case 2:
  24986. _a.sent();
  24987. _a.label = 3;
  24988. case 3: return [2];
  24989. }
  24990. });
  24991. });
  24992. };
  24993. return CustomCallback;
  24994. }(Callback));
  24995. exports.CustomCallback = CustomCallback;
  24996. function standardizeCallbacks(callbacks) {
  24997. if (callbacks == null) {
  24998. return null;
  24999. }
  25000. if (callbacks instanceof Callback) {
  25001. return [callbacks];
  25002. }
  25003. if (Array.isArray(callbacks) && callbacks[0] instanceof Callback) {
  25004. return callbacks;
  25005. }
  25006. var callbackConfigs = generic_utils.toList(callbacks);
  25007. return callbackConfigs.map(function (callbackConfig) { return new CustomCallback(callbackConfig); });
  25008. }
  25009. exports.standardizeCallbacks = standardizeCallbacks;
  25010. },{"./backend/tfjs_backend":169,"./utils/generic_utils":199,"@tensorflow/tfjs-core":54}],171:[function(require,module,exports){
  25011. "use strict";
  25012. Object.defineProperty(exports, "__esModule", { value: true });
  25013. var generic_utils_1 = require("./utils/generic_utils");
  25014. var nameMap = new Map();
  25015. exports.VALID_DATA_FORMAT_VALUES = ['channelsFirst', 'channelsLast'];
  25016. function checkDataFormat(value) {
  25017. generic_utils_1.checkStringTypeUnionValue(exports.VALID_DATA_FORMAT_VALUES, 'DataFormat', value);
  25018. }
  25019. exports.checkDataFormat = checkDataFormat;
  25020. exports.VALID_PADDING_MODE_VALUES = ['valid', 'same', 'causal'];
  25021. function checkPaddingMode(value) {
  25022. generic_utils_1.checkStringTypeUnionValue(exports.VALID_PADDING_MODE_VALUES, 'PaddingMode', value);
  25023. }
  25024. exports.checkPaddingMode = checkPaddingMode;
  25025. exports.VALID_POOL_MODE_VALUES = ['max', 'avg'];
  25026. function checkPoolMode(value) {
  25027. generic_utils_1.checkStringTypeUnionValue(exports.VALID_POOL_MODE_VALUES, 'PoolMode', value);
  25028. }
  25029. exports.checkPoolMode = checkPoolMode;
  25030. var _nameScopeStack = [];
  25031. var _nameScopeDivider = '/';
  25032. function nameScope(name, fn) {
  25033. _nameScopeStack.push(name);
  25034. try {
  25035. var val = fn();
  25036. _nameScopeStack.pop();
  25037. return val;
  25038. }
  25039. catch (e) {
  25040. _nameScopeStack.pop();
  25041. throw e;
  25042. }
  25043. }
  25044. exports.nameScope = nameScope;
  25045. function currentNameScopePrefix() {
  25046. if (_nameScopeStack.length === 0) {
  25047. return '';
  25048. }
  25049. else {
  25050. return _nameScopeStack.join(_nameScopeDivider) + _nameScopeDivider;
  25051. }
  25052. }
  25053. function getScopedTensorName(tensorName) {
  25054. if (!isValidTensorName(tensorName)) {
  25055. throw new Error('Not a valid tensor name: \'' + tensorName + '\'');
  25056. }
  25057. return currentNameScopePrefix() + tensorName;
  25058. }
  25059. exports.getScopedTensorName = getScopedTensorName;
  25060. function getUniqueTensorName(scopedName) {
  25061. if (!isValidTensorName(scopedName)) {
  25062. throw new Error('Not a valid tensor name: \'' + scopedName + '\'');
  25063. }
  25064. if (!nameMap.has(scopedName)) {
  25065. nameMap.set(scopedName, 0);
  25066. }
  25067. var index = nameMap.get(scopedName);
  25068. nameMap.set(scopedName, nameMap.get(scopedName) + 1);
  25069. if (index > 0) {
  25070. var result = scopedName + '_' + index;
  25071. nameMap.set(result, 1);
  25072. return result;
  25073. }
  25074. else {
  25075. return scopedName;
  25076. }
  25077. }
  25078. exports.getUniqueTensorName = getUniqueTensorName;
  25079. var tensorNameRegex = new RegExp(/^[A-Za-z][A-Za-z0-9\._\/]*$/);
  25080. function isValidTensorName(name) {
  25081. return name.match(tensorNameRegex) ? true : false;
  25082. }
  25083. exports.isValidTensorName = isValidTensorName;
  25084. },{"./utils/generic_utils":199}],172:[function(require,module,exports){
  25085. "use strict";
  25086. var __extends = (this && this.__extends) || (function () {
  25087. var extendStatics = Object.setPrototypeOf ||
  25088. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  25089. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  25090. return function (d, b) {
  25091. extendStatics(d, b);
  25092. function __() { this.constructor = d; }
  25093. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  25094. };
  25095. })();
  25096. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  25097. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  25098. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  25099. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  25100. return c > 3 && r && Object.defineProperty(target, key, r), r;
  25101. };
  25102. Object.defineProperty(exports, "__esModule", { value: true });
  25103. var tfc = require("@tensorflow/tfjs-core");
  25104. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  25105. var K = require("./backend/tfjs_backend");
  25106. var generic_utils_1 = require("./utils/generic_utils");
  25107. function calcL2Norms(w, axis) {
  25108. return tfjs_core_1.tidy(function () { return tfc.sqrt(tfc.sum(K.square(w), axis, true)); });
  25109. }
  25110. var Constraint = (function (_super) {
  25111. __extends(Constraint, _super);
  25112. function Constraint() {
  25113. return _super !== null && _super.apply(this, arguments) || this;
  25114. }
  25115. Constraint.prototype.getConfig = function () {
  25116. return {};
  25117. };
  25118. Constraint = __decorate([
  25119. tfjs_core_1.doc({ heading: 'Constraints', subheading: 'Classes', namespace: 'constraints' })
  25120. ], Constraint);
  25121. return Constraint;
  25122. }(tfjs_core_1.serialization.Serializable));
  25123. exports.Constraint = Constraint;
  25124. var MaxNorm = (function (_super) {
  25125. __extends(MaxNorm, _super);
  25126. function MaxNorm(config) {
  25127. var _this = _super.call(this) || this;
  25128. _this.defaultMaxValue = 2;
  25129. _this.defaultAxis = 0;
  25130. _this.maxValue =
  25131. config.maxValue != null ? config.maxValue : _this.defaultMaxValue;
  25132. _this.axis = config.axis != null ? config.axis : _this.defaultAxis;
  25133. return _this;
  25134. }
  25135. MaxNorm.prototype.apply = function (w) {
  25136. var _this = this;
  25137. return tfjs_core_1.tidy(function () {
  25138. var norms = calcL2Norms(w, _this.axis);
  25139. var desired = tfc.clipByValue(norms, 0, _this.maxValue);
  25140. return tfc.mul(w, tfc.div(desired, K.scalarPlusArray(K.getScalar(K.epsilon()), norms)));
  25141. });
  25142. };
  25143. MaxNorm.prototype.getConfig = function () {
  25144. return { maxValue: this.maxValue, axis: this.axis };
  25145. };
  25146. MaxNorm.className = 'MaxNorm';
  25147. return MaxNorm;
  25148. }(Constraint));
  25149. exports.MaxNorm = MaxNorm;
  25150. tfjs_core_1.serialization.SerializationMap.register(MaxNorm);
  25151. var UnitNorm = (function (_super) {
  25152. __extends(UnitNorm, _super);
  25153. function UnitNorm(config) {
  25154. var _this = _super.call(this) || this;
  25155. _this.defaultAxis = 0;
  25156. _this.axis = config.axis != null ? config.axis : _this.defaultAxis;
  25157. return _this;
  25158. }
  25159. UnitNorm.prototype.apply = function (w) {
  25160. var _this = this;
  25161. return tfjs_core_1.tidy(function () { return tfc.div(w, K.scalarPlusArray(K.getScalar(K.epsilon()), calcL2Norms(w, _this.axis))); });
  25162. };
  25163. UnitNorm.prototype.getConfig = function () {
  25164. return { axis: this.axis };
  25165. };
  25166. UnitNorm.className = 'UnitNorm';
  25167. return UnitNorm;
  25168. }(Constraint));
  25169. exports.UnitNorm = UnitNorm;
  25170. tfjs_core_1.serialization.SerializationMap.register(UnitNorm);
  25171. var NonNeg = (function (_super) {
  25172. __extends(NonNeg, _super);
  25173. function NonNeg() {
  25174. return _super !== null && _super.apply(this, arguments) || this;
  25175. }
  25176. NonNeg.prototype.apply = function (w) {
  25177. return tfc.relu(w);
  25178. };
  25179. NonNeg.className = 'NonNeg';
  25180. return NonNeg;
  25181. }(Constraint));
  25182. exports.NonNeg = NonNeg;
  25183. tfjs_core_1.serialization.SerializationMap.register(NonNeg);
  25184. var MinMaxNorm = (function (_super) {
  25185. __extends(MinMaxNorm, _super);
  25186. function MinMaxNorm(config) {
  25187. var _this = _super.call(this) || this;
  25188. _this.defaultMinValue = 0.0;
  25189. _this.defaultMaxValue = 1.0;
  25190. _this.defaultRate = 1.0;
  25191. _this.defaultAxis = 0;
  25192. _this.minValue =
  25193. config.minValue != null ? config.minValue : _this.defaultMinValue;
  25194. _this.maxValue =
  25195. config.maxValue != null ? config.maxValue : _this.defaultMaxValue;
  25196. _this.rate = config.rate != null ? config.rate : _this.defaultRate;
  25197. _this.axis = config.axis != null ? config.axis : _this.defaultAxis;
  25198. return _this;
  25199. }
  25200. MinMaxNorm.prototype.apply = function (w) {
  25201. var _this = this;
  25202. return tfjs_core_1.tidy(function () {
  25203. var norms = calcL2Norms(w, _this.axis);
  25204. var desired = tfc.add(K.scalarTimesArray(K.getScalar(_this.rate), tfc.clipByValue(norms, _this.minValue, _this.maxValue)), K.scalarTimesArray(K.getScalar(1.0 - _this.rate), norms));
  25205. return tfc.mul(w, tfc.div(desired, K.scalarPlusArray(K.getScalar(K.epsilon()), norms)));
  25206. });
  25207. };
  25208. MinMaxNorm.prototype.getConfig = function () {
  25209. return {
  25210. minValue: this.minValue,
  25211. maxValue: this.maxValue,
  25212. rate: this.rate,
  25213. axis: this.axis
  25214. };
  25215. };
  25216. MinMaxNorm.className = 'MinMaxNorm';
  25217. return MinMaxNorm;
  25218. }(Constraint));
  25219. exports.MinMaxNorm = MinMaxNorm;
  25220. tfjs_core_1.serialization.SerializationMap.register(MinMaxNorm);
  25221. exports.CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP = {
  25222. 'maxNorm': 'MaxNorm',
  25223. 'minMaxNorm': 'MinMaxNorm',
  25224. 'nonNeg': 'NonNeg',
  25225. 'unitNorm': 'UnitNorm'
  25226. };
  25227. function serializeConstraint(constraint) {
  25228. return generic_utils_1.serializeKerasObject(constraint);
  25229. }
  25230. exports.serializeConstraint = serializeConstraint;
  25231. function deserializeConstraint(config, customObjects) {
  25232. if (customObjects === void 0) { customObjects = {}; }
  25233. return generic_utils_1.deserializeKerasObject(config, tfjs_core_1.serialization.SerializationMap.getMap().classNameMap, customObjects, 'constraint');
  25234. }
  25235. exports.deserializeConstraint = deserializeConstraint;
  25236. function getConstraint(identifier) {
  25237. if (identifier == null) {
  25238. return null;
  25239. }
  25240. if (typeof identifier === 'string') {
  25241. var className = identifier in exports.CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP ?
  25242. exports.CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] :
  25243. identifier;
  25244. var config = { className: className, config: {} };
  25245. return deserializeConstraint(config);
  25246. }
  25247. else if (identifier instanceof Constraint) {
  25248. return identifier;
  25249. }
  25250. else {
  25251. return deserializeConstraint(identifier);
  25252. }
  25253. }
  25254. exports.getConstraint = getConstraint;
  25255. },{"./backend/tfjs_backend":169,"./utils/generic_utils":199,"@tensorflow/tfjs-core":54}],173:[function(require,module,exports){
  25256. "use strict";
  25257. Object.defineProperty(exports, "__esModule", { value: true });
  25258. var errors_1 = require("../errors");
  25259. var topology_1 = require("./topology");
  25260. function assertFeedCompatibility(key, val) {
  25261. if (key.dtype != null && key.dtype !== val.dtype) {
  25262. throw new errors_1.ValueError("The dtype of the feed (" + val.dtype + ") is incompatible with that of " +
  25263. ("the key '" + key.name + "' (" + key.dtype + ")."));
  25264. }
  25265. if (key.shape != null) {
  25266. if (key.shape.length !== val.shape.length) {
  25267. throw new errors_1.ValueError("The rank of feed (" + val.shape.length + ") does not match the rank of " +
  25268. ("the key (" + key.shape.length + ")."));
  25269. }
  25270. for (var i = 0; i < key.shape.length; ++i) {
  25271. if (key.shape[i] != null && key.shape[i] !== val.shape[i]) {
  25272. throw new errors_1.ValueError("The " + i + "-th dimension of the feed (" + val.shape[i] + ") is " +
  25273. ("incompatible with that of the key (" + key.shape[i] + ")."));
  25274. }
  25275. }
  25276. }
  25277. }
  25278. var FeedDict = (function () {
  25279. function FeedDict(feeds) {
  25280. this.id2Value = {};
  25281. if (feeds instanceof FeedDict) {
  25282. for (var id in feeds.id2Value) {
  25283. this.id2Value[id] = feeds.id2Value[id];
  25284. }
  25285. }
  25286. else {
  25287. if (feeds == null) {
  25288. return;
  25289. }
  25290. for (var _i = 0, feeds_1 = feeds; _i < feeds_1.length; _i++) {
  25291. var feed = feeds_1[_i];
  25292. this.add(feed.key, feed.value);
  25293. }
  25294. }
  25295. }
  25296. FeedDict.prototype.add = function (key, value) {
  25297. assertFeedCompatibility(key, value);
  25298. if (this.id2Value[key.id] == null) {
  25299. this.id2Value[key.id] = value;
  25300. }
  25301. else {
  25302. throw new errors_1.ValueError("Duplicate key: name=" + key.name + ", id=" + key.id);
  25303. }
  25304. return this;
  25305. };
  25306. FeedDict.prototype.addFeed = function (feed) {
  25307. this.add(feed.key, feed.value);
  25308. };
  25309. FeedDict.prototype.hasKey = function (key) {
  25310. return this.id2Value[key.id] != null;
  25311. };
  25312. FeedDict.prototype.getValue = function (key) {
  25313. if (this.id2Value[key.id] == null) {
  25314. throw new errors_1.ValueError("Nonexistent key: " + JSON.stringify(key));
  25315. }
  25316. else {
  25317. return this.id2Value[key.id];
  25318. }
  25319. };
  25320. return FeedDict;
  25321. }());
  25322. exports.FeedDict = FeedDict;
  25323. function execute(fetches, feedDict, kwargs) {
  25324. var arrayFetches = Array.isArray(fetches);
  25325. var fetchArray = arrayFetches ? fetches : [fetches];
  25326. var outputs = [];
  25327. var internalFeedDict = new FeedDict(feedDict);
  25328. for (var _i = 0, fetchArray_1 = fetchArray; _i < fetchArray_1.length; _i++) {
  25329. var fetch_1 = fetchArray_1[_i];
  25330. outputs.push(executeInternal(fetch_1, internalFeedDict, kwargs));
  25331. }
  25332. return arrayFetches ? outputs : outputs[0];
  25333. }
  25334. exports.execute = execute;
  25335. function executeInternal(fetch, internalFeedDict, kwargs) {
  25336. if (internalFeedDict.hasKey(fetch)) {
  25337. return internalFeedDict.getValue(fetch);
  25338. }
  25339. if (fetch.sourceLayer instanceof topology_1.InputLayer) {
  25340. throw new errors_1.ValueError("Missing a feed value for SymbolicTensor from InputLayer " +
  25341. ("'" + topology_1.InputLayer.name + "'"));
  25342. }
  25343. var inputs = fetch.inputs;
  25344. var inputValues = [];
  25345. for (var _i = 0, inputs_1 = inputs; _i < inputs_1.length; _i++) {
  25346. var input = inputs_1[_i];
  25347. var inputVal = executeInternal(input, internalFeedDict, kwargs);
  25348. inputValues.push(inputVal);
  25349. }
  25350. var output = fetch.sourceLayer.apply(inputValues, kwargs);
  25351. if (!Array.isArray(output)) {
  25352. output = [output];
  25353. }
  25354. var layerOutputs = getNodeOutputs(fetch);
  25355. var outputSymbolicTensors = Array.isArray(layerOutputs) ? layerOutputs : [layerOutputs];
  25356. for (var i = 0; i < outputSymbolicTensors.length; ++i) {
  25357. internalFeedDict.add(outputSymbolicTensors[i], output[i]);
  25358. }
  25359. return output.length === 1 ? output[0] : output[fetch.outputTensorIndex];
  25360. }
  25361. function getNodeOutputs(fetch) {
  25362. var layerOutputs;
  25363. if (fetch.sourceLayer.inboundNodes.length === 1) {
  25364. layerOutputs = fetch.sourceLayer.output;
  25365. }
  25366. else {
  25367. var nodeIndex = null;
  25368. for (var i = 0; i < fetch.sourceLayer.inboundNodes.length; ++i) {
  25369. for (var _i = 0, _a = fetch.sourceLayer.inboundNodes[i]
  25370. .outputTensors; _i < _a.length; _i++) {
  25371. var outputTensor = _a[_i];
  25372. if (outputTensor.id === fetch.id) {
  25373. nodeIndex = i;
  25374. break;
  25375. }
  25376. }
  25377. }
  25378. layerOutputs = fetch.sourceLayer.getOutputAt(nodeIndex);
  25379. }
  25380. return layerOutputs;
  25381. }
  25382. },{"../errors":176,"./topology":174}],174:[function(require,module,exports){
  25383. "use strict";
  25384. var __extends = (this && this.__extends) || (function () {
  25385. var extendStatics = Object.setPrototypeOf ||
  25386. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  25387. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  25388. return function (d, b) {
  25389. extendStatics(d, b);
  25390. function __() { this.constructor = d; }
  25391. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  25392. };
  25393. })();
  25394. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  25395. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  25396. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  25397. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  25398. return c > 3 && r && Object.defineProperty(target, key, r), r;
  25399. };
  25400. Object.defineProperty(exports, "__esModule", { value: true });
  25401. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  25402. var K = require("../backend/tfjs_backend");
  25403. var errors_1 = require("../errors");
  25404. var serialization_1 = require("../layers/serialization");
  25405. var types_1 = require("../types");
  25406. var generic_utils = require("../utils/generic_utils");
  25407. var serialization_utils_1 = require("../utils/serialization_utils");
  25408. var variables_1 = require("../variables");
  25409. var version_1 = require("../version");
  25410. var InputSpec = (function () {
  25411. function InputSpec(config) {
  25412. this.dtype = config.dtype;
  25413. this.shape = config.shape;
  25414. if (config.shape != null) {
  25415. this.ndim = config.shape.length;
  25416. }
  25417. else {
  25418. this.ndim = config.ndim;
  25419. }
  25420. this.maxNDim = config.maxNDim;
  25421. this.minNDim = config.minNDim;
  25422. this.axes = config.axes || {};
  25423. }
  25424. return InputSpec;
  25425. }());
  25426. exports.InputSpec = InputSpec;
  25427. var _nextNodeID = 0;
  25428. var Node = (function () {
  25429. function Node(config, callArgs) {
  25430. this.callArgs = callArgs;
  25431. this.id = _nextNodeID++;
  25432. this.outboundLayer = config.outboundLayer;
  25433. this.inboundLayers = config.inboundLayers;
  25434. this.nodeIndices = config.nodeIndices;
  25435. this.tensorIndices = config.tensorIndices;
  25436. this.inputTensors = config.inputTensors;
  25437. this.outputTensors = config.outputTensors;
  25438. this.inputMasks = config.inputMasks;
  25439. this.outputMasks = config.outputMasks;
  25440. this.inputShapes = config.inputShapes;
  25441. this.outputShapes = config.outputShapes;
  25442. for (var _i = 0, _a = config.inboundLayers; _i < _a.length; _i++) {
  25443. var layer = _a[_i];
  25444. if (layer != null) {
  25445. layer.outboundNodes.push(this);
  25446. }
  25447. }
  25448. config.outboundLayer.inboundNodes.push(this);
  25449. }
  25450. Node.prototype.getConfig = function () {
  25451. var inboundNames = [];
  25452. for (var _i = 0, _a = this.inboundLayers; _i < _a.length; _i++) {
  25453. var layer = _a[_i];
  25454. if (layer != null) {
  25455. inboundNames.push(layer.name);
  25456. }
  25457. else {
  25458. inboundNames.push(null);
  25459. }
  25460. }
  25461. return {
  25462. outboundLayer: this.outboundLayer ? this.outboundLayer.name : null,
  25463. inboundLayers: inboundNames,
  25464. nodeIndices: this.nodeIndices,
  25465. tensorIndices: this.tensorIndices
  25466. };
  25467. };
  25468. return Node;
  25469. }());
  25470. exports.Node = Node;
  25471. var _nextLayerID = 0;
  25472. var Layer = (function (_super) {
  25473. __extends(Layer, _super);
  25474. function Layer(config) {
  25475. var _this = _super.call(this) || this;
  25476. _this._callHook = null;
  25477. _this._addedWeightNames = [];
  25478. _this._stateful = false;
  25479. _this.id = _nextLayerID++;
  25480. _this.activityRegularizer = null;
  25481. _this.inputSpec = null;
  25482. _this.supportsMasking = false;
  25483. _this._trainableWeights = [];
  25484. _this._nonTrainableWeights = [];
  25485. _this._losses = [];
  25486. _this._updates = [];
  25487. _this._built = false;
  25488. _this.inboundNodes = [];
  25489. _this.outboundNodes = [];
  25490. var name = config.name;
  25491. if (!name) {
  25492. var prefix = _this.getClassName();
  25493. name = generic_utils.toSnakeCase(prefix) + '_' + K.getUid(prefix);
  25494. }
  25495. _this.name = name;
  25496. _this.trainable = config.trainable == null ? true : config.trainable;
  25497. _this.updatable = config.updatable == null ? true : config.updatable;
  25498. if (config.inputShape != null || config.batchInputShape != null) {
  25499. var batchInputShape = void 0;
  25500. if (config.batchInputShape != null) {
  25501. batchInputShape = config.batchInputShape;
  25502. }
  25503. else if (config.inputShape != null) {
  25504. var batchSize = null;
  25505. if (config.batchSize != null) {
  25506. batchSize = config.batchSize;
  25507. }
  25508. batchInputShape = [batchSize].concat(config.inputShape);
  25509. }
  25510. _this.batchInputShape = batchInputShape;
  25511. var dtype = config.dtype;
  25512. if (dtype == null) {
  25513. dtype = config.inputDType;
  25514. }
  25515. if (dtype == null) {
  25516. dtype = K.floatx();
  25517. }
  25518. _this.dtype = dtype;
  25519. }
  25520. if (config.weights != null) {
  25521. _this.initialWeights = config.weights;
  25522. }
  25523. else {
  25524. _this.initialWeights = null;
  25525. }
  25526. return _this;
  25527. }
  25528. Layer.nodeKey = function (layer, nodeIndex) {
  25529. return layer.name + '_ib-' + nodeIndex.toString();
  25530. };
  25531. Layer.prototype.getNodeAtIndex = function (nodeIndex, attrName) {
  25532. if (this.inboundNodes.length === 0) {
  25533. throw new errors_1.RuntimeError('The layer has never been called ' +
  25534. ("and thus has no defined " + attrName + "."));
  25535. }
  25536. if (this.inboundNodes.length <= nodeIndex) {
  25537. throw new errors_1.ValueError("Asked to get " + attrName + " at node " + nodeIndex + ", " +
  25538. ("but the layer has only " + this.inboundNodes.length + " inbound nodes."));
  25539. }
  25540. return this.inboundNodes[nodeIndex];
  25541. };
  25542. Layer.prototype.getInputAt = function (nodeIndex) {
  25543. return generic_utils.singletonOrArray(this.getNodeAtIndex(nodeIndex, 'input').inputTensors);
  25544. };
  25545. Layer.prototype.getOutputAt = function (nodeIndex) {
  25546. return generic_utils.singletonOrArray(this.getNodeAtIndex(nodeIndex, 'output').outputTensors);
  25547. };
  25548. Object.defineProperty(Layer.prototype, "input", {
  25549. get: function () {
  25550. if (this.inboundNodes.length > 1) {
  25551. throw new errors_1.AttributeError("Layer " + this.name +
  25552. ' has multiple inbound nodes, ' +
  25553. 'hence the notion of "layer input" ' +
  25554. 'is ill-defined. ' +
  25555. 'Use `getInputAt(nodeIndex)` instead.');
  25556. }
  25557. else if (this.inboundNodes.length === 0) {
  25558. throw new errors_1.AttributeError("Layer " + this.name +
  25559. ' is not connected, no input to return.');
  25560. }
  25561. return generic_utils.singletonOrArray(this.getNodeAtIndex(0, 'input').inputTensors);
  25562. },
  25563. enumerable: true,
  25564. configurable: true
  25565. });
  25566. Object.defineProperty(Layer.prototype, "output", {
  25567. get: function () {
  25568. if (this.inboundNodes.length === 0) {
  25569. throw new errors_1.AttributeError("Layer " + this.name +
  25570. ' has no inbound nodes.');
  25571. }
  25572. if (this.inboundNodes.length > 1) {
  25573. throw new errors_1.AttributeError("Layer " + this.name +
  25574. ' has multiple inbound nodes, ' +
  25575. 'hence the notion of "layer output" ' +
  25576. 'is ill-defined. ' +
  25577. 'Use `getOutputAt(nodeIndex)` instead.');
  25578. }
  25579. return generic_utils.singletonOrArray(this.getNodeAtIndex(0, 'output').outputTensors);
  25580. },
  25581. enumerable: true,
  25582. configurable: true
  25583. });
  25584. Object.defineProperty(Layer.prototype, "losses", {
  25585. get: function () {
  25586. return this._losses;
  25587. },
  25588. enumerable: true,
  25589. configurable: true
  25590. });
  25591. Layer.prototype.calculateLosses = function () {
  25592. return this.losses.map(function (lossFn) { return lossFn(); });
  25593. };
  25594. Object.defineProperty(Layer.prototype, "updates", {
  25595. get: function () {
  25596. return this._updates;
  25597. },
  25598. enumerable: true,
  25599. configurable: true
  25600. });
  25601. Object.defineProperty(Layer.prototype, "built", {
  25602. get: function () {
  25603. return this._built;
  25604. },
  25605. set: function (built) {
  25606. this._built = built;
  25607. },
  25608. enumerable: true,
  25609. configurable: true
  25610. });
  25611. Object.defineProperty(Layer.prototype, "trainableWeights", {
  25612. get: function () {
  25613. if (this.trainable) {
  25614. return this._trainableWeights;
  25615. }
  25616. else {
  25617. return [];
  25618. }
  25619. },
  25620. set: function (weights) {
  25621. this._trainableWeights = weights;
  25622. },
  25623. enumerable: true,
  25624. configurable: true
  25625. });
  25626. Object.defineProperty(Layer.prototype, "nonTrainableWeights", {
  25627. get: function () {
  25628. if (!this.trainable) {
  25629. return this._trainableWeights.concat(this._nonTrainableWeights);
  25630. }
  25631. else {
  25632. return this._nonTrainableWeights;
  25633. }
  25634. },
  25635. set: function (weights) {
  25636. this._nonTrainableWeights = weights;
  25637. },
  25638. enumerable: true,
  25639. configurable: true
  25640. });
  25641. Object.defineProperty(Layer.prototype, "weights", {
  25642. get: function () {
  25643. return this.trainableWeights.concat(this.nonTrainableWeights);
  25644. },
  25645. enumerable: true,
  25646. configurable: true
  25647. });
  25648. Object.defineProperty(Layer.prototype, "stateful", {
  25649. get: function () {
  25650. return this._stateful;
  25651. },
  25652. enumerable: true,
  25653. configurable: true
  25654. });
  25655. Layer.prototype.assertInputCompatibility = function (inputs) {
  25656. inputs = generic_utils.toList(inputs);
  25657. if (this.inputSpec == null || this.inputSpec.length === 0) {
  25658. return;
  25659. }
  25660. var inputSpec = generic_utils.toList(this.inputSpec);
  25661. if (inputs.length !== inputSpec.length) {
  25662. throw new errors_1.ValueError("Layer " + this.name + " expects " + inputSpec.length + " inputs, " +
  25663. ("but it received " + inputs.length + " input tensors. ") +
  25664. ("Input received: " + inputs));
  25665. }
  25666. for (var inputIndex = 0; inputIndex < inputs.length; inputIndex++) {
  25667. var x = inputs[inputIndex];
  25668. var spec = inputSpec[inputIndex];
  25669. if (spec == null) {
  25670. continue;
  25671. }
  25672. var ndim = x.rank;
  25673. if (spec.ndim != null) {
  25674. if (ndim !== spec.ndim) {
  25675. throw new errors_1.ValueError("Input " + inputIndex + " is incompatible with layer " + this.name + ": " +
  25676. ("expected ndim=" + spec.ndim + ", found ndim=" + ndim));
  25677. }
  25678. }
  25679. if (spec.maxNDim != null) {
  25680. if (ndim > spec.maxNDim) {
  25681. throw new errors_1.ValueError("Input " + inputIndex + " is incompatible with layer " + this.name +
  25682. (": expected max_ndim=" + spec.maxNDim + ", found ndim=" + ndim));
  25683. }
  25684. }
  25685. if (spec.minNDim != null) {
  25686. if (ndim < spec.minNDim) {
  25687. throw new errors_1.ValueError("Input " + inputIndex + " is incompatible with layer " + this.name +
  25688. (": expected min_ndim=" + spec.minNDim + ", found ndim=" + ndim + "."));
  25689. }
  25690. }
  25691. if (spec.dtype != null) {
  25692. if (K.dtype(x) !== spec.dtype) {
  25693. var xDType = K.dtype(x);
  25694. throw new errors_1.ValueError("Input " + inputIndex + " is incompatible with layer " + this.name + " " +
  25695. (": expected dtype=" + spec.dtype + ", found dtype=" + xDType + "."));
  25696. }
  25697. }
  25698. if (spec.axes) {
  25699. var xShape = K.intShape(x);
  25700. for (var key in spec.axes) {
  25701. var axis = Number(key);
  25702. var value = spec.axes[key];
  25703. var xShapeAtAxis = axis >= 0 ? xShape[axis] : xShape[xShape.length + axis];
  25704. if (value != null && [value, null].indexOf(xShapeAtAxis) === -1) {
  25705. throw new errors_1.ValueError("Input " + inputIndex + " is incompatible with layer " +
  25706. (this.name + ": expected axis " + axis + " of input shape to ") +
  25707. ("have value " + value + " but got shape " + xShape + "."));
  25708. }
  25709. }
  25710. }
  25711. if (spec.shape != null) {
  25712. var xShape = K.intShape(x);
  25713. for (var i = 0; i < spec.shape.length; ++i) {
  25714. var specDim = spec.shape[i];
  25715. var dim = xShape[i];
  25716. if (specDim != null && dim != null) {
  25717. if (specDim !== dim) {
  25718. throw new errors_1.ValueError("Input " + inputIndex + " is incompatible with layer " +
  25719. (this.name + ": expected shape=" + spec.shape + ", ") +
  25720. 'found shape=${xShape}.');
  25721. }
  25722. }
  25723. }
  25724. }
  25725. }
  25726. };
  25727. Layer.prototype.call = function (inputs, kwargs) {
  25728. return inputs;
  25729. };
  25730. Layer.prototype.invokeCallHook = function (inputs, kwargs) {
  25731. if (this._callHook != null) {
  25732. this._callHook(inputs, kwargs);
  25733. }
  25734. };
  25735. Layer.prototype.setCallHook = function (callHook) {
  25736. this._callHook = callHook;
  25737. };
  25738. Layer.prototype.clearCallHook = function () {
  25739. this._callHook = null;
  25740. };
  25741. Layer.prototype.apply = function (inputs, kwargs) {
  25742. var _this = this;
  25743. kwargs = kwargs || {};
  25744. var inputsList = generic_utils.toList(inputs);
  25745. var allAreSymbolic = true;
  25746. for (var _i = 0, inputsList_1 = inputsList; _i < inputsList_1.length; _i++) {
  25747. var input = inputsList_1[_i];
  25748. if (!(input instanceof types_1.SymbolicTensor)) {
  25749. allAreSymbolic = false;
  25750. break;
  25751. }
  25752. }
  25753. var noneAreSymbolic = true;
  25754. for (var _a = 0, inputsList_2 = inputsList; _a < inputsList_2.length; _a++) {
  25755. var input = inputsList_2[_a];
  25756. if (input instanceof types_1.SymbolicTensor) {
  25757. noneAreSymbolic = false;
  25758. break;
  25759. }
  25760. }
  25761. if (allAreSymbolic === noneAreSymbolic) {
  25762. throw new errors_1.ValueError('Arguments to apply() must be all ' +
  25763. 'SymbolicTensors or all Tensors');
  25764. }
  25765. return K.nameScope(this.name, function () {
  25766. if (!_this.built) {
  25767. _this.assertInputCompatibility(inputs);
  25768. var inputShapes = [];
  25769. for (var _i = 0, _a = generic_utils.toList(inputs); _i < _a.length; _i++) {
  25770. var xElem = _a[_i];
  25771. inputShapes.push(K.intShape(xElem));
  25772. }
  25773. _this.build(generic_utils.singletonOrArray(inputShapes));
  25774. _this.built = true;
  25775. if (_this.initialWeights) {
  25776. _this.setWeights(_this.initialWeights);
  25777. }
  25778. }
  25779. _this.assertInputCompatibility(inputs);
  25780. if (noneAreSymbolic) {
  25781. var output = _this.call(inputs, kwargs);
  25782. var outputList = generic_utils.toList(output);
  25783. var outputListCopy = [];
  25784. for (var _b = 0, outputList_1 = outputList; _b < outputList_1.length; _b++) {
  25785. var x = outputList_1[_b];
  25786. if (inputsList.indexOf(x) !== -1) {
  25787. x = K.identity(x);
  25788. }
  25789. outputListCopy.push(x);
  25790. }
  25791. output = generic_utils.singletonOrArray(outputListCopy);
  25792. if (_this.activityRegularizer != null) {
  25793. throw new errors_1.NotImplementedError('Layer invocation in the presence of activity ' +
  25794. 'regularizer(s) is not supported yet.');
  25795. }
  25796. return output;
  25797. }
  25798. else {
  25799. var inputShape = collectInputShape(inputs);
  25800. var outputShape = _this.computeOutputShape(inputShape);
  25801. var output = void 0;
  25802. var outputDType_1 = guessOutputDType(inputs);
  25803. if (outputShape != null && outputShape.length > 0 &&
  25804. Array.isArray(outputShape[0])) {
  25805. output = outputShape
  25806. .map(function (shape, index) { return new types_1.SymbolicTensor(outputDType_1, shape, _this, generic_utils.toList(inputs), kwargs, _this.name, index); });
  25807. }
  25808. else {
  25809. output = new types_1.SymbolicTensor(outputDType_1, outputShape, _this, generic_utils.toList(inputs), kwargs, _this.name);
  25810. }
  25811. _this.addInboundNode(inputs, output, null, null, inputShape, outputShape, kwargs);
  25812. if (_this.activityRegularizer != null) {
  25813. throw new errors_1.NotImplementedError('Layer invocation in the presence of activity ' +
  25814. 'regularizer(s) is not supported yet.');
  25815. }
  25816. return output;
  25817. }
  25818. });
  25819. };
  25820. Object.defineProperty(Layer.prototype, "outputShape", {
  25821. get: function () {
  25822. if (this.inboundNodes == null || this.inboundNodes.length === 0) {
  25823. throw new errors_1.AttributeError("The layer " + this.name + " has never been called and thus has no " +
  25824. "defined output shape.");
  25825. }
  25826. var allOutputShapes = [];
  25827. for (var _i = 0, _a = this.inboundNodes; _i < _a.length; _i++) {
  25828. var node = _a[_i];
  25829. var shapeString = JSON.stringify(node.outputShapes);
  25830. if (allOutputShapes.indexOf(shapeString) === -1) {
  25831. allOutputShapes.push(shapeString);
  25832. }
  25833. }
  25834. if (allOutputShapes.length === 1) {
  25835. var outputShapes = this.inboundNodes[0].outputShapes;
  25836. if (Array.isArray(outputShapes) && Array.isArray(outputShapes[0]) &&
  25837. outputShapes.length === 1) {
  25838. return outputShapes[0];
  25839. }
  25840. else {
  25841. return outputShapes;
  25842. }
  25843. }
  25844. else {
  25845. throw new errors_1.AttributeError("The layer " + this.name + " has multiple inbound nodes with different " +
  25846. "output shapes. Hence the notion of \"outut shape\" is ill-defined " +
  25847. "for the layer.");
  25848. }
  25849. },
  25850. enumerable: true,
  25851. configurable: true
  25852. });
  25853. Layer.prototype.countParams = function () {
  25854. if (!this.built) {
  25855. throw new errors_1.RuntimeError("You tried to call countParams() on " + this.name + ", " +
  25856. "but the layer is not built yet. Build it first by calling " +
  25857. "build(batchInputShape).");
  25858. }
  25859. return generic_utils.countParamsInWeights(this.weights);
  25860. };
  25861. Layer.prototype.build = function (inputShape) {
  25862. this.built = true;
  25863. };
  25864. Layer.prototype.getWeights = function (trainableOnly) {
  25865. if (trainableOnly === void 0) { trainableOnly = false; }
  25866. return variables_1.batchGetValue(trainableOnly ? this.trainableWeights : this.weights);
  25867. };
  25868. Layer.prototype.setWeights = function (weights) {
  25869. var _this = this;
  25870. tfjs_core_1.tidy(function () {
  25871. var params = _this.weights;
  25872. if (params.length !== weights.length) {
  25873. throw new errors_1.ValueError("You called setWeights(weights) on layer \"" + _this.name + "\" " +
  25874. ("with a weight list of length " + weights.length + ", ") +
  25875. ("but the layer was expecting " + params.length + " weights. ") +
  25876. ("Provided weights: " + weights + "..."));
  25877. }
  25878. if (params.length === 0) {
  25879. return;
  25880. }
  25881. var weightValueTuples = [];
  25882. var paramValues = variables_1.batchGetValue(params);
  25883. for (var i = 0; i < paramValues.length; ++i) {
  25884. var pv = paramValues[i];
  25885. var p = params[i];
  25886. var w = weights[i];
  25887. if (!tfjs_core_1.util.arraysEqual(pv.shape, w.shape)) {
  25888. throw new errors_1.ValueError("Layer weight shape " + pv.shape + " " +
  25889. ("not compatible with provided weight shape " + w.shape));
  25890. }
  25891. weightValueTuples.push([p, w]);
  25892. }
  25893. variables_1.batchSetValue(weightValueTuples);
  25894. });
  25895. };
  25896. Layer.prototype.addWeight = function (name, shape, dtype, initializer, regularizer, trainable, constraint) {
  25897. if (this._addedWeightNames.indexOf(name) !== -1) {
  25898. throw new errors_1.ValueError("Duplicate weight name " + name + " for layer " + this.name);
  25899. }
  25900. this._addedWeightNames.push(name);
  25901. if (dtype == null) {
  25902. dtype = K.floatx();
  25903. }
  25904. var weight = new variables_1.LayerVariable(initializer.apply(shape, dtype), dtype, name, trainable, constraint);
  25905. if (regularizer != null) {
  25906. this.addLoss(function () { return regularizer.apply(weight.read()); });
  25907. }
  25908. if (trainable == null) {
  25909. trainable = true;
  25910. }
  25911. if (trainable) {
  25912. this._trainableWeights.push(weight);
  25913. }
  25914. else {
  25915. this._nonTrainableWeights.push(weight);
  25916. }
  25917. return weight;
  25918. };
  25919. Layer.prototype.addLoss = function (losses) {
  25920. if (losses == null || Array.isArray(losses) && losses.length === 0) {
  25921. return;
  25922. }
  25923. losses = generic_utils.toList(losses);
  25924. if (this._losses !== undefined && this._losses !== null) {
  25925. (_a = this.losses).push.apply(_a, losses);
  25926. }
  25927. var _a;
  25928. };
  25929. Layer.prototype.computeOutputShape = function (inputShape) {
  25930. return inputShape;
  25931. };
  25932. Layer.prototype.computeMask = function (inputs, mask) {
  25933. var _this = this;
  25934. if (!this.supportsMasking) {
  25935. if (mask != null) {
  25936. if (Array.isArray(mask)) {
  25937. mask.forEach(function (maskElement) {
  25938. if (maskElement != null) {
  25939. throw new TypeError("Layer " + _this.name + " does not support masking," +
  25940. 'but was passed an inputMask.');
  25941. }
  25942. });
  25943. }
  25944. else {
  25945. throw new TypeError("Layer " + this.name + " does not support masking," +
  25946. 'but was passed an inputMask.');
  25947. }
  25948. }
  25949. return null;
  25950. }
  25951. return mask;
  25952. };
  25953. Layer.prototype.addInboundNode = function (inputTensors, outputTensors, inputMasks, outputMasks, inputShapes, outputShapes, kwargs) {
  25954. if (kwargs === void 0) { kwargs = null; }
  25955. var inputTensorList = generic_utils.toList(inputTensors);
  25956. outputTensors = generic_utils.toList(outputTensors);
  25957. inputMasks = generic_utils.toList(inputMasks);
  25958. outputMasks = generic_utils.toList(outputMasks);
  25959. inputShapes = generic_utils.normalizeShapeList(inputShapes);
  25960. outputShapes = generic_utils.normalizeShapeList(outputShapes);
  25961. var inboundLayers = [];
  25962. var nodeIndices = [];
  25963. var tensorIndices = [];
  25964. for (var _i = 0, inputTensorList_1 = inputTensorList; _i < inputTensorList_1.length; _i++) {
  25965. var x = inputTensorList_1[_i];
  25966. inboundLayers.push(x.sourceLayer);
  25967. nodeIndices.push(x.nodeIndex);
  25968. tensorIndices.push(x.tensorIndex);
  25969. }
  25970. new Node({
  25971. outboundLayer: this,
  25972. inboundLayers: inboundLayers,
  25973. nodeIndices: nodeIndices,
  25974. tensorIndices: tensorIndices,
  25975. inputTensors: inputTensorList,
  25976. outputTensors: outputTensors,
  25977. inputMasks: inputMasks,
  25978. outputMasks: outputMasks,
  25979. inputShapes: inputShapes,
  25980. outputShapes: outputShapes
  25981. }, kwargs);
  25982. for (var i = 0; i < outputTensors.length; i++) {
  25983. outputTensors[i].sourceLayer = this;
  25984. outputTensors[i].nodeIndex = this.inboundNodes.length - 1;
  25985. outputTensors[i].tensorIndex = i;
  25986. }
  25987. };
  25988. Layer.prototype.getConfig = function () {
  25989. var config = { name: this.name, trainable: this.trainable };
  25990. if (this.batchInputShape != null) {
  25991. config['batchInputShape'] = this.batchInputShape;
  25992. }
  25993. if (this.dtype != null) {
  25994. config['dtype'] = this.dtype;
  25995. }
  25996. return config;
  25997. };
  25998. __decorate([
  25999. tfjs_core_1.doc({ heading: 'Models', 'subheading': 'Classes' })
  26000. ], Layer.prototype, "apply", null);
  26001. Layer = __decorate([
  26002. tfjs_core_1.doc({ heading: 'Layers', subheading: 'Classes', namespace: 'layers' })
  26003. ], Layer);
  26004. return Layer;
  26005. }(tfjs_core_1.serialization.Serializable));
  26006. exports.Layer = Layer;
  26007. function collectInputShape(inputTensors) {
  26008. inputTensors =
  26009. generic_utils.toList(inputTensors);
  26010. var shapes = [];
  26011. for (var _i = 0, inputTensors_1 = inputTensors; _i < inputTensors_1.length; _i++) {
  26012. var x = inputTensors_1[_i];
  26013. shapes.push(K.intShape(x));
  26014. }
  26015. return generic_utils.singletonOrArray(shapes);
  26016. }
  26017. function guessOutputDType(inputTensors) {
  26018. return 'float32';
  26019. }
  26020. var InputLayer = (function (_super) {
  26021. __extends(InputLayer, _super);
  26022. function InputLayer(config) {
  26023. var _this = _super.call(this, {
  26024. dtype: config.dtype,
  26025. name: config.name != null ? config.name : K.getUid('input').toString()
  26026. }) || this;
  26027. if (config.batchSize == null) {
  26028. config.batchSize = null;
  26029. }
  26030. if (config.sparse == null) {
  26031. config.sparse = false;
  26032. }
  26033. _this.trainable = false;
  26034. _this.built = true;
  26035. _this.sparse = config.sparse;
  26036. if (config.inputShape != null && config.batchInputShape != null) {
  26037. throw new errors_1.ValueError('Only provide the inputShape OR ' +
  26038. 'batchInputShape argument to inputLayer, not both at the same time.');
  26039. }
  26040. var batchInputShape = config.batchInputShape;
  26041. if (batchInputShape == null) {
  26042. if (config.inputShape == null) {
  26043. throw new errors_1.ValueError('An InputLayer should be passed either a ' +
  26044. '`batchInputShape` or an `inputShape`.');
  26045. }
  26046. else {
  26047. batchInputShape = [config.batchSize].concat(config.inputShape);
  26048. }
  26049. }
  26050. else {
  26051. if (config.batchSize != null) {
  26052. throw new errors_1.ValueError('Cannot specify batchSize if batchInputShape is' +
  26053. 'specified when creating an InputLayer.');
  26054. }
  26055. }
  26056. var dtype = config.dtype || K.floatx();
  26057. _this.batchInputShape = batchInputShape;
  26058. _this.dtype = dtype;
  26059. _this.inputSpec = [{ shape: batchInputShape }];
  26060. var inputTensor = new types_1.SymbolicTensor(_this.dtype, _this.batchInputShape, _this, [], {}, _this.name);
  26061. inputTensor.nodeIndex = 0;
  26062. inputTensor.tensorIndex = 0;
  26063. new Node({
  26064. outboundLayer: _this,
  26065. inboundLayers: [],
  26066. nodeIndices: [],
  26067. tensorIndices: [],
  26068. inputTensors: [inputTensor],
  26069. outputTensors: [inputTensor],
  26070. inputMasks: [null],
  26071. outputMasks: [null],
  26072. inputShapes: [batchInputShape],
  26073. outputShapes: [batchInputShape]
  26074. });
  26075. return _this;
  26076. }
  26077. InputLayer.prototype.apply = function (inputs, kwargs) {
  26078. throw new errors_1.ValueError('Cannot pass any input to an ' +
  26079. ("InputLayer's apply() method. InputLayer name: " + this.name));
  26080. };
  26081. InputLayer.prototype.getConfig = function () {
  26082. return {
  26083. batchInputShape: this.batchInputShape,
  26084. dtype: this.dtype,
  26085. sparse: this.sparse,
  26086. name: this.name
  26087. };
  26088. };
  26089. InputLayer.className = 'InputLayer';
  26090. return InputLayer;
  26091. }(Layer));
  26092. exports.InputLayer = InputLayer;
  26093. tfjs_core_1.serialization.SerializationMap.register(InputLayer);
  26094. function Input(config) {
  26095. if (config.batchShape == null && config.shape == null) {
  26096. throw new Error('Please provide to Input either a `shape`' +
  26097. ' or a `batchShape` argument. Note that ' +
  26098. '`shape` does not include the batch ' +
  26099. 'dimension.');
  26100. }
  26101. if (config.batchShape != null && config.shape != null) {
  26102. throw new errors_1.ValueError('Please provide either a `shape` or `batchShape` ' +
  26103. 'argument to Input, but not both.');
  26104. }
  26105. var batchShape = config.batchShape;
  26106. if (config.shape != null && batchShape == null) {
  26107. batchShape = [null].concat(config.shape);
  26108. }
  26109. var dtype = config.dtype;
  26110. if (dtype == null) {
  26111. dtype = K.floatx();
  26112. }
  26113. var inputLayer = new InputLayer({
  26114. batchInputShape: batchShape,
  26115. name: config.name,
  26116. dtype: dtype,
  26117. sparse: config.sparse
  26118. });
  26119. var outputs = inputLayer.inboundNodes[0].outputTensors;
  26120. return outputs[0];
  26121. }
  26122. exports.Input = Input;
  26123. var Container = (function (_super) {
  26124. __extends(Container, _super);
  26125. function Container(config) {
  26126. var _this = _super.call(this, {}) || this;
  26127. _this.containerNodes = new Set();
  26128. _this.name = config.name;
  26129. if (_this.name == null) {
  26130. var prefix = _this.getClassName().toLowerCase();
  26131. _this.name = K.getUid(prefix);
  26132. }
  26133. _this.supportsMasking = false;
  26134. _this.trainable = true;
  26135. _this.updatable = true;
  26136. if (Array.isArray(config.inputs)) {
  26137. _this.inputs = config.inputs.slice();
  26138. }
  26139. else {
  26140. _this.inputs = [config.inputs];
  26141. }
  26142. if (Array.isArray(config.outputs)) {
  26143. _this.outputs = config.outputs.slice();
  26144. }
  26145. else {
  26146. _this.outputs = [config.outputs];
  26147. }
  26148. if (generic_utils.unique(_this.inputs).length !== _this.inputs.length) {
  26149. throw new errors_1.ValueError('The list of inputs passed to the model is ' +
  26150. 'redundant. All inputs should only appear once. Found: ' +
  26151. _this.inputs.map(function (x) { return x.name; }));
  26152. }
  26153. if (generic_utils.unique(_this.outputs).length !== _this.outputs.length) {
  26154. console.warn('The list of outputs passed to the model is redundant. ' +
  26155. 'All outputs should only appear once. Found: ' +
  26156. _this.outputs.map(function (x) { return x.name; }));
  26157. }
  26158. _this.inputLayers = [];
  26159. _this.inputLayersNodeIndices = [];
  26160. _this.inputLayersTensorIndices = [];
  26161. _this.outputLayers = [];
  26162. _this.outputLayersNodeIndices = [];
  26163. _this.outputLayersTensorIndices = [];
  26164. _this.layers = [];
  26165. for (var _i = 0, _a = _this.outputs; _i < _a.length; _i++) {
  26166. var x = _a[_i];
  26167. var layer = x.sourceLayer;
  26168. var nodeIndex = x.nodeIndex;
  26169. var tensorIndex = x.tensorIndex;
  26170. _this.outputLayers.push(layer);
  26171. _this.outputLayersNodeIndices.push(nodeIndex);
  26172. _this.outputLayersTensorIndices.push(tensorIndex);
  26173. }
  26174. for (var _b = 0, _c = _this.inputs; _b < _c.length; _b++) {
  26175. var x = _c[_b];
  26176. var layer = x.sourceLayer;
  26177. var nodeIndex = x.nodeIndex;
  26178. var tensorIndex = x.tensorIndex;
  26179. generic_utils.assert(nodeIndex === 0, 'input layer has >1 nodes');
  26180. generic_utils.assert(tensorIndex === 0, 'input layer has >1 tensors');
  26181. _this.inputLayers.push(layer);
  26182. _this.inputLayersNodeIndices.push(nodeIndex);
  26183. _this.inputLayersTensorIndices.push(tensorIndex);
  26184. }
  26185. _this.inputNames = [];
  26186. _this.outputNames = [];
  26187. _this.feedInputShapes = [];
  26188. _this.feedInputNames = [];
  26189. _this.feedOutputNames = [];
  26190. for (var i = 0; i < _this.inputLayers.length; i++) {
  26191. var layer = _this.inputLayers[i];
  26192. if (!(layer instanceof InputLayer)) {
  26193. throw new TypeError('Input layers to a Model must be InputLayer objects. ' +
  26194. ("Received inputs: " + config.inputs + ". ") +
  26195. ("Input " + i + " (0-based) originates ") +
  26196. ("from layer type " + layer.getClassName() + "."));
  26197. }
  26198. _this.inputNames.push(layer.name);
  26199. _this.feedInputShapes.push(layer.batchInputShape);
  26200. _this.feedInputNames.push(layer.name);
  26201. }
  26202. for (var _d = 0, _e = _this.outputLayers; _d < _e.length; _d++) {
  26203. var layer = _e[_d];
  26204. _this.outputNames.push(layer.name);
  26205. }
  26206. _this.internalInputShapes = _this.inputs.map(function (x) { return x.shape; });
  26207. _this.internalOutputShapes = _this.outputs.map(function (x) { return x.shape; });
  26208. var nodesDepths = {};
  26209. var nodeIDToNode = {};
  26210. var layersDepths = {};
  26211. var layerIDToLayer = {};
  26212. var layerIndices = {};
  26213. var nodesInDecreasingDepth = [];
  26214. var buildMapOfGraph = function (tensor, finishedNodes, nodesInProgress, layer, nodeIndex, tensorIndex) {
  26215. if (layer == null || nodeIndex == null || tensorIndex == null) {
  26216. layer = tensor.sourceLayer;
  26217. nodeIndex = tensor.nodeIndex;
  26218. tensorIndex = tensor.tensorIndex;
  26219. }
  26220. var node = layer.inboundNodes[nodeIndex];
  26221. if (nodesInProgress.indexOf(node) !== -1) {
  26222. throw new errors_1.RuntimeError("The tensor " + tensor.name + " at layer \"" + layer.name + "\" " +
  26223. 'is part of a cycle.');
  26224. }
  26225. if (finishedNodes.indexOf(node) !== -1) {
  26226. return;
  26227. }
  26228. _this.containerNodes.add(Container.nodeKey(layer, nodeIndex));
  26229. if (!(layer.id in layerIndices)) {
  26230. layerIndices[layer.id] = Object.keys(layerIndices).length;
  26231. }
  26232. if (nodesInProgress.indexOf(node) === -1) {
  26233. nodesInProgress.push(node);
  26234. }
  26235. var numInboundLayers = node.inboundLayers.length;
  26236. for (var i = 0; i < numInboundLayers; i++) {
  26237. var x = node.inputTensors[i];
  26238. var layer_1 = node.inboundLayers[i];
  26239. var nodeIndex_1 = node.nodeIndices[i];
  26240. var tensorIndex_1 = node.tensorIndices[i];
  26241. buildMapOfGraph(x, finishedNodes, nodesInProgress, layer_1, nodeIndex_1, tensorIndex_1);
  26242. }
  26243. finishedNodes.push(node);
  26244. while (nodesInProgress.indexOf(node) >= 0) {
  26245. nodesInProgress.splice(nodesInProgress.indexOf(node), 1);
  26246. }
  26247. nodesInDecreasingDepth.push(node);
  26248. };
  26249. var finishedNodes = [];
  26250. var nodesInProgress = [];
  26251. for (var _f = 0, _g = _this.outputs; _f < _g.length; _f++) {
  26252. var x = _g[_f];
  26253. buildMapOfGraph(x, finishedNodes, nodesInProgress);
  26254. }
  26255. var reversedNodesInDecreasingDepth = nodesInDecreasingDepth.slice().reverse();
  26256. for (var _h = 0, reversedNodesInDecreasingDepth_1 = reversedNodesInDecreasingDepth; _h < reversedNodesInDecreasingDepth_1.length; _h++) {
  26257. var node = reversedNodesInDecreasingDepth_1[_h];
  26258. nodeIDToNode[node.id] = node;
  26259. if (!(node.id in nodesDepths)) {
  26260. nodesDepths[node.id] = 0;
  26261. }
  26262. var depth = nodesDepths[node.id];
  26263. var previousDepth = (layersDepths[node.outboundLayer.id] == null ?
  26264. 0 :
  26265. layersDepths[node.outboundLayer.id]);
  26266. depth = Math.max(depth, previousDepth);
  26267. layersDepths[node.outboundLayer.id] = depth;
  26268. layerIDToLayer[node.outboundLayer.id] = node.outboundLayer;
  26269. nodesDepths[node.id] = depth;
  26270. for (var i = 0; i < node.inboundLayers.length; i++) {
  26271. var inboundLayer = node.inboundLayers[i];
  26272. var nodeIndex = node.nodeIndices[i];
  26273. var inboundNode = inboundLayer.inboundNodes[nodeIndex];
  26274. var previousDepth_1 = (nodesDepths[inboundNode.id] == null ? 0 :
  26275. nodesDepths[inboundNode.id]);
  26276. nodesDepths[inboundNode.id] = Math.max(depth + 1, previousDepth_1);
  26277. nodeIDToNode[inboundNode.id] = inboundNode;
  26278. }
  26279. }
  26280. var nodesByDepth = {};
  26281. for (var nodeID in nodesDepths) {
  26282. var depth = nodesDepths[nodeID];
  26283. if (!(depth in nodesByDepth)) {
  26284. nodesByDepth[depth] = [];
  26285. }
  26286. nodesByDepth[depth].push(nodeIDToNode[nodeID]);
  26287. }
  26288. var layersByDepth = {};
  26289. for (var layerID in layersDepths) {
  26290. var depth = layersDepths[layerID];
  26291. if (!(depth in layersByDepth)) {
  26292. layersByDepth[depth] = [];
  26293. }
  26294. layersByDepth[depth].push(layerIDToLayer[layerID]);
  26295. }
  26296. var depthKeys = Object.keys(layersByDepth)
  26297. .map(function (x) { return parseInt(x, 10); })
  26298. .sort(generic_utils.reverseNumberCompare);
  26299. _this.layers = [];
  26300. for (var _j = 0, depthKeys_1 = depthKeys; _j < depthKeys_1.length; _j++) {
  26301. var depth = depthKeys_1[_j];
  26302. var layersForDepth = layersByDepth[depth];
  26303. layersForDepth.sort(function (a, b) {
  26304. var aIndex = layerIndices[a.id];
  26305. var bIndex = layerIndices[b.id];
  26306. if (aIndex < bIndex) {
  26307. return -1;
  26308. }
  26309. if (aIndex > bIndex) {
  26310. return 1;
  26311. }
  26312. return 0;
  26313. });
  26314. for (var _k = 0, layersForDepth_1 = layersForDepth; _k < layersForDepth_1.length; _k++) {
  26315. var layer = layersForDepth_1[_k];
  26316. _this.layers.push(layer);
  26317. }
  26318. }
  26319. _this.layersByDepth = layersByDepth;
  26320. depthKeys = Object.keys(nodesByDepth)
  26321. .map(function (x) { return parseInt(x, 10); })
  26322. .sort(generic_utils.reverseNumberCompare);
  26323. var computableTensors = _this.inputs.slice();
  26324. var layersWithCompleteInput = [];
  26325. for (var _l = 0, depthKeys_2 = depthKeys; _l < depthKeys_2.length; _l++) {
  26326. var depth = depthKeys_2[_l];
  26327. for (var _m = 0, _o = nodesByDepth[depth]; _m < _o.length; _m++) {
  26328. var node = _o[_m];
  26329. var layer = node.outboundLayer;
  26330. if (layer != null) {
  26331. for (var _p = 0, _q = node.inputTensors; _p < _q.length; _p++) {
  26332. var x = _q[_p];
  26333. if (computableTensors.indexOf(x) === -1) {
  26334. throw new errors_1.RuntimeError("Graph disconnected: cannot obtain value for tensor " + x +
  26335. (" at layer \"" + layer.name + "\". ") +
  26336. 'The following previous layers were accessed without ' +
  26337. ("issue: " + layersWithCompleteInput));
  26338. }
  26339. }
  26340. for (var _r = 0, _s = node.outputTensors; _r < _s.length; _r++) {
  26341. var x = _s[_r];
  26342. computableTensors.push(x);
  26343. }
  26344. layersWithCompleteInput.push(layer.name);
  26345. }
  26346. }
  26347. }
  26348. _this.nodesByDepth = nodesByDepth;
  26349. var allNames = _this.layers.map(function (x) { return x.name; });
  26350. var _loop_1 = function (name_1) {
  26351. var numOccurrences = allNames.filter(function (x) { return x === name_1; }).length;
  26352. if (numOccurrences !== 1) {
  26353. throw new errors_1.RuntimeError("The name \"" + name_1 + "\" is used " + numOccurrences + " times " +
  26354. 'in the model. All layer names should be unique. Layer names: ' +
  26355. JSON.stringify(allNames));
  26356. }
  26357. };
  26358. for (var _t = 0, allNames_1 = allNames; _t < allNames_1.length; _t++) {
  26359. var name_1 = allNames_1[_t];
  26360. _loop_1(name_1);
  26361. }
  26362. _this.outboundNodes = [];
  26363. _this.inboundNodes = [];
  26364. new Node({
  26365. outboundLayer: _this,
  26366. inboundLayers: [],
  26367. nodeIndices: [],
  26368. tensorIndices: [],
  26369. inputTensors: _this.inputs,
  26370. outputTensors: _this.outputs,
  26371. inputMasks: _this.inputs.map(function (x) { return null; }),
  26372. outputMasks: _this.outputs.map(function (x) { return null; }),
  26373. inputShapes: _this.inputs.map(function (x) { return x.shape; }),
  26374. outputShapes: _this.outputs.map(function (x) { return x.shape; })
  26375. });
  26376. _this.built = true;
  26377. return _this;
  26378. }
  26379. Object.defineProperty(Container.prototype, "trainableWeights", {
  26380. get: function () {
  26381. if (this._trainableWeights.length > 0) {
  26382. throw new errors_1.ValueError('Container instance unexpectedly contains _trainableWeights.' +
  26383. 'The trainable weights of a Container are a union of the ' +
  26384. 'trainable weights of its consituent Layers. Its own ' +
  26385. '_trainableWeights must remain an empty Array.');
  26386. }
  26387. if (!this.trainable) {
  26388. return [];
  26389. }
  26390. var weights = [];
  26391. for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {
  26392. var layer = _a[_i];
  26393. weights = weights.concat(layer.trainableWeights);
  26394. }
  26395. return weights;
  26396. },
  26397. enumerable: true,
  26398. configurable: true
  26399. });
  26400. Object.defineProperty(Container.prototype, "nonTrainableWeights", {
  26401. get: function () {
  26402. var weights = [];
  26403. for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {
  26404. var layer = _a[_i];
  26405. weights.push.apply(weights, layer.nonTrainableWeights);
  26406. }
  26407. if (!this.trainable) {
  26408. var trainableWeights = [];
  26409. for (var _b = 0, _c = this.layers; _b < _c.length; _b++) {
  26410. var layer = _c[_b];
  26411. trainableWeights.push.apply(trainableWeights, layer.trainableWeights);
  26412. }
  26413. return trainableWeights.concat(weights);
  26414. }
  26415. return weights;
  26416. },
  26417. enumerable: true,
  26418. configurable: true
  26419. });
  26420. Object.defineProperty(Container.prototype, "weights", {
  26421. get: function () {
  26422. return this.trainableWeights.concat(this.nonTrainableWeights);
  26423. },
  26424. enumerable: true,
  26425. configurable: true
  26426. });
  26427. Container.prototype.loadWeights = function (weightsJSON, skipMismatch, isNamedTensorMap) {
  26428. if (skipMismatch === void 0) { skipMismatch = false; }
  26429. if (isNamedTensorMap === void 0) { isNamedTensorMap = false; }
  26430. if (isNamedTensorMap) {
  26431. loadWeightsFromNamedTensorMap(weightsJSON, this.layers);
  26432. }
  26433. else {
  26434. loadWeightsFromJson(weightsJSON, this.layers, skipMismatch);
  26435. }
  26436. };
  26437. Container.prototype.updatedConfig = function () {
  26438. var theConfig = this.getConfig();
  26439. var modelConfig = {
  26440. className: this.getClassName(),
  26441. config: theConfig,
  26442. kerasVersion: "tfjs-layers " + version_1.version,
  26443. backend: 'TensorFlow.js'
  26444. };
  26445. return modelConfig;
  26446. };
  26447. Container.prototype.toJSON = function (unused, returnString) {
  26448. if (returnString === void 0) { returnString = true; }
  26449. var modelConfig = serialization_utils_1.convertTsToPythonic(this.updatedConfig());
  26450. return returnString ? JSON.stringify(modelConfig) : modelConfig;
  26451. };
  26452. Container.prototype.call = function (inputs, kwargs) {
  26453. var _this = this;
  26454. return tfjs_core_1.tidy(function () {
  26455. inputs = generic_utils.toList(inputs);
  26456. var masks;
  26457. if ('mask' in kwargs) {
  26458. masks = generic_utils.toList(kwargs['mask']);
  26459. }
  26460. else {
  26461. masks = generic_utils.pyListRepeat(null, inputs.length);
  26462. }
  26463. return _this.runInternalGraph(inputs, masks)[0];
  26464. });
  26465. };
  26466. Container.prototype.computeMask = function (inputs, mask) {
  26467. var _this = this;
  26468. return tfjs_core_1.tidy(function () {
  26469. inputs = generic_utils.toList(inputs);
  26470. var masks;
  26471. if (mask == null) {
  26472. masks = generic_utils.pyListRepeat(null, inputs.length);
  26473. }
  26474. else {
  26475. masks = generic_utils.toList(mask);
  26476. }
  26477. return _this.runInternalGraph(inputs, masks)[1];
  26478. });
  26479. };
  26480. Container.prototype.computeOutputShape = function (inputShape) {
  26481. var inputShapes = generic_utils.normalizeShapeList(inputShape);
  26482. if (inputShapes.length !== this.inputLayers.length) {
  26483. throw new errors_1.ValueError("Invalid inputShape argument " + inputShape + ": " +
  26484. ("model has " + this.inputLayers.length + " tensor inputs."));
  26485. }
  26486. var layersToOutputShapes = {};
  26487. for (var i = 0; i < inputShapes.length; i++) {
  26488. var layer = this.inputLayers[i];
  26489. var inputShape_1 = inputShapes[i];
  26490. var shapeKey = layer.name + '_0_0';
  26491. layersToOutputShapes[shapeKey] = inputShape_1;
  26492. }
  26493. var depthKeys = Object.keys(this.nodesByDepth)
  26494. .map(function (x) { return parseInt(x, 10); })
  26495. .sort(generic_utils.reverseNumberCompare);
  26496. if (depthKeys.length > 1) {
  26497. for (var _i = 0, depthKeys_3 = depthKeys; _i < depthKeys_3.length; _i++) {
  26498. var depth = depthKeys_3[_i];
  26499. var nodes = this.nodesByDepth[depth];
  26500. for (var _a = 0, nodes_1 = nodes; _a < nodes_1.length; _a++) {
  26501. var node = nodes_1[_a];
  26502. var layer = node.outboundLayer;
  26503. if (this.inputLayers.map(function (x) { return x.id; }).indexOf(layer.id) !== -1) {
  26504. continue;
  26505. }
  26506. var inputShapes_1 = [];
  26507. for (var j = 0; j < node.inboundLayers.length; j++) {
  26508. var inboundLayer = node.inboundLayers[j];
  26509. var nodeIndex_2 = node.nodeIndices[j];
  26510. var tensorIndex = node.tensorIndices[j];
  26511. var shapeKey = inboundLayer.name + "_" + nodeIndex_2 + "_" + tensorIndex;
  26512. var inputShape_2 = layersToOutputShapes[shapeKey];
  26513. inputShapes_1.push(inputShape_2);
  26514. }
  26515. var outputShape = layer.computeOutputShape(generic_utils.singletonOrArray(inputShapes_1));
  26516. var outputShapes_1 = generic_utils.normalizeShapeList(outputShape);
  26517. var nodeIndex = layer.inboundNodes.indexOf(node);
  26518. for (var j = 0; j < outputShapes_1.length; j++) {
  26519. var shapeKey = layer.name + "_" + nodeIndex + "_" + j;
  26520. layersToOutputShapes[shapeKey] = outputShapes_1[j];
  26521. }
  26522. }
  26523. }
  26524. }
  26525. var outputShapes = [];
  26526. var outputShapeKeys = [];
  26527. for (var i = 0; i < this.outputLayers.length; i++) {
  26528. var layer = this.outputLayers[i];
  26529. var nodeIndex = this.outputLayersNodeIndices[i];
  26530. var tensorIndex = this.outputLayersTensorIndices[i];
  26531. var shapeKey = layer.name + "_" + nodeIndex + "_" + tensorIndex;
  26532. outputShapeKeys.push(shapeKey);
  26533. }
  26534. for (var i = 0; i < outputShapeKeys.length; i++) {
  26535. var key = outputShapeKeys[i];
  26536. generic_utils.assert(key in layersToOutputShapes);
  26537. outputShapes.push(layersToOutputShapes[key]);
  26538. }
  26539. return generic_utils.singletonOrArray(outputShapes);
  26540. };
  26541. Container.prototype.runInternalGraph = function (inputs, masks) {
  26542. if (masks == null) {
  26543. masks = generic_utils.pyListRepeat(null, inputs.length);
  26544. }
  26545. var tensorMap = {};
  26546. for (var i = 0; i < this.inputs.length; ++i) {
  26547. var x = this.inputs[i];
  26548. var y = inputs[i];
  26549. var mask = masks[i];
  26550. tensorMap[x.id] = [y, mask];
  26551. }
  26552. var depthKeys = Object.keys(this.nodesByDepth)
  26553. .map(function (x) { return parseInt(x, 10); })
  26554. .sort(generic_utils.reverseNumberCompare);
  26555. for (var _i = 0, depthKeys_4 = depthKeys; _i < depthKeys_4.length; _i++) {
  26556. var depth = depthKeys_4[_i];
  26557. var nodes = this.nodesByDepth[depth];
  26558. for (var _a = 0, nodes_2 = nodes; _a < nodes_2.length; _a++) {
  26559. var node = nodes_2[_a];
  26560. var layer = node.outboundLayer;
  26561. var referenceInputTensors = node.inputTensors;
  26562. var referenceOutputTensors = node.outputTensors;
  26563. var computedData = new Array();
  26564. for (var _b = 0, referenceInputTensors_1 = referenceInputTensors; _b < referenceInputTensors_1.length; _b++) {
  26565. var x = referenceInputTensors_1[_b];
  26566. if (x.id in tensorMap) {
  26567. computedData.push(tensorMap[x.id]);
  26568. }
  26569. }
  26570. if (computedData.length === referenceInputTensors.length) {
  26571. var kwargs = {};
  26572. var computedTensors = void 0;
  26573. var computedMasks = void 0;
  26574. var outputTensors_1 = void 0;
  26575. var outputMasks_1 = void 0;
  26576. if (node.callArgs != null) {
  26577. kwargs = node.callArgs;
  26578. }
  26579. if (computedData.length === 1) {
  26580. var _c = computedData[0], computedTensor = _c[0], computedMask = _c[1];
  26581. if (kwargs.mask == null) {
  26582. kwargs['mask'] = computedMask;
  26583. }
  26584. outputTensors_1 =
  26585. generic_utils.toList(layer.call(computedTensor, kwargs));
  26586. outputMasks_1 = generic_utils.toList(layer.computeMask(computedTensor, computedMask));
  26587. computedTensors = [computedTensor];
  26588. computedMasks = [computedMask];
  26589. }
  26590. else {
  26591. computedTensors = computedData.map(function (x) { return x[0]; });
  26592. computedMasks = computedData.map(function (x) { return x[1]; });
  26593. if (kwargs.mask == null) {
  26594. kwargs['mask'] = computedMasks;
  26595. }
  26596. outputTensors_1 =
  26597. generic_utils.toList(layer.call(computedTensors, kwargs));
  26598. outputMasks_1 = generic_utils.toList(layer.computeMask(computedTensors, computedMasks));
  26599. }
  26600. if (layer.activityRegularizer) {
  26601. throw new errors_1.NotImplementedError('Model invocation with concrete Tensor value(s) in the ' +
  26602. 'presence of activity regularizer(s) is not supported yet.');
  26603. }
  26604. for (var i = 0; i < referenceOutputTensors.length; ++i) {
  26605. var x = referenceOutputTensors[i];
  26606. var y = outputTensors_1[i];
  26607. var mask = outputMasks_1[i];
  26608. tensorMap[x.id] = [y, mask];
  26609. }
  26610. }
  26611. }
  26612. }
  26613. var outputTensors = [];
  26614. var outputMasks = [];
  26615. var outputShapes = [];
  26616. for (var _d = 0, _e = this.outputs; _d < _e.length; _d++) {
  26617. var x = _e[_d];
  26618. generic_utils.assert(x.id in tensorMap, "Could not compute output " + x.name + " : " + x.id);
  26619. var _f = tensorMap[x.id], tensor = _f[0], mask = _f[1];
  26620. outputShapes.push(tensor.shape);
  26621. outputTensors.push(tensor);
  26622. outputMasks.push(mask);
  26623. }
  26624. return [outputTensors, outputMasks, outputShapes];
  26625. };
  26626. Container.prototype.buildNodeConversionMap = function (layers) {
  26627. var nodeConversionMap = {};
  26628. var keptNodes;
  26629. for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {
  26630. var layer = _a[_i];
  26631. keptNodes = layer instanceof Container ? 1 : 0;
  26632. for (var originalNodeIndex = 0; originalNodeIndex < layer.inboundNodes.length; originalNodeIndex++) {
  26633. var nodeKey = Container.nodeKey(layer, originalNodeIndex);
  26634. if (nodeKey in this.containerNodes) {
  26635. nodeConversionMap[nodeKey] = keptNodes;
  26636. keptNodes += 1;
  26637. }
  26638. }
  26639. }
  26640. return nodeConversionMap;
  26641. };
  26642. Container.prototype.getLayer = function (name, index) {
  26643. if (index != null) {
  26644. if (this.layers.length <= index) {
  26645. throw new errors_1.ValueError("Was asked to retrieve layer at index " + index + ", but model only " +
  26646. ("has " + this.layers.length + " layer(s)."));
  26647. }
  26648. else {
  26649. return this.layers[index];
  26650. }
  26651. }
  26652. else {
  26653. if (name == null) {
  26654. throw new errors_1.ValueError('Provide either a layer name or layer index');
  26655. }
  26656. }
  26657. for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {
  26658. var layer = _a[_i];
  26659. if (layer.name === name) {
  26660. return layer;
  26661. }
  26662. }
  26663. throw new errors_1.ValueError("No such layer: " + name);
  26664. };
  26665. Container.prototype.calculateLosses = function () {
  26666. var _this = this;
  26667. return tfjs_core_1.tidy(function () {
  26668. var losses = [];
  26669. for (var _i = 0, _a = _this.layers; _i < _a.length; _i++) {
  26670. var layer = _a[_i];
  26671. for (var nodeIndex = 0; nodeIndex < layer.inboundNodes.length; ++nodeIndex) {
  26672. var nodeKey = Container.nodeKey(layer, nodeIndex);
  26673. if (_this.containerNodes.has(nodeKey)) {
  26674. losses.push.apply(losses, layer.calculateLosses());
  26675. }
  26676. }
  26677. }
  26678. return losses;
  26679. });
  26680. };
  26681. Container.prototype.getConfig = function () {
  26682. var config = { name: this.name };
  26683. var nodeConversionMap = this.buildNodeConversionMap(this.layers);
  26684. var layerConfigs = [];
  26685. for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {
  26686. var layer = _a[_i];
  26687. var layerClassName = layer.getClassName();
  26688. var layerConfig = layer.getConfig();
  26689. var filteredInboundNodes = [];
  26690. for (var originalNodeIndex = 0; originalNodeIndex < layer.inboundNodes.length; originalNodeIndex++) {
  26691. var node = layer.inboundNodes[originalNodeIndex];
  26692. var nodeKey = Container.nodeKey(layer, originalNodeIndex);
  26693. var kwargs = {};
  26694. if (this.containerNodes.has(nodeKey)) {
  26695. if (node.callArgs) {
  26696. var testString = JSON.stringify(node.callArgs);
  26697. if (testString.indexOf('undefined') === -1) {
  26698. kwargs = node.callArgs;
  26699. }
  26700. else {
  26701. console.warn("Layer " + layer.name + " was passed " +
  26702. "non-serializable keyword arguments: " +
  26703. (node.callArgs + ". They will not be included ") +
  26704. "in the serialized model (and thus will be " +
  26705. "missing at deserialization time).");
  26706. kwargs = {};
  26707. }
  26708. }
  26709. if (node.inboundLayers.length > 0) {
  26710. var nodeData = [];
  26711. for (var i = 0; i < node.inboundLayers.length; i++) {
  26712. var inboundLayer = node.inboundLayers[i];
  26713. var nodeIndex = node.nodeIndices[i];
  26714. var tensorIndex = node.tensorIndices[i];
  26715. var nodeKey_1 = Container.nodeKey(inboundLayer, nodeIndex);
  26716. var newNodeIndex = nodeConversionMap[nodeKey_1];
  26717. if (newNodeIndex === null || newNodeIndex === undefined) {
  26718. newNodeIndex = 0;
  26719. }
  26720. nodeData.push([inboundLayer.name, newNodeIndex, tensorIndex, kwargs]);
  26721. }
  26722. filteredInboundNodes.push(nodeData);
  26723. }
  26724. }
  26725. }
  26726. layerConfigs.push({
  26727. name: layer.name,
  26728. className: layerClassName,
  26729. config: layerConfig,
  26730. inboundNodes: filteredInboundNodes
  26731. });
  26732. }
  26733. config['layers'] = layerConfigs;
  26734. var modelInputs = [];
  26735. for (var i = 0; i < this.inputLayers.length; i++) {
  26736. var layer = this.inputLayers[i];
  26737. var nodeIndex = this.inputLayersNodeIndices[i];
  26738. var nodeKey = Container.nodeKey(layer, nodeIndex);
  26739. if (!this.containerNodes.has(nodeKey)) {
  26740. continue;
  26741. }
  26742. var newNodeIndex = nodeConversionMap[nodeKey];
  26743. if (newNodeIndex === null || newNodeIndex === undefined) {
  26744. newNodeIndex = 0;
  26745. }
  26746. var tensorIndex = this.inputLayersTensorIndices[i];
  26747. modelInputs.push([layer.name, newNodeIndex, tensorIndex]);
  26748. }
  26749. config['inputLayers'] = modelInputs;
  26750. var modelOutputs = [];
  26751. for (var i = 0; i < this.outputLayers.length; i++) {
  26752. var layer = this.outputLayers[i];
  26753. var nodeIndex = this.outputLayersNodeIndices[i];
  26754. var nodeKey = Container.nodeKey(layer, nodeIndex);
  26755. if (!this.containerNodes.has(nodeKey)) {
  26756. continue;
  26757. }
  26758. var newNodeIndex = nodeConversionMap[nodeKey];
  26759. if (newNodeIndex === null || newNodeIndex === undefined) {
  26760. newNodeIndex = 0;
  26761. }
  26762. var tensorIndex = this.outputLayersTensorIndices[i];
  26763. modelOutputs.push([layer.name, newNodeIndex, tensorIndex]);
  26764. }
  26765. config['outputLayers'] = modelOutputs;
  26766. return config;
  26767. };
  26768. Container.fromConfig = function (cls, config) {
  26769. var createdLayers = {};
  26770. var unprocessedNodes = {};
  26771. function addUnprocessedNode(layer, nodeData) {
  26772. if (!(layer.name in unprocessedNodes)) {
  26773. unprocessedNodes[layer.name] = [nodeData];
  26774. }
  26775. else {
  26776. unprocessedNodes[layer.name].push(nodeData);
  26777. }
  26778. }
  26779. function processNode(layer, nodeData) {
  26780. var inputTensors = [];
  26781. var kwargs;
  26782. for (var _i = 0, nodeData_1 = nodeData; _i < nodeData_1.length; _i++) {
  26783. var inputData = nodeData_1[_i];
  26784. var inboundLayerName = inputData[0];
  26785. var inboundNodeIndex = inputData[1];
  26786. var inboundTensorIndex = inputData[2];
  26787. if (inputData.length === 3) {
  26788. kwargs = {};
  26789. }
  26790. else if (inputData.length === 4) {
  26791. kwargs = inputData[3];
  26792. }
  26793. else {
  26794. throw new errors_1.ValueError("Improperly formatted model config for layer " + JSON.stringify(layer) + ": " + JSON.stringify(inputData));
  26795. }
  26796. if (!(inboundLayerName in createdLayers)) {
  26797. addUnprocessedNode(layer, nodeData);
  26798. return;
  26799. }
  26800. var inboundLayer = createdLayers[inboundLayerName];
  26801. if (inboundLayer.inboundNodes.length <= inboundNodeIndex) {
  26802. addUnprocessedNode(layer, nodeData);
  26803. return;
  26804. }
  26805. var inboundNode = inboundLayer.inboundNodes[inboundNodeIndex];
  26806. inputTensors.push(inboundNode.outputTensors[inboundTensorIndex]);
  26807. }
  26808. if (inputTensors.length > 0) {
  26809. layer.apply(generic_utils.singletonOrArray(inputTensors), kwargs);
  26810. }
  26811. }
  26812. function processLayer(layerData) {
  26813. var layerName = layerData.name;
  26814. var layer = serialization_1.deserialize(layerData, config.customObjects != null ?
  26815. config.customObjects :
  26816. {});
  26817. createdLayers[layerName] = layer;
  26818. var inboundNodesData = layerData.inboundNodes;
  26819. for (var _i = 0, inboundNodesData_1 = inboundNodesData; _i < inboundNodesData_1.length; _i++) {
  26820. var nodeData = inboundNodesData_1[_i];
  26821. if (!(nodeData instanceof Array)) {
  26822. throw new errors_1.ValueError("Corrupted configuration, expected array for nodeData: " + nodeData);
  26823. }
  26824. addUnprocessedNode(layer, nodeData);
  26825. }
  26826. }
  26827. var name = config.name;
  26828. var layersFromConfig = config.layers;
  26829. for (var _i = 0, layersFromConfig_1 = layersFromConfig; _i < layersFromConfig_1.length; _i++) {
  26830. var layerData = layersFromConfig_1[_i];
  26831. processLayer(layerData);
  26832. }
  26833. while (!generic_utils.isObjectEmpty(unprocessedNodes)) {
  26834. for (var _a = 0, layersFromConfig_2 = layersFromConfig; _a < layersFromConfig_2.length; _a++) {
  26835. var layerData = layersFromConfig_2[_a];
  26836. var layer = createdLayers[layerData.name];
  26837. if (layer.name in unprocessedNodes) {
  26838. for (var _b = 0, _c = unprocessedNodes[layer.name]; _b < _c.length; _b++) {
  26839. var nodeData = _c[_b];
  26840. processNode(layer, nodeData);
  26841. }
  26842. delete unprocessedNodes[layer.name];
  26843. }
  26844. }
  26845. }
  26846. var inputTensors = [];
  26847. var outputTensors = [];
  26848. var inputLayersFromConfig = config.inputLayers;
  26849. for (var _d = 0, inputLayersFromConfig_1 = inputLayersFromConfig; _d < inputLayersFromConfig_1.length; _d++) {
  26850. var layerData = inputLayersFromConfig_1[_d];
  26851. var layerName = layerData[0];
  26852. var nodeIndex = layerData[1];
  26853. var tensorIndex = layerData[2];
  26854. generic_utils.assert(layerName in createdLayers);
  26855. var layer = createdLayers[layerName];
  26856. var layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;
  26857. inputTensors.push(layerOutputTensors[tensorIndex]);
  26858. }
  26859. var outputLayersFromConfig = config.outputLayers;
  26860. for (var _e = 0, outputLayersFromConfig_1 = outputLayersFromConfig; _e < outputLayersFromConfig_1.length; _e++) {
  26861. var layerData = outputLayersFromConfig_1[_e];
  26862. var layerName = layerData[0];
  26863. var nodeIndex = layerData[1];
  26864. var tensorIndex = layerData[2];
  26865. generic_utils.assert(layerName in createdLayers);
  26866. var layer = createdLayers[layerName];
  26867. var layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;
  26868. outputTensors.push(layerOutputTensors[tensorIndex]);
  26869. }
  26870. return new cls({ inputs: inputTensors, outputs: outputTensors, name: name });
  26871. };
  26872. Object.defineProperty(Container.prototype, "stateful", {
  26873. get: function () {
  26874. if (this._stateful) {
  26875. throw new errors_1.ValueError('Container instance unexpectedly has _stateful = true. The ' +
  26876. 'statefulness of a Container is determined by the Layers it ' +
  26877. 'contains. Its _stateful property must remain the default false.');
  26878. }
  26879. for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {
  26880. var layer = _a[_i];
  26881. if (layer.stateful) {
  26882. return true;
  26883. }
  26884. }
  26885. return false;
  26886. },
  26887. enumerable: true,
  26888. configurable: true
  26889. });
  26890. __decorate([
  26891. tfjs_core_1.doc({
  26892. heading: 'Layers',
  26893. subheading: 'Classes',
  26894. namespace: 'layers',
  26895. subclasses: ['Model']
  26896. })
  26897. ], Container.prototype, "getLayer", null);
  26898. return Container;
  26899. }(Layer));
  26900. exports.Container = Container;
  26901. function getSourceInputs(tensor, layer, nodeIndex) {
  26902. if (layer == null || (nodeIndex != null && nodeIndex > 0)) {
  26903. layer = tensor.sourceLayer;
  26904. nodeIndex = tensor.nodeIndex;
  26905. }
  26906. if (layer.inboundNodes.length === 0) {
  26907. return [tensor];
  26908. }
  26909. else {
  26910. var node = layer.inboundNodes[nodeIndex];
  26911. if (node.inboundLayers.length === 0) {
  26912. return node.inputTensors;
  26913. }
  26914. else {
  26915. var sourceTensors = [];
  26916. for (var i = 0; i < node.inboundLayers.length; i++) {
  26917. var x = node.inputTensors[i];
  26918. var layer_2 = node.inboundLayers[i];
  26919. var nodeIndex_3 = node.nodeIndices[i];
  26920. var previousSources = getSourceInputs(x, layer_2, nodeIndex_3);
  26921. for (var _i = 0, previousSources_1 = previousSources; _i < previousSources_1.length; _i++) {
  26922. var x_1 = previousSources_1[_i];
  26923. if (sourceTensors.indexOf(x_1) === -1) {
  26924. sourceTensors.push(x_1);
  26925. }
  26926. }
  26927. }
  26928. return sourceTensors;
  26929. }
  26930. }
  26931. }
  26932. exports.getSourceInputs = getSourceInputs;
  26933. function loadTensor(dtype, shape, value) {
  26934. var dataType = generic_utils.stringToDType(dtype);
  26935. return tfjs_core_1.Tensor.make(shape, { values: shape.length === 0 ? value : tfjs_core_1.util.flatten(value) }, dataType);
  26936. }
  26937. function preprocessWeightsForLoading(layer, weights, originalKerasVersion, originalBackend) {
  26938. if (!originalKerasVersion.startsWith('2.')) {
  26939. throw new errors_1.ValueError('Unsupported Keras version in weights being loaded: ' +
  26940. originalKerasVersion);
  26941. }
  26942. return weights;
  26943. }
  26944. function loadWeightsFromNamedTensorMap(weights, layers) {
  26945. var nameToWeight = {};
  26946. var totalWeightsCount = 0;
  26947. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  26948. var layer = layers_1[_i];
  26949. for (var _a = 0, _b = layer.weights; _a < _b.length; _a++) {
  26950. var weight = _b[_a];
  26951. if (nameToWeight[weight.originalName] != null) {
  26952. throw new errors_1.ValueError("Duplicate weight name: " + weight.originalName);
  26953. }
  26954. nameToWeight[weight.originalName] = weight;
  26955. totalWeightsCount++;
  26956. }
  26957. }
  26958. var weightValueTuples = [];
  26959. for (var name_2 in weights) {
  26960. weightValueTuples.push([nameToWeight[name_2], weights[name_2]]);
  26961. delete nameToWeight[name_2];
  26962. }
  26963. var unsetNames = [];
  26964. for (var name_3 in nameToWeight) {
  26965. unsetNames.push(name_3);
  26966. }
  26967. if (unsetNames.length > 0) {
  26968. throw new errors_1.ValueError(unsetNames.length + " of " + totalWeightsCount + " weights are not set: " +
  26969. ("" + unsetNames));
  26970. }
  26971. variables_1.batchSetValue(weightValueTuples);
  26972. }
  26973. exports.loadWeightsFromNamedTensorMap = loadWeightsFromNamedTensorMap;
  26974. function loadWeightsFromJson(weightsJSON, layers, skipMismatch) {
  26975. if (skipMismatch === void 0) { skipMismatch = false; }
  26976. var originalKerasVersion = weightsJSON['keras_version'];
  26977. var originalBackend = weightsJSON['backend'];
  26978. var layerNames = layers.map(function (layer) { return layer.name; });
  26979. var index = {};
  26980. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  26981. var layer = layers_2[_i];
  26982. if (layer.name != null) {
  26983. if (index[layer.name] == null) {
  26984. index[layer.name] = [];
  26985. }
  26986. index[layer.name].push(layer);
  26987. }
  26988. }
  26989. var nameToWeights = weightsJSON['weights'];
  26990. var weightValueTuples = [];
  26991. for (var k = 0; k < layerNames.length; ++k) {
  26992. var name_4 = layerNames[k];
  26993. var layerWeights = nameToWeights[name_4];
  26994. if (layerWeights == null) {
  26995. layerWeights = [];
  26996. }
  26997. var weightValues = [];
  26998. for (var n = 0; n < layerWeights.length; ++n) {
  26999. var weightEntry = layerWeights[n];
  27000. weightValues.push(new variables_1.LayerVariable(loadTensor(weightEntry['dtype'], weightEntry['shape'], weightEntry['value'])));
  27001. }
  27002. for (var _a = 0, _b = index[name_4]; _a < _b.length; _a++) {
  27003. var layer = _b[_a];
  27004. var symbolicWeights = layer.weights;
  27005. weightValues = preprocessWeightsForLoading(layer, weightValues, originalKerasVersion, originalBackend);
  27006. if (weightValues.length !== symbolicWeights.length) {
  27007. if (skipMismatch) {
  27008. console.warn("Skipping loading of weights of layer " + layer.name + " " +
  27009. ("due to mismatch in number of weights: (" + weightValues.length + " ") +
  27010. ("vs " + symbolicWeights.length + ")."));
  27011. }
  27012. else {
  27013. throw new errors_1.ValueError("Layer #" + k + " (named \"" + layer.name + "\") expects " +
  27014. (symbolicWeights.length + " weight(s), but the saved weights ") +
  27015. ("have " + weightValues.length + " element(s)."));
  27016. }
  27017. }
  27018. for (var i = 0; i < weightValues.length; ++i) {
  27019. if (skipMismatch) {
  27020. if (!tfjs_core_1.util.arraysEqual(symbolicWeights[i].shape, weightValues[i].shape)) {
  27021. console.warn("Skipping loading of weights for layer " + layer.name + " due " +
  27022. ("to mismatch in shape (" + symbolicWeights[i].shape + " vs ") +
  27023. (weightValues[i].shape + ")"));
  27024. continue;
  27025. }
  27026. }
  27027. weightValueTuples.push([symbolicWeights[i], weightValues[i].read()]);
  27028. }
  27029. }
  27030. }
  27031. variables_1.batchSetValue(weightValueTuples);
  27032. }
  27033. exports.loadWeightsFromJson = loadWeightsFromJson;
  27034. },{"../backend/tfjs_backend":169,"../errors":176,"../layers/serialization":190,"../types":197,"../utils/generic_utils":199,"../utils/serialization_utils":202,"../variables":203,"../version":204,"@tensorflow/tfjs-core":54}],175:[function(require,module,exports){
  27035. "use strict";
  27036. var __extends = (this && this.__extends) || (function () {
  27037. var extendStatics = Object.setPrototypeOf ||
  27038. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  27039. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  27040. return function (d, b) {
  27041. extendStatics(d, b);
  27042. function __() { this.constructor = d; }
  27043. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  27044. };
  27045. })();
  27046. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  27047. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  27048. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  27049. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  27050. return c > 3 && r && Object.defineProperty(target, key, r), r;
  27051. };
  27052. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  27053. return new (P || (P = Promise))(function (resolve, reject) {
  27054. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  27055. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  27056. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  27057. step((generator = generator.apply(thisArg, _arguments || [])).next());
  27058. });
  27059. };
  27060. var __generator = (this && this.__generator) || function (thisArg, body) {
  27061. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  27062. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  27063. function verb(n) { return function (v) { return step([n, v]); }; }
  27064. function step(op) {
  27065. if (f) throw new TypeError("Generator is already executing.");
  27066. while (_) try {
  27067. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  27068. if (y = 0, t) op = [0, t.value];
  27069. switch (op[0]) {
  27070. case 0: case 1: t = op; break;
  27071. case 4: _.label++; return { value: op[1], done: false };
  27072. case 5: _.label++; y = op[1]; op = [0]; continue;
  27073. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  27074. default:
  27075. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  27076. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  27077. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  27078. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  27079. if (t[2]) _.ops.pop();
  27080. _.trys.pop(); continue;
  27081. }
  27082. op = body.call(thisArg, _);
  27083. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  27084. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  27085. }
  27086. };
  27087. Object.defineProperty(exports, "__esModule", { value: true });
  27088. var tfc = require("@tensorflow/tfjs-core");
  27089. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  27090. var K = require("../backend/tfjs_backend");
  27091. var callbacks_1 = require("../callbacks");
  27092. var errors_1 = require("../errors");
  27093. var losses = require("../losses");
  27094. var Metrics = require("../metrics");
  27095. var optimizers = require("../optimizers");
  27096. var generic_utils_1 = require("../utils/generic_utils");
  27097. var layer_utils_1 = require("../utils/layer_utils");
  27098. var math_utils_1 = require("../utils/math_utils");
  27099. var executor_1 = require("./executor");
  27100. var topology_1 = require("./topology");
  27101. function isDataTensor(x) {
  27102. return x instanceof tfjs_core_1.Tensor;
  27103. }
  27104. exports.isDataTensor = isDataTensor;
  27105. function isDataArray(x) {
  27106. return Array.isArray(x);
  27107. }
  27108. exports.isDataArray = isDataArray;
  27109. function isDataDict(x) {
  27110. return !isDataTensor(x) && !isDataArray(x);
  27111. }
  27112. exports.isDataDict = isDataDict;
  27113. function standardizeInputData(data, names, shapes, checkBatchAxis, exceptionPrefix) {
  27114. if (checkBatchAxis === void 0) { checkBatchAxis = true; }
  27115. if (exceptionPrefix === void 0) { exceptionPrefix = ''; }
  27116. if (names == null || names.length === 0) {
  27117. if (data != null) {
  27118. var gotUnexpectedData = false;
  27119. if (isDataArray(data) && data.length > 0) {
  27120. gotUnexpectedData = true;
  27121. }
  27122. else if (isDataDict(data)) {
  27123. for (var key in data) {
  27124. if (data.hasOwnProperty(key)) {
  27125. gotUnexpectedData = true;
  27126. break;
  27127. }
  27128. }
  27129. }
  27130. else {
  27131. gotUnexpectedData = true;
  27132. }
  27133. if (gotUnexpectedData) {
  27134. throw new errors_1.ValueError("Error when checking model " + exceptionPrefix + " expected no data, " +
  27135. ("but got " + data));
  27136. }
  27137. }
  27138. return [];
  27139. }
  27140. if (data == null) {
  27141. return names.map(function (name) { return null; });
  27142. }
  27143. var arrays;
  27144. if (isDataDict(data)) {
  27145. data = data;
  27146. arrays = [];
  27147. for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
  27148. var name_1 = names_1[_i];
  27149. if (data[name_1] == null) {
  27150. throw new errors_1.ValueError("No data provided for \"" + name_1 + "\". Need data for each key in: " +
  27151. ("" + names));
  27152. }
  27153. arrays.push(data[name_1]);
  27154. }
  27155. }
  27156. else if (isDataArray(data)) {
  27157. data = data;
  27158. if (data.length !== names.length) {
  27159. throw new errors_1.ValueError("Error when checking model " + exceptionPrefix + ": the Array of " +
  27160. "Tensors that you are passing to your model is not the size the " +
  27161. ("model expected. Expected to see " + names.length + " Tensor(s), but ") +
  27162. ("instead got the following list of Tensor(s): " + data));
  27163. }
  27164. arrays = data;
  27165. }
  27166. else {
  27167. data = data;
  27168. if (names.length > 1) {
  27169. throw new errors_1.ValueError("The model " + exceptionPrefix + " expects " + names.length + " Tensor(s), " +
  27170. ("but only received one Tensor. Found: Tensor with shape " + data.shape));
  27171. }
  27172. arrays = [data];
  27173. }
  27174. for (var i = 0; i < names.length; ++i) {
  27175. var array = arrays[i];
  27176. if (array.shape.length === 1) {
  27177. arrays[i] = K.expandDims(array, 1);
  27178. }
  27179. }
  27180. if (shapes != null) {
  27181. for (var i = 0; i < names.length; ++i) {
  27182. if (shapes[i] == null) {
  27183. continue;
  27184. }
  27185. var array = arrays[i];
  27186. if (array.shape.length !== shapes[i].length) {
  27187. throw new errors_1.ValueError("Error when checking " + exceptionPrefix + ": expected " + names[i] + " " +
  27188. ("to have " + shapes[i].length + " dimension(s). but got array with ") +
  27189. ("shape " + array.shape));
  27190. }
  27191. for (var j = 0; j < shapes[i].length; ++j) {
  27192. if (j === 0 && !checkBatchAxis) {
  27193. continue;
  27194. }
  27195. var dim = array.shape[j];
  27196. var refDim = shapes[i][j];
  27197. if (refDim != null && refDim >= 0 && dim !== refDim) {
  27198. throw new errors_1.ValueError("Error when checking " + exceptionPrefix + ": expected " + names[i] + " " +
  27199. ("to have shape [" + shapes[i] + "], but got array with shape ") +
  27200. ("[" + array.shape + "]."));
  27201. }
  27202. }
  27203. }
  27204. }
  27205. return arrays;
  27206. }
  27207. exports.standardizeInputData = standardizeInputData;
  27208. function checkArrayLengths(inputs, targets, weights) {
  27209. var setX = generic_utils_1.unique(inputs.map(function (input) { return input.shape[0]; }));
  27210. setX.sort();
  27211. var setY = generic_utils_1.unique(targets.map(function (target) { return target.shape[0]; }));
  27212. setY.sort();
  27213. if (setX.length > 1) {
  27214. throw new errors_1.ValueError("All input Tensors (x) should have the same number of samples. " +
  27215. "Got array shapes: " +
  27216. ("" + JSON.stringify(inputs.map(function (input) { return input.shape; }))));
  27217. }
  27218. if (setY.length > 1) {
  27219. throw new errors_1.ValueError("All target Tensors (y) should have the same number of samples. " +
  27220. "Got array shapes: " +
  27221. ("" + JSON.stringify(targets.map(function (target) { return target.shape; }))));
  27222. }
  27223. if (setX.length > 0 && setY.length > 0 && !tfjs_core_1.util.arraysEqual(setX, setY)) {
  27224. throw new errors_1.ValueError("Input Tensors should have the same number of samples as target " +
  27225. ("Tensors. Found " + setX[0] + " input sample(s) and " + setY[0] + " target ") +
  27226. "sample(s).");
  27227. }
  27228. }
  27229. exports.checkArrayLengths = checkArrayLengths;
  27230. function checkLossAndTargetCompatibility(targets, lossFns, outputShapes) {
  27231. var keyLosses = [
  27232. losses.meanSquaredError, losses.binaryCrossentropy,
  27233. losses.categoricalCrossentropy
  27234. ];
  27235. for (var i = 0; i < targets.length; ++i) {
  27236. var y = targets[i];
  27237. var loss = lossFns[i];
  27238. var shape = outputShapes[i];
  27239. if (loss == null) {
  27240. continue;
  27241. }
  27242. if (loss === losses.categoricalCrossentropy) {
  27243. if (y.shape[y.shape.length - 1] === 1) {
  27244. throw new errors_1.ValueError("You are passing a target array of shape " + y.shape + " while using " +
  27245. "a loss 'categorical_crossentropy'. 'categorical_crossentropy'" +
  27246. "expects targets to be binary matrices (1s and 0s) of shape " +
  27247. "[samples, classes].");
  27248. }
  27249. }
  27250. if (keyLosses.indexOf(loss) !== -1) {
  27251. var slicedYShape = y.shape.slice(1);
  27252. var slicedShape = shape.slice(1);
  27253. for (var j = 0; j < slicedYShape.length; ++j) {
  27254. var targetDim = slicedYShape[j];
  27255. var outDim = slicedShape[j];
  27256. if (outDim != null && targetDim !== outDim) {
  27257. throw new errors_1.ValueError("A target Tensor with shape " + y.shape + " was passed for an " +
  27258. ("output of shape " + shape + ", while using a loss function that ") +
  27259. "expects targets to have the same shape as the output.");
  27260. }
  27261. }
  27262. }
  27263. }
  27264. }
  27265. function makeBatches(size, batchSize) {
  27266. var output = [];
  27267. var batchStart = 0;
  27268. var batchEnd = null;
  27269. while (batchStart < size) {
  27270. batchEnd = batchStart + batchSize;
  27271. if (batchEnd >= size) {
  27272. batchEnd = size;
  27273. }
  27274. output.push([batchStart, batchEnd]);
  27275. batchStart = batchEnd;
  27276. }
  27277. return output;
  27278. }
  27279. exports.makeBatches = makeBatches;
  27280. function sliceArrays(arrays, start, stop) {
  27281. if (arrays == null) {
  27282. return [null];
  27283. }
  27284. else if (Array.isArray(arrays)) {
  27285. return arrays.map(function (array) { return K.sliceAlongFirstAxis(array, start, stop - start); });
  27286. }
  27287. else {
  27288. return K.sliceAlongFirstAxis(arrays, start, stop - start);
  27289. }
  27290. }
  27291. function sliceArraysByIndices(arrays, indices) {
  27292. return tfc.tidy(function () {
  27293. if (arrays == null) {
  27294. return null;
  27295. }
  27296. else if (Array.isArray(arrays)) {
  27297. return arrays.map(function (array) { return sliceArraysByIndices(array, indices); });
  27298. }
  27299. else {
  27300. return K.gather(arrays, indices.dtype === 'int32' ? indices : indices.toInt());
  27301. }
  27302. });
  27303. }
  27304. exports.sliceArraysByIndices = sliceArraysByIndices;
  27305. function checkInputData(data, names, shapes, checkBatchAxis, exceptionPrefix) {
  27306. if (checkBatchAxis === void 0) { checkBatchAxis = true; }
  27307. if (exceptionPrefix === void 0) { exceptionPrefix = ''; }
  27308. var arrays;
  27309. if (Array.isArray(data)) {
  27310. if (data.length !== names.length) {
  27311. throw new errors_1.ValueError("Error when checking model " + exceptionPrefix + ": the Array of " +
  27312. "Tensors that you are passing to your model is not the size the " +
  27313. ("the model expected. Expected to see " + names.length + " Tensor(s),") +
  27314. (" but instead got " + data.length + " Tensors(s)."));
  27315. }
  27316. arrays = data;
  27317. }
  27318. else {
  27319. if (names.length > 1) {
  27320. throw new errors_1.ValueError("The model expects " + names.length + " " + exceptionPrefix + " Tensors, " +
  27321. "but only received one Tensor. Found: array with shape " +
  27322. (JSON.stringify(data.shape) + "."));
  27323. }
  27324. arrays = [data];
  27325. }
  27326. if (shapes != null) {
  27327. for (var i = 0; i < names.length; ++i) {
  27328. if (shapes[i] == null) {
  27329. continue;
  27330. }
  27331. var array = arrays[i];
  27332. if (array.shape.length !== shapes[i].length) {
  27333. throw new errors_1.ValueError("Error when checking " + exceptionPrefix + ": expected " + names[i] + " " +
  27334. ("to have " + shapes[i].length + " dimension(s), but got array with ") +
  27335. ("shape " + JSON.stringify(array.shape)));
  27336. }
  27337. for (var j = 0; j < shapes[i].length; ++j) {
  27338. if (j === 0 && !checkBatchAxis) {
  27339. continue;
  27340. }
  27341. var dim = array.shape[j];
  27342. var refDim = shapes[i][j];
  27343. if (refDim != null) {
  27344. if (refDim !== dim) {
  27345. throw new errors_1.ValueError("Error when checking " + exceptionPrefix + ": expected " +
  27346. (names[i] + " to have shape " + JSON.stringify(shapes[i]) + " but ") +
  27347. ("got array with shape " + JSON.stringify(array.shape) + "."));
  27348. }
  27349. }
  27350. }
  27351. }
  27352. }
  27353. }
  27354. function collectMetrics(metrics, outputNames) {
  27355. if (metrics == null || Array.isArray(metrics) && metrics.length === 0) {
  27356. return outputNames.map(function (name) { return []; });
  27357. }
  27358. if (Array.isArray(metrics)) {
  27359. return outputNames.map(function (name) { return metrics; });
  27360. }
  27361. else if (metrics != null) {
  27362. var nestedMetrics = [];
  27363. for (var _i = 0, outputNames_1 = outputNames; _i < outputNames_1.length; _i++) {
  27364. var name_2 = outputNames_1[_i];
  27365. var outputMetrics = metrics.hasOwnProperty(name_2) ? metrics[name_2] : [];
  27366. if (!Array.isArray(outputMetrics)) {
  27367. outputMetrics = [outputMetrics];
  27368. }
  27369. nestedMetrics.push(outputMetrics);
  27370. }
  27371. return nestedMetrics;
  27372. }
  27373. else {
  27374. throw new TypeError('Type of metrics argument not understood. Expected an Array or ' +
  27375. 'Object, found: ' + metrics);
  27376. }
  27377. }
  27378. var ModelLoggingVerbosity;
  27379. (function (ModelLoggingVerbosity) {
  27380. ModelLoggingVerbosity[ModelLoggingVerbosity["SILENT"] = 0] = "SILENT";
  27381. ModelLoggingVerbosity[ModelLoggingVerbosity["VERBOSE"] = 1] = "VERBOSE";
  27382. })(ModelLoggingVerbosity = exports.ModelLoggingVerbosity || (exports.ModelLoggingVerbosity = {}));
  27383. var Model = (function (_super) {
  27384. __extends(Model, _super);
  27385. function Model(config) {
  27386. return _super.call(this, config) || this;
  27387. }
  27388. Model.prototype.summary = function (lineLength, positions, printFn) {
  27389. if (printFn === void 0) { printFn = console.log; }
  27390. if (!this.built) {
  27391. throw new errors_1.ValueError("This model has never been called, thus its weights have not been " +
  27392. "created yet. So no summary can be displayed. Build the model " +
  27393. "first (e.g., by calling it on some test data).");
  27394. }
  27395. layer_utils_1.printSummary(this, lineLength, positions, printFn);
  27396. };
  27397. Model.prototype.compile = function (config) {
  27398. var _this = this;
  27399. if (config.loss == null) {
  27400. config.loss = [];
  27401. }
  27402. this.loss = config.loss;
  27403. if (typeof config.optimizer === 'string') {
  27404. this.optimizer = optimizers.getOptimizer(config.optimizer);
  27405. }
  27406. else {
  27407. if (!(config.optimizer instanceof tfjs_core_1.Optimizer)) {
  27408. throw new errors_1.ValueError("User-defined optimizer must be an instance of tf.Optimizer.");
  27409. }
  27410. this.optimizer = config.optimizer;
  27411. }
  27412. var lossFunctions = [];
  27413. if (!Array.isArray(config.loss) && typeof config.loss !== 'string' &&
  27414. typeof config.loss !== 'function') {
  27415. config.loss = config.loss;
  27416. for (var name_3 in config.loss) {
  27417. if (this.outputNames.indexOf(name_3) === -1) {
  27418. throw new errors_1.ValueError("Unknown entry in loss dictionary: \"" + name_3 + "\". Only expect the " +
  27419. ("following keys: " + this.outputNames));
  27420. }
  27421. }
  27422. for (var name_4 in this.outputNames) {
  27423. if (config.loss[name_4] == null) {
  27424. console.warn("Output \"" + name_4 + "\" is missing from loss dictionary. We assume " +
  27425. "this was done on purpose, and we will not be expecting data " +
  27426. ("to be passed to " + name_4 + " during training"));
  27427. }
  27428. lossFunctions.push(losses.get(config.loss[name_4]));
  27429. }
  27430. }
  27431. else if (Array.isArray(config.loss)) {
  27432. if (config.loss.length !== this.outputs.length) {
  27433. throw new errors_1.ValueError("When passing an Array as loss, it should have one entry per " +
  27434. ("model output. The model has " + this.outputs.length + " output(s), ") +
  27435. ("but you passed loss=" + config.loss + "."));
  27436. }
  27437. var theLosses = config.loss;
  27438. lossFunctions = theLosses.map(function (l) { return losses.get(l); });
  27439. }
  27440. else {
  27441. var lossFunction_1 = losses.get(config.loss);
  27442. this.outputs.map(function (layer) {
  27443. lossFunctions.push(lossFunction_1);
  27444. });
  27445. }
  27446. this.lossFunctions = lossFunctions;
  27447. this.feedOutputNames = [];
  27448. this.feedOutputShapes = [];
  27449. this.feedLossFns = [];
  27450. for (var i = 0; i < this.outputs.length; ++i) {
  27451. var shape = this.internalOutputShapes[i];
  27452. var name_5 = this.outputNames[i];
  27453. this.feedOutputNames.push(name_5);
  27454. this.feedOutputShapes.push(shape);
  27455. this.feedLossFns.push(this.lossFunctions[i]);
  27456. }
  27457. var skipTargetIndices = [];
  27458. this.metrics = config.metrics;
  27459. this.metricsNames = ['loss'];
  27460. this.metricsTensors = [];
  27461. K.nameScope('loss', function () {
  27462. for (var i = 0; i < _this.outputs.length; ++i) {
  27463. if (skipTargetIndices.indexOf(i) !== -1) {
  27464. continue;
  27465. }
  27466. var weightedLoss = _this.lossFunctions[i];
  27467. if (_this.outputs.length > 1) {
  27468. _this.metricsTensors.push([weightedLoss, i]);
  27469. _this.metricsNames.push(_this.outputNames[i] + '_loss');
  27470. }
  27471. }
  27472. });
  27473. var nestedMetrics = collectMetrics(config.metrics, this.outputNames);
  27474. var appendMetric = function (outputIndex, metricName, metricTensor) {
  27475. if (_this.outputNames.length > 1) {
  27476. metricName = _this.outputNames[outputIndex] + '_' + metricName;
  27477. }
  27478. _this.metricsNames.push(metricName);
  27479. _this.metricsTensors.push([metricTensor, outputIndex]);
  27480. };
  27481. K.nameScope('metric', function () {
  27482. var _loop_1 = function (i) {
  27483. if (skipTargetIndices.indexOf(i) !== -1) {
  27484. return "continue";
  27485. }
  27486. var outputMetrics = nestedMetrics[i];
  27487. var handleMetrics = function (metrics) {
  27488. var metricNamePrefix = '';
  27489. var metricName;
  27490. var accFn;
  27491. var weightedMetricFn;
  27492. var _loop_2 = function (metric) {
  27493. if (['accuracy', 'acc', 'crossentropy', 'ce'].indexOf(metric) !==
  27494. -1) {
  27495. var outputShape = _this.internalOutputShapes[i];
  27496. if (outputShape[outputShape.length - 1] === 1 ||
  27497. _this.lossFunctions[i] === losses.binaryCrossentropy) {
  27498. if (['accuracy', 'acc'].indexOf(metric) !== -1) {
  27499. accFn = Metrics.binaryAccuracy;
  27500. }
  27501. else if (['crossentropy', 'ce'].indexOf(metric) !== -1) {
  27502. accFn = Metrics.binaryCrossentropy;
  27503. }
  27504. }
  27505. else if (_this.lossFunctions[i] ===
  27506. losses.sparseCategoricalCrossentropy) {
  27507. if (['accuracy', 'acc'].indexOf(metric) !== -1) {
  27508. accFn = Metrics.sparseCategoricalAccuracy;
  27509. }
  27510. else if (['crossentropy', 'ce'].indexOf(metric) !== -1) {
  27511. accFn = Metrics.sparseCategoricalCrossentropy;
  27512. }
  27513. }
  27514. else {
  27515. if (['accuracy', 'acc'].indexOf(metric) !== -1) {
  27516. accFn = Metrics.categoricalAccuracy;
  27517. }
  27518. else if (['crossentropy', 'ce'].indexOf(metric) !== -1) {
  27519. accFn = Metrics.categoricalCrossentropy;
  27520. }
  27521. }
  27522. var suffix = void 0;
  27523. if (['accuracy', 'acc'].indexOf(metric) !== -1) {
  27524. suffix = 'acc';
  27525. }
  27526. else if (['crossentropy', 'ce'].indexOf(metric) !== -1) {
  27527. suffix = 'ce';
  27528. }
  27529. weightedMetricFn = accFn;
  27530. metricName = metricNamePrefix + suffix;
  27531. }
  27532. else {
  27533. var metricFn = Metrics.get(metric);
  27534. weightedMetricFn = metricFn;
  27535. metricName = metricNamePrefix + metric;
  27536. }
  27537. var metricResult;
  27538. K.nameScope(metricName, function () {
  27539. metricResult = weightedMetricFn;
  27540. });
  27541. appendMetric(i, metricName, metricResult);
  27542. };
  27543. for (var _i = 0, metrics_1 = metrics; _i < metrics_1.length; _i++) {
  27544. var metric = metrics_1[_i];
  27545. _loop_2(metric);
  27546. }
  27547. };
  27548. handleMetrics(outputMetrics);
  27549. };
  27550. for (var i = 0; i < _this.outputs.length; ++i) {
  27551. _loop_1(i);
  27552. }
  27553. });
  27554. this.collectedTrainableWeights = this.trainableWeights;
  27555. };
  27556. Model.prototype.checkTrainableWeightsConsistency = function () {
  27557. if (this.collectedTrainableWeights == null) {
  27558. return;
  27559. }
  27560. if (this.trainableWeights.length !==
  27561. this.collectedTrainableWeights.length) {
  27562. console.warn('Discrepancy between trainableweights and collected trainable ' +
  27563. 'weights. Did you set `model.trainable` without calling ' +
  27564. '`model.compile()` afterwards?');
  27565. }
  27566. };
  27567. Model.prototype.evaluate = function (x, y, config) {
  27568. if (config === void 0) { config = {}; }
  27569. var batchSize = config.batchSize == null ? 32 : config.batchSize;
  27570. var standardizedOuts = this.standardizeUserData(x, y, true, batchSize);
  27571. var ins = standardizedOuts[0].concat(standardizedOuts[1]);
  27572. this.makeTestFunction();
  27573. var f = this.testFunction;
  27574. var testOuts = this.testLoop(f, ins, batchSize, config.verbose, config.steps);
  27575. return generic_utils_1.singletonOrArray(testOuts);
  27576. };
  27577. Model.prototype.checkNumSamples = function (ins, batchSize, steps, stepsName) {
  27578. if (stepsName === void 0) { stepsName = 'steps'; }
  27579. var numSamples;
  27580. if (steps != null) {
  27581. numSamples = null;
  27582. if (batchSize != null) {
  27583. throw new errors_1.ValueError("If " + stepsName + " is set, batchSize must be null or undefined." +
  27584. ("Got batchSize = " + batchSize));
  27585. }
  27586. }
  27587. else if (ins != null) {
  27588. if (Array.isArray(ins)) {
  27589. numSamples = ins[0].shape[0];
  27590. }
  27591. else {
  27592. numSamples = ins.shape[0];
  27593. }
  27594. }
  27595. else {
  27596. throw new errors_1.ValueError("Either the input data should have a defined shape, or " +
  27597. (stepsName + " shoud be specified."));
  27598. }
  27599. return numSamples;
  27600. };
  27601. Model.prototype.execute = function (inputs, outputs) {
  27602. if (Array.isArray(outputs) && outputs.length === 0) {
  27603. throw new errors_1.ValueError('`outputs` is an empty Array, which is not allowed.');
  27604. }
  27605. var outputsIsArray = Array.isArray(outputs);
  27606. var outputNames = (outputsIsArray ? outputs :
  27607. [outputs]);
  27608. var outputSymbolicTensors = this.retrieveSymbolicTensors(outputNames);
  27609. var feedDict = new executor_1.FeedDict();
  27610. if (inputs instanceof tfjs_core_1.Tensor) {
  27611. inputs = [inputs];
  27612. }
  27613. if (Array.isArray(inputs)) {
  27614. if (inputs.length !== this.inputs.length) {
  27615. throw new errors_1.ValueError("The number of inputs provided (" + inputs.length + ") " +
  27616. "does not match the number of inputs of this model " +
  27617. ("(" + this.inputs.length + ")."));
  27618. }
  27619. for (var i = 0; i < this.inputs.length; ++i) {
  27620. feedDict.add(this.inputs[i], inputs[i]);
  27621. }
  27622. }
  27623. else {
  27624. for (var _i = 0, _a = this.inputs; _i < _a.length; _i++) {
  27625. var input = _a[_i];
  27626. var tensorValue = inputs[input.name];
  27627. if (tensorValue == null) {
  27628. throw new errors_1.ValueError("No value is provided for the model's input " + input.name);
  27629. }
  27630. feedDict.add(input, tensorValue);
  27631. }
  27632. }
  27633. var executeOutputs = executor_1.execute(outputSymbolicTensors, feedDict);
  27634. return outputsIsArray ? executeOutputs : executeOutputs[0];
  27635. };
  27636. Model.prototype.retrieveSymbolicTensors = function (symbolicTensorNames) {
  27637. var outputSymbolicTensors = generic_utils_1.pyListRepeat(null, symbolicTensorNames.length);
  27638. var outputsRemaining = symbolicTensorNames.length;
  27639. for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {
  27640. var layer = _a[_i];
  27641. var layerOutputs = Array.isArray(layer.output) ?
  27642. layer.output :
  27643. [layer.output];
  27644. var layerOutputNames = layerOutputs.map(function (output) { return output.name; });
  27645. for (var i = 0; i < symbolicTensorNames.length; ++i) {
  27646. var index = layerOutputNames.indexOf(symbolicTensorNames[i]);
  27647. if (index !== -1) {
  27648. outputSymbolicTensors[i] = layerOutputs[index];
  27649. outputsRemaining--;
  27650. }
  27651. if (outputsRemaining === 0) {
  27652. break;
  27653. }
  27654. }
  27655. if (outputsRemaining === 0) {
  27656. break;
  27657. }
  27658. }
  27659. if (outputsRemaining > 0) {
  27660. var remainingNames_1 = [];
  27661. outputSymbolicTensors.forEach(function (tensor, i) {
  27662. if (tensor == null) {
  27663. remainingNames_1.push(symbolicTensorNames[i]);
  27664. }
  27665. });
  27666. throw new errors_1.ValueError("Cannot find SymbolicTensors for output name(s): " +
  27667. ("" + JSON.stringify(remainingNames_1)));
  27668. }
  27669. return outputSymbolicTensors;
  27670. };
  27671. Model.prototype.predictLoop = function (ins, batchSize, verbose) {
  27672. var _this = this;
  27673. if (batchSize === void 0) { batchSize = 32; }
  27674. if (verbose === void 0) { verbose = false; }
  27675. var numSamples = this.checkNumSamples(ins);
  27676. if (verbose) {
  27677. throw new errors_1.NotImplementedError('Verbose predictLoop() is not implemented yet.');
  27678. }
  27679. var batches = makeBatches(numSamples, batchSize);
  27680. var outs = [];
  27681. var _loop_3 = function (batchIndex) {
  27682. var batchOuts = tfc.tidy(function () {
  27683. var batchStart = batches[batchIndex][0];
  27684. var batchEnd = batches[batchIndex][1];
  27685. var insBatch = sliceArrays(ins, batchStart, batchEnd);
  27686. var feeds = [];
  27687. if (Array.isArray(insBatch)) {
  27688. for (var i = 0; i < insBatch.length; ++i) {
  27689. feeds.push({ key: _this.inputs[i], value: insBatch[i] });
  27690. }
  27691. }
  27692. else {
  27693. feeds.push({ key: _this.inputs[0], value: insBatch });
  27694. }
  27695. var feedDict = new executor_1.FeedDict(feeds);
  27696. return executor_1.execute(_this.outputs, feedDict);
  27697. });
  27698. if (batchIndex === 0) {
  27699. for (var _i = 0, batchOuts_1 = batchOuts; _i < batchOuts_1.length; _i++) {
  27700. var batchOut = batchOuts_1[_i];
  27701. outs.push(batchOut);
  27702. }
  27703. }
  27704. else {
  27705. for (var i = 0; i < batchOuts.length; ++i) {
  27706. outs[i] = K.concatAlongFirstAxis(outs[i], batchOuts[i]);
  27707. }
  27708. }
  27709. };
  27710. for (var batchIndex = 0; batchIndex < batches.length; ++batchIndex) {
  27711. _loop_3(batchIndex);
  27712. }
  27713. return generic_utils_1.singletonOrArray(outs);
  27714. };
  27715. Model.prototype.predict = function (x, config) {
  27716. if (config === void 0) { config = {}; }
  27717. checkInputData(x, this.inputNames, this.feedInputShapes, false);
  27718. var batchSize = config.batchSize == null ? 32 : config.batchSize;
  27719. return this.predictLoop(x, batchSize);
  27720. };
  27721. Model.prototype.predictOnBatch = function (x) {
  27722. checkInputData(x, this.inputNames, this.feedInputShapes, true);
  27723. return this.predictLoop(x, x.shape[0]);
  27724. };
  27725. Model.prototype.standardizeUserData = function (x, y, checkBatchAxis, batchSize) {
  27726. if (checkBatchAxis === void 0) { checkBatchAxis = true; }
  27727. if (this.optimizer == null) {
  27728. throw new errors_1.RuntimeError('You must compile a model before training/testing. Use ' +
  27729. 'Model.compile(modelCompileConfig).');
  27730. }
  27731. var outputShapes = [];
  27732. for (var i = 0; i < this.feedOutputShapes.length; ++i) {
  27733. var outputShape = this.feedOutputShapes[i];
  27734. var lossFn = this.feedLossFns[i];
  27735. if (lossFn === losses.sparseCategoricalCrossentropy) {
  27736. outputShapes.push(outputShape.slice(0, outputShape.length - 1).concat([1]));
  27737. }
  27738. else {
  27739. outputShapes.push(outputShape);
  27740. }
  27741. }
  27742. x = standardizeInputData(x, this.feedInputNames, this.feedInputShapes, false, 'input');
  27743. y = standardizeInputData(y, this.feedOutputNames, outputShapes, false, 'target');
  27744. checkArrayLengths(x, y, null);
  27745. checkLossAndTargetCompatibility(y, this.feedLossFns, this.feedOutputShapes);
  27746. if (this.stateful && batchSize != null && batchSize > 0) {
  27747. if (x[0].shape[0] % batchSize !== 0) {
  27748. throw new errors_1.ValueError("In a stateful network, you should only pass inputs with a " +
  27749. "number of samples that is divisible by the batch size " +
  27750. (batchSize + ". Found: " + x[0].shape[0] + " sample(s)."));
  27751. }
  27752. }
  27753. return [x, y, null];
  27754. };
  27755. Model.prototype.fitLoop = function (f, ins, outLabels, batchSize, epochs, verbose, callbacks, valF, valIns, shuffle, callbackMetrics, initialEpoch, stepsPerEpoch, validationSteps) {
  27756. if (initialEpoch === void 0) { initialEpoch = 0; }
  27757. return __awaiter(this, void 0, void 0, function () {
  27758. var _this = this;
  27759. var doValidation, numTrainSamples, indexArray, callbackList, _loop_4, this_1, epoch, state_1;
  27760. return __generator(this, function (_a) {
  27761. switch (_a.label) {
  27762. case 0:
  27763. if (batchSize == null) {
  27764. batchSize = 32;
  27765. }
  27766. if (epochs == null) {
  27767. epochs = 1;
  27768. }
  27769. if (shuffle == null) {
  27770. shuffle = true;
  27771. }
  27772. if (initialEpoch == null) {
  27773. initialEpoch = 0;
  27774. }
  27775. doValidation = false;
  27776. if (valF != null && valIns != null) {
  27777. doValidation = true;
  27778. }
  27779. if (validationSteps != null) {
  27780. doValidation = true;
  27781. if (stepsPerEpoch == null) {
  27782. throw new errors_1.ValueError('Can only use `validationSteps` when doing step-wise training, ' +
  27783. 'i.e., `stepsPerEpoch` must be set.');
  27784. }
  27785. }
  27786. numTrainSamples = this.checkNumSamples(ins, batchSize, stepsPerEpoch, 'steps_per_epoch');
  27787. if (numTrainSamples != null) {
  27788. indexArray = math_utils_1.range(0, numTrainSamples);
  27789. }
  27790. this.history = new callbacks_1.History();
  27791. if (callbacks == null) {
  27792. callbacks = [new callbacks_1.BaseLogger()];
  27793. }
  27794. else {
  27795. callbacks = [new callbacks_1.BaseLogger()].concat(callbacks);
  27796. }
  27797. callbacks = callbacks.concat([this.history]);
  27798. if (verbose > 0) {
  27799. throw new errors_1.NotImplementedError('Verbose mode is not implemented yet.');
  27800. }
  27801. callbackList = new callbacks_1.CallbackList(callbacks);
  27802. callbackList.setModel(this);
  27803. callbackList.setParams({
  27804. epochs: epochs,
  27805. steps: stepsPerEpoch,
  27806. verbose: verbose,
  27807. doValidation: doValidation,
  27808. metrics: callbackMetrics,
  27809. });
  27810. return [4, callbackList.onTrainBegin()];
  27811. case 1:
  27812. _a.sent();
  27813. this.stopTraining = false;
  27814. _loop_4 = function (epoch) {
  27815. var epochLogs, epochIndexArray1D_1, batches_1, _loop_5, batchIndex, state_2;
  27816. return __generator(this, function (_a) {
  27817. switch (_a.label) {
  27818. case 0: return [4, callbackList.onEpochBegin(epoch)];
  27819. case 1:
  27820. _a.sent();
  27821. epochLogs = {};
  27822. if (!(stepsPerEpoch != null)) return [3, 2];
  27823. throw new errors_1.NotImplementedError('stepsPerEpoch mode is not implemented yet.');
  27824. case 2:
  27825. if (shuffle === 'batch') {
  27826. throw new errors_1.NotImplementedError('batch shuffling is not implemneted yet');
  27827. }
  27828. else if (shuffle) {
  27829. tfjs_core_1.util.shuffle(indexArray);
  27830. }
  27831. epochIndexArray1D_1 = tfjs_core_1.tensor1d(indexArray);
  27832. batches_1 = makeBatches(numTrainSamples, batchSize);
  27833. _loop_5 = function (batchIndex) {
  27834. var batchLogs;
  27835. return __generator(this, function (_a) {
  27836. switch (_a.label) {
  27837. case 0:
  27838. batchLogs = {};
  27839. return [4, callbackList.onBatchBegin(batchIndex, batchLogs)];
  27840. case 1:
  27841. _a.sent();
  27842. tfc.tidy(function () {
  27843. var batchStart = batches_1[batchIndex][0];
  27844. var batchEnd = batches_1[batchIndex][1];
  27845. var batchIds = K.sliceAlongFirstAxis(epochIndexArray1D_1, batchStart, batchEnd - batchStart);
  27846. batchLogs['batch'] = batchIndex;
  27847. batchLogs['size'] = batchEnd - batchStart;
  27848. var insBatch = sliceArraysByIndices(ins, batchIds);
  27849. var outs = f(insBatch);
  27850. for (var i = 0; i < outLabels.length; ++i) {
  27851. var label = outLabels[i];
  27852. var out = outs[i];
  27853. batchLogs[label] = out;
  27854. tfc.keep(out);
  27855. }
  27856. if (batchIndex === batches_1.length - 1) {
  27857. if (doValidation) {
  27858. var valOuts = _this.testLoop(valF, valIns, batchSize);
  27859. for (var i = 0; i < outLabels.length; ++i) {
  27860. var label = outLabels[i];
  27861. var out = valOuts[i];
  27862. tfc.keep(out);
  27863. epochLogs['val_' + label] = out;
  27864. }
  27865. }
  27866. }
  27867. });
  27868. return [4, callbackList.onBatchEnd(batchIndex, batchLogs)];
  27869. case 2:
  27870. _a.sent();
  27871. callbacks_1.disposeTensorsInLogs(batchLogs);
  27872. if (this_1.stopTraining) {
  27873. return [2, "break"];
  27874. }
  27875. return [2];
  27876. }
  27877. });
  27878. };
  27879. batchIndex = 0;
  27880. _a.label = 3;
  27881. case 3:
  27882. if (!(batchIndex < batches_1.length)) return [3, 6];
  27883. return [5, _loop_5(batchIndex)];
  27884. case 4:
  27885. state_2 = _a.sent();
  27886. if (state_2 === "break")
  27887. return [3, 6];
  27888. _a.label = 5;
  27889. case 5:
  27890. ++batchIndex;
  27891. return [3, 3];
  27892. case 6:
  27893. epochIndexArray1D_1.dispose();
  27894. _a.label = 7;
  27895. case 7: return [4, callbackList.onEpochEnd(epoch, epochLogs)];
  27896. case 8:
  27897. _a.sent();
  27898. if (this_1.stopTraining) {
  27899. return [2, "break"];
  27900. }
  27901. return [2];
  27902. }
  27903. });
  27904. };
  27905. this_1 = this;
  27906. epoch = initialEpoch;
  27907. _a.label = 2;
  27908. case 2:
  27909. if (!(epoch < epochs)) return [3, 5];
  27910. return [5, _loop_4(epoch)];
  27911. case 3:
  27912. state_1 = _a.sent();
  27913. if (state_1 === "break")
  27914. return [3, 5];
  27915. _a.label = 4;
  27916. case 4:
  27917. ++epoch;
  27918. return [3, 2];
  27919. case 5: return [4, callbackList.onTrainEnd()];
  27920. case 6:
  27921. _a.sent();
  27922. return [4, this.history.syncData()];
  27923. case 7:
  27924. _a.sent();
  27925. return [2, this.history];
  27926. }
  27927. });
  27928. });
  27929. };
  27930. Model.prototype.testLoop = function (f, ins, batchSize, verbose, steps) {
  27931. if (verbose === void 0) { verbose = 0; }
  27932. var numSamples = this.checkNumSamples(ins, batchSize, steps, 'steps');
  27933. var outs = [];
  27934. if (verbose === 1) {
  27935. throw new errors_1.NotImplementedError('Verbose mode is not implemented yet.');
  27936. }
  27937. if (steps != null) {
  27938. throw new errors_1.NotImplementedError('steps mode in testLoop() is not implemented yet');
  27939. }
  27940. else {
  27941. var batches = makeBatches(numSamples, batchSize);
  27942. var indexArray = tfjs_core_1.tensor1d(math_utils_1.range(0, numSamples));
  27943. for (var batchIndex = 0; batchIndex < batches.length; ++batchIndex) {
  27944. var batchStart = batches[batchIndex][0];
  27945. var batchEnd = batches[batchIndex][1];
  27946. var batchIds = K.sliceAlongFirstAxis(indexArray, batchStart, batchEnd - batchStart);
  27947. var insBatch = sliceArraysByIndices(ins, batchIds);
  27948. var batchOuts = f(insBatch);
  27949. if (batchIndex === 0) {
  27950. for (var i = 0; i < batchOuts.length; ++i) {
  27951. outs.push(K.getScalar(0));
  27952. }
  27953. }
  27954. for (var i = 0; i < batchOuts.length; ++i) {
  27955. var batchOut = batchOuts[i];
  27956. outs[i] =
  27957. tfc.add(outs[i], K.scalarTimesArray(K.getScalar(batchEnd - batchStart), batchOut));
  27958. }
  27959. }
  27960. for (var i = 0; i < outs.length; ++i) {
  27961. outs[i] = tfc.div(outs[i], K.getScalar(numSamples));
  27962. }
  27963. }
  27964. return outs;
  27965. };
  27966. Model.prototype.getDedupedMetricsNames = function () {
  27967. var outLabels = this.metricsNames;
  27968. var dedupedOutLabels = [];
  27969. for (var i = 0; i < outLabels.length; ++i) {
  27970. var label = outLabels[i];
  27971. var newLabel = label;
  27972. if (generic_utils_1.count(outLabels, label) > 1) {
  27973. var dupIndex = generic_utils_1.count(outLabels.slice(0, i), label);
  27974. newLabel += "_" + dupIndex;
  27975. }
  27976. dedupedOutLabels.push(newLabel);
  27977. }
  27978. return dedupedOutLabels;
  27979. };
  27980. Model.prototype.makeTestFunction = function () {
  27981. var _this = this;
  27982. this.testFunction = function (data) {
  27983. return tfc.tidy(function () {
  27984. var valOutputs = [];
  27985. var totalLoss;
  27986. var inputs = data.slice(0, _this.inputs.length);
  27987. var targets = data.slice(_this.inputs.length, _this.inputs.length + _this.outputs.length);
  27988. var feeds = [];
  27989. for (var i = 0; i < _this.inputs.length; ++i) {
  27990. feeds.push({ key: _this.inputs[i], value: inputs[i] });
  27991. }
  27992. var feedDict = new executor_1.FeedDict(feeds);
  27993. var outputs = executor_1.execute(_this.outputs, feedDict);
  27994. for (var i = 0; i < _this.lossFunctions.length; ++i) {
  27995. var lossFunction = _this.lossFunctions[i];
  27996. var loss = tfc.mean(lossFunction(targets[i], outputs[i]));
  27997. if (i === 0) {
  27998. totalLoss = loss;
  27999. }
  28000. else {
  28001. totalLoss = tfc.add(totalLoss, loss);
  28002. }
  28003. valOutputs.push(totalLoss);
  28004. }
  28005. for (var i = 0; i < _this.metricsTensors.length; ++i) {
  28006. var metric = _this.metricsTensors[i][0];
  28007. var outputIndex = _this.metricsTensors[i][1];
  28008. var meanMetric = tfc.mean(metric(targets[outputIndex], outputs[outputIndex]));
  28009. valOutputs.push(meanMetric);
  28010. }
  28011. return valOutputs;
  28012. });
  28013. };
  28014. };
  28015. Model.prototype.fit = function (x, y, config) {
  28016. if (config === void 0) { config = {}; }
  28017. return __awaiter(this, void 0, void 0, function () {
  28018. var _this = this;
  28019. var batchSize, standardizedOuts, inputs, targets, doValidation, valX, valY, valIns, needValidationDisposal, valStandardized, splitAt, originalBatchSize, ins, trainFunction, outLabels, valFunction, callbackMetrics, callbacks, out;
  28020. return __generator(this, function (_a) {
  28021. switch (_a.label) {
  28022. case 0:
  28023. batchSize = config.batchSize == null ? 32 : config.batchSize;
  28024. standardizedOuts = this.standardizeUserData(x, y, false, batchSize);
  28025. inputs = standardizedOuts[0];
  28026. targets = standardizedOuts[1];
  28027. doValidation = false;
  28028. needValidationDisposal = false;
  28029. if (config.validationData != null && config.validationData.length > 0) {
  28030. doValidation = true;
  28031. if (config.validationData.length === 2) {
  28032. valX = config.validationData[0];
  28033. valY = config.validationData[1];
  28034. }
  28035. else if (config.validationData.length === 3) {
  28036. throw new errors_1.NotImplementedError('validationData including sample weights is not supported yet.');
  28037. }
  28038. else {
  28039. throw new errors_1.ValueError("When passing validation data, it must contain 2 (valX, valY) " +
  28040. "or 3 (valX, valY, valSampleWeight) items; " +
  28041. (config.validationData + " is invalid."));
  28042. }
  28043. valStandardized = this.standardizeUserData(valX, valY, true, batchSize);
  28044. valX = valStandardized[0];
  28045. valY = valStandardized[1];
  28046. valIns = valX.concat(valY);
  28047. }
  28048. else if (config.validationSplit != null && config.validationSplit > 0 &&
  28049. config.validationSplit < 1) {
  28050. doValidation = true;
  28051. splitAt = Math.floor(inputs[0].shape[0] * (1 - config.validationSplit));
  28052. originalBatchSize = inputs[0].shape[0];
  28053. valX = sliceArrays(inputs, splitAt, originalBatchSize);
  28054. inputs = sliceArrays(inputs, 0, splitAt);
  28055. valY = sliceArrays(targets, splitAt, originalBatchSize);
  28056. targets = sliceArrays(targets, 0, splitAt);
  28057. needValidationDisposal = true;
  28058. valIns = valX.concat(valY);
  28059. }
  28060. else if (config.validationSteps != null) {
  28061. doValidation = true;
  28062. }
  28063. ins = inputs.concat(targets);
  28064. this.checkTrainableWeightsConsistency();
  28065. trainFunction = function (data) {
  28066. var losses = [];
  28067. var lossValues = [];
  28068. var inputs = data.slice(0, _this.inputs.length);
  28069. var targets = data.slice(_this.inputs.length, _this.inputs.length + _this.outputs.length);
  28070. var metricsValues = [];
  28071. var totalLossFunction = function () {
  28072. var feeds = [];
  28073. for (var i = 0; i < _this.inputs.length; ++i) {
  28074. feeds.push({ key: _this.inputs[i], value: inputs[i] });
  28075. }
  28076. var feedDict = new executor_1.FeedDict(feeds);
  28077. var outputs = executor_1.execute(_this.outputs, feedDict, { 'training': true });
  28078. var totalLoss;
  28079. for (var i = 0; i < _this.lossFunctions.length; ++i) {
  28080. var lossFunction = _this.lossFunctions[i];
  28081. var loss = lossFunction(targets[i], outputs[i]);
  28082. losses.push(loss);
  28083. var meanLoss = tfc.mean(loss);
  28084. lossValues.push(meanLoss);
  28085. if (i === 0) {
  28086. totalLoss = loss;
  28087. }
  28088. else {
  28089. totalLoss = tfc.add(totalLoss, loss);
  28090. }
  28091. }
  28092. for (var i = 0; i < _this.metricsTensors.length; ++i) {
  28093. var metric = _this.metricsTensors[i][0];
  28094. var outputIndex = _this.metricsTensors[i][1];
  28095. var meanMetric = tfc.mean(metric(targets[outputIndex], outputs[outputIndex]));
  28096. tfc.keep(meanMetric);
  28097. metricsValues.push(meanMetric);
  28098. }
  28099. totalLoss = tfc.mean(totalLoss);
  28100. _this.calculateLosses().forEach(function (regularizerLoss) {
  28101. totalLoss = tfc.add(totalLoss, regularizerLoss);
  28102. });
  28103. return totalLoss;
  28104. };
  28105. var variables = _this.collectedTrainableWeights.map(function (param) { return param.read(); });
  28106. var returnCost = true;
  28107. var totalLossValue = _this.optimizer.minimize(totalLossFunction, returnCost, variables);
  28108. return [totalLossValue].concat(metricsValues);
  28109. };
  28110. outLabels = this.getDedupedMetricsNames();
  28111. if (doValidation) {
  28112. this.makeTestFunction();
  28113. valFunction = this.testFunction;
  28114. callbackMetrics =
  28115. outLabels.slice().concat(outLabels.map(function (n) { return 'val_' + n; }));
  28116. }
  28117. else {
  28118. valFunction = null;
  28119. valIns = [];
  28120. callbackMetrics = outLabels.slice();
  28121. }
  28122. callbacks = callbacks_1.standardizeCallbacks(config.callbacks);
  28123. return [4, this.fitLoop(trainFunction, ins, outLabels, batchSize, config.epochs, config.verbose, callbacks, valFunction, valIns, config.shuffle, callbackMetrics, null, null, null)];
  28124. case 1:
  28125. out = _a.sent();
  28126. if (needValidationDisposal) {
  28127. valIns.forEach(function (tensor) { return tensor.dispose(); });
  28128. inputs.forEach(function (tensor) { return tensor.dispose(); });
  28129. targets.forEach(function (tensor) { return tensor.dispose(); });
  28130. }
  28131. return [2, out];
  28132. }
  28133. });
  28134. });
  28135. };
  28136. Model.prototype.getNamedWeights = function (config) {
  28137. var namedWeights = {};
  28138. var trainableOnly = config != null && config.trainableOnly;
  28139. var weights = trainableOnly ? this.trainableWeights : this.weights;
  28140. var weightValues = this.getWeights(trainableOnly);
  28141. for (var i = 0; i < weights.length; ++i) {
  28142. if (trainableOnly && !weights[i].trainable) {
  28143. continue;
  28144. }
  28145. namedWeights[weights[i].originalName] = weightValues[i];
  28146. }
  28147. return namedWeights;
  28148. };
  28149. Model.prototype.save = function (handlerOrURL, config) {
  28150. return __awaiter(this, void 0, void 0, function () {
  28151. var handlers, weightDataAndSpecs, returnString, unusedArg, modelConfig;
  28152. return __generator(this, function (_a) {
  28153. switch (_a.label) {
  28154. case 0:
  28155. if (typeof handlerOrURL === 'string') {
  28156. handlers = tfjs_core_1.io.getSaveHandlers(handlerOrURL);
  28157. if (handlers.length === 0) {
  28158. throw new errors_1.ValueError("Cannot find any save handlers for URL '" + handlerOrURL + "'");
  28159. }
  28160. else if (handlers.length > 1) {
  28161. throw new errors_1.ValueError("Found more than one (" + handlers.length + ") save handlers for " +
  28162. ("URL '" + handlerOrURL + "'"));
  28163. }
  28164. handlerOrURL = handlers[0];
  28165. }
  28166. if (handlerOrURL.save == null) {
  28167. throw new errors_1.ValueError('Model.save() cannot proceed because the IOHandler provided does ' +
  28168. 'not have the `save` attribute defined.');
  28169. }
  28170. return [4, tfjs_core_1.io.encodeWeights(this.getNamedWeights(config))];
  28171. case 1:
  28172. weightDataAndSpecs = _a.sent();
  28173. returnString = false;
  28174. unusedArg = null;
  28175. modelConfig = this.toJSON(unusedArg, returnString);
  28176. return [2, handlerOrURL.save({
  28177. modelTopology: modelConfig,
  28178. weightData: weightDataAndSpecs.data,
  28179. weightSpecs: weightDataAndSpecs.specs
  28180. })];
  28181. }
  28182. });
  28183. });
  28184. };
  28185. Model.className = 'Model';
  28186. __decorate([
  28187. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes' })
  28188. ], Model.prototype, "summary", null);
  28189. __decorate([
  28190. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes', configParamIndices: [0] })
  28191. ], Model.prototype, "compile", null);
  28192. __decorate([
  28193. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes', configParamIndices: [2] })
  28194. ], Model.prototype, "evaluate", null);
  28195. __decorate([
  28196. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes', configParamIndices: [1] })
  28197. ], Model.prototype, "predict", null);
  28198. __decorate([
  28199. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes' })
  28200. ], Model.prototype, "predictOnBatch", null);
  28201. __decorate([
  28202. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes', configParamIndices: [2] })
  28203. ], Model.prototype, "fit", null);
  28204. __decorate([
  28205. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes', configParamIndices: [1] })
  28206. ], Model.prototype, "save", null);
  28207. Model = __decorate([
  28208. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes' })
  28209. ], Model);
  28210. return Model;
  28211. }(topology_1.Container));
  28212. exports.Model = Model;
  28213. tfjs_core_1.serialization.SerializationMap.register(Model);
  28214. },{"../backend/tfjs_backend":169,"../callbacks":170,"../errors":176,"../losses":192,"../metrics":193,"../optimizers":195,"../utils/generic_utils":199,"../utils/layer_utils":200,"../utils/math_utils":201,"./executor":173,"./topology":174,"@tensorflow/tfjs-core":54}],176:[function(require,module,exports){
  28215. "use strict";
  28216. var __extends = (this && this.__extends) || (function () {
  28217. var extendStatics = Object.setPrototypeOf ||
  28218. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  28219. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  28220. return function (d, b) {
  28221. extendStatics(d, b);
  28222. function __() { this.constructor = d; }
  28223. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  28224. };
  28225. })();
  28226. Object.defineProperty(exports, "__esModule", { value: true });
  28227. var AttributeError = (function (_super) {
  28228. __extends(AttributeError, _super);
  28229. function AttributeError(message) {
  28230. var _this = _super.call(this, message) || this;
  28231. Object.setPrototypeOf(_this, AttributeError.prototype);
  28232. return _this;
  28233. }
  28234. return AttributeError;
  28235. }(Error));
  28236. exports.AttributeError = AttributeError;
  28237. var RuntimeError = (function (_super) {
  28238. __extends(RuntimeError, _super);
  28239. function RuntimeError(message) {
  28240. var _this = _super.call(this, message) || this;
  28241. Object.setPrototypeOf(_this, RuntimeError.prototype);
  28242. return _this;
  28243. }
  28244. return RuntimeError;
  28245. }(Error));
  28246. exports.RuntimeError = RuntimeError;
  28247. var ValueError = (function (_super) {
  28248. __extends(ValueError, _super);
  28249. function ValueError(message) {
  28250. var _this = _super.call(this, message) || this;
  28251. Object.setPrototypeOf(_this, ValueError.prototype);
  28252. return _this;
  28253. }
  28254. return ValueError;
  28255. }(Error));
  28256. exports.ValueError = ValueError;
  28257. var NotImplementedError = (function (_super) {
  28258. __extends(NotImplementedError, _super);
  28259. function NotImplementedError(message) {
  28260. var _this = _super.call(this, message) || this;
  28261. Object.setPrototypeOf(_this, NotImplementedError.prototype);
  28262. return _this;
  28263. }
  28264. return NotImplementedError;
  28265. }(Error));
  28266. exports.NotImplementedError = NotImplementedError;
  28267. var AssertionError = (function (_super) {
  28268. __extends(AssertionError, _super);
  28269. function AssertionError(message) {
  28270. var _this = _super.call(this, message) || this;
  28271. Object.setPrototypeOf(_this, AssertionError.prototype);
  28272. return _this;
  28273. }
  28274. return AssertionError;
  28275. }(Error));
  28276. exports.AssertionError = AssertionError;
  28277. var IndexError = (function (_super) {
  28278. __extends(IndexError, _super);
  28279. function IndexError(message) {
  28280. var _this = _super.call(this, message) || this;
  28281. Object.setPrototypeOf(_this, IndexError.prototype);
  28282. return _this;
  28283. }
  28284. return IndexError;
  28285. }(Error));
  28286. exports.IndexError = IndexError;
  28287. },{}],177:[function(require,module,exports){
  28288. "use strict";
  28289. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  28290. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  28291. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  28292. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  28293. return c > 3 && r && Object.defineProperty(target, key, r), r;
  28294. };
  28295. Object.defineProperty(exports, "__esModule", { value: true });
  28296. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  28297. var constraints_1 = require("./constraints");
  28298. var topology_1 = require("./engine/topology");
  28299. var training_1 = require("./engine/training");
  28300. var initializers_1 = require("./initializers");
  28301. var advanced_activations_1 = require("./layers/advanced_activations");
  28302. var convolutional_1 = require("./layers/convolutional");
  28303. var convolutional_depthwise_1 = require("./layers/convolutional_depthwise");
  28304. var core_1 = require("./layers/core");
  28305. var embeddings_1 = require("./layers/embeddings");
  28306. var merge_1 = require("./layers/merge");
  28307. var normalization_1 = require("./layers/normalization");
  28308. var padding_1 = require("./layers/padding");
  28309. var pooling_1 = require("./layers/pooling");
  28310. var recurrent_1 = require("./layers/recurrent");
  28311. var wrappers_1 = require("./layers/wrappers");
  28312. var losses_1 = require("./losses");
  28313. var metrics_1 = require("./metrics");
  28314. var models_1 = require("./models");
  28315. var regularizers_1 = require("./regularizers");
  28316. var ModelExports = (function () {
  28317. function ModelExports() {
  28318. }
  28319. ModelExports.model = function (config) {
  28320. return new training_1.Model(config);
  28321. };
  28322. ModelExports.sequential = function (config) {
  28323. return new models_1.Sequential(config);
  28324. };
  28325. ModelExports.loadModel = function (pathOrIOHandler) {
  28326. return models_1.loadModelInternal(pathOrIOHandler);
  28327. };
  28328. ModelExports.input = function (config) {
  28329. return topology_1.Input(config);
  28330. };
  28331. __decorate([
  28332. tfjs_core_1.doc({ heading: 'Models', subheading: 'Creation', configParamIndices: [0] })
  28333. ], ModelExports, "model", null);
  28334. __decorate([
  28335. tfjs_core_1.doc({ heading: 'Models', subheading: 'Creation', configParamIndices: [0] })
  28336. ], ModelExports, "sequential", null);
  28337. __decorate([
  28338. tfjs_core_1.doc({
  28339. heading: 'Models',
  28340. subheading: 'Loading',
  28341. useDocsFrom: 'loadModelInternal'
  28342. })
  28343. ], ModelExports, "loadModel", null);
  28344. __decorate([
  28345. tfjs_core_1.doc({
  28346. heading: 'Models',
  28347. subheading: 'Inputs',
  28348. useDocsFrom: 'Input',
  28349. configParamIndices: [0]
  28350. })
  28351. ], ModelExports, "input", null);
  28352. return ModelExports;
  28353. }());
  28354. exports.ModelExports = ModelExports;
  28355. var LayerExports = (function () {
  28356. function LayerExports() {
  28357. }
  28358. LayerExports.inputLayer = function (config) {
  28359. return new topology_1.InputLayer(config);
  28360. };
  28361. LayerExports.elu = function (config) {
  28362. return new advanced_activations_1.ELU(config);
  28363. };
  28364. LayerExports.leakyReLU = function (config) {
  28365. return new advanced_activations_1.LeakyReLU(config);
  28366. };
  28367. LayerExports.softmax = function (config) {
  28368. return new advanced_activations_1.Softmax(config);
  28369. };
  28370. LayerExports.thresholdedReLU = function (config) {
  28371. return new advanced_activations_1.ThresholdedReLU(config);
  28372. };
  28373. LayerExports.conv1d = function (config) {
  28374. return new convolutional_1.Conv1D(config);
  28375. };
  28376. LayerExports.conv2d = function (config) {
  28377. return new convolutional_1.Conv2D(config);
  28378. };
  28379. LayerExports.conv2dTranspose = function (config) {
  28380. return new convolutional_1.Conv2DTranspose(config);
  28381. };
  28382. LayerExports.separableConv2d = function (config) {
  28383. return new convolutional_1.SeparableConv2D(config);
  28384. };
  28385. LayerExports.cropping2D = function (config) {
  28386. return new convolutional_1.Cropping2D(config);
  28387. };
  28388. LayerExports.upSampling2d = function (config) {
  28389. return new convolutional_1.UpSampling2D(config);
  28390. };
  28391. LayerExports.depthwiseConv2d = function (config) {
  28392. return new convolutional_depthwise_1.DepthwiseConv2D(config);
  28393. };
  28394. LayerExports.activation = function (config) {
  28395. return new core_1.Activation(config);
  28396. };
  28397. LayerExports.dense = function (config) {
  28398. return new core_1.Dense(config);
  28399. };
  28400. LayerExports.dropout = function (config) {
  28401. return new core_1.Dropout(config);
  28402. };
  28403. LayerExports.flatten = function (config) {
  28404. return new core_1.Flatten(config);
  28405. };
  28406. LayerExports.repeatVector = function (config) {
  28407. return new core_1.RepeatVector(config);
  28408. };
  28409. LayerExports.reshape = function (config) {
  28410. return new core_1.Reshape(config);
  28411. };
  28412. LayerExports.embedding = function (config) {
  28413. return new embeddings_1.Embedding(config);
  28414. };
  28415. LayerExports.add = function (config) {
  28416. return new merge_1.Add(config);
  28417. };
  28418. LayerExports.average = function (config) {
  28419. return new merge_1.Average(config);
  28420. };
  28421. LayerExports.concatenate = function (config) {
  28422. return new merge_1.Concatenate(config);
  28423. };
  28424. LayerExports.maximum = function (config) {
  28425. return new merge_1.Maximum(config);
  28426. };
  28427. LayerExports.minimum = function (config) {
  28428. return new merge_1.Minimum(config);
  28429. };
  28430. LayerExports.multiply = function (config) {
  28431. return new merge_1.Multiply(config);
  28432. };
  28433. LayerExports.batchNormalization = function (config) {
  28434. return new normalization_1.BatchNormalization(config);
  28435. };
  28436. LayerExports.zeroPadding2d = function (config) {
  28437. return new padding_1.ZeroPadding2D(config);
  28438. };
  28439. LayerExports.averagePooling1d = function (config) {
  28440. return new pooling_1.AveragePooling1D(config);
  28441. };
  28442. LayerExports.avgPool1d = function (config) {
  28443. return LayerExports.averagePooling1d(config);
  28444. };
  28445. LayerExports.avgPooling1d = function (config) {
  28446. return LayerExports.averagePooling1d(config);
  28447. };
  28448. LayerExports.averagePooling2d = function (config) {
  28449. return new pooling_1.AveragePooling2D(config);
  28450. };
  28451. LayerExports.avgPool2d = function (config) {
  28452. return LayerExports.averagePooling2d(config);
  28453. };
  28454. LayerExports.avgPooling2d = function (config) {
  28455. return LayerExports.averagePooling2d(config);
  28456. };
  28457. LayerExports.globalAveragePooling1d = function (config) {
  28458. return new pooling_1.GlobalAveragePooling1D(config);
  28459. };
  28460. LayerExports.globalAveragePooling2d = function (config) {
  28461. return new pooling_1.GlobalAveragePooling2D(config);
  28462. };
  28463. LayerExports.globalMaxPooling1d = function (config) {
  28464. return new pooling_1.GlobalMaxPooling1D(config);
  28465. };
  28466. LayerExports.globalMaxPooling2d = function (config) {
  28467. return new pooling_1.GlobalMaxPooling2D(config);
  28468. };
  28469. LayerExports.maxPooling1d = function (config) {
  28470. return new pooling_1.MaxPooling1D(config);
  28471. };
  28472. LayerExports.maxPooling2d = function (config) {
  28473. return new pooling_1.MaxPooling2D(config);
  28474. };
  28475. LayerExports.gru = function (config) {
  28476. return new recurrent_1.GRU(config);
  28477. };
  28478. LayerExports.gruCell = function (config) {
  28479. return new recurrent_1.GRUCell(config);
  28480. };
  28481. LayerExports.lstm = function (config) {
  28482. return new recurrent_1.LSTM(config);
  28483. };
  28484. LayerExports.lstmCell = function (config) {
  28485. return new recurrent_1.LSTMCell(config);
  28486. };
  28487. LayerExports.simpleRNN = function (config) {
  28488. return new recurrent_1.SimpleRNN(config);
  28489. };
  28490. LayerExports.simpleRNNCell = function (config) {
  28491. return new recurrent_1.SimpleRNNCell(config);
  28492. };
  28493. LayerExports.rnn = function (config) {
  28494. return new recurrent_1.RNN(config);
  28495. };
  28496. LayerExports.stackedRNNCells = function (config) {
  28497. return new recurrent_1.StackedRNNCells(config);
  28498. };
  28499. LayerExports.bidirectional = function (config) {
  28500. return new wrappers_1.Bidirectional(config);
  28501. };
  28502. LayerExports.timeDistributed = function (config) {
  28503. return new wrappers_1.TimeDistributed(config);
  28504. };
  28505. LayerExports.Layer = topology_1.Layer;
  28506. LayerExports.RNN = recurrent_1.RNN;
  28507. LayerExports.RNNCell = recurrent_1.RNNCell;
  28508. LayerExports.input = ModelExports.input;
  28509. __decorate([
  28510. tfjs_core_1.doc({
  28511. heading: 'Layers',
  28512. subheading: 'Inputs',
  28513. namespace: 'layers',
  28514. useDocsFrom: 'InputLayer',
  28515. configParamIndices: [0]
  28516. })
  28517. ], LayerExports, "inputLayer", null);
  28518. __decorate([
  28519. tfjs_core_1.doc({
  28520. heading: 'Layers',
  28521. subheading: 'Advanced Activation',
  28522. namespace: 'layers',
  28523. useDocsFrom: 'ELU',
  28524. configParamIndices: [0]
  28525. })
  28526. ], LayerExports, "elu", null);
  28527. __decorate([
  28528. tfjs_core_1.doc({
  28529. heading: 'Layers',
  28530. subheading: 'Advanced Activation',
  28531. namespace: 'layers',
  28532. useDocsFrom: 'LeakyReLU',
  28533. configParamIndices: [0]
  28534. })
  28535. ], LayerExports, "leakyReLU", null);
  28536. __decorate([
  28537. tfjs_core_1.doc({
  28538. heading: 'Layers',
  28539. subheading: 'Advanced Activation',
  28540. namespace: 'layers',
  28541. useDocsFrom: 'Softmax',
  28542. configParamIndices: [0]
  28543. })
  28544. ], LayerExports, "softmax", null);
  28545. __decorate([
  28546. tfjs_core_1.doc({
  28547. heading: 'Layers',
  28548. subheading: 'Advanced Activation',
  28549. namespace: 'layers',
  28550. useDocsFrom: 'ThresholdedReLU',
  28551. configParamIndices: [0]
  28552. })
  28553. ], LayerExports, "thresholdedReLU", null);
  28554. __decorate([
  28555. tfjs_core_1.doc({
  28556. heading: 'Layers',
  28557. subheading: 'Convolutional',
  28558. namespace: 'layers',
  28559. useDocsFrom: 'Conv1D',
  28560. configParamIndices: [0]
  28561. })
  28562. ], LayerExports, "conv1d", null);
  28563. __decorate([
  28564. tfjs_core_1.doc({
  28565. heading: 'Layers',
  28566. subheading: 'Convolutional',
  28567. namespace: 'layers',
  28568. useDocsFrom: 'Conv2D',
  28569. configParamIndices: [0]
  28570. })
  28571. ], LayerExports, "conv2d", null);
  28572. __decorate([
  28573. tfjs_core_1.doc({
  28574. heading: 'Layers',
  28575. subheading: 'Convolutional',
  28576. namespace: 'layers',
  28577. useDocsFrom: 'Conv2DTranspose',
  28578. configParamIndices: [0]
  28579. })
  28580. ], LayerExports, "conv2dTranspose", null);
  28581. __decorate([
  28582. tfjs_core_1.doc({
  28583. heading: 'Layers',
  28584. subheading: 'Convolutional',
  28585. namespace: 'layers',
  28586. useDocsFrom: 'SeparableConv2D',
  28587. configParamIndices: [0]
  28588. })
  28589. ], LayerExports, "separableConv2d", null);
  28590. __decorate([
  28591. tfjs_core_1.doc({
  28592. heading: 'Layers',
  28593. subheading: 'Convolutional',
  28594. namespace: 'layers',
  28595. useDocsFrom: 'Cropping2D',
  28596. configParamIndices: [0]
  28597. })
  28598. ], LayerExports, "cropping2D", null);
  28599. __decorate([
  28600. tfjs_core_1.doc({
  28601. heading: 'Layers',
  28602. subheading: 'Convolutional',
  28603. namespace: 'layers',
  28604. useDocsFrom: 'UpSampling2D',
  28605. configParamIndices: [0]
  28606. })
  28607. ], LayerExports, "upSampling2d", null);
  28608. __decorate([
  28609. tfjs_core_1.doc({
  28610. heading: 'Layers',
  28611. subheading: 'Convolutional',
  28612. namespace: 'layers',
  28613. useDocsFrom: 'DepthwiseConv2D',
  28614. configParamIndices: [0]
  28615. })
  28616. ], LayerExports, "depthwiseConv2d", null);
  28617. __decorate([
  28618. tfjs_core_1.doc({
  28619. heading: 'Layers',
  28620. subheading: 'Basic',
  28621. namespace: 'layers',
  28622. useDocsFrom: 'Activation',
  28623. configParamIndices: [0]
  28624. })
  28625. ], LayerExports, "activation", null);
  28626. __decorate([
  28627. tfjs_core_1.doc({
  28628. heading: 'Layers',
  28629. subheading: 'Basic',
  28630. namespace: 'layers',
  28631. useDocsFrom: 'Dense',
  28632. configParamIndices: [0]
  28633. })
  28634. ], LayerExports, "dense", null);
  28635. __decorate([
  28636. tfjs_core_1.doc({
  28637. heading: 'Layers',
  28638. subheading: 'Basic',
  28639. namespace: 'layers',
  28640. useDocsFrom: 'Dropout',
  28641. configParamIndices: [0]
  28642. })
  28643. ], LayerExports, "dropout", null);
  28644. __decorate([
  28645. tfjs_core_1.doc({
  28646. heading: 'Layers',
  28647. subheading: 'Basic',
  28648. namespace: 'layers',
  28649. useDocsFrom: 'Flatten',
  28650. configParamIndices: [0]
  28651. })
  28652. ], LayerExports, "flatten", null);
  28653. __decorate([
  28654. tfjs_core_1.doc({
  28655. heading: 'Layers',
  28656. subheading: 'Basic',
  28657. namespace: 'layers',
  28658. useDocsFrom: 'RepeatVector',
  28659. configParamIndices: [0]
  28660. })
  28661. ], LayerExports, "repeatVector", null);
  28662. __decorate([
  28663. tfjs_core_1.doc({
  28664. heading: 'Layers',
  28665. subheading: 'Basic',
  28666. namespace: 'layers',
  28667. useDocsFrom: 'Reshape',
  28668. configParamIndices: [0]
  28669. })
  28670. ], LayerExports, "reshape", null);
  28671. __decorate([
  28672. tfjs_core_1.doc({
  28673. heading: 'Layers',
  28674. subheading: 'Basic',
  28675. namespace: 'layers',
  28676. useDocsFrom: 'Embedding',
  28677. configParamIndices: [0]
  28678. })
  28679. ], LayerExports, "embedding", null);
  28680. __decorate([
  28681. tfjs_core_1.doc({
  28682. heading: 'Layers',
  28683. subheading: 'Merge',
  28684. namespace: 'layers',
  28685. useDocsFrom: 'Add',
  28686. configParamIndices: [0]
  28687. })
  28688. ], LayerExports, "add", null);
  28689. __decorate([
  28690. tfjs_core_1.doc({
  28691. heading: 'Layers',
  28692. subheading: 'Merge',
  28693. namespace: 'layers',
  28694. useDocsFrom: 'Average',
  28695. configParamIndices: [0]
  28696. })
  28697. ], LayerExports, "average", null);
  28698. __decorate([
  28699. tfjs_core_1.doc({
  28700. heading: 'Layers',
  28701. subheading: 'Merge',
  28702. namespace: 'layers',
  28703. useDocsFrom: 'Concatenate',
  28704. configParamIndices: [0]
  28705. })
  28706. ], LayerExports, "concatenate", null);
  28707. __decorate([
  28708. tfjs_core_1.doc({
  28709. heading: 'Layers',
  28710. subheading: 'Merge',
  28711. namespace: 'layers',
  28712. useDocsFrom: 'Maximum',
  28713. configParamIndices: [0]
  28714. })
  28715. ], LayerExports, "maximum", null);
  28716. __decorate([
  28717. tfjs_core_1.doc({
  28718. heading: 'Layers',
  28719. subheading: 'Merge',
  28720. namespace: 'layers',
  28721. useDocsFrom: 'Minimum',
  28722. configParamIndices: [0]
  28723. })
  28724. ], LayerExports, "minimum", null);
  28725. __decorate([
  28726. tfjs_core_1.doc({
  28727. heading: 'Layers',
  28728. subheading: 'Merge',
  28729. namespace: 'layers',
  28730. useDocsFrom: 'Multiply',
  28731. configParamIndices: [0]
  28732. })
  28733. ], LayerExports, "multiply", null);
  28734. __decorate([
  28735. tfjs_core_1.doc({
  28736. heading: 'Layers',
  28737. subheading: 'Normalization',
  28738. namespace: 'layers',
  28739. useDocsFrom: 'BatchNormalization',
  28740. configParamIndices: [0]
  28741. })
  28742. ], LayerExports, "batchNormalization", null);
  28743. __decorate([
  28744. tfjs_core_1.doc({
  28745. heading: 'Layers',
  28746. subheading: 'Padding',
  28747. namespace: 'layers',
  28748. useDocsFrom: 'ZeroPadding2D',
  28749. configParamIndices: [0]
  28750. })
  28751. ], LayerExports, "zeroPadding2d", null);
  28752. __decorate([
  28753. tfjs_core_1.doc({
  28754. heading: 'Layers',
  28755. subheading: 'Pooling',
  28756. namespace: 'layers',
  28757. useDocsFrom: 'AveragePooling1D',
  28758. configParamIndices: [0]
  28759. })
  28760. ], LayerExports, "averagePooling1d", null);
  28761. __decorate([
  28762. tfjs_core_1.doc({
  28763. heading: 'Layers',
  28764. subheading: 'Pooling',
  28765. namespace: 'layers',
  28766. useDocsFrom: 'AveragePooling2D',
  28767. configParamIndices: [0]
  28768. })
  28769. ], LayerExports, "averagePooling2d", null);
  28770. __decorate([
  28771. tfjs_core_1.doc({
  28772. heading: 'Layers',
  28773. subheading: 'Pooling',
  28774. namespace: 'layers',
  28775. useDocsFrom: 'GlobalAveragePooling1D',
  28776. configParamIndices: [0]
  28777. })
  28778. ], LayerExports, "globalAveragePooling1d", null);
  28779. __decorate([
  28780. tfjs_core_1.doc({
  28781. heading: 'Layers',
  28782. subheading: 'Pooling',
  28783. namespace: 'layers',
  28784. useDocsFrom: 'GlobalAveragePooling2D',
  28785. configParamIndices: [0]
  28786. })
  28787. ], LayerExports, "globalAveragePooling2d", null);
  28788. __decorate([
  28789. tfjs_core_1.doc({
  28790. heading: 'Layers',
  28791. subheading: 'Pooling',
  28792. namespace: 'layers',
  28793. useDocsFrom: 'GlobalMaxPooling1D',
  28794. configParamIndices: [0]
  28795. })
  28796. ], LayerExports, "globalMaxPooling1d", null);
  28797. __decorate([
  28798. tfjs_core_1.doc({
  28799. heading: 'Layers',
  28800. subheading: 'Pooling',
  28801. namespace: 'layers',
  28802. useDocsFrom: 'GlobalMaxPooling2D',
  28803. configParamIndices: [0]
  28804. })
  28805. ], LayerExports, "globalMaxPooling2d", null);
  28806. __decorate([
  28807. tfjs_core_1.doc({
  28808. heading: 'Layers',
  28809. subheading: 'Pooling',
  28810. namespace: 'layers',
  28811. useDocsFrom: 'MaxPooling1D',
  28812. configParamIndices: [0]
  28813. })
  28814. ], LayerExports, "maxPooling1d", null);
  28815. __decorate([
  28816. tfjs_core_1.doc({
  28817. heading: 'Layers',
  28818. subheading: 'Pooling',
  28819. namespace: 'layers',
  28820. useDocsFrom: 'MaxPooling2D',
  28821. configParamIndices: [0]
  28822. })
  28823. ], LayerExports, "maxPooling2d", null);
  28824. __decorate([
  28825. tfjs_core_1.doc({
  28826. heading: 'Layers',
  28827. subheading: 'Recurrent',
  28828. namespace: 'layers',
  28829. useDocsFrom: 'GRU',
  28830. configParamIndices: [0]
  28831. })
  28832. ], LayerExports, "gru", null);
  28833. __decorate([
  28834. tfjs_core_1.doc({
  28835. heading: 'Layers',
  28836. subheading: 'Recurrent',
  28837. namespace: 'layers',
  28838. useDocsFrom: 'GRUCell',
  28839. configParamIndices: [0]
  28840. })
  28841. ], LayerExports, "gruCell", null);
  28842. __decorate([
  28843. tfjs_core_1.doc({
  28844. heading: 'Layers',
  28845. subheading: 'Recurrent',
  28846. namespace: 'layers',
  28847. useDocsFrom: 'LSTM',
  28848. configParamIndices: [0]
  28849. })
  28850. ], LayerExports, "lstm", null);
  28851. __decorate([
  28852. tfjs_core_1.doc({
  28853. heading: 'Layers',
  28854. subheading: 'Recurrent',
  28855. namespace: 'layers',
  28856. useDocsFrom: 'LSTMCell',
  28857. configParamIndices: [0]
  28858. })
  28859. ], LayerExports, "lstmCell", null);
  28860. __decorate([
  28861. tfjs_core_1.doc({
  28862. heading: 'Layers',
  28863. subheading: 'Recurrent',
  28864. namespace: 'layers',
  28865. useDocsFrom: 'SimpleRNN',
  28866. configParamIndices: [0]
  28867. })
  28868. ], LayerExports, "simpleRNN", null);
  28869. __decorate([
  28870. tfjs_core_1.doc({
  28871. heading: 'Layers',
  28872. subheading: 'Recurrent',
  28873. namespace: 'layers',
  28874. useDocsFrom: 'SimpleRNNCell',
  28875. configParamIndices: [0]
  28876. })
  28877. ], LayerExports, "simpleRNNCell", null);
  28878. __decorate([
  28879. tfjs_core_1.doc({
  28880. heading: 'Layers',
  28881. subheading: 'Recurrent',
  28882. namespace: 'layers',
  28883. useDocsFrom: 'RNN',
  28884. configParamIndices: [0]
  28885. })
  28886. ], LayerExports, "rnn", null);
  28887. __decorate([
  28888. tfjs_core_1.doc({
  28889. heading: 'Layers',
  28890. subheading: 'Recurrent',
  28891. namespace: 'layers',
  28892. useDocsFrom: 'RNN',
  28893. configParamIndices: [0]
  28894. })
  28895. ], LayerExports, "stackedRNNCells", null);
  28896. __decorate([
  28897. tfjs_core_1.doc({
  28898. heading: 'Layers',
  28899. subheading: 'Wrapper',
  28900. namespace: 'layers',
  28901. useDocsFrom: 'Bidirectional',
  28902. configParamIndices: [0]
  28903. })
  28904. ], LayerExports, "bidirectional", null);
  28905. __decorate([
  28906. tfjs_core_1.doc({
  28907. heading: 'Layers',
  28908. subheading: 'Wrapper',
  28909. namespace: 'layers',
  28910. useDocsFrom: 'TimeDistributed',
  28911. configParamIndices: [0]
  28912. })
  28913. ], LayerExports, "timeDistributed", null);
  28914. return LayerExports;
  28915. }());
  28916. exports.LayerExports = LayerExports;
  28917. var ConstraintExports = (function () {
  28918. function ConstraintExports() {
  28919. }
  28920. ConstraintExports.maxNorm = function (config) {
  28921. return new constraints_1.MaxNorm(config);
  28922. };
  28923. ConstraintExports.unitNorm = function (config) {
  28924. return new constraints_1.UnitNorm(config);
  28925. };
  28926. ConstraintExports.nonNeg = function () {
  28927. return new constraints_1.NonNeg();
  28928. };
  28929. ConstraintExports.minMaxNorm = function (config) {
  28930. return new constraints_1.MinMaxNorm(config);
  28931. };
  28932. __decorate([
  28933. tfjs_core_1.doc({
  28934. heading: 'Constraints',
  28935. namespace: 'constraints',
  28936. useDocsFrom: 'MaxNorm',
  28937. configParamIndices: [0]
  28938. })
  28939. ], ConstraintExports, "maxNorm", null);
  28940. __decorate([
  28941. tfjs_core_1.doc({
  28942. heading: 'Constraints',
  28943. namespace: 'constraints',
  28944. useDocsFrom: 'UnitNorm',
  28945. configParamIndices: [0]
  28946. })
  28947. ], ConstraintExports, "unitNorm", null);
  28948. __decorate([
  28949. tfjs_core_1.doc({ heading: 'Constraints', namespace: 'constraints', useDocsFrom: 'NonNeg' })
  28950. ], ConstraintExports, "nonNeg", null);
  28951. __decorate([
  28952. tfjs_core_1.doc({
  28953. heading: 'Constraints',
  28954. namespace: 'constraints',
  28955. useDocsFrom: 'MinMaxNormConfig',
  28956. configParamIndices: [0]
  28957. })
  28958. ], ConstraintExports, "minMaxNorm", null);
  28959. return ConstraintExports;
  28960. }());
  28961. exports.ConstraintExports = ConstraintExports;
  28962. var InitializerExports = (function () {
  28963. function InitializerExports() {
  28964. }
  28965. InitializerExports.zeros = function () {
  28966. return new initializers_1.Zeros();
  28967. };
  28968. InitializerExports.ones = function () {
  28969. return new initializers_1.Ones();
  28970. };
  28971. InitializerExports.constant = function (config) {
  28972. return new initializers_1.Constant(config);
  28973. };
  28974. InitializerExports.randomUniform = function (config) {
  28975. return new initializers_1.RandomUniform(config);
  28976. };
  28977. InitializerExports.randomNormal = function (config) {
  28978. return new initializers_1.RandomNormal(config);
  28979. };
  28980. InitializerExports.truncatedNormal = function (config) {
  28981. return new initializers_1.TruncatedNormal(config);
  28982. };
  28983. InitializerExports.identity = function (config) {
  28984. return new initializers_1.Identity(config);
  28985. };
  28986. InitializerExports.varianceScaling = function (config) {
  28987. return new initializers_1.VarianceScaling(config);
  28988. };
  28989. InitializerExports.glorotUniform = function (config) {
  28990. return new initializers_1.GlorotUniform(config);
  28991. };
  28992. InitializerExports.glorotNormal = function (config) {
  28993. return new initializers_1.GlorotNormal(config);
  28994. };
  28995. InitializerExports.heNormal = function (config) {
  28996. return new initializers_1.HeNormal(config);
  28997. };
  28998. InitializerExports.leCunNormal = function (config) {
  28999. return new initializers_1.LeCunNormal(config);
  29000. };
  29001. InitializerExports.orthogonal = function (config) {
  29002. return new initializers_1.Orthogonal(config);
  29003. };
  29004. __decorate([
  29005. tfjs_core_1.doc({
  29006. heading: 'Initializers',
  29007. namespace: 'initializers',
  29008. useDocsFrom: 'Zeros'
  29009. })
  29010. ], InitializerExports, "zeros", null);
  29011. __decorate([
  29012. tfjs_core_1.doc({ heading: 'Initializers', namespace: 'initializers', useDocsFrom: 'Ones' })
  29013. ], InitializerExports, "ones", null);
  29014. __decorate([
  29015. tfjs_core_1.doc({
  29016. heading: 'Initializers',
  29017. namespace: 'initializers',
  29018. useDocsFrom: 'Constant',
  29019. configParamIndices: [0]
  29020. })
  29021. ], InitializerExports, "constant", null);
  29022. __decorate([
  29023. tfjs_core_1.doc({
  29024. heading: 'Initializers',
  29025. namespace: 'initializers',
  29026. useDocsFrom: 'RandomUniform',
  29027. configParamIndices: [0]
  29028. })
  29029. ], InitializerExports, "randomUniform", null);
  29030. __decorate([
  29031. tfjs_core_1.doc({
  29032. heading: 'Initializers',
  29033. namespace: 'initializers',
  29034. useDocsFrom: 'RandomNormal',
  29035. configParamIndices: [0]
  29036. })
  29037. ], InitializerExports, "randomNormal", null);
  29038. __decorate([
  29039. tfjs_core_1.doc({
  29040. heading: 'Initializers',
  29041. namespace: 'initializers',
  29042. useDocsFrom: 'TruncatedNormal',
  29043. configParamIndices: [0]
  29044. })
  29045. ], InitializerExports, "truncatedNormal", null);
  29046. __decorate([
  29047. tfjs_core_1.doc({
  29048. heading: 'Initializers',
  29049. namespace: 'initializers',
  29050. useDocsFrom: 'Identity',
  29051. configParamIndices: [0]
  29052. })
  29053. ], InitializerExports, "identity", null);
  29054. __decorate([
  29055. tfjs_core_1.doc({
  29056. heading: 'Initializers',
  29057. namespace: 'initializers',
  29058. useDocsFrom: 'VarianceScaling',
  29059. configParamIndices: [0]
  29060. })
  29061. ], InitializerExports, "varianceScaling", null);
  29062. __decorate([
  29063. tfjs_core_1.doc({
  29064. heading: 'Initializers',
  29065. namespace: 'initializers',
  29066. useDocsFrom: 'GlorotUniform',
  29067. configParamIndices: [0]
  29068. })
  29069. ], InitializerExports, "glorotUniform", null);
  29070. __decorate([
  29071. tfjs_core_1.doc({
  29072. heading: 'Initializers',
  29073. namespace: 'initializers',
  29074. useDocsFrom: 'GlorotNormal',
  29075. configParamIndices: [0]
  29076. })
  29077. ], InitializerExports, "glorotNormal", null);
  29078. __decorate([
  29079. tfjs_core_1.doc({
  29080. heading: 'Initializers',
  29081. namespace: 'initializers',
  29082. useDocsFrom: 'HeNormal',
  29083. configParamIndices: [0]
  29084. })
  29085. ], InitializerExports, "heNormal", null);
  29086. __decorate([
  29087. tfjs_core_1.doc({
  29088. heading: 'Initializers',
  29089. namespace: 'initializers',
  29090. useDocsFrom: 'LeCunNormal',
  29091. configParamIndices: [0]
  29092. })
  29093. ], InitializerExports, "leCunNormal", null);
  29094. __decorate([
  29095. tfjs_core_1.doc({
  29096. heading: 'Initializers',
  29097. namespace: 'initializers',
  29098. useDocsFrom: 'Orthogonal',
  29099. configParamIndices: [0]
  29100. })
  29101. ], InitializerExports, "orthogonal", null);
  29102. return InitializerExports;
  29103. }());
  29104. exports.InitializerExports = InitializerExports;
  29105. var MetricExports = (function () {
  29106. function MetricExports() {
  29107. }
  29108. MetricExports.binaryAccuracy = function (yTrue, yPred) {
  29109. return metrics_1.binaryAccuracy(yTrue, yPred);
  29110. };
  29111. MetricExports.binaryCrossentropy = function (yTrue, yPred) {
  29112. return metrics_1.binaryCrossentropy(yTrue, yPred);
  29113. };
  29114. MetricExports.categoricalAccuracy = function (yTrue, yPred) {
  29115. return metrics_1.categoricalAccuracy(yTrue, yPred);
  29116. };
  29117. MetricExports.categoricalCrossentropy = function (yTrue, yPred) {
  29118. return losses_1.categoricalCrossentropy(yTrue, yPred);
  29119. };
  29120. MetricExports.cosineProximity = function (yTrue, yPred) {
  29121. return losses_1.cosineProximity(yTrue, yPred);
  29122. };
  29123. MetricExports.prototype.meanAbsoluteError = function (yTrue, yPred) {
  29124. return losses_1.meanAbsoluteError(yTrue, yPred);
  29125. };
  29126. MetricExports.prototype.meanAbsolutePercentageError = function (yTrue, yPred) {
  29127. return losses_1.meanAbsolutePercentageError(yTrue, yPred);
  29128. };
  29129. MetricExports.prototype.MAPE = function (yTrue, yPred) {
  29130. return losses_1.meanAbsolutePercentageError(yTrue, yPred);
  29131. };
  29132. MetricExports.prototype.mape = function (yTrue, yPred) {
  29133. return losses_1.meanAbsolutePercentageError(yTrue, yPred);
  29134. };
  29135. MetricExports.meanSquaredError = function (yTrue, yPred) {
  29136. return losses_1.meanSquaredError(yTrue, yPred);
  29137. };
  29138. MetricExports.MSE = function (yTrue, yPred) {
  29139. return losses_1.meanSquaredError(yTrue, yPred);
  29140. };
  29141. MetricExports.mse = function (yTrue, yPred) {
  29142. return losses_1.meanSquaredError(yTrue, yPred);
  29143. };
  29144. __decorate([
  29145. tfjs_core_1.doc({
  29146. heading: 'Metrics',
  29147. namespace: 'metrics',
  29148. useDocsFrom: 'meanAbsoluteError'
  29149. })
  29150. ], MetricExports.prototype, "meanAbsoluteError", null);
  29151. __decorate([
  29152. tfjs_core_1.doc({
  29153. heading: 'Metrics',
  29154. namespace: 'metrics',
  29155. useDocsFrom: 'meanAbsolutePercentageError'
  29156. })
  29157. ], MetricExports.prototype, "meanAbsolutePercentageError", null);
  29158. __decorate([
  29159. tfjs_core_1.doc({ heading: 'Metrics', namespace: 'metrics', useDocsFrom: 'binaryAccuracy' })
  29160. ], MetricExports, "binaryAccuracy", null);
  29161. __decorate([
  29162. tfjs_core_1.doc({
  29163. heading: 'Metrics',
  29164. namespace: 'metrics',
  29165. useDocsFrom: 'binaryCrossentropy'
  29166. })
  29167. ], MetricExports, "binaryCrossentropy", null);
  29168. __decorate([
  29169. tfjs_core_1.doc({
  29170. heading: 'Metrics',
  29171. namespace: 'metrics',
  29172. useDocsFrom: 'categoricalAccuracy'
  29173. })
  29174. ], MetricExports, "categoricalAccuracy", null);
  29175. __decorate([
  29176. tfjs_core_1.doc({
  29177. heading: 'Metrics',
  29178. namespace: 'metrics',
  29179. useDocsFrom: 'categoricalCrossentropy'
  29180. })
  29181. ], MetricExports, "categoricalCrossentropy", null);
  29182. __decorate([
  29183. tfjs_core_1.doc({
  29184. heading: 'Metrics',
  29185. namespace: 'metrics',
  29186. useDocsFrom: 'cosineProximity'
  29187. })
  29188. ], MetricExports, "cosineProximity", null);
  29189. __decorate([
  29190. tfjs_core_1.doc({
  29191. heading: 'Metrics',
  29192. namespace: 'metrics',
  29193. useDocsFrom: 'meanSquaredError'
  29194. })
  29195. ], MetricExports, "meanSquaredError", null);
  29196. return MetricExports;
  29197. }());
  29198. exports.MetricExports = MetricExports;
  29199. var RegularizerExports = (function () {
  29200. function RegularizerExports() {
  29201. }
  29202. RegularizerExports.l1l2 = function (config) {
  29203. return new regularizers_1.L1L2(config);
  29204. };
  29205. RegularizerExports.l1 = function (config) {
  29206. return regularizers_1.l1(config);
  29207. };
  29208. RegularizerExports.l2 = function (config) {
  29209. return regularizers_1.l2(config);
  29210. };
  29211. __decorate([
  29212. tfjs_core_1.doc({
  29213. heading: 'Regularizers',
  29214. namespace: 'regularizers',
  29215. useDocsFrom: 'L1L2',
  29216. configParamIndices: [0]
  29217. })
  29218. ], RegularizerExports, "l1l2", null);
  29219. __decorate([
  29220. tfjs_core_1.doc({
  29221. heading: 'Regularizers',
  29222. namespace: 'regularizers',
  29223. useDocsFrom: 'L1L2',
  29224. configParamIndices: [0]
  29225. })
  29226. ], RegularizerExports, "l1", null);
  29227. __decorate([
  29228. tfjs_core_1.doc({
  29229. heading: 'Regularizers',
  29230. namespace: 'regularizers',
  29231. useDocsFrom: 'L1L2',
  29232. configParamIndices: [0]
  29233. })
  29234. ], RegularizerExports, "l2", null);
  29235. return RegularizerExports;
  29236. }());
  29237. exports.RegularizerExports = RegularizerExports;
  29238. },{"./constraints":172,"./engine/topology":174,"./engine/training":175,"./initializers":179,"./layers/advanced_activations":180,"./layers/convolutional":181,"./layers/convolutional_depthwise":182,"./layers/core":183,"./layers/embeddings":184,"./layers/merge":185,"./layers/normalization":186,"./layers/padding":187,"./layers/pooling":188,"./layers/recurrent":189,"./layers/wrappers":191,"./losses":192,"./metrics":193,"./models":194,"./regularizers":196,"@tensorflow/tfjs-core":54}],178:[function(require,module,exports){
  29239. "use strict";
  29240. Object.defineProperty(exports, "__esModule", { value: true });
  29241. var exports_1 = require("./exports");
  29242. var callbacks_1 = require("./callbacks");
  29243. exports.Callback = callbacks_1.Callback;
  29244. exports.CallbackList = callbacks_1.CallbackList;
  29245. exports.CustomCallback = callbacks_1.CustomCallback;
  29246. var training_1 = require("./engine/training");
  29247. exports.Model = training_1.Model;
  29248. var recurrent_1 = require("./layers/recurrent");
  29249. exports.RNN = recurrent_1.RNN;
  29250. var models_1 = require("./models");
  29251. exports.Sequential = models_1.Sequential;
  29252. var types_1 = require("./types");
  29253. exports.SymbolicTensor = types_1.SymbolicTensor;
  29254. var version_1 = require("./version");
  29255. exports.version_layers = version_1.version;
  29256. exports.model = exports_1.ModelExports.model;
  29257. exports.sequential = exports_1.ModelExports.sequential;
  29258. exports.loadModel = exports_1.ModelExports.loadModel;
  29259. exports.input = exports_1.ModelExports.input;
  29260. exports.layers = exports_1.LayerExports;
  29261. exports.constraints = exports_1.ConstraintExports;
  29262. exports.initializers = exports_1.InitializerExports;
  29263. exports.metrics = exports_1.MetricExports;
  29264. exports.regularizers = exports_1.RegularizerExports;
  29265. },{"./callbacks":170,"./engine/training":175,"./exports":177,"./layers/recurrent":189,"./models":194,"./types":197,"./version":204}],179:[function(require,module,exports){
  29266. "use strict";
  29267. var __extends = (this && this.__extends) || (function () {
  29268. var extendStatics = Object.setPrototypeOf ||
  29269. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  29270. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  29271. return function (d, b) {
  29272. extendStatics(d, b);
  29273. function __() { this.constructor = d; }
  29274. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  29275. };
  29276. })();
  29277. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  29278. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  29279. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  29280. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  29281. return c > 3 && r && Object.defineProperty(target, key, r), r;
  29282. };
  29283. Object.defineProperty(exports, "__esModule", { value: true });
  29284. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  29285. var K = require("./backend/tfjs_backend");
  29286. var common_1 = require("./common");
  29287. var errors_1 = require("./errors");
  29288. var generic_utils_1 = require("./utils/generic_utils");
  29289. var math_utils_1 = require("./utils/math_utils");
  29290. exports.VALID_FAN_MODE_VALUES = ['fanIn', 'fanOut', 'fanAvg'];
  29291. function checkFanMode(value) {
  29292. generic_utils_1.checkStringTypeUnionValue(exports.VALID_FAN_MODE_VALUES, 'FanMode', value);
  29293. }
  29294. exports.checkFanMode = checkFanMode;
  29295. exports.VALID_DISTRIBUTION_VALUES = ['normal', 'uniform'];
  29296. function checkDistribution(value) {
  29297. generic_utils_1.checkStringTypeUnionValue(exports.VALID_DISTRIBUTION_VALUES, 'Distribution', value);
  29298. }
  29299. exports.checkDistribution = checkDistribution;
  29300. var Initializer = (function (_super) {
  29301. __extends(Initializer, _super);
  29302. function Initializer() {
  29303. return _super !== null && _super.apply(this, arguments) || this;
  29304. }
  29305. Initializer.prototype.fromConfigUsesCustomObjects = function () {
  29306. return false;
  29307. };
  29308. Initializer.prototype.getConfig = function () {
  29309. return {};
  29310. };
  29311. Initializer = __decorate([
  29312. tfjs_core_1.doc({ heading: 'Initializers', subheading: 'Classes', namespace: 'initializers' })
  29313. ], Initializer);
  29314. return Initializer;
  29315. }(tfjs_core_1.serialization.Serializable));
  29316. exports.Initializer = Initializer;
  29317. var Zeros = (function (_super) {
  29318. __extends(Zeros, _super);
  29319. function Zeros() {
  29320. return _super !== null && _super.apply(this, arguments) || this;
  29321. }
  29322. Zeros.prototype.apply = function (shape, dtype) {
  29323. return tfjs_core_1.zeros(shape, dtype);
  29324. };
  29325. Zeros.className = 'Zeros';
  29326. return Zeros;
  29327. }(Initializer));
  29328. exports.Zeros = Zeros;
  29329. tfjs_core_1.serialization.SerializationMap.register(Zeros);
  29330. var Ones = (function (_super) {
  29331. __extends(Ones, _super);
  29332. function Ones() {
  29333. return _super !== null && _super.apply(this, arguments) || this;
  29334. }
  29335. Ones.prototype.apply = function (shape, dtype) {
  29336. return tfjs_core_1.ones(shape, dtype);
  29337. };
  29338. Ones.className = 'Ones';
  29339. return Ones;
  29340. }(Initializer));
  29341. exports.Ones = Ones;
  29342. tfjs_core_1.serialization.SerializationMap.register(Ones);
  29343. var Constant = (function (_super) {
  29344. __extends(Constant, _super);
  29345. function Constant(config) {
  29346. var _this = _super.call(this) || this;
  29347. _this.value = config.value;
  29348. return _this;
  29349. }
  29350. Constant.prototype.apply = function (shape, dtype) {
  29351. var _this = this;
  29352. return tfjs_core_1.tidy(function () { return K.scalarTimesArray(tfjs_core_1.scalar(_this.value), tfjs_core_1.ones(shape, dtype)); });
  29353. };
  29354. Constant.prototype.getConfig = function () {
  29355. return {
  29356. value: this.value,
  29357. };
  29358. };
  29359. Constant.className = 'Constant';
  29360. return Constant;
  29361. }(Initializer));
  29362. exports.Constant = Constant;
  29363. tfjs_core_1.serialization.SerializationMap.register(Constant);
  29364. var RandomUniform = (function (_super) {
  29365. __extends(RandomUniform, _super);
  29366. function RandomUniform(config) {
  29367. var _this = _super.call(this) || this;
  29368. _this.DEFAULT_MINVAL = -0.05;
  29369. _this.DEFAULT_MAXVAL = 0.05;
  29370. _this.minval = config.minval || _this.DEFAULT_MINVAL;
  29371. _this.maxval = config.maxval || _this.DEFAULT_MAXVAL;
  29372. _this.seed = config.seed;
  29373. return _this;
  29374. }
  29375. RandomUniform.prototype.apply = function (shape, dtype) {
  29376. return tfjs_core_1.randomUniform(shape, this.minval, this.maxval, dtype);
  29377. };
  29378. RandomUniform.prototype.getConfig = function () {
  29379. return { minval: this.minval, maxval: this.maxval, seed: this.seed };
  29380. };
  29381. RandomUniform.className = 'RandomUniform';
  29382. return RandomUniform;
  29383. }(Initializer));
  29384. exports.RandomUniform = RandomUniform;
  29385. tfjs_core_1.serialization.SerializationMap.register(RandomUniform);
  29386. var RandomNormal = (function (_super) {
  29387. __extends(RandomNormal, _super);
  29388. function RandomNormal(config) {
  29389. var _this = _super.call(this) || this;
  29390. _this.DEFAULT_MEAN = 0.;
  29391. _this.DEFAULT_STDDEV = 0.05;
  29392. _this.mean = config.mean || _this.DEFAULT_MEAN;
  29393. _this.stddev = config.stddev || _this.DEFAULT_STDDEV;
  29394. _this.seed = config.seed;
  29395. return _this;
  29396. }
  29397. RandomNormal.prototype.apply = function (shape, dtype) {
  29398. if (dtype === 'bool') {
  29399. throw new errors_1.NotImplementedError("randomNormal does not support dType bool.");
  29400. }
  29401. return K.randomNormal(shape, this.mean, this.stddev, dtype, this.seed);
  29402. };
  29403. RandomNormal.prototype.getConfig = function () {
  29404. return { mean: this.mean, stddev: this.stddev, seed: this.seed };
  29405. };
  29406. RandomNormal.className = 'RandomNormal';
  29407. return RandomNormal;
  29408. }(Initializer));
  29409. exports.RandomNormal = RandomNormal;
  29410. tfjs_core_1.serialization.SerializationMap.register(RandomNormal);
  29411. var TruncatedNormal = (function (_super) {
  29412. __extends(TruncatedNormal, _super);
  29413. function TruncatedNormal(config) {
  29414. var _this = _super.call(this) || this;
  29415. _this.DEFAULT_MEAN = 0.;
  29416. _this.DEFAULT_STDDEV = 0.05;
  29417. _this.mean = config.mean || _this.DEFAULT_MEAN;
  29418. _this.stddev = config.stddev || _this.DEFAULT_STDDEV;
  29419. _this.seed = config.seed;
  29420. return _this;
  29421. }
  29422. TruncatedNormal.prototype.apply = function (shape, dtype) {
  29423. if (dtype === 'bool') {
  29424. throw new errors_1.NotImplementedError("truncatedNormal does not support dType bool.");
  29425. }
  29426. return tfjs_core_1.truncatedNormal(shape, this.mean, this.stddev, dtype, this.seed);
  29427. };
  29428. TruncatedNormal.prototype.getConfig = function () {
  29429. return { mean: this.mean, stddev: this.stddev, seed: this.seed };
  29430. };
  29431. TruncatedNormal.className = 'TruncatedNormal';
  29432. return TruncatedNormal;
  29433. }(Initializer));
  29434. exports.TruncatedNormal = TruncatedNormal;
  29435. tfjs_core_1.serialization.SerializationMap.register(TruncatedNormal);
  29436. var Identity = (function (_super) {
  29437. __extends(Identity, _super);
  29438. function Identity(config) {
  29439. var _this = _super.call(this) || this;
  29440. _this.gain = config.gain != null ? tfjs_core_1.scalar(config.gain) : K.getScalar(1.0);
  29441. return _this;
  29442. }
  29443. Identity.prototype.apply = function (shape, dtype) {
  29444. var _this = this;
  29445. return tfjs_core_1.tidy(function () {
  29446. if (shape.length !== 2 || shape[0] !== shape[1]) {
  29447. throw new errors_1.ValueError('Identity matrix initializer can only be used for' +
  29448. ' 2D square matrices.');
  29449. }
  29450. else {
  29451. return K.scalarTimesArray(_this.gain, tfjs_core_1.eye(shape[0]));
  29452. }
  29453. });
  29454. };
  29455. Identity.prototype.getConfig = function () {
  29456. return { gain: this.gain.get() };
  29457. };
  29458. Identity.className = 'Identity';
  29459. return Identity;
  29460. }(Initializer));
  29461. exports.Identity = Identity;
  29462. tfjs_core_1.serialization.SerializationMap.register(Identity);
  29463. function computeFans(shape, dataFormat) {
  29464. if (dataFormat === void 0) { dataFormat = 'channelsLast'; }
  29465. var fanIn;
  29466. var fanOut;
  29467. common_1.checkDataFormat(dataFormat);
  29468. if (shape.length === 2) {
  29469. fanIn = shape[0];
  29470. fanOut = shape[1];
  29471. }
  29472. else if ([3, 4, 5].indexOf(shape.length) !== -1) {
  29473. if (dataFormat === 'channelsFirst') {
  29474. var receptiveFieldSize = math_utils_1.arrayProd(shape, 2);
  29475. fanIn = shape[1] * receptiveFieldSize;
  29476. fanOut = shape[0] * receptiveFieldSize;
  29477. }
  29478. else if (dataFormat === 'channelsLast') {
  29479. var receptiveFieldSize = math_utils_1.arrayProd(shape, 0, shape.length - 2);
  29480. fanIn = shape[shape.length - 2] * receptiveFieldSize;
  29481. fanOut = shape[shape.length - 1] * receptiveFieldSize;
  29482. }
  29483. }
  29484. else {
  29485. var shapeProd = math_utils_1.arrayProd(shape);
  29486. fanIn = Math.sqrt(shapeProd);
  29487. fanOut = Math.sqrt(shapeProd);
  29488. }
  29489. return [fanIn, fanOut];
  29490. }
  29491. var VarianceScaling = (function (_super) {
  29492. __extends(VarianceScaling, _super);
  29493. function VarianceScaling(config) {
  29494. var _this = _super.call(this) || this;
  29495. if (config.scale < 0.0) {
  29496. throw new errors_1.ValueError("scale must be a positive float. Got: " + config.scale);
  29497. }
  29498. _this.scale = config.scale == null ? 1.0 : config.scale;
  29499. _this.mode = config.mode;
  29500. checkFanMode(_this.mode);
  29501. _this.distribution = config.distribution;
  29502. checkDistribution(_this.distribution);
  29503. _this.seed = config.seed;
  29504. return _this;
  29505. }
  29506. VarianceScaling.prototype.apply = function (shape, dtype) {
  29507. var fans = computeFans(shape);
  29508. var fanIn = fans[0];
  29509. var fanOut = fans[1];
  29510. var scale = this.scale;
  29511. if (this.mode === 'fanIn') {
  29512. scale /= Math.max(1, fanIn);
  29513. }
  29514. else if (this.mode === 'fanOut') {
  29515. scale /= Math.max(1, fanOut);
  29516. }
  29517. else {
  29518. scale /= Math.max(1, (fanIn + fanOut) / 2);
  29519. }
  29520. if (this.distribution === 'normal') {
  29521. var stddev = Math.sqrt(scale);
  29522. if (dtype === 'bool') {
  29523. throw new errors_1.NotImplementedError(this.getClassName() + " does not support dType bool.");
  29524. }
  29525. return tfjs_core_1.truncatedNormal(shape, 0, stddev, dtype, this.seed);
  29526. }
  29527. else {
  29528. var limit = Math.sqrt(3 * scale);
  29529. return tfjs_core_1.randomUniform(shape, -limit, limit, dtype);
  29530. }
  29531. };
  29532. VarianceScaling.prototype.getConfig = function () {
  29533. return {
  29534. scale: this.scale,
  29535. mode: this.mode,
  29536. distribution: this.distribution,
  29537. seed: this.seed
  29538. };
  29539. };
  29540. VarianceScaling.className = 'VarianceScaling';
  29541. return VarianceScaling;
  29542. }(Initializer));
  29543. exports.VarianceScaling = VarianceScaling;
  29544. tfjs_core_1.serialization.SerializationMap.register(VarianceScaling);
  29545. var GlorotUniform = (function (_super) {
  29546. __extends(GlorotUniform, _super);
  29547. function GlorotUniform(config) {
  29548. return _super.call(this, {
  29549. scale: 1.0,
  29550. mode: 'fanAvg',
  29551. distribution: 'uniform',
  29552. seed: config == null ? null : config.seed
  29553. }) || this;
  29554. }
  29555. GlorotUniform.prototype.getClassName = function () {
  29556. return VarianceScaling.className;
  29557. };
  29558. return GlorotUniform;
  29559. }(VarianceScaling));
  29560. exports.GlorotUniform = GlorotUniform;
  29561. var GlorotNormal = (function (_super) {
  29562. __extends(GlorotNormal, _super);
  29563. function GlorotNormal(config) {
  29564. return _super.call(this, {
  29565. scale: 1.0,
  29566. mode: 'fanAvg',
  29567. distribution: 'normal',
  29568. seed: config == null ? null : config.seed
  29569. }) || this;
  29570. }
  29571. GlorotNormal.prototype.getClassName = function () {
  29572. return VarianceScaling.className;
  29573. };
  29574. return GlorotNormal;
  29575. }(VarianceScaling));
  29576. exports.GlorotNormal = GlorotNormal;
  29577. var HeNormal = (function (_super) {
  29578. __extends(HeNormal, _super);
  29579. function HeNormal(config) {
  29580. return _super.call(this, {
  29581. scale: 2.0,
  29582. mode: 'fanIn',
  29583. distribution: 'normal',
  29584. seed: config == null ? null : config.seed
  29585. }) || this;
  29586. }
  29587. HeNormal.prototype.getClassName = function () {
  29588. return VarianceScaling.className;
  29589. };
  29590. return HeNormal;
  29591. }(VarianceScaling));
  29592. exports.HeNormal = HeNormal;
  29593. var LeCunNormal = (function (_super) {
  29594. __extends(LeCunNormal, _super);
  29595. function LeCunNormal(config) {
  29596. return _super.call(this, {
  29597. scale: 1.0,
  29598. mode: 'fanIn',
  29599. distribution: 'normal',
  29600. seed: config == null ? null : config.seed
  29601. }) || this;
  29602. }
  29603. LeCunNormal.prototype.getClassName = function () {
  29604. return VarianceScaling.className;
  29605. };
  29606. return LeCunNormal;
  29607. }(VarianceScaling));
  29608. exports.LeCunNormal = LeCunNormal;
  29609. var Orthogonal = (function (_super) {
  29610. __extends(Orthogonal, _super);
  29611. function Orthogonal(config) {
  29612. var _this = _super.call(this) || this;
  29613. _this.DEFAULT_GAIN = 1;
  29614. _this.gain = config.gain == null ? _this.DEFAULT_GAIN : config.gain;
  29615. _this.seed = config.seed;
  29616. if (_this.seed != null) {
  29617. throw new errors_1.NotImplementedError('Random seed is not implemented for Orthogonal Initializer yet.');
  29618. }
  29619. return _this;
  29620. }
  29621. Orthogonal.prototype.apply = function (shape, dtype) {
  29622. var _this = this;
  29623. return tfjs_core_1.tidy(function () {
  29624. if (shape.length !== 2) {
  29625. throw new errors_1.NotImplementedError('The Orthogonal Initializer does not support non-2D shapes yet.');
  29626. }
  29627. if (shape[0] * shape[1] > 2000) {
  29628. console.warn("Orthogonal initializer is being called on a matrix with more " +
  29629. ("than 2000 (" + shape[0] * shape[1] + ") elements: ") +
  29630. "Slowness may result.");
  29631. }
  29632. var normalizedShape = shape[0] > shape[1] ? [shape[1], shape[0]] : shape;
  29633. var a = K.randomNormal(normalizedShape, 0, 1, 'float32');
  29634. var q = tfjs_core_1.linalg.gramSchmidt(a);
  29635. if (shape[0] > shape[1]) {
  29636. q = q.transpose();
  29637. }
  29638. return K.scalarTimesArray(K.getScalar(_this.gain), q);
  29639. });
  29640. };
  29641. Orthogonal.prototype.getConfig = function () {
  29642. return {
  29643. gain: this.gain,
  29644. seed: this.seed,
  29645. };
  29646. };
  29647. Orthogonal.className = 'Orthogonal';
  29648. return Orthogonal;
  29649. }(Initializer));
  29650. exports.Orthogonal = Orthogonal;
  29651. tfjs_core_1.serialization.SerializationMap.register(Orthogonal);
  29652. exports.INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP = {
  29653. 'constant': 'Constant',
  29654. 'glorotNormal': 'GlorotNormal',
  29655. 'glorotUniform': 'GlorotUniform',
  29656. 'heNormal': 'HeNormal',
  29657. 'identity': 'Identity',
  29658. 'leCunNormal': 'LeCunNormal',
  29659. 'ones': 'Ones',
  29660. 'orthogonal': 'Orthogonal',
  29661. 'randomNormal': 'RandomNormal',
  29662. 'randomUniform': 'RandomUniform',
  29663. 'truncatedNormal': 'TruncatedNormal',
  29664. 'varianceScaling': 'VarianceScaling',
  29665. 'zeros': 'Zeros'
  29666. };
  29667. function deserializeInitializer(config, customObjects) {
  29668. if (customObjects === void 0) { customObjects = {}; }
  29669. return generic_utils_1.deserializeKerasObject(config, tfjs_core_1.serialization.SerializationMap.getMap().classNameMap, customObjects, 'initializer');
  29670. }
  29671. function serializeInitializer(initializer) {
  29672. return generic_utils_1.serializeKerasObject(initializer);
  29673. }
  29674. exports.serializeInitializer = serializeInitializer;
  29675. function getInitializer(identifier) {
  29676. if (typeof identifier === 'string') {
  29677. var className = identifier in exports.INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP ?
  29678. exports.INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] :
  29679. identifier;
  29680. if (className === 'GlorotUniform') {
  29681. return new GlorotUniform();
  29682. }
  29683. else if (className === 'GlorotNormal') {
  29684. return new GlorotNormal();
  29685. }
  29686. else if (className === 'HeNormal') {
  29687. return new HeNormal();
  29688. }
  29689. else if (className === 'LeCunNormal') {
  29690. return new LeCunNormal();
  29691. }
  29692. else {
  29693. var config = { className: className, config: {} };
  29694. return deserializeInitializer(config);
  29695. }
  29696. }
  29697. else if (identifier instanceof Initializer) {
  29698. return identifier;
  29699. }
  29700. else {
  29701. return deserializeInitializer(identifier);
  29702. }
  29703. }
  29704. exports.getInitializer = getInitializer;
  29705. },{"./backend/tfjs_backend":169,"./common":171,"./errors":176,"./utils/generic_utils":199,"./utils/math_utils":201,"@tensorflow/tfjs-core":54}],180:[function(require,module,exports){
  29706. "use strict";
  29707. var __extends = (this && this.__extends) || (function () {
  29708. var extendStatics = Object.setPrototypeOf ||
  29709. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  29710. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  29711. return function (d, b) {
  29712. extendStatics(d, b);
  29713. function __() { this.constructor = d; }
  29714. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  29715. };
  29716. })();
  29717. Object.defineProperty(exports, "__esModule", { value: true });
  29718. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  29719. var activations_1 = require("../activations");
  29720. var tfjs_backend_1 = require("../backend/tfjs_backend");
  29721. var tfjs_backend_2 = require("../backend/tfjs_backend");
  29722. var topology_1 = require("../engine/topology");
  29723. var errors_1 = require("../errors");
  29724. var generic_utils = require("../utils/generic_utils");
  29725. var LeakyReLU = (function (_super) {
  29726. __extends(LeakyReLU, _super);
  29727. function LeakyReLU(config) {
  29728. var _this = _super.call(this, config == null ? {} : config) || this;
  29729. _this.DEFAULT_ALPHA = 0.3;
  29730. if (config == null) {
  29731. config = {};
  29732. }
  29733. _this.alpha = config.alpha == null ? _this.DEFAULT_ALPHA : config.alpha;
  29734. return _this;
  29735. }
  29736. LeakyReLU.prototype.call = function (inputs, kwargs) {
  29737. var x = generic_utils.getExactlyOneTensor(inputs);
  29738. return tfjs_core_1.leakyRelu(x, this.alpha);
  29739. };
  29740. LeakyReLU.prototype.computeOutputShape = function (inputShape) {
  29741. return inputShape;
  29742. };
  29743. LeakyReLU.prototype.getConfig = function () {
  29744. var config = { alpha: this.alpha };
  29745. var baseConfig = _super.prototype.getConfig.call(this);
  29746. Object.assign(config, baseConfig);
  29747. return config;
  29748. };
  29749. LeakyReLU.className = 'LeakyReLU';
  29750. return LeakyReLU;
  29751. }(topology_1.Layer));
  29752. exports.LeakyReLU = LeakyReLU;
  29753. tfjs_core_1.serialization.SerializationMap.register(LeakyReLU);
  29754. var ELU = (function (_super) {
  29755. __extends(ELU, _super);
  29756. function ELU(config) {
  29757. var _this = _super.call(this, config == null ? {} : config) || this;
  29758. _this.DEFAULT_ALPHA = 1.0;
  29759. if (config == null) {
  29760. config = {};
  29761. }
  29762. if (config.alpha != null && config.alpha !== _this.DEFAULT_ALPHA) {
  29763. throw new errors_1.NotImplementedError("Non-default alpha value (" + config.alpha + ") is not supported by the " +
  29764. "ELU layer yet.");
  29765. }
  29766. _this.alpha = config.alpha == null ? _this.DEFAULT_ALPHA : config.alpha;
  29767. return _this;
  29768. }
  29769. ELU.prototype.call = function (inputs, kwargs) {
  29770. var x = generic_utils.getExactlyOneTensor(inputs);
  29771. return tfjs_core_1.elu(x);
  29772. };
  29773. ELU.prototype.computeOutputShape = function (inputShape) {
  29774. return inputShape;
  29775. };
  29776. ELU.prototype.getConfig = function () {
  29777. var config = { alpha: this.alpha };
  29778. var baseConfig = _super.prototype.getConfig.call(this);
  29779. Object.assign(config, baseConfig);
  29780. return config;
  29781. };
  29782. ELU.className = 'ELU';
  29783. return ELU;
  29784. }(topology_1.Layer));
  29785. exports.ELU = ELU;
  29786. tfjs_core_1.serialization.SerializationMap.register(ELU);
  29787. var ThresholdedReLU = (function (_super) {
  29788. __extends(ThresholdedReLU, _super);
  29789. function ThresholdedReLU(config) {
  29790. var _this = _super.call(this, config == null ? {} : config) || this;
  29791. _this.DEFAULT_THETA = 1.0;
  29792. if (config == null) {
  29793. config = {};
  29794. }
  29795. _this.theta = config.theta == null ? _this.DEFAULT_THETA : config.theta;
  29796. _this.thetaTensor = tfjs_backend_2.getScalar(_this.theta);
  29797. return _this;
  29798. }
  29799. ThresholdedReLU.prototype.call = function (inputs, kwargs) {
  29800. var x = generic_utils.getExactlyOneTensor(inputs);
  29801. return x.mul(tfjs_backend_1.cast(x.greater(this.thetaTensor), 'float32'));
  29802. };
  29803. ThresholdedReLU.prototype.computeOutputShape = function (inputShape) {
  29804. return inputShape;
  29805. };
  29806. ThresholdedReLU.prototype.getConfig = function () {
  29807. var config = { theta: this.theta };
  29808. var baseConfig = _super.prototype.getConfig.call(this);
  29809. Object.assign(config, baseConfig);
  29810. return config;
  29811. };
  29812. ThresholdedReLU.className = 'ThresholdedReLU';
  29813. return ThresholdedReLU;
  29814. }(topology_1.Layer));
  29815. exports.ThresholdedReLU = ThresholdedReLU;
  29816. tfjs_core_1.serialization.SerializationMap.register(ThresholdedReLU);
  29817. var Softmax = (function (_super) {
  29818. __extends(Softmax, _super);
  29819. function Softmax(config) {
  29820. var _this = _super.call(this, config == null ? {} : config) || this;
  29821. _this.DEFAULT_AXIS = 1.0;
  29822. if (config == null) {
  29823. config = {};
  29824. }
  29825. _this.softmax = new activations_1.Softmax().apply;
  29826. _this.axis = config.axis == null ? _this.DEFAULT_AXIS : config.axis;
  29827. return _this;
  29828. }
  29829. Softmax.prototype.call = function (inputs, kwargs) {
  29830. var x = generic_utils.getExactlyOneTensor(inputs);
  29831. return this.softmax(x, this.axis);
  29832. };
  29833. Softmax.prototype.computeOutputShape = function (inputShape) {
  29834. return inputShape;
  29835. };
  29836. Softmax.prototype.getConfig = function () {
  29837. var config = { axis: this.axis };
  29838. var baseConfig = _super.prototype.getConfig.call(this);
  29839. Object.assign(config, baseConfig);
  29840. return config;
  29841. };
  29842. Softmax.className = 'Softmax';
  29843. return Softmax;
  29844. }(topology_1.Layer));
  29845. exports.Softmax = Softmax;
  29846. tfjs_core_1.serialization.SerializationMap.register(Softmax);
  29847. },{"../activations":167,"../backend/tfjs_backend":169,"../engine/topology":174,"../errors":176,"../utils/generic_utils":199,"@tensorflow/tfjs-core":54}],181:[function(require,module,exports){
  29848. "use strict";
  29849. var __extends = (this && this.__extends) || (function () {
  29850. var extendStatics = Object.setPrototypeOf ||
  29851. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  29852. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  29853. return function (d, b) {
  29854. extendStatics(d, b);
  29855. function __() { this.constructor = d; }
  29856. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  29857. };
  29858. })();
  29859. Object.defineProperty(exports, "__esModule", { value: true });
  29860. var tfc = require("@tensorflow/tfjs-core");
  29861. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  29862. var activations_1 = require("../activations");
  29863. var common_1 = require("../backend/common");
  29864. var K = require("../backend/tfjs_backend");
  29865. var common_2 = require("../common");
  29866. var constraints_1 = require("../constraints");
  29867. var topology_1 = require("../engine/topology");
  29868. var errors_1 = require("../errors");
  29869. var initializers_1 = require("../initializers");
  29870. var regularizers_1 = require("../regularizers");
  29871. var conv_utils_1 = require("../utils/conv_utils");
  29872. var generic_utils = require("../utils/generic_utils");
  29873. function preprocessConv2DInput(x, dataFormat) {
  29874. return tfjs_core_1.tidy(function () {
  29875. common_2.checkDataFormat(dataFormat);
  29876. if (dataFormat === 'channelsFirst') {
  29877. return tfc.transpose(x, [0, 2, 3, 1]);
  29878. }
  29879. else {
  29880. return x;
  29881. }
  29882. });
  29883. }
  29884. exports.preprocessConv2DInput = preprocessConv2DInput;
  29885. function conv1dWithBias(x, kernel, bias, strides, padding, dataFormat, dilationRate) {
  29886. if (strides === void 0) { strides = 1; }
  29887. if (padding === void 0) { padding = 'valid'; }
  29888. if (dilationRate === void 0) { dilationRate = 1; }
  29889. return tfjs_core_1.tidy(function () {
  29890. if (dataFormat == null) {
  29891. dataFormat = common_1.imageDataFormat();
  29892. }
  29893. common_2.checkDataFormat(dataFormat);
  29894. if (x.shape.length !== 3) {
  29895. throw new errors_1.ValueError("The input of a conv1dWithBias operation should be 3, but is " +
  29896. (x.shape.length + " instead."));
  29897. }
  29898. if (kernel.shape.length !== 3) {
  29899. throw new errors_1.ValueError("The kernel for a conv1dWithBias operation should be 3, but is " +
  29900. (kernel.shape.length + " instead"));
  29901. }
  29902. if (bias != null && bias.shape.length !== 1) {
  29903. throw new errors_1.ValueError("The bias for a conv1dWithBias operation should be 1, but is " +
  29904. (kernel.shape.length + " instead"));
  29905. }
  29906. if (dataFormat === 'channelsFirst') {
  29907. x = tfc.transpose(x, [0, 2, 1]);
  29908. }
  29909. if (padding === 'causal') {
  29910. throw new errors_1.NotImplementedError('The support for CAUSAL padding mode in conv1dWithBias is not ' +
  29911. 'implemented yet.');
  29912. }
  29913. var y = tfc.conv1d(x, kernel, strides, padding === 'same' ? 'same' : 'valid', 'NWC', dilationRate);
  29914. if (bias != null) {
  29915. y = K.biasAdd(y, bias);
  29916. }
  29917. return y;
  29918. });
  29919. }
  29920. exports.conv1dWithBias = conv1dWithBias;
  29921. function conv1d(x, kernel, strides, padding, dataFormat, dilationRate) {
  29922. if (strides === void 0) { strides = 1; }
  29923. if (padding === void 0) { padding = 'valid'; }
  29924. if (dilationRate === void 0) { dilationRate = 1; }
  29925. return tfjs_core_1.tidy(function () {
  29926. common_2.checkDataFormat(dataFormat);
  29927. return conv1dWithBias(x, kernel, null, strides, padding, dataFormat, dilationRate);
  29928. });
  29929. }
  29930. exports.conv1d = conv1d;
  29931. function conv2d(x, kernel, strides, padding, dataFormat, dilationRate) {
  29932. if (strides === void 0) { strides = [1, 1]; }
  29933. if (padding === void 0) { padding = 'valid'; }
  29934. return tfjs_core_1.tidy(function () {
  29935. common_2.checkDataFormat(dataFormat);
  29936. return conv2dWithBias(x, kernel, null, strides, padding, dataFormat, dilationRate);
  29937. });
  29938. }
  29939. exports.conv2d = conv2d;
  29940. function conv2dWithBias(x, kernel, bias, strides, padding, dataFormat, dilationRate) {
  29941. if (strides === void 0) { strides = [1, 1]; }
  29942. if (padding === void 0) { padding = 'valid'; }
  29943. return tfjs_core_1.tidy(function () {
  29944. if (dataFormat == null) {
  29945. dataFormat = common_1.imageDataFormat();
  29946. }
  29947. common_2.checkDataFormat(dataFormat);
  29948. if (x.rank !== 3 && x.rank !== 4) {
  29949. throw new errors_1.ValueError("conv2dWithBias expects input to be of rank 3 or 4, but received " +
  29950. (x.rank + "."));
  29951. }
  29952. if (kernel.rank !== 3 && kernel.rank !== 4) {
  29953. throw new errors_1.ValueError("conv2dWithBias expects kernel to be of rank 3 or 4, but received " +
  29954. (x.rank + "."));
  29955. }
  29956. var y = preprocessConv2DInput(x, dataFormat);
  29957. if (padding === 'causal') {
  29958. throw new errors_1.NotImplementedError('The support for CAUSAL padding mode in conv1dWithBias is not ' +
  29959. 'implemented yet.');
  29960. }
  29961. y = tfc.conv2d(y, kernel, strides, padding === 'same' ? 'same' : 'valid', 'NHWC', dilationRate);
  29962. if (bias != null) {
  29963. y = K.biasAdd(y, bias);
  29964. }
  29965. if (dataFormat === 'channelsFirst') {
  29966. y = tfc.transpose(y, [0, 3, 1, 2]);
  29967. }
  29968. return y;
  29969. });
  29970. }
  29971. exports.conv2dWithBias = conv2dWithBias;
  29972. var BaseConv = (function (_super) {
  29973. __extends(BaseConv, _super);
  29974. function BaseConv(rank, config) {
  29975. var _this = _super.call(this, config) || this;
  29976. _this.bias = null;
  29977. _this.DEFAULT_KERNEL_INITIALIZER = 'glorotNormal';
  29978. _this.DEFAULT_BIAS_INITIALIZER = 'zeros';
  29979. BaseConv.verifyConfig(config);
  29980. _this.rank = rank;
  29981. if (_this.rank !== 1 && _this.rank !== 2) {
  29982. throw new errors_1.NotImplementedError("Convolution layer for rank other than 1 or 2 (" + _this.rank + ") is " +
  29983. "not implemented yet.");
  29984. }
  29985. _this.kernelSize = conv_utils_1.normalizeArray(config.kernelSize, rank, 'kernelSize');
  29986. _this.strides = conv_utils_1.normalizeArray(config.strides == null ? 1 : config.strides, rank, 'strides');
  29987. _this.padding = config.padding == null ? 'valid' : config.padding;
  29988. common_2.checkPaddingMode(_this.padding);
  29989. _this.dataFormat =
  29990. config.dataFormat == null ? 'channelsLast' : config.dataFormat;
  29991. common_2.checkDataFormat(_this.dataFormat);
  29992. _this.activation = activations_1.getActivation(config.activation);
  29993. _this.useBias = config.useBias == null ? true : config.useBias;
  29994. _this.biasInitializer =
  29995. initializers_1.getInitializer(config.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
  29996. _this.biasConstraint = constraints_1.getConstraint(config.biasConstraint);
  29997. _this.biasRegularizer = regularizers_1.getRegularizer(config.biasRegularizer);
  29998. _this.activityRegularizer = regularizers_1.getRegularizer(config.activityRegularizer);
  29999. _this.dilationRate = config.dilationRate == null ? 1 : config.dilationRate;
  30000. if (_this.rank === 1 &&
  30001. (Array.isArray(_this.dilationRate) &&
  30002. _this.dilationRate.length !== 1)) {
  30003. throw new errors_1.ValueError("dilationRate must be a number or an array of a single number " +
  30004. "for 1D convolution, but received " +
  30005. ("" + JSON.stringify(_this.dilationRate)));
  30006. }
  30007. if (_this.rank === 2) {
  30008. if (typeof _this.dilationRate === 'number') {
  30009. _this.dilationRate = [_this.dilationRate, _this.dilationRate];
  30010. }
  30011. else if (_this.dilationRate.length !== 2) {
  30012. throw new errors_1.ValueError("dilationRate must be a number or array of two numbers for 2D " +
  30013. ("convolution, but received " + JSON.stringify(_this.dilationRate)));
  30014. }
  30015. }
  30016. return _this;
  30017. }
  30018. BaseConv.verifyConfig = function (config) {
  30019. generic_utils.assert('kernelSize' in config, "required key 'kernelSize' not in config");
  30020. if (typeof config.kernelSize !== 'number' &&
  30021. !generic_utils.checkArrayTypeAndLength(config.kernelSize, 'number', 1, 2))
  30022. throw new errors_1.ValueError("BaseConv expects config.kernelSize to be number or number[] with " +
  30023. ("length 1 or 2, but received " + JSON.stringify(config.kernelSize) + "."));
  30024. };
  30025. return BaseConv;
  30026. }(topology_1.Layer));
  30027. exports.BaseConv = BaseConv;
  30028. var Conv = (function (_super) {
  30029. __extends(Conv, _super);
  30030. function Conv(rank, config) {
  30031. var _this = _super.call(this, rank, config) || this;
  30032. _this.kernel = null;
  30033. Conv.verifyConfig(config);
  30034. _this.filters = config.filters;
  30035. _this.kernelInitializer = initializers_1.getInitializer(config.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
  30036. _this.kernelConstraint = constraints_1.getConstraint(config.kernelConstraint);
  30037. _this.kernelRegularizer = regularizers_1.getRegularizer(config.kernelRegularizer);
  30038. return _this;
  30039. }
  30040. Conv.prototype.build = function (inputShape) {
  30041. inputShape = generic_utils.getExactlyOneShape(inputShape);
  30042. var channelAxis = this.dataFormat === 'channelsFirst' ? 1 : inputShape.length - 1;
  30043. if (inputShape[channelAxis] == null) {
  30044. throw new errors_1.ValueError("The channel dimension of the input should be defined. " +
  30045. ("Found " + inputShape[channelAxis]));
  30046. }
  30047. var inputDim = inputShape[channelAxis];
  30048. var kernelShape = this.kernelSize.concat([inputDim, this.filters]);
  30049. this.kernel = this.addWeight('kernel', kernelShape, null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
  30050. if (this.useBias) {
  30051. this.bias = this.addWeight('bias', [this.filters], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
  30052. }
  30053. this.inputSpec = [{ ndim: this.rank + 2, axes: (_a = {}, _a[channelAxis] = inputDim, _a) }];
  30054. this.built = true;
  30055. var _a;
  30056. };
  30057. Conv.prototype.call = function (inputs, kwargs) {
  30058. var _this = this;
  30059. return tfjs_core_1.tidy(function () {
  30060. inputs = generic_utils.getExactlyOneTensor(inputs);
  30061. var outputs;
  30062. var biasValue = _this.bias == null ? null : _this.bias.read();
  30063. if (_this.rank === 1) {
  30064. outputs = conv1dWithBias(inputs, _this.kernel.read(), biasValue, _this.strides[0], _this.padding, _this.dataFormat, _this.dilationRate);
  30065. }
  30066. else if (_this.rank === 2) {
  30067. outputs = conv2dWithBias(inputs, _this.kernel.read(), biasValue, _this.strides, _this.padding, _this.dataFormat, _this.dilationRate);
  30068. }
  30069. else if (_this.rank === 3) {
  30070. throw new errors_1.NotImplementedError('3D convolution is not implemented yet.');
  30071. }
  30072. if (_this.activation != null) {
  30073. outputs = _this.activation.apply(outputs);
  30074. }
  30075. return outputs;
  30076. });
  30077. };
  30078. Conv.prototype.computeOutputShape = function (inputShape) {
  30079. inputShape = generic_utils.getExactlyOneShape(inputShape);
  30080. var newSpace = [];
  30081. var space = (this.dataFormat === 'channelsLast') ?
  30082. inputShape.slice(1, inputShape.length - 1) :
  30083. inputShape.slice(2);
  30084. for (var i = 0; i < space.length; ++i) {
  30085. var newDim = conv_utils_1.convOutputLength(space[i], this.kernelSize[i], this.padding, this.strides[i], typeof this.dilationRate === 'number' ? this.dilationRate :
  30086. this.dilationRate[i]);
  30087. newSpace.push(newDim);
  30088. }
  30089. var outputShape = [inputShape[0]];
  30090. if (this.dataFormat === 'channelsLast') {
  30091. outputShape = outputShape.concat(newSpace);
  30092. outputShape.push(this.filters);
  30093. }
  30094. else {
  30095. outputShape.push(this.filters);
  30096. outputShape = outputShape.concat(newSpace);
  30097. }
  30098. return outputShape;
  30099. };
  30100. Conv.prototype.getConfig = function () {
  30101. var config = {
  30102. rank: this.rank,
  30103. filters: this.filters,
  30104. kernelSize: this.kernelSize,
  30105. strides: this.strides,
  30106. padding: this.padding,
  30107. dataFormat: this.dataFormat,
  30108. dilationRate: this.dilationRate,
  30109. activation: activations_1.serializeActivation(this.activation),
  30110. useBias: this.useBias,
  30111. kernelInitializer: initializers_1.serializeInitializer(this.kernelInitializer),
  30112. biasInitializer: initializers_1.serializeInitializer(this.biasInitializer),
  30113. kernelRegularizer: regularizers_1.serializeRegularizer(this.kernelRegularizer),
  30114. biasRegularizer: regularizers_1.serializeRegularizer(this.biasRegularizer),
  30115. activityRegularizer: regularizers_1.serializeRegularizer(this.activityRegularizer),
  30116. kernelConstraint: constraints_1.serializeConstraint(this.kernelConstraint),
  30117. biasConstraint: constraints_1.serializeConstraint(this.biasConstraint)
  30118. };
  30119. var baseConfig = _super.prototype.getConfig.call(this);
  30120. Object.assign(config, baseConfig);
  30121. return config;
  30122. };
  30123. Conv.verifyConfig = function (config) {
  30124. if (!('filters' in config) || typeof config.filters !== 'number' ||
  30125. config.filters < 1) {
  30126. throw new errors_1.ValueError("Convolution layer expected config.filters to be a 'number' > 0 " +
  30127. ("but got " + JSON.stringify(config.filters)));
  30128. }
  30129. };
  30130. return Conv;
  30131. }(BaseConv));
  30132. exports.Conv = Conv;
  30133. var Conv2D = (function (_super) {
  30134. __extends(Conv2D, _super);
  30135. function Conv2D(config) {
  30136. var _this = _super.call(this, 2, config) || this;
  30137. Conv2D.verifyConfig(config);
  30138. return _this;
  30139. }
  30140. Conv2D.prototype.getConfig = function () {
  30141. var config = _super.prototype.getConfig.call(this);
  30142. delete config['rank'];
  30143. return config;
  30144. };
  30145. Conv2D.verifyConfig = function (config) {
  30146. if ((typeof config.kernelSize !== 'number') &&
  30147. !generic_utils.checkArrayTypeAndLength(config.kernelSize, 'number', 1, 2))
  30148. throw new errors_1.ValueError("Conv2D expects config.kernelSize to be number or number[] with " +
  30149. ("length 1 or 2, but received " + JSON.stringify(config.kernelSize) + "."));
  30150. };
  30151. Conv2D.className = 'Conv2D';
  30152. return Conv2D;
  30153. }(Conv));
  30154. exports.Conv2D = Conv2D;
  30155. tfjs_core_1.serialization.SerializationMap.register(Conv2D);
  30156. var Conv2DTranspose = (function (_super) {
  30157. __extends(Conv2DTranspose, _super);
  30158. function Conv2DTranspose(config) {
  30159. var _this = _super.call(this, config) || this;
  30160. _this.inputSpec = [new topology_1.InputSpec({ ndim: 4 })];
  30161. if (_this.padding !== 'same' && _this.padding !== 'valid') {
  30162. throw new errors_1.ValueError("Conv2DTranspose currently supports only padding modes 'same' " +
  30163. ("and 'valid', but received padding mode " + _this.padding));
  30164. }
  30165. return _this;
  30166. }
  30167. Conv2DTranspose.prototype.build = function (inputShape) {
  30168. inputShape = generic_utils.getExactlyOneShape(inputShape);
  30169. if (inputShape.length !== 4) {
  30170. throw new errors_1.ValueError('Input should have rank 4; Received input shape: ' +
  30171. JSON.stringify(inputShape));
  30172. }
  30173. var channelAxis = this.dataFormat === 'channelsFirst' ? 1 : inputShape.length - 1;
  30174. if (inputShape[channelAxis] == null) {
  30175. throw new errors_1.ValueError('The channel dimension of the inputs should be defined. ' +
  30176. 'Found `None`.');
  30177. }
  30178. var inputDim = inputShape[channelAxis];
  30179. var kernelShape = this.kernelSize.concat([this.filters, inputDim]);
  30180. this.kernel = this.addWeight('kernel', kernelShape, 'float32', this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
  30181. if (this.useBias) {
  30182. this.bias = this.addWeight('bias', [this.filters], 'float32', this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
  30183. }
  30184. this.inputSpec =
  30185. [new topology_1.InputSpec({ ndim: 4, axes: (_a = {}, _a[channelAxis] = inputDim, _a) })];
  30186. this.built = true;
  30187. var _a;
  30188. };
  30189. Conv2DTranspose.prototype.call = function (inputs, kwargs) {
  30190. var _this = this;
  30191. return tfc.tidy(function () {
  30192. var input = generic_utils.getExactlyOneTensor(inputs);
  30193. if (input.shape.length !== 4) {
  30194. throw new errors_1.ValueError("Conv2DTranspose.call() expects input tensor to be rank-4, but " +
  30195. ("received a tensor of rank-" + input.shape.length));
  30196. }
  30197. var inputShape = input.shape;
  30198. var batchSize = inputShape[0];
  30199. var hAxis;
  30200. var wAxis;
  30201. if (_this.dataFormat === 'channelsFirst') {
  30202. hAxis = 2;
  30203. wAxis = 3;
  30204. }
  30205. else {
  30206. hAxis = 1;
  30207. wAxis = 2;
  30208. }
  30209. var height = inputShape[hAxis];
  30210. var width = inputShape[wAxis];
  30211. var kernelH = _this.kernelSize[0];
  30212. var kernelW = _this.kernelSize[1];
  30213. var strideH = _this.strides[0];
  30214. var strideW = _this.strides[1];
  30215. var outHeight = conv_utils_1.deconvLength(height, strideH, kernelH, _this.padding);
  30216. var outWidth = conv_utils_1.deconvLength(width, strideW, kernelW, _this.padding);
  30217. var outputShape = [batchSize, outHeight, outWidth, _this.filters];
  30218. if (_this.dataFormat !== 'channelsLast') {
  30219. input = tfc.transpose(input, [0, 2, 3, 1]);
  30220. }
  30221. var outputs = tfc.conv2dTranspose(input, _this.kernel.read(), outputShape, _this.strides, _this.padding);
  30222. if (_this.dataFormat !== 'channelsLast') {
  30223. outputs = tfc.transpose(outputs, [0, 3, 1, 2]);
  30224. }
  30225. if (_this.bias != null) {
  30226. outputs =
  30227. K.biasAdd(outputs, _this.bias.read(), _this.dataFormat);
  30228. }
  30229. if (_this.activation != null) {
  30230. outputs = _this.activation.apply(outputs);
  30231. }
  30232. return outputs;
  30233. });
  30234. };
  30235. Conv2DTranspose.prototype.computeOutputShape = function (inputShape) {
  30236. inputShape = generic_utils.getExactlyOneShape(inputShape);
  30237. var outputShape = inputShape.slice();
  30238. var channelAxis;
  30239. var heightAxis;
  30240. var widthAxis;
  30241. if (this.dataFormat === 'channelsFirst') {
  30242. channelAxis = 1;
  30243. heightAxis = 2;
  30244. widthAxis = 3;
  30245. }
  30246. else {
  30247. channelAxis = 3;
  30248. heightAxis = 1;
  30249. widthAxis = 2;
  30250. }
  30251. var kernelH = this.kernelSize[0];
  30252. var kernelW = this.kernelSize[1];
  30253. var strideH = this.strides[0];
  30254. var strideW = this.strides[1];
  30255. outputShape[channelAxis] = this.filters;
  30256. outputShape[heightAxis] =
  30257. conv_utils_1.deconvLength(outputShape[heightAxis], strideH, kernelH, this.padding);
  30258. outputShape[widthAxis] =
  30259. conv_utils_1.deconvLength(outputShape[widthAxis], strideW, kernelW, this.padding);
  30260. return outputShape;
  30261. };
  30262. Conv2DTranspose.prototype.getConfig = function () {
  30263. var config = _super.prototype.getConfig.call(this);
  30264. delete config['dilationRate'];
  30265. return config;
  30266. };
  30267. Conv2DTranspose.className = 'Conv2DTranspose';
  30268. return Conv2DTranspose;
  30269. }(Conv2D));
  30270. exports.Conv2DTranspose = Conv2DTranspose;
  30271. tfjs_core_1.serialization.SerializationMap.register(Conv2DTranspose);
  30272. var SeparableConv = (function (_super) {
  30273. __extends(SeparableConv, _super);
  30274. function SeparableConv(rank, config) {
  30275. var _this = _super.call(this, rank, config) || this;
  30276. _this.DEFAULT_DEPTHWISE_INITIALIZER = 'glorotUniform';
  30277. _this.DEFAULT_POINTWISE_INITIALIZER = 'glorotUniform';
  30278. _this.depthwiseKernel = null;
  30279. _this.pointwiseKernel = null;
  30280. if (config.filters == null) {
  30281. throw new errors_1.ValueError('The `filters` configuration field is required by SeparableConv, ' +
  30282. 'but is unspecified.');
  30283. }
  30284. if (config.kernelInitializer != null || config.kernelRegularizer != null ||
  30285. config.kernelConstraint != null) {
  30286. throw new errors_1.ValueError('Fields kernelInitializer, kernelRegularizer and kernelConstraint ' +
  30287. 'are invalid for SeparableConv2D. Use depthwiseInitializer, ' +
  30288. 'depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, ' +
  30289. 'pointwiseRegularizer and pointwiseConstraint instead.');
  30290. }
  30291. if (config.padding != null && config.padding !== 'same' &&
  30292. config.padding !== 'valid') {
  30293. throw new errors_1.ValueError("SeparableConv" + _this.rank + "D supports only padding modes: " +
  30294. ("'same' and 'valid', but received " + JSON.stringify(config.padding)));
  30295. }
  30296. _this.depthMultiplier =
  30297. config.depthMultiplier == null ? 1 : config.depthMultiplier;
  30298. _this.depthwiseInitializer = initializers_1.getInitializer(config.depthwiseInitializer || _this.DEFAULT_DEPTHWISE_INITIALIZER);
  30299. _this.depthwiseRegularizer = regularizers_1.getRegularizer(config.depthwiseRegularizer);
  30300. _this.depthwiseConstraint = constraints_1.getConstraint(config.depthwiseConstraint);
  30301. _this.pointwiseInitializer = initializers_1.getInitializer(config.depthwiseInitializer || _this.DEFAULT_POINTWISE_INITIALIZER);
  30302. _this.pointwiseRegularizer = regularizers_1.getRegularizer(config.pointwiseRegularizer);
  30303. _this.pointwiseConstraint = constraints_1.getConstraint(config.pointwiseConstraint);
  30304. return _this;
  30305. }
  30306. SeparableConv.prototype.build = function (inputShape) {
  30307. inputShape = generic_utils.getExactlyOneShape(inputShape);
  30308. if (inputShape.length < this.rank + 2) {
  30309. throw new errors_1.ValueError("Inputs to SeparableConv" + this.rank + "D should have rank " +
  30310. (this.rank + 2 + ", but received input shape: ") +
  30311. ("" + JSON.stringify(inputShape)));
  30312. }
  30313. var channelAxis = this.dataFormat === 'channelsFirst' ? 1 : inputShape.length - 1;
  30314. if (inputShape[channelAxis] == null || inputShape[channelAxis] < 0) {
  30315. throw new errors_1.ValueError("The channel dimension of the inputs should be defined, " +
  30316. ("but found " + JSON.stringify(inputShape[channelAxis])));
  30317. }
  30318. var inputDim = inputShape[channelAxis];
  30319. var depthwiseKernelShape = this.kernelSize.concat([inputDim, this.depthMultiplier]);
  30320. var pointwiseKernelShape = [];
  30321. for (var i = 0; i < this.rank; ++i) {
  30322. pointwiseKernelShape.push(1);
  30323. }
  30324. pointwiseKernelShape.push(inputDim * this.depthMultiplier, this.filters);
  30325. var trainable = true;
  30326. this.depthwiseKernel = this.addWeight('depthwise_kernel', depthwiseKernelShape, 'float32', this.depthwiseInitializer, this.depthwiseRegularizer, trainable, this.depthwiseConstraint);
  30327. this.pointwiseKernel = this.addWeight('pointwise_kernel', pointwiseKernelShape, 'float32', this.pointwiseInitializer, this.pointwiseRegularizer, trainable, this.pointwiseConstraint);
  30328. if (this.useBias) {
  30329. this.bias = this.addWeight('bias', [this.filters], 'float32', this.biasInitializer, this.biasRegularizer, trainable, this.biasConstraint);
  30330. }
  30331. else {
  30332. this.bias = null;
  30333. }
  30334. this.inputSpec =
  30335. [new topology_1.InputSpec({ ndim: this.rank + 2, axes: (_a = {}, _a[channelAxis] = inputDim, _a) })];
  30336. this.built = true;
  30337. var _a;
  30338. };
  30339. SeparableConv.prototype.call = function (inputs, kwargs) {
  30340. var _this = this;
  30341. return tfjs_core_1.tidy(function () {
  30342. inputs = generic_utils.getExactlyOneTensor(inputs);
  30343. var output;
  30344. if (_this.rank === 1) {
  30345. throw new errors_1.NotImplementedError('1D separable convolution is not implemented yet.');
  30346. }
  30347. else if (_this.rank === 2) {
  30348. if (_this.dataFormat === 'channelsFirst') {
  30349. inputs = tfc.transpose(inputs, [0, 2, 3, 1]);
  30350. }
  30351. output = tfc.separableConv2d(inputs, _this.depthwiseKernel.read(), _this.pointwiseKernel.read(), _this.strides, _this.padding, _this.dilationRate, 'NHWC');
  30352. }
  30353. if (_this.useBias) {
  30354. output = K.biasAdd(output, _this.bias.read(), _this.dataFormat);
  30355. }
  30356. if (_this.activation != null) {
  30357. output = _this.activation.apply(output);
  30358. }
  30359. if (_this.dataFormat === 'channelsFirst') {
  30360. output = tfc.transpose(output, [0, 3, 1, 2]);
  30361. }
  30362. return output;
  30363. });
  30364. };
  30365. SeparableConv.prototype.getConfig = function () {
  30366. var config = _super.prototype.getConfig.call(this);
  30367. delete config['rank'];
  30368. delete config['kernelInitializer'];
  30369. delete config['kernelRegularizer'];
  30370. delete config['kernelConstraint'];
  30371. config['depthwiseInitializer'] =
  30372. initializers_1.serializeInitializer(this.depthwiseInitializer);
  30373. config['pointwiseInitializer'] =
  30374. initializers_1.serializeInitializer(this.pointwiseInitializer);
  30375. config['depthwiseRegularizer'] =
  30376. regularizers_1.serializeRegularizer(this.depthwiseRegularizer);
  30377. config['pointwiseRegularizer'] =
  30378. regularizers_1.serializeRegularizer(this.pointwiseRegularizer);
  30379. config['depthwiseConstraint'] =
  30380. constraints_1.serializeConstraint(this.depthwiseConstraint);
  30381. config['pointwiseConstraint'] =
  30382. constraints_1.serializeConstraint(this.pointwiseConstraint);
  30383. return config;
  30384. };
  30385. SeparableConv.className = 'SeparableConv';
  30386. return SeparableConv;
  30387. }(Conv));
  30388. exports.SeparableConv = SeparableConv;
  30389. var SeparableConv2D = (function (_super) {
  30390. __extends(SeparableConv2D, _super);
  30391. function SeparableConv2D(config) {
  30392. return _super.call(this, 2, config) || this;
  30393. }
  30394. SeparableConv2D.className = 'SeparableConv2D';
  30395. return SeparableConv2D;
  30396. }(SeparableConv));
  30397. exports.SeparableConv2D = SeparableConv2D;
  30398. tfjs_core_1.serialization.SerializationMap.register(SeparableConv2D);
  30399. var Conv1D = (function (_super) {
  30400. __extends(Conv1D, _super);
  30401. function Conv1D(config) {
  30402. var _this = _super.call(this, 1, config) || this;
  30403. Conv1D.verifyConfig(config);
  30404. _this.inputSpec = [{ ndim: 3 }];
  30405. return _this;
  30406. }
  30407. Conv1D.prototype.getConfig = function () {
  30408. var config = _super.prototype.getConfig.call(this);
  30409. delete config['rank'];
  30410. delete config['dataFormat'];
  30411. return config;
  30412. };
  30413. Conv1D.verifyConfig = function (config) {
  30414. if (typeof config.kernelSize !== 'number' &&
  30415. !generic_utils.checkArrayTypeAndLength(config.kernelSize, 'number', 1, 1))
  30416. throw new errors_1.ValueError("Conv1D expects config.kernelSize to be number or number[] with " +
  30417. ("length 1, but received " + JSON.stringify(config.kernelSize) + "."));
  30418. };
  30419. Conv1D.className = 'Conv1D';
  30420. return Conv1D;
  30421. }(Conv));
  30422. exports.Conv1D = Conv1D;
  30423. tfjs_core_1.serialization.SerializationMap.register(Conv1D);
  30424. var Cropping2D = (function (_super) {
  30425. __extends(Cropping2D, _super);
  30426. function Cropping2D(config) {
  30427. var _this = _super.call(this, config) || this;
  30428. if (typeof config.cropping === 'number')
  30429. _this.cropping = [
  30430. [config.cropping, config.cropping], [config.cropping, config.cropping]
  30431. ];
  30432. else if (typeof config.cropping[0] === 'number')
  30433. _this.cropping = [
  30434. [config.cropping[0], config.cropping[0]],
  30435. [config.cropping[1], config.cropping[1]]
  30436. ];
  30437. else
  30438. _this.cropping = config.cropping;
  30439. _this.dataFormat =
  30440. config.dataFormat === undefined ? 'channelsLast' : config.dataFormat;
  30441. _this.inputSpec = [{ ndim: 4 }];
  30442. return _this;
  30443. }
  30444. Cropping2D.prototype.computeOutputShape = function (inputShape) {
  30445. if (this.dataFormat === 'channelsFirst')
  30446. return [
  30447. inputShape[0], inputShape[1],
  30448. inputShape[2] - this.cropping[0][0] - this.cropping[0][1],
  30449. inputShape[2] - this.cropping[1][0] - this.cropping[1][1]
  30450. ];
  30451. else
  30452. return [
  30453. inputShape[0],
  30454. inputShape[1] - this.cropping[0][0] - this.cropping[0][1],
  30455. inputShape[2] - this.cropping[1][0] - this.cropping[1][1], inputShape[3]
  30456. ];
  30457. };
  30458. Cropping2D.prototype.call = function (inputs, kwargs) {
  30459. var _this = this;
  30460. return tfjs_core_1.tidy(function () {
  30461. inputs = generic_utils.getExactlyOneTensor(inputs);
  30462. if (_this.dataFormat === 'channelsLast') {
  30463. var hSliced = K.sliceAlongAxis(inputs, _this.cropping[0][0], inputs.shape[1] - _this.cropping[0][0] - _this.cropping[0][1], 2);
  30464. return K.sliceAlongAxis(hSliced, _this.cropping[1][0], inputs.shape[2] - _this.cropping[1][1] - _this.cropping[1][0], 3);
  30465. }
  30466. else {
  30467. var hSliced = K.sliceAlongAxis(inputs, _this.cropping[0][0], inputs.shape[2] - _this.cropping[0][0] - _this.cropping[0][1], 3);
  30468. return K.sliceAlongAxis(hSliced, _this.cropping[1][0], inputs.shape[3] - _this.cropping[1][1] - _this.cropping[1][0], 4);
  30469. }
  30470. });
  30471. };
  30472. Cropping2D.prototype.getConfig = function () {
  30473. var config = { cropping: this.cropping, dataFormat: this.dataFormat };
  30474. var baseConfig = _super.prototype.getConfig.call(this);
  30475. Object.assign(config, baseConfig);
  30476. return config;
  30477. };
  30478. Cropping2D.className = 'Cropping2D';
  30479. return Cropping2D;
  30480. }(topology_1.Layer));
  30481. exports.Cropping2D = Cropping2D;
  30482. tfjs_core_1.serialization.SerializationMap.register(Cropping2D);
  30483. var UpSampling2D = (function (_super) {
  30484. __extends(UpSampling2D, _super);
  30485. function UpSampling2D(config) {
  30486. var _this = _super.call(this, config) || this;
  30487. _this.DEFAULT_SIZE = [2, 2];
  30488. _this.inputSpec = [{ ndim: 4 }];
  30489. _this.size = config.size === undefined ? _this.DEFAULT_SIZE : config.size;
  30490. _this.dataFormat =
  30491. config.dataFormat === undefined ? 'channelsLast' : config.dataFormat;
  30492. return _this;
  30493. }
  30494. UpSampling2D.prototype.computeOutputShape = function (inputShape) {
  30495. if (this.dataFormat === 'channelsFirst') {
  30496. var height = this.size[0] * inputShape[2];
  30497. var width = this.size[1] * inputShape[3];
  30498. return [inputShape[0], inputShape[1], height, width];
  30499. }
  30500. else {
  30501. var height = this.size[0] * inputShape[1];
  30502. var width = this.size[1] * inputShape[2];
  30503. return [inputShape[0], height, width, inputShape[3]];
  30504. }
  30505. };
  30506. UpSampling2D.prototype.call = function (inputs, kwargs) {
  30507. var _this = this;
  30508. return tfc.tidy(function () {
  30509. var input = generic_utils.getExactlyOneTensor(inputs);
  30510. var inputShape = input.shape;
  30511. if (_this.dataFormat === 'channelsFirst') {
  30512. input = tfc.transpose(input, [0, 2, 3, 1]);
  30513. var height = _this.size[0] * inputShape[2];
  30514. var width = _this.size[1] * inputShape[3];
  30515. var resized = input.resizeNearestNeighbor([height, width]);
  30516. return tfc.transpose(resized, [0, 3, 1, 2]);
  30517. }
  30518. else {
  30519. var height = _this.size[0] * inputShape[1];
  30520. var width = _this.size[1] * inputShape[2];
  30521. return input.resizeNearestNeighbor([height, width]);
  30522. }
  30523. });
  30524. };
  30525. UpSampling2D.prototype.getConfig = function () {
  30526. var config = { size: this.size, dataFormat: this.dataFormat };
  30527. var baseConfig = _super.prototype.getConfig.call(this);
  30528. Object.assign(config, baseConfig);
  30529. return config;
  30530. };
  30531. UpSampling2D.className = 'UpSampling2D';
  30532. return UpSampling2D;
  30533. }(topology_1.Layer));
  30534. exports.UpSampling2D = UpSampling2D;
  30535. tfjs_core_1.serialization.SerializationMap.register(UpSampling2D);
  30536. },{"../activations":167,"../backend/common":168,"../backend/tfjs_backend":169,"../common":171,"../constraints":172,"../engine/topology":174,"../errors":176,"../initializers":179,"../regularizers":196,"../utils/conv_utils":198,"../utils/generic_utils":199,"@tensorflow/tfjs-core":54}],182:[function(require,module,exports){
  30537. "use strict";
  30538. var __extends = (this && this.__extends) || (function () {
  30539. var extendStatics = Object.setPrototypeOf ||
  30540. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  30541. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  30542. return function (d, b) {
  30543. extendStatics(d, b);
  30544. function __() { this.constructor = d; }
  30545. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  30546. };
  30547. })();
  30548. Object.defineProperty(exports, "__esModule", { value: true });
  30549. var tfc = require("@tensorflow/tfjs-core");
  30550. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  30551. var common_1 = require("../backend/common");
  30552. var K = require("../backend/tfjs_backend");
  30553. var common_2 = require("../common");
  30554. var constraints_1 = require("../constraints");
  30555. var errors_1 = require("../errors");
  30556. var initializers_1 = require("../initializers");
  30557. var regularizers_1 = require("../regularizers");
  30558. var conv_utils_1 = require("../utils/conv_utils");
  30559. var generic_utils_1 = require("../utils/generic_utils");
  30560. var convolutional_1 = require("./convolutional");
  30561. function depthwiseConv2d(x, depthwiseKernel, strides, padding, dataFormat, dilationRate) {
  30562. if (strides === void 0) { strides = [1, 1]; }
  30563. if (padding === void 0) { padding = 'valid'; }
  30564. return tfjs_core_1.tidy(function () {
  30565. if (dataFormat == null) {
  30566. dataFormat = common_1.imageDataFormat();
  30567. }
  30568. common_2.checkDataFormat(dataFormat);
  30569. var y = convolutional_1.preprocessConv2DInput(x, dataFormat);
  30570. if (x.rank !== 4) {
  30571. throw new errors_1.ValueError("Input for depthwiseConv2d is required to be 4-D, but is instead " +
  30572. (x.rank + "-D"));
  30573. }
  30574. if (depthwiseKernel.rank !== 4) {
  30575. throw new errors_1.ValueError("depthwiseKernel is required to be 4-D, but is instead " +
  30576. (depthwiseKernel.rank + "-D"));
  30577. }
  30578. y = tfc.depthwiseConv2d(y, depthwiseKernel, strides, padding === 'same' ? 'same' : 'valid', 'NHWC', dilationRate);
  30579. if (dataFormat === 'channelsFirst') {
  30580. y = tfc.transpose(y, [0, 3, 1, 2]);
  30581. }
  30582. return y;
  30583. });
  30584. }
  30585. exports.depthwiseConv2d = depthwiseConv2d;
  30586. var DepthwiseConv2D = (function (_super) {
  30587. __extends(DepthwiseConv2D, _super);
  30588. function DepthwiseConv2D(config) {
  30589. var _this = _super.call(this, 2, config) || this;
  30590. _this.depthwiseKernel = null;
  30591. _this.depthMultiplier =
  30592. config.depthMultiplier == null ? 1 : config.depthMultiplier;
  30593. _this.depthwiseInitializer = initializers_1.getInitializer(config.depthwiseInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
  30594. _this.depthwiseConstraint = constraints_1.getConstraint(config.depthwiseConstraint);
  30595. _this.depthwiseRegularizer = regularizers_1.getRegularizer(config.depthwiseRegularizer);
  30596. return _this;
  30597. }
  30598. DepthwiseConv2D.prototype.build = function (inputShape) {
  30599. inputShape = generic_utils_1.getExactlyOneShape(inputShape);
  30600. if (inputShape.length < 4) {
  30601. throw new errors_1.ValueError("Inputs to DepthwiseConv2D should have rank 4. " +
  30602. ("Received input shape: " + JSON.stringify(inputShape) + "."));
  30603. }
  30604. var channelAxis = this.dataFormat === 'channelsFirst' ? 1 : 3;
  30605. if (inputShape[channelAxis] == null || inputShape[channelAxis] < 0) {
  30606. throw new errors_1.ValueError('The channel dimension of the inputs to DepthwiseConv2D should ' +
  30607. ("be defined, but is not (" + inputShape[channelAxis] + ")."));
  30608. }
  30609. var inputDim = inputShape[channelAxis];
  30610. var depthwiseKernelShape = [
  30611. this.kernelSize[0], this.kernelSize[1], inputDim, this.depthMultiplier
  30612. ];
  30613. this.depthwiseKernel = this.addWeight('depthwise_kernel', depthwiseKernelShape, null, this.depthwiseInitializer, this.depthwiseRegularizer, true, this.depthwiseConstraint);
  30614. if (this.useBias) {
  30615. this.bias = this.addWeight('bias', [inputDim * this.depthMultiplier], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
  30616. }
  30617. else {
  30618. this.bias = null;
  30619. }
  30620. this.built = true;
  30621. };
  30622. DepthwiseConv2D.prototype.call = function (inputs, kwargs) {
  30623. var _this = this;
  30624. return tfjs_core_1.tidy(function () {
  30625. inputs = generic_utils_1.getExactlyOneTensor(inputs);
  30626. var outputs = depthwiseConv2d(inputs, _this.depthwiseKernel.read(), _this.strides, _this.padding, _this.dataFormat, null);
  30627. if (_this.useBias) {
  30628. outputs = K.biasAdd(outputs, _this.bias.read(), _this.dataFormat);
  30629. }
  30630. if (_this.activation != null) {
  30631. outputs = _this.activation.apply(outputs);
  30632. }
  30633. return outputs;
  30634. });
  30635. };
  30636. DepthwiseConv2D.prototype.computeOutputShape = function (inputShape) {
  30637. inputShape = generic_utils_1.getExactlyOneShape(inputShape);
  30638. var rows = this.dataFormat === 'channelsFirst' ? inputShape[2] : inputShape[1];
  30639. var cols = this.dataFormat === 'channelsFirst' ? inputShape[3] : inputShape[2];
  30640. var outFilters = this.dataFormat === 'channelsFirst' ?
  30641. inputShape[1] * this.depthMultiplier :
  30642. inputShape[3] * this.depthMultiplier;
  30643. var outRows = conv_utils_1.convOutputLength(rows, this.kernelSize[0], this.padding, this.strides[0]);
  30644. var outCols = conv_utils_1.convOutputLength(cols, this.kernelSize[1], this.padding, this.strides[1]);
  30645. if (this.dataFormat === 'channelsFirst') {
  30646. return [inputShape[0], outFilters, outRows, outCols];
  30647. }
  30648. else {
  30649. return [inputShape[0], outRows, outCols, outFilters];
  30650. }
  30651. };
  30652. DepthwiseConv2D.className = 'DepthwiseConv2D';
  30653. return DepthwiseConv2D;
  30654. }(convolutional_1.BaseConv));
  30655. exports.DepthwiseConv2D = DepthwiseConv2D;
  30656. tfjs_core_1.serialization.SerializationMap.register(DepthwiseConv2D);
  30657. },{"../backend/common":168,"../backend/tfjs_backend":169,"../common":171,"../constraints":172,"../errors":176,"../initializers":179,"../regularizers":196,"../utils/conv_utils":198,"../utils/generic_utils":199,"./convolutional":181,"@tensorflow/tfjs-core":54}],183:[function(require,module,exports){
  30658. "use strict";
  30659. var __extends = (this && this.__extends) || (function () {
  30660. var extendStatics = Object.setPrototypeOf ||
  30661. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  30662. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  30663. return function (d, b) {
  30664. extendStatics(d, b);
  30665. function __() { this.constructor = d; }
  30666. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  30667. };
  30668. })();
  30669. Object.defineProperty(exports, "__esModule", { value: true });
  30670. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  30671. var activations_1 = require("../activations");
  30672. var K = require("../backend/tfjs_backend");
  30673. var constraints_1 = require("../constraints");
  30674. var topology_1 = require("../engine/topology");
  30675. var errors_1 = require("../errors");
  30676. var initializers_1 = require("../initializers");
  30677. var regularizers_1 = require("../regularizers");
  30678. var generic_utils = require("../utils/generic_utils");
  30679. var generic_utils_1 = require("../utils/generic_utils");
  30680. var math_utils = require("../utils/math_utils");
  30681. var Dropout = (function (_super) {
  30682. __extends(Dropout, _super);
  30683. function Dropout(config) {
  30684. var _this = _super.call(this, config) || this;
  30685. _this.rate = Math.max(Math.min(config.rate, 1), 0);
  30686. _this.rateScalar = K.getScalar(_this.rate);
  30687. _this.noiseShape = config.noiseShape;
  30688. _this.seed = config.seed;
  30689. if (_this.seed != null) {
  30690. throw new errors_1.NotImplementedError('Non-default seed is not implemented in Dropout layer yet: ' +
  30691. _this.seed);
  30692. }
  30693. _this.supportsMasking = true;
  30694. return _this;
  30695. }
  30696. Dropout.prototype.getNoiseShape = function (input) {
  30697. if (this.noiseShape == null) {
  30698. return this.noiseShape;
  30699. }
  30700. var inputShape = input.shape;
  30701. var noiseShape = [];
  30702. for (var i = 0; i < this.noiseShape.length; ++i) {
  30703. noiseShape.push(this.noiseShape[i] == null ? inputShape[i] : this.noiseShape[i]);
  30704. }
  30705. return noiseShape;
  30706. };
  30707. Dropout.prototype.call = function (inputs, kwargs) {
  30708. var _this = this;
  30709. return tfjs_core_1.tidy(function () {
  30710. _this.invokeCallHook(inputs, kwargs);
  30711. var input = generic_utils.getExactlyOneTensor(inputs);
  30712. if (_this.noiseShape != null &&
  30713. !tfjs_core_1.util.arraysEqual(input.shape, _this.noiseShape)) {
  30714. throw new errors_1.NotImplementedError('Non-default noise shape is not implemented in Dropout ' +
  30715. 'layer yet: ' + JSON.stringify(_this.noiseShape));
  30716. }
  30717. if (0 < _this.rate && _this.rate < 1) {
  30718. var training = kwargs['training'] == null ? false : kwargs['training'];
  30719. var noiseShape_1 = _this.getNoiseShape(input);
  30720. var output = K.inTrainPhase(function () { return K.dropout(input, _this.rateScalar, noiseShape_1, _this.seed); }, function () { return input; }, training);
  30721. return output;
  30722. }
  30723. return inputs;
  30724. });
  30725. };
  30726. Dropout.prototype.getConfig = function () {
  30727. var config = {
  30728. rate: this.rate,
  30729. noiseShape: this.noiseShape,
  30730. seed: this.seed,
  30731. };
  30732. var baseConfig = _super.prototype.getConfig.call(this);
  30733. Object.assign(config, baseConfig);
  30734. return config;
  30735. };
  30736. Dropout.className = 'Dropout';
  30737. return Dropout;
  30738. }(topology_1.Layer));
  30739. exports.Dropout = Dropout;
  30740. tfjs_core_1.serialization.SerializationMap.register(Dropout);
  30741. var Dense = (function (_super) {
  30742. __extends(Dense, _super);
  30743. function Dense(config) {
  30744. var _this = _super.call(this, config) || this;
  30745. _this.activation = null;
  30746. _this.useBias = true;
  30747. _this.kernel = null;
  30748. _this.bias = null;
  30749. _this.DEFAULT_KERNEL_INITIALIZER = 'glorotNormal';
  30750. _this.DEFAULT_BIAS_INITIALIZER = 'zeros';
  30751. if (config.batchInputShape == null && config.inputShape == null &&
  30752. config.inputDim != null) {
  30753. var batchSize = null;
  30754. if (config.batchSize != null) {
  30755. batchSize = config.batchSize;
  30756. }
  30757. _this.batchInputShape = [batchSize, config.inputDim];
  30758. }
  30759. _this.units = config.units;
  30760. _this.activation = activations_1.getActivation(config.activation);
  30761. if (config.useBias != null) {
  30762. _this.useBias = config.useBias;
  30763. }
  30764. _this.kernelInitializer = initializers_1.getInitializer(config.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
  30765. _this.biasInitializer =
  30766. initializers_1.getInitializer(config.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
  30767. _this.kernelConstraint = constraints_1.getConstraint(config.kernelConstraint);
  30768. _this.biasConstraint = constraints_1.getConstraint(config.biasConstraint);
  30769. _this.kernelRegularizer = regularizers_1.getRegularizer(config.kernelRegularizer);
  30770. _this.biasRegularizer = regularizers_1.getRegularizer(config.biasRegularizer);
  30771. _this.activityRegularizer = regularizers_1.getRegularizer(config.activityRegularizer);
  30772. _this.inputSpec = [{ minNDim: 2 }];
  30773. return _this;
  30774. }
  30775. Dense.prototype.build = function (inputShape) {
  30776. inputShape = generic_utils.getExactlyOneShape(inputShape);
  30777. var inputLastDim = inputShape[inputShape.length - 1];
  30778. if (this.kernel == null) {
  30779. this.kernel = this.addWeight('kernel', [inputLastDim, this.units], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
  30780. if (this.useBias) {
  30781. this.bias = this.addWeight('bias', [this.units], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
  30782. }
  30783. }
  30784. this.inputSpec = [{ minNDim: 2, axes: (_a = {}, _a[-1] = inputLastDim, _a) }];
  30785. this.built = true;
  30786. var _a;
  30787. };
  30788. Dense.prototype.computeOutputShape = function (inputShape) {
  30789. inputShape = generic_utils.getExactlyOneShape(inputShape);
  30790. var outputShape = inputShape.slice();
  30791. outputShape[outputShape.length - 1] = this.units;
  30792. return outputShape;
  30793. };
  30794. Dense.prototype.call = function (inputs, kwargs) {
  30795. var _this = this;
  30796. return tfjs_core_1.tidy(function () {
  30797. _this.invokeCallHook(inputs, kwargs);
  30798. var input = generic_utils.getExactlyOneTensor(inputs);
  30799. var output = K.dot(input, _this.kernel.read());
  30800. if (_this.bias != null) {
  30801. output = K.biasAdd(output, _this.bias.read());
  30802. }
  30803. if (_this.activation != null) {
  30804. output = _this.activation.apply(output);
  30805. }
  30806. return output;
  30807. });
  30808. };
  30809. Dense.prototype.getConfig = function () {
  30810. var config = {
  30811. units: this.units,
  30812. activation: activations_1.serializeActivation(this.activation),
  30813. useBias: this.useBias,
  30814. kernelInitializer: initializers_1.serializeInitializer(this.kernelInitializer),
  30815. biasInitializer: initializers_1.serializeInitializer(this.biasInitializer),
  30816. kernelRegularizer: regularizers_1.serializeRegularizer(this.kernelRegularizer),
  30817. biasRegularizer: regularizers_1.serializeRegularizer(this.biasRegularizer),
  30818. activityRegularizer: regularizers_1.serializeRegularizer(this.activityRegularizer),
  30819. kernelConstraint: constraints_1.serializeConstraint(this.kernelConstraint),
  30820. biasConstraint: constraints_1.serializeConstraint(this.biasConstraint)
  30821. };
  30822. var baseConfig = _super.prototype.getConfig.call(this);
  30823. Object.assign(config, baseConfig);
  30824. return config;
  30825. };
  30826. Dense.className = 'Dense';
  30827. return Dense;
  30828. }(topology_1.Layer));
  30829. exports.Dense = Dense;
  30830. tfjs_core_1.serialization.SerializationMap.register(Dense);
  30831. var Flatten = (function (_super) {
  30832. __extends(Flatten, _super);
  30833. function Flatten(config) {
  30834. var _this = _super.call(this, config || {}) || this;
  30835. _this.inputSpec = [{ minNDim: 3 }];
  30836. return _this;
  30837. }
  30838. Flatten.prototype.computeOutputShape = function (inputShape) {
  30839. inputShape = generic_utils.getExactlyOneShape(inputShape);
  30840. for (var _i = 0, _a = inputShape.slice(1); _i < _a.length; _i++) {
  30841. var dim = _a[_i];
  30842. if (dim == null) {
  30843. throw new errors_1.ValueError("The shape of the input to \"Flatten\" is not fully defined " +
  30844. ("(got " + inputShape.slice(1) + "). Make sure to pass a complete ") +
  30845. "\"input_shape\" or \"batch_input_shape\" argument to the first " +
  30846. "layer in your model.");
  30847. }
  30848. }
  30849. return [inputShape[0], math_utils.arrayProd(inputShape, 1)];
  30850. };
  30851. Flatten.prototype.call = function (inputs, kwargs) {
  30852. var _this = this;
  30853. return tfjs_core_1.tidy(function () {
  30854. _this.invokeCallHook(inputs, kwargs);
  30855. return K.batchFlatten(generic_utils.getExactlyOneTensor(inputs));
  30856. });
  30857. };
  30858. Flatten.className = 'Flatten';
  30859. return Flatten;
  30860. }(topology_1.Layer));
  30861. exports.Flatten = Flatten;
  30862. tfjs_core_1.serialization.SerializationMap.register(Flatten);
  30863. var Activation = (function (_super) {
  30864. __extends(Activation, _super);
  30865. function Activation(config) {
  30866. var _this = _super.call(this, config) || this;
  30867. _this.supportsMasking = true;
  30868. _this.activation = activations_1.getActivation(config.activation);
  30869. return _this;
  30870. }
  30871. Activation.prototype.call = function (inputs, kwargs) {
  30872. var _this = this;
  30873. return tfjs_core_1.tidy(function () {
  30874. _this.invokeCallHook(inputs, kwargs);
  30875. var input = generic_utils.getExactlyOneTensor(inputs);
  30876. return _this.activation.apply(input);
  30877. });
  30878. };
  30879. Activation.prototype.getConfig = function () {
  30880. var config = { activation: activations_1.serializeActivation(this.activation) };
  30881. var baseConfig = _super.prototype.getConfig.call(this);
  30882. Object.assign(config, baseConfig);
  30883. return config;
  30884. };
  30885. Activation.className = 'Activation';
  30886. return Activation;
  30887. }(topology_1.Layer));
  30888. exports.Activation = Activation;
  30889. tfjs_core_1.serialization.SerializationMap.register(Activation);
  30890. var RepeatVector = (function (_super) {
  30891. __extends(RepeatVector, _super);
  30892. function RepeatVector(config) {
  30893. var _this = _super.call(this, config) || this;
  30894. _this.n = config.n;
  30895. _this.inputSpec = [{ ndim: 2 }];
  30896. return _this;
  30897. }
  30898. RepeatVector.prototype.computeOutputShape = function (inputShape) {
  30899. return [inputShape[0], this.n, inputShape[1]];
  30900. };
  30901. RepeatVector.prototype.call = function (inputs, kwargs) {
  30902. var _this = this;
  30903. return tfjs_core_1.tidy(function () {
  30904. inputs = generic_utils_1.getExactlyOneTensor(inputs);
  30905. return K.repeat(inputs, _this.n);
  30906. });
  30907. };
  30908. RepeatVector.prototype.getConfig = function () {
  30909. var config = {
  30910. n: this.n,
  30911. };
  30912. var baseConfig = _super.prototype.getConfig.call(this);
  30913. Object.assign(config, baseConfig);
  30914. return config;
  30915. };
  30916. RepeatVector.className = 'RepeatVector';
  30917. return RepeatVector;
  30918. }(topology_1.Layer));
  30919. exports.RepeatVector = RepeatVector;
  30920. tfjs_core_1.serialization.SerializationMap.register(RepeatVector);
  30921. var Reshape = (function (_super) {
  30922. __extends(Reshape, _super);
  30923. function Reshape(config) {
  30924. var _this = _super.call(this, config) || this;
  30925. _this.targetShape = config.targetShape;
  30926. for (var i = 0; i < _this.targetShape.length; ++i) {
  30927. if (_this.isUnknown(_this.targetShape[i])) {
  30928. _this.targetShape[i] = null;
  30929. }
  30930. }
  30931. return _this;
  30932. }
  30933. Reshape.prototype.isUnknown = function (dim) {
  30934. return dim < 0 || dim == null;
  30935. };
  30936. Reshape.prototype.fixUnknownDimension = function (inputShape, outputShape) {
  30937. var errorMsg = 'Total size of new array must be unchanged.';
  30938. var finalShape = outputShape.slice();
  30939. var known = 1;
  30940. var unknown = null;
  30941. for (var i = 0; i < finalShape.length; ++i) {
  30942. var dim = finalShape[i];
  30943. if (this.isUnknown(dim)) {
  30944. if (unknown === null) {
  30945. unknown = i;
  30946. }
  30947. else {
  30948. throw new errors_1.ValueError('Can only specifiy one unknown dimension.');
  30949. }
  30950. }
  30951. else {
  30952. known *= dim;
  30953. }
  30954. }
  30955. var originalSize = math_utils.arrayProd(inputShape);
  30956. if (unknown !== null) {
  30957. if (known === 0 || originalSize % known !== 0) {
  30958. throw new errors_1.ValueError(errorMsg);
  30959. }
  30960. finalShape[unknown] = originalSize / known;
  30961. }
  30962. else if (originalSize !== known) {
  30963. throw new errors_1.ValueError(errorMsg);
  30964. }
  30965. return finalShape;
  30966. };
  30967. Reshape.prototype.computeOutputShape = function (inputShape) {
  30968. var anyUnknownDims = false;
  30969. for (var i = 0; i < inputShape.length; ++i) {
  30970. if (this.isUnknown(inputShape[i])) {
  30971. anyUnknownDims = true;
  30972. break;
  30973. }
  30974. }
  30975. if (anyUnknownDims) {
  30976. return inputShape.slice(0, 1).concat(this.targetShape);
  30977. }
  30978. else {
  30979. return inputShape.slice(0, 1).concat(this.fixUnknownDimension(inputShape.slice(1), this.targetShape));
  30980. }
  30981. };
  30982. Reshape.prototype.call = function (inputs, kwargs) {
  30983. var _this = this;
  30984. return tfjs_core_1.tidy(function () {
  30985. _this.invokeCallHook(inputs, kwargs);
  30986. var input = generic_utils.getExactlyOneTensor(inputs);
  30987. var inputShape = K.shape(input);
  30988. var outputShape = inputShape.slice(0, 1).concat(_this.fixUnknownDimension(inputShape.slice(1), _this.targetShape));
  30989. return input.reshape(outputShape);
  30990. });
  30991. };
  30992. Reshape.prototype.getConfig = function () {
  30993. var config = {
  30994. targetShape: this.targetShape,
  30995. };
  30996. var baseConfig = _super.prototype.getConfig.call(this);
  30997. Object.assign(config, baseConfig);
  30998. return config;
  30999. };
  31000. Reshape.className = 'Reshape';
  31001. return Reshape;
  31002. }(topology_1.Layer));
  31003. exports.Reshape = Reshape;
  31004. tfjs_core_1.serialization.SerializationMap.register(Reshape);
  31005. },{"../activations":167,"../backend/tfjs_backend":169,"../constraints":172,"../engine/topology":174,"../errors":176,"../initializers":179,"../regularizers":196,"../utils/generic_utils":199,"../utils/math_utils":201,"@tensorflow/tfjs-core":54}],184:[function(require,module,exports){
  31006. "use strict";
  31007. var __extends = (this && this.__extends) || (function () {
  31008. var extendStatics = Object.setPrototypeOf ||
  31009. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  31010. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  31011. return function (d, b) {
  31012. extendStatics(d, b);
  31013. function __() { this.constructor = d; }
  31014. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  31015. };
  31016. })();
  31017. Object.defineProperty(exports, "__esModule", { value: true });
  31018. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  31019. var K = require("../backend/tfjs_backend");
  31020. var constraints_1 = require("../constraints");
  31021. var topology_1 = require("../engine/topology");
  31022. var errors_1 = require("../errors");
  31023. var initializers_1 = require("../initializers");
  31024. var regularizers_1 = require("../regularizers");
  31025. var generic_utils = require("../utils/generic_utils");
  31026. var generic_utils_1 = require("../utils/generic_utils");
  31027. var Embedding = (function (_super) {
  31028. __extends(Embedding, _super);
  31029. function Embedding(config) {
  31030. var _this = _super.call(this, config) || this;
  31031. _this.embeddings = null;
  31032. _this.DEFAULT_EMBEDDINGS_INITIALIZER = 'randomUniform';
  31033. if (config.batchInputShape == null && config.inputShape == null) {
  31034. var batchSize = null;
  31035. if (config.batchSize != null) {
  31036. batchSize = config.batchSize;
  31037. }
  31038. if (config.inputLength == null) {
  31039. _this.batchInputShape = [batchSize, null];
  31040. }
  31041. else {
  31042. _this.batchInputShape =
  31043. [batchSize].concat(generic_utils.toList(config.inputLength));
  31044. }
  31045. }
  31046. _this.inputDim = config.inputDim;
  31047. _this.outputDim = config.outputDim;
  31048. _this.embeddingsInitializer = initializers_1.getInitializer(config.embeddingsInitializer || _this.DEFAULT_EMBEDDINGS_INITIALIZER);
  31049. _this.embeddingsRegularizer = regularizers_1.getRegularizer(config.embeddingsRegularizer);
  31050. _this.activityRegularizer = regularizers_1.getRegularizer(config.activityRegularizer);
  31051. _this.embeddingsConstraint = constraints_1.getConstraint(config.embeddingsConstraint);
  31052. _this.maskZero = config.maskZero;
  31053. _this.inputLength = config.inputLength;
  31054. return _this;
  31055. }
  31056. Embedding.prototype.build = function (inputShape) {
  31057. this.embeddings = this.addWeight('embeddings', [this.inputDim, this.outputDim], this.dtype, this.embeddingsInitializer, this.embeddingsRegularizer, true, this.embeddingsConstraint);
  31058. this.built = true;
  31059. };
  31060. Embedding.prototype.computeMask = function (inputs, mask) {
  31061. throw new errors_1.NotImplementedError('computeMask has not been implemented for Embedding yet');
  31062. };
  31063. Embedding.prototype.computeOutputShape = function (inputShape) {
  31064. inputShape = generic_utils.getExactlyOneShape(inputShape);
  31065. if (this.inputLength == null) {
  31066. return inputShape.concat([this.outputDim]);
  31067. }
  31068. var inLens = generic_utils.toList(this.inputLength);
  31069. if (inLens.length !== inputShape.length - 1) {
  31070. throw new errors_1.ValueError("\"inputLength\" is " + this.inputLength + ", but received " +
  31071. ("input shape has shape " + inputShape));
  31072. }
  31073. else {
  31074. var i = 0;
  31075. for (var k = 0; k < inLens.length; ++k) {
  31076. var s1 = inLens[k];
  31077. var s2 = inputShape[k + 1];
  31078. if ((s1 != null) && (s2 != null) && (s1 !== s2)) {
  31079. throw new errors_1.ValueError("\"inputLength\" is " + this.inputLength + ", but received " +
  31080. ("input shape has shape " + inputShape));
  31081. }
  31082. else if (s1 == null) {
  31083. inLens[i] = s2;
  31084. }
  31085. i++;
  31086. }
  31087. }
  31088. return [inputShape[0]].concat(inLens, [this.outputDim]);
  31089. };
  31090. Embedding.prototype.call = function (inputs, kwargs) {
  31091. var _this = this;
  31092. return tfjs_core_1.tidy(function () {
  31093. _this.invokeCallHook(inputs, kwargs);
  31094. var input = generic_utils.getExactlyOneTensor(inputs);
  31095. if (K.dtype(input) !== 'int32') {
  31096. input = K.cast(input, 'int32');
  31097. }
  31098. var output = K.gather(_this.embeddings.read(), input.as1D());
  31099. return output.reshape(generic_utils_1.getExactlyOneShape(_this.computeOutputShape(input.shape)));
  31100. });
  31101. };
  31102. Embedding.prototype.getConfig = function () {
  31103. var config = {
  31104. inputDim: this.inputDim,
  31105. outputDim: this.outputDim,
  31106. embeddingsInitializer: initializers_1.serializeInitializer(this.embeddingsInitializer),
  31107. embeddingsRegularizer: regularizers_1.serializeRegularizer(this.embeddingsRegularizer),
  31108. activityRegularizer: regularizers_1.serializeRegularizer(this.activityRegularizer),
  31109. embeddingsConstraint: constraints_1.serializeConstraint(this.embeddingsConstraint),
  31110. maskZero: this.maskZero,
  31111. inputLength: this.inputLength
  31112. };
  31113. var baseConfig = _super.prototype.getConfig.call(this);
  31114. Object.assign(config, baseConfig);
  31115. return config;
  31116. };
  31117. Embedding.className = 'Embedding';
  31118. return Embedding;
  31119. }(topology_1.Layer));
  31120. exports.Embedding = Embedding;
  31121. tfjs_core_1.serialization.SerializationMap.register(Embedding);
  31122. },{"../backend/tfjs_backend":169,"../constraints":172,"../engine/topology":174,"../errors":176,"../initializers":179,"../regularizers":196,"../utils/generic_utils":199,"@tensorflow/tfjs-core":54}],185:[function(require,module,exports){
  31123. "use strict";
  31124. var __extends = (this && this.__extends) || (function () {
  31125. var extendStatics = Object.setPrototypeOf ||
  31126. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  31127. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  31128. return function (d, b) {
  31129. extendStatics(d, b);
  31130. function __() { this.constructor = d; }
  31131. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  31132. };
  31133. })();
  31134. Object.defineProperty(exports, "__esModule", { value: true });
  31135. var tfc = require("@tensorflow/tfjs-core");
  31136. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  31137. var K = require("../backend/tfjs_backend");
  31138. var topology_1 = require("../engine/topology");
  31139. var errors_1 = require("../errors");
  31140. var generic_utils = require("../utils/generic_utils");
  31141. var mathUtils = require("../utils/math_utils");
  31142. var Merge = (function (_super) {
  31143. __extends(Merge, _super);
  31144. function Merge(config) {
  31145. var _this = _super.call(this, config || {}) || this;
  31146. _this.supportsMasking = true;
  31147. return _this;
  31148. }
  31149. Merge.prototype.mergeFunction = function (inputs) {
  31150. throw new errors_1.NotImplementedError();
  31151. };
  31152. Merge.prototype.computeElementwiseOpOutputShape = function (shape1, shape2) {
  31153. if (shape1 == null || shape2 == null) {
  31154. return null;
  31155. }
  31156. else if (shape1.length < shape2.length) {
  31157. return this.computeElementwiseOpOutputShape(shape2, shape1);
  31158. }
  31159. else if (shape2.length === 0) {
  31160. return shape1;
  31161. }
  31162. var outputShape = shape1.slice(0, shape1.length - shape2.length);
  31163. for (var k = 0; k < shape2.length; ++k) {
  31164. var i = shape1[shape1.length - shape2.length + k];
  31165. var j = shape2[k];
  31166. if (i == null || j == null || i < 0 || j < 0) {
  31167. outputShape.push(null);
  31168. }
  31169. else if (i === 1) {
  31170. outputShape.push(j);
  31171. }
  31172. else if (j === 1) {
  31173. outputShape.push(i);
  31174. }
  31175. else {
  31176. if (i !== j) {
  31177. throw new errors_1.ValueError('Operands could not be broadcast together with shapes ' +
  31178. JSON.stringify(shape1) + ' ' + JSON.stringify(shape2));
  31179. }
  31180. outputShape.push(i);
  31181. }
  31182. }
  31183. return outputShape;
  31184. };
  31185. Merge.prototype.build = function (inputShape) {
  31186. if (Array.isArray(inputShape) && !Array.isArray(inputShape[0])) {
  31187. inputShape = [generic_utils.getExactlyOneShape(inputShape)];
  31188. }
  31189. inputShape = inputShape;
  31190. if (inputShape.length < 2) {
  31191. throw new errors_1.ValueError('A merge layer should be called on an Array of at least 2 inputs.' +
  31192. (" Got " + inputShape.length + " input(s)."));
  31193. }
  31194. var batchSizes = [];
  31195. for (var _i = 0, inputShape_1 = inputShape; _i < inputShape_1.length; _i++) {
  31196. var shape = inputShape_1[_i];
  31197. if (shape != null && shape[0] !== null) {
  31198. batchSizes.push(shape[0]);
  31199. }
  31200. }
  31201. batchSizes = generic_utils.unique(batchSizes);
  31202. if (batchSizes.length > 1) {
  31203. throw new errors_1.ValueError("Can not merge tensors with different batch sizes. " +
  31204. ("Got tensors with shapes: " + JSON.stringify(inputShape) + "."));
  31205. }
  31206. var outputShape = inputShape[0] == null ? null : inputShape[0].slice(1);
  31207. for (var i = 1; i < inputShape.length; ++i) {
  31208. var shape = inputShape[i] == null ? null : inputShape[i].slice(1);
  31209. outputShape = this.computeElementwiseOpOutputShape(outputShape, shape);
  31210. }
  31211. var allRanks = inputShape.map(function (shape) { return shape.length; });
  31212. if (inputShape.indexOf(null) === -1 &&
  31213. generic_utils.unique(allRanks).length === 1) {
  31214. this.reshapeRequired = false;
  31215. }
  31216. else {
  31217. this.reshapeRequired = true;
  31218. }
  31219. };
  31220. Merge.prototype.call = function (inputs, kwargs) {
  31221. var _this = this;
  31222. return tfjs_core_1.tidy(function () {
  31223. inputs = inputs;
  31224. if (_this.reshapeRequired) {
  31225. var reshapedInputs = [];
  31226. var inputDims = inputs.map(function (input) { return input.rank; });
  31227. if (inputDims.indexOf(null) === -1) {
  31228. var maxNDim = mathUtils.max(inputDims);
  31229. for (var _i = 0, inputs_1 = inputs; _i < inputs_1.length; _i++) {
  31230. var x = inputs_1[_i];
  31231. var xNDim = x.rank;
  31232. for (var k = 0; k < maxNDim - xNDim; ++k) {
  31233. x = K.expandDims(x, 1);
  31234. }
  31235. reshapedInputs.push(x);
  31236. }
  31237. return _this.mergeFunction(reshapedInputs);
  31238. }
  31239. else {
  31240. var transposed = false;
  31241. for (var _a = 0, inputs_2 = inputs; _a < inputs_2.length; _a++) {
  31242. var x = inputs_2[_a];
  31243. var xNDim = x.rank;
  31244. if (xNDim == null) {
  31245. var xShape = K.shape(x);
  31246. var batchSize = xShape[0];
  31247. var newShape = xShape.slice(1).concat([batchSize]);
  31248. var xTransposed = x.reshape([batchSize].concat(mathUtils.arrayProd(xShape.slice(1))));
  31249. xTransposed = tfc.transpose(xTransposed, [1, 0]);
  31250. xTransposed = xTransposed.reshape(newShape);
  31251. reshapedInputs.push(xTransposed);
  31252. transposed = true;
  31253. }
  31254. else if (xNDim > 1) {
  31255. var dims = mathUtils.range(1, xNDim).concat([0]);
  31256. reshapedInputs.push(tfc.transpose(x, dims));
  31257. transposed = true;
  31258. }
  31259. else {
  31260. reshapedInputs.push(x);
  31261. }
  31262. }
  31263. var y = _this.mergeFunction(reshapedInputs);
  31264. var yNDim = y.rank;
  31265. if (transposed) {
  31266. if (yNDim == null) {
  31267. var yShape = K.shape(y);
  31268. var yNDim_1 = yShape.length;
  31269. var batchSize = yShape[yNDim_1 - 1];
  31270. var newShape = [batchSize].concat(yShape.slice(0, yShape.length - 1));
  31271. y = tfc.transpose(y.reshape([-1, batchSize]), [1, 0])
  31272. .reshape(newShape);
  31273. }
  31274. else if (yNDim > 1) {
  31275. var dims = [yNDim - 1].concat(mathUtils.range(0, yNDim - 1));
  31276. y = tfc.transpose(y, dims);
  31277. }
  31278. }
  31279. return y;
  31280. }
  31281. }
  31282. else {
  31283. return _this.mergeFunction(inputs);
  31284. }
  31285. });
  31286. };
  31287. Merge.prototype.computeOutputShape = function (inputShape) {
  31288. inputShape = inputShape;
  31289. var outputShape;
  31290. if (inputShape[0] == null) {
  31291. outputShape = null;
  31292. }
  31293. else {
  31294. outputShape = inputShape[0].slice(1);
  31295. }
  31296. for (var i = 1; i < inputShape.length; ++i) {
  31297. var shape = inputShape[i] == null ? null : inputShape[i].slice(1);
  31298. outputShape = this.computeElementwiseOpOutputShape(outputShape, shape);
  31299. }
  31300. var batchSizes = [];
  31301. for (var _i = 0, inputShape_2 = inputShape; _i < inputShape_2.length; _i++) {
  31302. var shape = inputShape_2[_i];
  31303. if (shape != null && shape[0] !== null) {
  31304. batchSizes.push(shape[0]);
  31305. }
  31306. }
  31307. batchSizes = generic_utils.unique(batchSizes);
  31308. if (batchSizes.length === 1) {
  31309. outputShape = batchSizes.concat(outputShape);
  31310. }
  31311. else {
  31312. outputShape = [null].concat(outputShape);
  31313. }
  31314. return outputShape;
  31315. };
  31316. return Merge;
  31317. }(topology_1.Layer));
  31318. exports.Merge = Merge;
  31319. var Add = (function (_super) {
  31320. __extends(Add, _super);
  31321. function Add(config) {
  31322. return _super.call(this, config) || this;
  31323. }
  31324. Add.prototype.mergeFunction = function (inputs) {
  31325. return tfjs_core_1.tidy(function () {
  31326. var output = tfc.zeros(inputs[0].shape);
  31327. for (var _i = 0, inputs_3 = inputs; _i < inputs_3.length; _i++) {
  31328. var input = inputs_3[_i];
  31329. output = tfc.add(output, input);
  31330. }
  31331. return output;
  31332. });
  31333. };
  31334. Add.className = 'Add';
  31335. return Add;
  31336. }(Merge));
  31337. exports.Add = Add;
  31338. tfjs_core_1.serialization.SerializationMap.register(Add);
  31339. function add(config) {
  31340. if (Array.isArray(config)) {
  31341. var layer = new Add({});
  31342. return layer.apply(config);
  31343. }
  31344. else {
  31345. return new Add(config);
  31346. }
  31347. }
  31348. exports.add = add;
  31349. var Multiply = (function (_super) {
  31350. __extends(Multiply, _super);
  31351. function Multiply(config) {
  31352. return _super.call(this, config) || this;
  31353. }
  31354. Multiply.prototype.mergeFunction = function (inputs) {
  31355. return tfjs_core_1.tidy(function () {
  31356. var output = tfc.ones(inputs[0].shape);
  31357. for (var _i = 0, inputs_4 = inputs; _i < inputs_4.length; _i++) {
  31358. var input = inputs_4[_i];
  31359. output = tfc.mul(output, input);
  31360. }
  31361. return output;
  31362. });
  31363. };
  31364. Multiply.className = 'Multiply';
  31365. return Multiply;
  31366. }(Merge));
  31367. exports.Multiply = Multiply;
  31368. tfjs_core_1.serialization.SerializationMap.register(Multiply);
  31369. function multiply(config) {
  31370. if (Array.isArray(config)) {
  31371. var layer = new Multiply({});
  31372. return layer.apply(config);
  31373. }
  31374. else {
  31375. return new Multiply(config);
  31376. }
  31377. }
  31378. exports.multiply = multiply;
  31379. var Average = (function (_super) {
  31380. __extends(Average, _super);
  31381. function Average(config) {
  31382. return _super.call(this, config) || this;
  31383. }
  31384. Average.prototype.mergeFunction = function (inputs) {
  31385. return tfjs_core_1.tidy(function () {
  31386. var output = tfc.zeros(inputs[0].shape);
  31387. for (var _i = 0, inputs_5 = inputs; _i < inputs_5.length; _i++) {
  31388. var input = inputs_5[_i];
  31389. output = tfc.add(output, input);
  31390. }
  31391. return K.scalarTimesArray(K.getScalar(1 / inputs.length), output);
  31392. });
  31393. };
  31394. Average.className = 'Average';
  31395. return Average;
  31396. }(Merge));
  31397. exports.Average = Average;
  31398. tfjs_core_1.serialization.SerializationMap.register(Average);
  31399. function average(config) {
  31400. if (Array.isArray(config)) {
  31401. var layer = new Average({});
  31402. return layer.apply(config);
  31403. }
  31404. else {
  31405. return new Average(config);
  31406. }
  31407. }
  31408. exports.average = average;
  31409. var Maximum = (function (_super) {
  31410. __extends(Maximum, _super);
  31411. function Maximum(config) {
  31412. return _super.call(this, config) || this;
  31413. }
  31414. Maximum.prototype.mergeFunction = function (inputs) {
  31415. return tfjs_core_1.tidy(function () {
  31416. var output = inputs[0];
  31417. for (var i = 1; i < inputs.length; ++i) {
  31418. output = tfc.maximum(output, inputs[i]);
  31419. }
  31420. return output;
  31421. });
  31422. };
  31423. Maximum.className = 'Maximum';
  31424. return Maximum;
  31425. }(Merge));
  31426. exports.Maximum = Maximum;
  31427. tfjs_core_1.serialization.SerializationMap.register(Maximum);
  31428. function maximum(config) {
  31429. if (Array.isArray(config)) {
  31430. var layer = new Maximum({});
  31431. return layer.apply(config);
  31432. }
  31433. else {
  31434. return new Maximum(config);
  31435. }
  31436. }
  31437. exports.maximum = maximum;
  31438. var Minimum = (function (_super) {
  31439. __extends(Minimum, _super);
  31440. function Minimum(config) {
  31441. return _super.call(this, config) || this;
  31442. }
  31443. Minimum.prototype.mergeFunction = function (inputs) {
  31444. return tfjs_core_1.tidy(function () {
  31445. var output = inputs[0];
  31446. for (var i = 1; i < inputs.length; ++i) {
  31447. output = tfc.minimum(output, inputs[i]);
  31448. }
  31449. return output;
  31450. });
  31451. };
  31452. Minimum.className = 'Minimum';
  31453. return Minimum;
  31454. }(Merge));
  31455. exports.Minimum = Minimum;
  31456. tfjs_core_1.serialization.SerializationMap.register(Minimum);
  31457. function minimum(config) {
  31458. if (Array.isArray(config)) {
  31459. var layer = new Minimum({});
  31460. return layer.apply(config);
  31461. }
  31462. else {
  31463. return new Minimum(config);
  31464. }
  31465. }
  31466. exports.minimum = minimum;
  31467. var Concatenate = (function (_super) {
  31468. __extends(Concatenate, _super);
  31469. function Concatenate(config) {
  31470. var _this = _super.call(this, config) || this;
  31471. _this.DEFAULT_AXIS = -1;
  31472. if (config == null) {
  31473. config = {};
  31474. }
  31475. _this.axis = config.axis == null ? _this.DEFAULT_AXIS : config.axis;
  31476. _this.supportsMasking = true;
  31477. _this.reshapeRequired = false;
  31478. return _this;
  31479. }
  31480. Concatenate.prototype.build = function (inputShape) {
  31481. if (!(Array.isArray(inputShape) && Array.isArray(inputShape[0])) ||
  31482. inputShape.length === 1) {
  31483. throw new errors_1.ValueError('A `Concatenate` layer should be called on a list of at least 2 ' +
  31484. 'inputs');
  31485. }
  31486. inputShape = inputShape;
  31487. var allNoneShape = true;
  31488. for (var _i = 0, inputShape_3 = inputShape; _i < inputShape_3.length; _i++) {
  31489. var shape = inputShape_3[_i];
  31490. if (shape != null) {
  31491. allNoneShape = false;
  31492. break;
  31493. }
  31494. }
  31495. if (allNoneShape) {
  31496. return;
  31497. }
  31498. var shapeSet = [];
  31499. for (var i = 0; i < inputShape.length; ++i) {
  31500. var shapeWithoutConcatAxis = inputShape[i].slice();
  31501. shapeWithoutConcatAxis.splice(this.axis, 1);
  31502. var exists = false;
  31503. for (var _a = 0, shapeSet_1 = shapeSet; _a < shapeSet_1.length; _a++) {
  31504. var shape = shapeSet_1[_a];
  31505. if (tfjs_core_1.util.arraysEqual(shape, shapeWithoutConcatAxis)) {
  31506. exists = true;
  31507. break;
  31508. }
  31509. }
  31510. if (!exists) {
  31511. shapeSet.push(shapeWithoutConcatAxis);
  31512. }
  31513. }
  31514. if (shapeSet.length > 1) {
  31515. throw new errors_1.ValueError('A `Concatenate` layer requires inputs with matching shapes ' +
  31516. 'except for the concat axis. Got input shapes: ' +
  31517. JSON.stringify(inputShape));
  31518. }
  31519. };
  31520. Concatenate.prototype.mergeFunction = function (inputs) {
  31521. var _this = this;
  31522. return tfjs_core_1.tidy(function () {
  31523. return K.concatenate(inputs, _this.axis);
  31524. });
  31525. };
  31526. Concatenate.prototype.computeOutputShape = function (inputShape) {
  31527. if (!(Array.isArray(inputShape) && Array.isArray(inputShape[0]))) {
  31528. throw new errors_1.ValueError('A `Concatenate` layer should be called on a list of inputs.');
  31529. }
  31530. var inputShapes = inputShape;
  31531. var outputShape = inputShapes[0].slice();
  31532. var axis = this.axis < 0 ? outputShape.length + this.axis : this.axis;
  31533. for (var _i = 0, _a = inputShapes.slice(1); _i < _a.length; _i++) {
  31534. var shape = _a[_i];
  31535. if (outputShape[axis] == null || shape[axis] == null) {
  31536. outputShape[axis] = null;
  31537. break;
  31538. }
  31539. outputShape[axis] += shape[axis];
  31540. }
  31541. return outputShape;
  31542. };
  31543. Concatenate.prototype.getConfig = function () {
  31544. var config = {
  31545. 'axis': this.axis,
  31546. };
  31547. var baseConfig = _super.prototype.getConfig.call(this);
  31548. Object.assign(config, baseConfig);
  31549. return config;
  31550. };
  31551. Concatenate.className = 'Concatenate';
  31552. return Concatenate;
  31553. }(Merge));
  31554. exports.Concatenate = Concatenate;
  31555. tfjs_core_1.serialization.SerializationMap.register(Concatenate);
  31556. function concatenate(config) {
  31557. if (Array.isArray(config)) {
  31558. var layer = new Concatenate({});
  31559. return layer.apply(config);
  31560. }
  31561. else {
  31562. return new Concatenate(config);
  31563. }
  31564. }
  31565. exports.concatenate = concatenate;
  31566. },{"../backend/tfjs_backend":169,"../engine/topology":174,"../errors":176,"../utils/generic_utils":199,"../utils/math_utils":201,"@tensorflow/tfjs-core":54}],186:[function(require,module,exports){
  31567. "use strict";
  31568. var __extends = (this && this.__extends) || (function () {
  31569. var extendStatics = Object.setPrototypeOf ||
  31570. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  31571. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  31572. return function (d, b) {
  31573. extendStatics(d, b);
  31574. function __() { this.constructor = d; }
  31575. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  31576. };
  31577. })();
  31578. Object.defineProperty(exports, "__esModule", { value: true });
  31579. var tfc = require("@tensorflow/tfjs-core");
  31580. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  31581. var K = require("../backend/tfjs_backend");
  31582. var constraints_1 = require("../constraints");
  31583. var topology_1 = require("../engine/topology");
  31584. var errors_1 = require("../errors");
  31585. var initializers_1 = require("../initializers");
  31586. var regularizers_1 = require("../regularizers");
  31587. var generic_utils = require("../utils/generic_utils");
  31588. var math_utils = require("../utils/math_utils");
  31589. function batchNormalization(x, mean, variance, beta, gamma, epsilon) {
  31590. if (epsilon === void 0) { epsilon = 1e-3; }
  31591. var out;
  31592. if (x.rank === 2) {
  31593. out = tfc.batchNormalization2d(x, mean, variance, epsilon, gamma, beta);
  31594. }
  31595. else if (x.rank === 3) {
  31596. out = tfc.batchNormalization3d(x, mean, variance, epsilon, gamma, beta);
  31597. }
  31598. else if (x.rank === 4) {
  31599. out = tfc.batchNormalization4d(x, mean, variance, epsilon, gamma, beta);
  31600. }
  31601. else {
  31602. throw new errors_1.NotImplementedError("batchNormalization is not implememnted for array of rank " + x.rank + " " +
  31603. "yet");
  31604. }
  31605. return out;
  31606. }
  31607. exports.batchNormalization = batchNormalization;
  31608. function regularNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon) {
  31609. if (epsilon === void 0) { epsilon = 1e-3; }
  31610. return tfjs_core_1.tidy(function () {
  31611. var meanAndVariance = tfc.moments(x, reductionAxes);
  31612. var mean = meanAndVariance.mean;
  31613. var variance = meanAndVariance.variance;
  31614. var normed = batchNormalization(x, mean, variance, beta, gamma, epsilon);
  31615. return [normed, mean, variance];
  31616. });
  31617. }
  31618. function broadcastNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon) {
  31619. if (epsilon === void 0) { epsilon = 1e-3; }
  31620. return tfjs_core_1.tidy(function () {
  31621. var meanAndVariance = tfc.moments(x, reductionAxes);
  31622. var mean = meanAndVariance.mean;
  31623. var variance = meanAndVariance.variance;
  31624. var targetShape = [];
  31625. for (var _i = 0, _a = math_utils.range(0, x.rank); _i < _a.length; _i++) {
  31626. var axis = _a[_i];
  31627. if (reductionAxes.indexOf(axis) !== -1) {
  31628. targetShape.push(1);
  31629. }
  31630. else {
  31631. targetShape.push(x.shape[axis]);
  31632. }
  31633. }
  31634. var broadcastMean = mean.reshape(targetShape);
  31635. var broadcastVariance = variance.reshape(targetShape);
  31636. var broadcastGamma = gamma == null ? null : gamma.reshape(targetShape);
  31637. var broadcastBeta = beta == null ? null : beta.reshape(targetShape);
  31638. var normed = batchNormalization(x, broadcastMean, broadcastVariance, broadcastBeta, broadcastGamma, epsilon);
  31639. return [normed, mean, variance];
  31640. });
  31641. }
  31642. function normalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon) {
  31643. if (epsilon === void 0) { epsilon = 1e-3; }
  31644. if (tfjs_core_1.util.arraysEqual(reductionAxes.slice().sort(), math_utils.range(0, x.rank - 1))) {
  31645. return regularNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon);
  31646. }
  31647. else {
  31648. return broadcastNormalizeBatchInTraining(x, gamma, beta, reductionAxes, epsilon);
  31649. }
  31650. }
  31651. exports.normalizeBatchInTraining = normalizeBatchInTraining;
  31652. var BatchNormalization = (function (_super) {
  31653. __extends(BatchNormalization, _super);
  31654. function BatchNormalization(config) {
  31655. var _this = _super.call(this, config) || this;
  31656. _this.supportsMasking = true;
  31657. _this.axis = config.axis == null ? -1 : config.axis;
  31658. _this.momentum = config.momentum == null ? 0.99 : config.momentum;
  31659. _this.epsilon = config.epsilon == null ? 1e-3 : config.epsilon;
  31660. _this.center = config.center == null ? true : config.center;
  31661. _this.scale = config.scale == null ? true : config.scale;
  31662. _this.betaInitializer = initializers_1.getInitializer(config.betaInitializer || 'zeros');
  31663. _this.gammaInitializer = initializers_1.getInitializer(config.gammaInitializer || 'ones');
  31664. _this.movingMeanInitializer =
  31665. initializers_1.getInitializer(config.movingMeanInitializer || 'zeros');
  31666. _this.movingVarianceInitializer =
  31667. initializers_1.getInitializer(config.movingVarianceInitializer || 'ones');
  31668. _this.betaConstraint = constraints_1.getConstraint(config.betaConstraint);
  31669. _this.gammaConstraint = constraints_1.getConstraint(config.gammaConstraint);
  31670. _this.betaRegularizer = regularizers_1.getRegularizer(config.betaRegularizer);
  31671. _this.gammaRegularizer = regularizers_1.getRegularizer(config.gammaRegularizer);
  31672. _this.stepCount = 0;
  31673. return _this;
  31674. }
  31675. BatchNormalization.prototype.build = function (inputShape) {
  31676. inputShape = generic_utils.getExactlyOneShape(inputShape);
  31677. var axis = this.axis >= 0 ? this.axis : (this.axis + inputShape.length);
  31678. var dim = inputShape[axis];
  31679. if (dim == null) {
  31680. throw new errors_1.ValueError("Axis " + axis + " of input tensor should have a defined dimension but " +
  31681. "the layer received an input with shape " +
  31682. (JSON.stringify(inputShape) + "."));
  31683. }
  31684. this.inputSpec =
  31685. [new topology_1.InputSpec({ ndim: inputShape.length, axes: (_a = {}, _a[axis] = dim, _a) })];
  31686. var shape = [dim];
  31687. if (this.scale) {
  31688. this.gamma = this.addWeight('gamma', shape, null, this.gammaInitializer, this.gammaRegularizer, true, this.gammaConstraint);
  31689. }
  31690. if (this.center) {
  31691. this.beta = this.addWeight('beta', shape, null, this.betaInitializer, this.betaRegularizer, true, this.betaConstraint);
  31692. }
  31693. this.movingMean = this.addWeight('moving_mean', shape, null, this.movingMeanInitializer, null, false);
  31694. this.movingVariance = this.addWeight('moving_variance', shape, null, this.movingVarianceInitializer, null, false);
  31695. this.built = true;
  31696. var _a;
  31697. };
  31698. BatchNormalization.prototype.call = function (inputs, kwargs) {
  31699. var _this = this;
  31700. return tfjs_core_1.tidy(function () {
  31701. var training = kwargs['training'] == null ? false : kwargs['training'];
  31702. var input = generic_utils.getExactlyOneTensor(inputs);
  31703. var inputShape = K.shape(input);
  31704. var ndim = inputShape.length;
  31705. var reductionAxes = math_utils.range(0, ndim);
  31706. var axis = _this.axis >= 0 ? _this.axis : (_this.axis + ndim);
  31707. reductionAxes.splice(axis, 1);
  31708. var broadcastShape = generic_utils.pyListRepeat(1, ndim);
  31709. broadcastShape[axis] = inputShape[axis];
  31710. var sortedReductionAxes = reductionAxes.slice();
  31711. sortedReductionAxes.sort();
  31712. var needsBroadcasting = !tfjs_core_1.util.arraysEqual(sortedReductionAxes, math_utils.range(0, ndim).slice(0, ndim - 1));
  31713. var normalizeInference = function () {
  31714. if (needsBroadcasting) {
  31715. var broadcastMovingMean = _this.movingMean.read().reshape(broadcastShape);
  31716. var broadcastMovingVariance = _this.movingVariance.read().reshape(broadcastShape);
  31717. var broadcastBeta = _this.center ? _this.beta.read().reshape(broadcastShape) : null;
  31718. var broadcastGamma = _this.scale ? _this.gamma.read().reshape(broadcastShape) : null;
  31719. return batchNormalization(input, broadcastMovingMean, broadcastMovingVariance, broadcastBeta, broadcastGamma, _this.epsilon);
  31720. }
  31721. else {
  31722. return batchNormalization(input, _this.movingMean.read(), _this.movingVariance.read(), _this.beta == null ? null : _this.beta.read(), _this.gamma == null ? null : _this.gamma.read(), _this.epsilon);
  31723. }
  31724. };
  31725. if (!training) {
  31726. return normalizeInference();
  31727. }
  31728. var _a = normalizeBatchInTraining(input, _this.gamma.read(), _this.beta.read(), reductionAxes, _this.epsilon), normedTraining = _a[0], mean = _a[1], variance = _a[2];
  31729. var sampleSize = math_utils.arrayProd(reductionAxes.map(function (axis) { return input.shape[axis]; }));
  31730. var varianceDebiased = variance.mul(K.getScalar(sampleSize / (sampleSize - (1 + _this.epsilon))));
  31731. var updateMovingMeanAndVariance = function () {
  31732. _this.stepCount++;
  31733. var newMovingMean = tfc.movingAverage(_this.movingMean.read(), mean, _this.momentum, _this.stepCount);
  31734. _this.movingMean.write(newMovingMean);
  31735. var newMovingVariance = tfc.movingAverage(_this.movingVariance.read(), varianceDebiased, _this.momentum, _this.stepCount);
  31736. _this.movingVariance.write(newMovingVariance);
  31737. };
  31738. updateMovingMeanAndVariance();
  31739. return normedTraining;
  31740. });
  31741. };
  31742. BatchNormalization.prototype.getConfig = function () {
  31743. var config = {
  31744. axis: this.axis,
  31745. momentum: this.momentum,
  31746. epsilon: this.epsilon,
  31747. center: this.center,
  31748. scale: this.scale,
  31749. betaInitializer: initializers_1.serializeInitializer(this.betaInitializer),
  31750. gammaInitializer: initializers_1.serializeInitializer(this.gammaInitializer),
  31751. movingMeanInitializer: initializers_1.serializeInitializer(this.movingMeanInitializer),
  31752. movingVarianceInitializer: initializers_1.serializeInitializer(this.movingVarianceInitializer),
  31753. betaRegularizer: regularizers_1.serializeRegularizer(this.betaRegularizer),
  31754. gammaRegularizer: regularizers_1.serializeRegularizer(this.gammaRegularizer),
  31755. betaConstraint: constraints_1.serializeConstraint(this.betaConstraint),
  31756. gammaConstraint: constraints_1.serializeConstraint(this.gammaConstraint)
  31757. };
  31758. var baseConfig = _super.prototype.getConfig.call(this);
  31759. Object.assign(config, baseConfig);
  31760. return config;
  31761. };
  31762. BatchNormalization.className = 'BatchNormalization';
  31763. return BatchNormalization;
  31764. }(topology_1.Layer));
  31765. exports.BatchNormalization = BatchNormalization;
  31766. tfjs_core_1.serialization.SerializationMap.register(BatchNormalization);
  31767. },{"../backend/tfjs_backend":169,"../constraints":172,"../engine/topology":174,"../errors":176,"../initializers":179,"../regularizers":196,"../utils/generic_utils":199,"../utils/math_utils":201,"@tensorflow/tfjs-core":54}],187:[function(require,module,exports){
  31768. "use strict";
  31769. var __extends = (this && this.__extends) || (function () {
  31770. var extendStatics = Object.setPrototypeOf ||
  31771. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  31772. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  31773. return function (d, b) {
  31774. extendStatics(d, b);
  31775. function __() { this.constructor = d; }
  31776. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  31777. };
  31778. })();
  31779. Object.defineProperty(exports, "__esModule", { value: true });
  31780. var tfc = require("@tensorflow/tfjs-core");
  31781. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  31782. var common_1 = require("../backend/common");
  31783. var topology_1 = require("../engine/topology");
  31784. var errors_1 = require("../errors");
  31785. var generic_utils_1 = require("../utils/generic_utils");
  31786. function temporalPadding(x, padding) {
  31787. return tfjs_core_1.tidy(function () {
  31788. if (x.rank !== 3) {
  31789. throw new errors_1.ValueError("temporalPadding expects input tensor to be 3-D, but received a " +
  31790. (x.rank + "-D tensor."));
  31791. }
  31792. if (padding == null) {
  31793. padding = [1, 1];
  31794. }
  31795. if (padding.length !== 2) {
  31796. throw new errors_1.ValueError("temporalPadding expects input padding pattern to be a length-2 " +
  31797. ("array, but received a length-" + padding.length + " array."));
  31798. }
  31799. var pattern = [[0, 0], padding, [0, 0]];
  31800. return tfc.pad(x, pattern);
  31801. });
  31802. }
  31803. exports.temporalPadding = temporalPadding;
  31804. function spatial2dPadding(x, padding, dataFormat) {
  31805. return tfjs_core_1.tidy(function () {
  31806. if (x.rank !== 4) {
  31807. throw new errors_1.ValueError("temporalPadding expects input tensor to be 4-D, but received a " +
  31808. (x.rank + "-D tensor."));
  31809. }
  31810. if (padding == null) {
  31811. padding = [[1, 1], [1, 1]];
  31812. }
  31813. if (padding.length !== 2 || padding[0].length !== 2 ||
  31814. padding[1].length !== 2) {
  31815. throw new errors_1.ValueError('spatial2dPadding expects `padding` to be an Array of two Arrays, ' +
  31816. 'each of which is an Array of two integers.');
  31817. }
  31818. if (dataFormat == null) {
  31819. dataFormat = common_1.imageDataFormat();
  31820. }
  31821. if (dataFormat !== 'channelsLast' && dataFormat !== 'channelsFirst') {
  31822. throw new errors_1.ValueError("Unknown data format: " + dataFormat + ". " +
  31823. "Supported data formats are 'channelsLast' and 'channelsFirst.");
  31824. }
  31825. var pattern;
  31826. if (dataFormat === 'channelsFirst') {
  31827. pattern = [[0, 0], [0, 0], padding[0], padding[1]];
  31828. }
  31829. else {
  31830. pattern = [[0, 0], padding[0], padding[1], [0, 0]];
  31831. }
  31832. return tfc.pad(x, pattern);
  31833. });
  31834. }
  31835. exports.spatial2dPadding = spatial2dPadding;
  31836. var ZeroPadding2D = (function (_super) {
  31837. __extends(ZeroPadding2D, _super);
  31838. function ZeroPadding2D(config) {
  31839. var _this = this;
  31840. if (config == null) {
  31841. config = {};
  31842. }
  31843. _this = _super.call(this, config) || this;
  31844. _this.dataFormat =
  31845. config.dataFormat == null ? common_1.imageDataFormat() : config.dataFormat;
  31846. if (config.padding == null) {
  31847. _this.padding = [[1, 1], [1, 1]];
  31848. }
  31849. else if (typeof config.padding === 'number') {
  31850. _this.padding =
  31851. [[config.padding, config.padding], [config.padding, config.padding]];
  31852. }
  31853. else {
  31854. config.padding = config.padding;
  31855. if (config.padding.length !== 2) {
  31856. throw new errors_1.ValueError("ZeroPadding2D expects padding to be a length-2 array, but " +
  31857. ("received a length-" + config.padding.length + " array."));
  31858. }
  31859. var heightPadding = void 0;
  31860. var widthPadding = void 0;
  31861. if (typeof config.padding[0] === 'number') {
  31862. heightPadding =
  31863. [config.padding[0], config.padding[0]];
  31864. widthPadding =
  31865. [config.padding[1], config.padding[1]];
  31866. }
  31867. else {
  31868. config.padding = config.padding;
  31869. if (config.padding[0].length !== 2) {
  31870. throw new errors_1.ValueError("ZeroPadding2D expects height padding to be a length-2 array, " +
  31871. ("but received a length-" + config.padding[0].length + " array."));
  31872. }
  31873. heightPadding = config.padding[0];
  31874. if (config.padding[1].length !== 2) {
  31875. throw new errors_1.ValueError("ZeroPadding2D expects width padding to be a length-2 array, " +
  31876. ("but received a length-" + config.padding[1].length + " array."));
  31877. }
  31878. widthPadding = config.padding[1];
  31879. }
  31880. _this.padding = [heightPadding, widthPadding];
  31881. }
  31882. _this.inputSpec = [new topology_1.InputSpec({ ndim: 4 })];
  31883. return _this;
  31884. }
  31885. ZeroPadding2D.prototype.computeOutputShape = function (inputShape) {
  31886. inputShape = generic_utils_1.getExactlyOneShape(inputShape);
  31887. var rows;
  31888. var cols;
  31889. if (this.dataFormat === 'channelsFirst') {
  31890. if (inputShape[2] != null && inputShape[2] >= 0) {
  31891. rows = inputShape[2] + this.padding[0][0] + this.padding[0][1];
  31892. }
  31893. else {
  31894. rows = null;
  31895. }
  31896. if (inputShape[3] != null && inputShape[3] >= 0) {
  31897. cols = inputShape[3] + this.padding[1][0] + this.padding[1][1];
  31898. }
  31899. else {
  31900. cols = null;
  31901. }
  31902. return [inputShape[0], inputShape[1], rows, cols];
  31903. }
  31904. else {
  31905. if (inputShape[1] != null && inputShape[1] >= 0) {
  31906. rows = inputShape[1] + this.padding[0][0] + this.padding[0][1];
  31907. }
  31908. else {
  31909. rows = null;
  31910. }
  31911. if (inputShape[2] != null && inputShape[2] >= 0) {
  31912. cols = inputShape[2] + this.padding[1][0] + this.padding[1][1];
  31913. }
  31914. else {
  31915. cols = null;
  31916. }
  31917. return [inputShape[0], rows, cols, inputShape[3]];
  31918. }
  31919. };
  31920. ZeroPadding2D.prototype.call = function (inputs, kwargs) {
  31921. var _this = this;
  31922. return tfjs_core_1.tidy(function () { return spatial2dPadding(generic_utils_1.getExactlyOneTensor(inputs), _this.padding, _this.dataFormat); });
  31923. };
  31924. ZeroPadding2D.prototype.getConfig = function () {
  31925. var config = {
  31926. padding: this.padding,
  31927. dataFormat: this.dataFormat,
  31928. };
  31929. var baseConfig = _super.prototype.getConfig.call(this);
  31930. Object.assign(config, baseConfig);
  31931. return config;
  31932. };
  31933. ZeroPadding2D.className = 'ZeroPadding2D';
  31934. return ZeroPadding2D;
  31935. }(topology_1.Layer));
  31936. exports.ZeroPadding2D = ZeroPadding2D;
  31937. tfjs_core_1.serialization.SerializationMap.register(ZeroPadding2D);
  31938. },{"../backend/common":168,"../engine/topology":174,"../errors":176,"../utils/generic_utils":199,"@tensorflow/tfjs-core":54}],188:[function(require,module,exports){
  31939. "use strict";
  31940. var __extends = (this && this.__extends) || (function () {
  31941. var extendStatics = Object.setPrototypeOf ||
  31942. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  31943. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  31944. return function (d, b) {
  31945. extendStatics(d, b);
  31946. function __() { this.constructor = d; }
  31947. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  31948. };
  31949. })();
  31950. Object.defineProperty(exports, "__esModule", { value: true });
  31951. var tfc = require("@tensorflow/tfjs-core");
  31952. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  31953. var common_1 = require("../backend/common");
  31954. var K = require("../backend/tfjs_backend");
  31955. var common_2 = require("../common");
  31956. var topology_1 = require("../engine/topology");
  31957. var topology_2 = require("../engine/topology");
  31958. var errors_1 = require("../errors");
  31959. var conv_utils_1 = require("../utils/conv_utils");
  31960. var generic_utils = require("../utils/generic_utils");
  31961. var convolutional_1 = require("./convolutional");
  31962. function pool2d(x, poolSize, strides, padding, dataFormat, poolMode) {
  31963. return tfjs_core_1.tidy(function () {
  31964. common_2.checkDataFormat(dataFormat);
  31965. common_2.checkPoolMode(poolMode);
  31966. common_2.checkPaddingMode(padding);
  31967. if (strides == null) {
  31968. strides = [1, 1];
  31969. }
  31970. if (padding == null) {
  31971. padding = 'valid';
  31972. }
  31973. if (dataFormat == null) {
  31974. dataFormat = common_1.imageDataFormat();
  31975. }
  31976. if (poolMode == null) {
  31977. poolMode = 'max';
  31978. }
  31979. x = convolutional_1.preprocessConv2DInput(x, dataFormat);
  31980. var y;
  31981. var paddingString = (padding === 'same') ? 'same' : 'valid';
  31982. if (poolMode === 'max') {
  31983. y = tfc.maxPool(x, poolSize, strides, paddingString);
  31984. }
  31985. else {
  31986. y = tfc.avgPool(x, poolSize, strides, paddingString);
  31987. }
  31988. if (dataFormat === 'channelsFirst') {
  31989. y = tfc.transpose(y, [0, 3, 1, 2]);
  31990. }
  31991. return y;
  31992. });
  31993. }
  31994. exports.pool2d = pool2d;
  31995. var Pooling1D = (function (_super) {
  31996. __extends(Pooling1D, _super);
  31997. function Pooling1D(config) {
  31998. var _this = this;
  31999. if (config.poolSize == null) {
  32000. config.poolSize = 2;
  32001. }
  32002. _this = _super.call(this, config) || this;
  32003. if (typeof config.poolSize === 'number') {
  32004. _this.poolSize = [config.poolSize];
  32005. }
  32006. else if (Array.isArray(config.poolSize) &&
  32007. config.poolSize.length === 1 &&
  32008. typeof config.poolSize[0] === 'number') {
  32009. _this.poolSize = config.poolSize;
  32010. }
  32011. else {
  32012. throw new errors_1.ValueError("poolSize for 1D convolutional layer must be a number or an " +
  32013. "Array of a single number, but received " +
  32014. ("" + JSON.stringify(config.poolSize)));
  32015. }
  32016. if (config.strides == null) {
  32017. _this.strides = _this.poolSize;
  32018. }
  32019. else {
  32020. if (typeof config.strides === 'number') {
  32021. _this.strides = [config.strides];
  32022. }
  32023. else if (Array.isArray(config.strides) &&
  32024. config.strides.length === 1 &&
  32025. typeof config.strides[0] === 'number') {
  32026. _this.strides = config.strides;
  32027. }
  32028. else {
  32029. throw new errors_1.ValueError("strides for 1D convolutional layer must be a number or an " +
  32030. "Array of a single number, but received " +
  32031. ("" + JSON.stringify(config.strides)));
  32032. }
  32033. }
  32034. _this.padding = config.padding == null ? 'valid' : config.padding;
  32035. common_2.checkPaddingMode(_this.padding);
  32036. _this.inputSpec = [new topology_1.InputSpec({ ndim: 3 })];
  32037. return _this;
  32038. }
  32039. Pooling1D.prototype.computeOutputShape = function (inputShape) {
  32040. inputShape = generic_utils.getExactlyOneShape(inputShape);
  32041. var length = conv_utils_1.convOutputLength(inputShape[1], this.poolSize[0], this.padding, this.strides[0]);
  32042. return [inputShape[0], length, inputShape[2]];
  32043. };
  32044. Pooling1D.prototype.call = function (inputs, kwargs) {
  32045. var _this = this;
  32046. return tfjs_core_1.tidy(function () {
  32047. _this.invokeCallHook(inputs, kwargs);
  32048. inputs = K.expandDims(generic_utils.getExactlyOneTensor(inputs), 2);
  32049. var output = _this.poolingFunction(generic_utils.getExactlyOneTensor(inputs), [_this.poolSize[0], 1], [_this.strides[0], 1], _this.padding, 'channelsLast');
  32050. return tfc.squeeze(output, [2]);
  32051. });
  32052. };
  32053. Pooling1D.prototype.getConfig = function () {
  32054. var config = {
  32055. poolSize: this.poolSize,
  32056. padding: this.padding,
  32057. strides: this.strides,
  32058. };
  32059. var baseConfig = _super.prototype.getConfig.call(this);
  32060. Object.assign(config, baseConfig);
  32061. return config;
  32062. };
  32063. return Pooling1D;
  32064. }(topology_2.Layer));
  32065. exports.Pooling1D = Pooling1D;
  32066. var MaxPooling1D = (function (_super) {
  32067. __extends(MaxPooling1D, _super);
  32068. function MaxPooling1D(config) {
  32069. return _super.call(this, config) || this;
  32070. }
  32071. MaxPooling1D.prototype.poolingFunction = function (inputs, poolSize, strides, padding, dataFormat) {
  32072. common_2.checkDataFormat(dataFormat);
  32073. common_2.checkPaddingMode(padding);
  32074. return pool2d(inputs, poolSize, strides, padding, dataFormat, 'max');
  32075. };
  32076. MaxPooling1D.className = 'MaxPooling1D';
  32077. return MaxPooling1D;
  32078. }(Pooling1D));
  32079. exports.MaxPooling1D = MaxPooling1D;
  32080. tfjs_core_1.serialization.SerializationMap.register(MaxPooling1D);
  32081. var AveragePooling1D = (function (_super) {
  32082. __extends(AveragePooling1D, _super);
  32083. function AveragePooling1D(config) {
  32084. return _super.call(this, config) || this;
  32085. }
  32086. AveragePooling1D.prototype.poolingFunction = function (inputs, poolSize, strides, padding, dataFormat) {
  32087. common_2.checkDataFormat(dataFormat);
  32088. common_2.checkPaddingMode(padding);
  32089. return pool2d(inputs, poolSize, strides, padding, dataFormat, 'avg');
  32090. };
  32091. AveragePooling1D.className = 'AveragePooling1D';
  32092. return AveragePooling1D;
  32093. }(Pooling1D));
  32094. exports.AveragePooling1D = AveragePooling1D;
  32095. tfjs_core_1.serialization.SerializationMap.register(AveragePooling1D);
  32096. var Pooling2D = (function (_super) {
  32097. __extends(Pooling2D, _super);
  32098. function Pooling2D(config) {
  32099. var _this = this;
  32100. if (config.poolSize == null) {
  32101. config.poolSize = [2, 2];
  32102. }
  32103. _this = _super.call(this, config) || this;
  32104. _this.poolSize = Array.isArray(config.poolSize) ?
  32105. config.poolSize :
  32106. [config.poolSize, config.poolSize];
  32107. if (config.strides == null) {
  32108. _this.strides = _this.poolSize;
  32109. }
  32110. else if (Array.isArray(config.strides)) {
  32111. if (config.strides.length !== 2) {
  32112. throw new errors_1.ValueError("If the strides property of a 2D pooling layer is an Array, " +
  32113. "it is expected to have a length of 2, but received length " +
  32114. (config.strides.length + "."));
  32115. }
  32116. _this.strides = config.strides;
  32117. }
  32118. else {
  32119. _this.strides = [config.strides, config.strides];
  32120. }
  32121. _this.padding = config.padding == null ? 'valid' : config.padding;
  32122. _this.dataFormat =
  32123. config.dataFormat == null ? 'channelsLast' : config.dataFormat;
  32124. common_2.checkDataFormat(_this.dataFormat);
  32125. common_2.checkPaddingMode(_this.padding);
  32126. _this.inputSpec = [new topology_1.InputSpec({ ndim: 4 })];
  32127. return _this;
  32128. }
  32129. Pooling2D.prototype.computeOutputShape = function (inputShape) {
  32130. inputShape = generic_utils.getExactlyOneShape(inputShape);
  32131. var rows = this.dataFormat === 'channelsFirst' ? inputShape[2] : inputShape[1];
  32132. var cols = this.dataFormat === 'channelsFirst' ? inputShape[3] : inputShape[2];
  32133. rows =
  32134. conv_utils_1.convOutputLength(rows, this.poolSize[0], this.padding, this.strides[0]);
  32135. cols =
  32136. conv_utils_1.convOutputLength(cols, this.poolSize[1], this.padding, this.strides[1]);
  32137. if (this.dataFormat === 'channelsFirst') {
  32138. return [inputShape[0], inputShape[1], rows, cols];
  32139. }
  32140. else {
  32141. return [inputShape[0], rows, cols, inputShape[3]];
  32142. }
  32143. };
  32144. Pooling2D.prototype.call = function (inputs, kwargs) {
  32145. var _this = this;
  32146. return tfjs_core_1.tidy(function () {
  32147. _this.invokeCallHook(inputs, kwargs);
  32148. return _this.poolingFunction(generic_utils.getExactlyOneTensor(inputs), _this.poolSize, _this.strides, _this.padding, _this.dataFormat);
  32149. });
  32150. };
  32151. Pooling2D.prototype.getConfig = function () {
  32152. var config = {
  32153. poolSize: this.poolSize,
  32154. padding: this.padding,
  32155. strides: this.strides,
  32156. dataFormat: this.dataFormat
  32157. };
  32158. var baseConfig = _super.prototype.getConfig.call(this);
  32159. Object.assign(config, baseConfig);
  32160. return config;
  32161. };
  32162. return Pooling2D;
  32163. }(topology_2.Layer));
  32164. exports.Pooling2D = Pooling2D;
  32165. var MaxPooling2D = (function (_super) {
  32166. __extends(MaxPooling2D, _super);
  32167. function MaxPooling2D(config) {
  32168. return _super.call(this, config) || this;
  32169. }
  32170. MaxPooling2D.prototype.poolingFunction = function (inputs, poolSize, strides, padding, dataFormat) {
  32171. common_2.checkDataFormat(dataFormat);
  32172. common_2.checkPaddingMode(padding);
  32173. return pool2d(inputs, poolSize, strides, padding, dataFormat, 'max');
  32174. };
  32175. MaxPooling2D.className = 'MaxPooling2D';
  32176. return MaxPooling2D;
  32177. }(Pooling2D));
  32178. exports.MaxPooling2D = MaxPooling2D;
  32179. tfjs_core_1.serialization.SerializationMap.register(MaxPooling2D);
  32180. var AveragePooling2D = (function (_super) {
  32181. __extends(AveragePooling2D, _super);
  32182. function AveragePooling2D(config) {
  32183. return _super.call(this, config) || this;
  32184. }
  32185. AveragePooling2D.prototype.poolingFunction = function (inputs, poolSize, strides, padding, dataFormat) {
  32186. common_2.checkDataFormat(dataFormat);
  32187. common_2.checkPaddingMode(padding);
  32188. return pool2d(inputs, poolSize, strides, padding, dataFormat, 'avg');
  32189. };
  32190. AveragePooling2D.className = 'AveragePooling2D';
  32191. return AveragePooling2D;
  32192. }(Pooling2D));
  32193. exports.AveragePooling2D = AveragePooling2D;
  32194. tfjs_core_1.serialization.SerializationMap.register(AveragePooling2D);
  32195. var GlobalPooling1D = (function (_super) {
  32196. __extends(GlobalPooling1D, _super);
  32197. function GlobalPooling1D(config) {
  32198. var _this = _super.call(this, config) || this;
  32199. _this.inputSpec = [new topology_1.InputSpec({ ndim: 3 })];
  32200. return _this;
  32201. }
  32202. GlobalPooling1D.prototype.computeOutputShape = function (inputShape) {
  32203. return [inputShape[0], inputShape[2]];
  32204. };
  32205. GlobalPooling1D.prototype.call = function (inputs, kwargs) {
  32206. throw new errors_1.NotImplementedError();
  32207. };
  32208. return GlobalPooling1D;
  32209. }(topology_2.Layer));
  32210. exports.GlobalPooling1D = GlobalPooling1D;
  32211. var GlobalAveragePooling1D = (function (_super) {
  32212. __extends(GlobalAveragePooling1D, _super);
  32213. function GlobalAveragePooling1D(config) {
  32214. return _super.call(this, config) || this;
  32215. }
  32216. GlobalAveragePooling1D.prototype.call = function (inputs, kwargs) {
  32217. return tfjs_core_1.tidy(function () {
  32218. var input = generic_utils.getExactlyOneTensor(inputs);
  32219. return tfc.mean(input, 1);
  32220. });
  32221. };
  32222. GlobalAveragePooling1D.className = 'GlobalAveragePooling1D';
  32223. return GlobalAveragePooling1D;
  32224. }(GlobalPooling1D));
  32225. exports.GlobalAveragePooling1D = GlobalAveragePooling1D;
  32226. tfjs_core_1.serialization.SerializationMap.register(GlobalAveragePooling1D);
  32227. var GlobalMaxPooling1D = (function (_super) {
  32228. __extends(GlobalMaxPooling1D, _super);
  32229. function GlobalMaxPooling1D(config) {
  32230. return _super.call(this, config) || this;
  32231. }
  32232. GlobalMaxPooling1D.prototype.call = function (inputs, kwargs) {
  32233. return tfjs_core_1.tidy(function () {
  32234. var input = generic_utils.getExactlyOneTensor(inputs);
  32235. return tfc.max(input, 1);
  32236. });
  32237. };
  32238. GlobalMaxPooling1D.className = 'GlobalMaxPooling1D';
  32239. return GlobalMaxPooling1D;
  32240. }(GlobalPooling1D));
  32241. exports.GlobalMaxPooling1D = GlobalMaxPooling1D;
  32242. tfjs_core_1.serialization.SerializationMap.register(GlobalMaxPooling1D);
  32243. var GlobalPooling2D = (function (_super) {
  32244. __extends(GlobalPooling2D, _super);
  32245. function GlobalPooling2D(config) {
  32246. var _this = _super.call(this, config) || this;
  32247. _this.dataFormat =
  32248. config.dataFormat == null ? 'channelsLast' : config.dataFormat;
  32249. common_2.checkDataFormat(_this.dataFormat);
  32250. _this.inputSpec = [new topology_1.InputSpec({ ndim: 4 })];
  32251. return _this;
  32252. }
  32253. GlobalPooling2D.prototype.computeOutputShape = function (inputShape) {
  32254. inputShape = inputShape;
  32255. if (this.dataFormat === 'channelsLast') {
  32256. return [inputShape[0], inputShape[3]];
  32257. }
  32258. else {
  32259. return [inputShape[0], inputShape[1]];
  32260. }
  32261. };
  32262. GlobalPooling2D.prototype.call = function (inputs, kwargs) {
  32263. throw new errors_1.NotImplementedError();
  32264. };
  32265. GlobalPooling2D.prototype.getConfig = function () {
  32266. var config = { dataFormat: this.dataFormat };
  32267. var baseConfig = _super.prototype.getConfig.call(this);
  32268. Object.assign(config, baseConfig);
  32269. return config;
  32270. };
  32271. return GlobalPooling2D;
  32272. }(topology_2.Layer));
  32273. exports.GlobalPooling2D = GlobalPooling2D;
  32274. var GlobalAveragePooling2D = (function (_super) {
  32275. __extends(GlobalAveragePooling2D, _super);
  32276. function GlobalAveragePooling2D() {
  32277. return _super !== null && _super.apply(this, arguments) || this;
  32278. }
  32279. GlobalAveragePooling2D.prototype.call = function (inputs, kwargs) {
  32280. var _this = this;
  32281. return tfjs_core_1.tidy(function () {
  32282. var input = generic_utils.getExactlyOneTensor(inputs);
  32283. if (_this.dataFormat === 'channelsLast') {
  32284. return tfc.mean(input, [1, 2]);
  32285. }
  32286. else {
  32287. return tfc.mean(input, [2, 3]);
  32288. }
  32289. });
  32290. };
  32291. GlobalAveragePooling2D.className = 'GlobalAveragePooling2D';
  32292. return GlobalAveragePooling2D;
  32293. }(GlobalPooling2D));
  32294. exports.GlobalAveragePooling2D = GlobalAveragePooling2D;
  32295. tfjs_core_1.serialization.SerializationMap.register(GlobalAveragePooling2D);
  32296. var GlobalMaxPooling2D = (function (_super) {
  32297. __extends(GlobalMaxPooling2D, _super);
  32298. function GlobalMaxPooling2D() {
  32299. return _super !== null && _super.apply(this, arguments) || this;
  32300. }
  32301. GlobalMaxPooling2D.prototype.call = function (inputs, kwargs) {
  32302. var _this = this;
  32303. return tfjs_core_1.tidy(function () {
  32304. var input = generic_utils.getExactlyOneTensor(inputs);
  32305. if (_this.dataFormat === 'channelsLast') {
  32306. return tfc.max(input, [1, 2]);
  32307. }
  32308. else {
  32309. return tfc.max(input, [2, 3]);
  32310. }
  32311. });
  32312. };
  32313. GlobalMaxPooling2D.className = 'GlobalMaxPooling2D';
  32314. return GlobalMaxPooling2D;
  32315. }(GlobalPooling2D));
  32316. exports.GlobalMaxPooling2D = GlobalMaxPooling2D;
  32317. tfjs_core_1.serialization.SerializationMap.register(GlobalMaxPooling2D);
  32318. },{"../backend/common":168,"../backend/tfjs_backend":169,"../common":171,"../engine/topology":174,"../errors":176,"../utils/conv_utils":198,"../utils/generic_utils":199,"./convolutional":181,"@tensorflow/tfjs-core":54}],189:[function(require,module,exports){
  32319. "use strict";
  32320. var __extends = (this && this.__extends) || (function () {
  32321. var extendStatics = Object.setPrototypeOf ||
  32322. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  32323. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  32324. return function (d, b) {
  32325. extendStatics(d, b);
  32326. function __() { this.constructor = d; }
  32327. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  32328. };
  32329. })();
  32330. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  32331. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  32332. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  32333. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  32334. return c > 3 && r && Object.defineProperty(target, key, r), r;
  32335. };
  32336. Object.defineProperty(exports, "__esModule", { value: true });
  32337. var tfc = require("@tensorflow/tfjs-core");
  32338. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  32339. var activations_1 = require("../activations");
  32340. var K = require("../backend/tfjs_backend");
  32341. var constraints_1 = require("../constraints");
  32342. var topology_1 = require("../engine/topology");
  32343. var topology_2 = require("../engine/topology");
  32344. var errors_1 = require("../errors");
  32345. var initializers_1 = require("../initializers");
  32346. var regularizers_1 = require("../regularizers");
  32347. var types_1 = require("../types");
  32348. var generic_utils = require("../utils/generic_utils");
  32349. var math_utils = require("../utils/math_utils");
  32350. var variables_1 = require("../variables");
  32351. var serialization_1 = require("./serialization");
  32352. function rnn(stepFunction, inputs, initialStates, goBackwards, mask, constants, unroll, inputLength) {
  32353. if (goBackwards === void 0) { goBackwards = false; }
  32354. if (unroll === void 0) { unroll = false; }
  32355. var ndim = inputs.shape.length;
  32356. if (ndim < 3) {
  32357. throw new errors_1.ValueError("Input should be at least 3D, but is " + ndim + "D.");
  32358. }
  32359. var axes = [1, 0].concat(math_utils.range(2, ndim));
  32360. inputs = tfc.transpose(inputs, axes);
  32361. if (mask != null) {
  32362. throw new errors_1.NotImplementedError('The rnn() function of the deeplearn.js backend does not support ' +
  32363. 'masking yet.');
  32364. }
  32365. if (constants != null) {
  32366. throw new errors_1.NotImplementedError('The rnn() functoin of the deeplearn.js backend does not support ' +
  32367. 'constants yet.');
  32368. }
  32369. if (unroll) {
  32370. console.warn('Backend rnn(): the unroll = true option is not applicable to the ' +
  32371. 'imperative deeplearn.js backend.');
  32372. }
  32373. if (goBackwards) {
  32374. inputs = tfc.reverse(inputs, 0);
  32375. }
  32376. var outputs;
  32377. var lastOutput;
  32378. var states = initialStates;
  32379. var timeSteps = inputs.shape[0];
  32380. for (var t = 0; t < timeSteps; ++t) {
  32381. var currentInput = K.sliceAlongFirstAxis(inputs, t, 1);
  32382. currentInput = currentInput.reshape(currentInput.shape.slice(1));
  32383. var stepOutputs = stepFunction(currentInput, states);
  32384. lastOutput = stepOutputs[0];
  32385. if (t === 0) {
  32386. outputs = lastOutput.reshape([1].concat(lastOutput.shape));
  32387. }
  32388. else {
  32389. outputs = K.concatAlongFirstAxis(outputs, lastOutput.reshape([1].concat(lastOutput.shape)));
  32390. }
  32391. states = stepOutputs[1];
  32392. }
  32393. return [
  32394. lastOutput,
  32395. tfc.transpose(outputs, [1, 0].concat(math_utils.range(2, outputs.shape.length))),
  32396. states
  32397. ];
  32398. }
  32399. exports.rnn = rnn;
  32400. var RNN = (function (_super) {
  32401. __extends(RNN, _super);
  32402. function RNN(config) {
  32403. var _this = _super.call(this, config) || this;
  32404. var cell;
  32405. if (config.cell == null) {
  32406. throw new errors_1.ValueError('cell property is missing for the constructor of RNN.');
  32407. }
  32408. else if (Array.isArray(config.cell)) {
  32409. cell = new StackedRNNCells({ cells: config.cell });
  32410. }
  32411. else {
  32412. cell = config.cell;
  32413. }
  32414. if (cell.stateSize == null) {
  32415. throw new errors_1.ValueError('The RNN cell should have an attribute `stateSize` (tuple of ' +
  32416. 'integers, one integer per RNN state).');
  32417. }
  32418. _this.cell = cell;
  32419. _this.returnSequences =
  32420. config.returnSequences == null ? false : config.returnSequences;
  32421. _this.returnState = config.returnState == null ? false : config.returnState;
  32422. _this.goBackwards = config.goBackwards == null ? false : config.goBackwards;
  32423. _this._stateful = config.stateful == null ? false : config.stateful;
  32424. _this.unroll = config.unroll == null ? false : config.unroll;
  32425. _this.supportsMasking = true;
  32426. _this.inputSpec = [new topology_1.InputSpec({ ndim: 3 })];
  32427. _this.stateSpec = null;
  32428. _this.states = null;
  32429. _this.numConstants = null;
  32430. return _this;
  32431. }
  32432. RNN.prototype.getStates = function () {
  32433. if (this.states == null) {
  32434. var numStates = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
  32435. return math_utils.range(0, numStates).map(function (x) { return null; });
  32436. }
  32437. else {
  32438. return this.states;
  32439. }
  32440. };
  32441. RNN.prototype.setStates = function (states) {
  32442. this.states = states;
  32443. };
  32444. RNN.prototype.computeOutputShape = function (inputShape) {
  32445. if (generic_utils.isArrayOfShapes(inputShape)) {
  32446. inputShape = inputShape[0];
  32447. }
  32448. inputShape = inputShape;
  32449. var stateSize = this.cell.stateSize;
  32450. if (!Array.isArray(stateSize)) {
  32451. stateSize = [stateSize];
  32452. }
  32453. var outputDim = stateSize[0];
  32454. var outputShape;
  32455. if (this.returnSequences) {
  32456. outputShape = [inputShape[0], inputShape[1], outputDim];
  32457. }
  32458. else {
  32459. outputShape = [inputShape[0], outputDim];
  32460. }
  32461. if (this.returnState) {
  32462. var stateShape = [];
  32463. for (var _i = 0, stateSize_1 = stateSize; _i < stateSize_1.length; _i++) {
  32464. var dim = stateSize_1[_i];
  32465. stateShape.push([inputShape[0], dim]);
  32466. }
  32467. return [outputShape].concat(stateShape);
  32468. }
  32469. else {
  32470. return outputShape;
  32471. }
  32472. };
  32473. RNN.prototype.computeMask = function (inputs, mask) {
  32474. throw new errors_1.NotImplementedError('computeMask has not been implemented for RNN yet');
  32475. };
  32476. RNN.prototype.build = function (inputShape) {
  32477. var constantShape = null;
  32478. if (this.numConstants != null) {
  32479. throw new errors_1.NotImplementedError('Constants support is not implemented in RNN yet.');
  32480. }
  32481. if (generic_utils.isArrayOfShapes(inputShape)) {
  32482. inputShape = inputShape[0];
  32483. }
  32484. inputShape = inputShape;
  32485. var batchSize = this.stateful ? inputShape[0] : null;
  32486. var inputDim = inputShape[inputShape.length - 1];
  32487. this.inputSpec[0] = new topology_1.InputSpec({ shape: [batchSize, null, inputDim] });
  32488. var stepInputShape = [inputShape[0]].concat(inputShape.slice(2));
  32489. if (constantShape != null) {
  32490. throw new errors_1.NotImplementedError('Constants support is not implemented in RNN yet.');
  32491. }
  32492. else {
  32493. this.cell.build(stepInputShape);
  32494. }
  32495. var stateSize;
  32496. if (Array.isArray(this.cell.stateSize)) {
  32497. stateSize = this.cell.stateSize;
  32498. }
  32499. else {
  32500. stateSize = [this.cell.stateSize];
  32501. }
  32502. if (this.stateSpec != null) {
  32503. if (!tfjs_core_1.util.arraysEqual(this.stateSpec.map(function (spec) { return spec.shape[spec.shape.length - 1]; }), stateSize)) {
  32504. throw new errors_1.ValueError("An initialState was passed that is not compatible with " +
  32505. ("cell.stateSize. Received stateSpec=" + this.stateSpec + "; ") +
  32506. ("However cell.stateSize is " + this.cell.stateSize));
  32507. }
  32508. }
  32509. else {
  32510. this.stateSpec =
  32511. stateSize.map(function (dim) { return new topology_1.InputSpec({ shape: [null, dim] }); });
  32512. }
  32513. if (this.stateful) {
  32514. throw new errors_1.NotImplementedError('stateful RNN layer is not implemented yet');
  32515. }
  32516. };
  32517. RNN.prototype.resetStates = function (states) {
  32518. var _this = this;
  32519. tfjs_core_1.tidy(function () {
  32520. if (!_this.stateful) {
  32521. throw new errors_1.AttributeError('Cannot call resetState() on an RNN Layer that is not stateful.');
  32522. }
  32523. var batchSize = _this.inputSpec[0].shape[0];
  32524. if (batchSize == null) {
  32525. throw new errors_1.ValueError('If an RNN is stateful, it needs to know its batch size. Specify ' +
  32526. 'the batch size of your input tensors: \n' +
  32527. '- If using a Sequential model, specify the batch size by ' +
  32528. 'passing a `batchInputShape` option to your first layer.\n' +
  32529. '- If using the functional API, specify the batch size by ' +
  32530. 'passing a `batchShape` option to your Input layer.');
  32531. }
  32532. if (_this.states == null) {
  32533. if (Array.isArray(_this.cell.stateSize)) {
  32534. _this.states =
  32535. _this.cell.stateSize.map(function (dim) { return tfc.zeros([batchSize, dim]); });
  32536. }
  32537. else {
  32538. _this.states = [tfc.zeros([batchSize, _this.cell.stateSize])];
  32539. }
  32540. }
  32541. else if (states == null) {
  32542. if (Array.isArray(_this.cell.stateSize)) {
  32543. _this.states =
  32544. _this.cell.stateSize.map(function (dim) { return tfc.zeros([batchSize, dim]); });
  32545. }
  32546. else {
  32547. _this.states[0] = tfc.zeros([batchSize, _this.cell.stateSize]);
  32548. }
  32549. }
  32550. else {
  32551. if (!Array.isArray(states)) {
  32552. states = [states];
  32553. }
  32554. if (states.length !== _this.states.length) {
  32555. throw new errors_1.ValueError("Layer " + _this.name + " expects " + _this.states.length + " state(s), " +
  32556. ("but it received " + states.length + " state value(s). Input ") +
  32557. ("received: " + states));
  32558. }
  32559. for (var index = 0; index < _this.states.length; ++index) {
  32560. var value = states[index];
  32561. var dim = Array.isArray(_this.cell.stateSize) ?
  32562. _this.cell.stateSize[index] :
  32563. _this.cell.stateSize;
  32564. var expectedShape = [batchSize, dim];
  32565. if (!tfjs_core_1.util.arraysEqual(value.shape, expectedShape)) {
  32566. throw new errors_1.ValueError("State " + index + " is incompatible with layer " + _this.name + ": " +
  32567. ("expected shape=" + expectedShape + ", received shape=" + value.shape));
  32568. }
  32569. _this.states[index] = value;
  32570. }
  32571. }
  32572. });
  32573. };
  32574. RNN.prototype.standardizeArgs = function (inputs, initialState, constants) {
  32575. if (Array.isArray(inputs)) {
  32576. if (initialState != null || constants != null) {
  32577. throw new errors_1.ValueError('When inputs is an array, neither initialState or constants ' +
  32578. 'should be provided');
  32579. }
  32580. if (this.numConstants != null) {
  32581. constants =
  32582. inputs.slice(inputs.length - this.numConstants, inputs.length);
  32583. inputs = inputs.slice(0, inputs.length - this.numConstants);
  32584. }
  32585. if (inputs.length > 1) {
  32586. initialState = inputs.slice(1, inputs.length);
  32587. }
  32588. inputs = inputs[0];
  32589. }
  32590. function toListOrNull(x) {
  32591. if (x == null || Array.isArray(x)) {
  32592. return x;
  32593. }
  32594. else {
  32595. return [x];
  32596. }
  32597. }
  32598. initialState = toListOrNull(initialState);
  32599. constants = toListOrNull(constants);
  32600. return { inputs: inputs, initialState: initialState, constants: constants };
  32601. };
  32602. RNN.prototype.apply = function (inputs, kwargs) {
  32603. var initialState = kwargs == null ? null : kwargs['initialState'];
  32604. var constants = kwargs == null ? null : kwargs['constants'];
  32605. if (kwargs == null) {
  32606. kwargs = {};
  32607. }
  32608. var standardized = this.standardizeArgs(inputs, initialState, constants);
  32609. inputs = standardized.inputs;
  32610. initialState = standardized.initialState;
  32611. constants = standardized.constants;
  32612. var additionalInputs = [];
  32613. var additionalSpecs = [];
  32614. if (initialState != null) {
  32615. kwargs['initialState'] = initialState;
  32616. additionalInputs = additionalInputs.concat(initialState);
  32617. this.stateSpec = [];
  32618. for (var _i = 0, initialState_1 = initialState; _i < initialState_1.length; _i++) {
  32619. var state = initialState_1[_i];
  32620. this.stateSpec.push(new topology_1.InputSpec({ shape: state.shape }));
  32621. }
  32622. additionalSpecs = additionalSpecs.concat(this.stateSpec);
  32623. }
  32624. if (constants != null) {
  32625. kwargs['constants'] = constants;
  32626. additionalInputs = additionalInputs.concat(constants);
  32627. this.numConstants = constants.length;
  32628. }
  32629. var isTensor = additionalInputs[0] instanceof types_1.SymbolicTensor;
  32630. if (isTensor) {
  32631. var fullInput = [inputs].concat(additionalInputs);
  32632. var fullInputSpec = this.inputSpec.concat(additionalSpecs);
  32633. var originalInputSpec = this.inputSpec;
  32634. this.inputSpec = fullInputSpec;
  32635. var output = _super.prototype.apply.call(this, fullInput, kwargs);
  32636. this.inputSpec = originalInputSpec;
  32637. return output;
  32638. }
  32639. else {
  32640. return _super.prototype.apply.call(this, inputs, kwargs);
  32641. }
  32642. };
  32643. RNN.prototype.call = function (inputs, kwargs) {
  32644. var _this = this;
  32645. return tfjs_core_1.tidy(function () {
  32646. var mask = kwargs == null ? null : kwargs['mask'];
  32647. var training = kwargs == null ? null : kwargs['training'];
  32648. var initialState = kwargs == null ? null : kwargs['initialState'];
  32649. inputs = generic_utils.getExactlyOneTensor(inputs);
  32650. if (initialState == null) {
  32651. if (_this.stateful) {
  32652. throw new errors_1.NotImplementedError('stateful RNN layer is not implemented yet.');
  32653. }
  32654. else {
  32655. initialState = _this.getInitialState(inputs);
  32656. }
  32657. }
  32658. if (mask != null) {
  32659. throw new errors_1.NotImplementedError('Masking is not implemented for RNN yet');
  32660. }
  32661. var numStates = Array.isArray(_this.cell.stateSize) ? _this.cell.stateSize.length : 1;
  32662. if (initialState.length !== numStates) {
  32663. throw new errors_1.ValueError("RNN Layer has " + numStates + " state(s) but was passed " +
  32664. (initialState.length + " initial state(s)."));
  32665. }
  32666. var inputShape = inputs.shape;
  32667. var timesteps = inputShape[1];
  32668. if (_this.unroll) {
  32669. console.warn('Ignoring unroll = true for RNN layer, due to imperative backend.');
  32670. }
  32671. var cellCallKwargs = { training: training };
  32672. var step = function (inputs, states) {
  32673. var outputs = _this.cell.call([inputs].concat(states), cellCallKwargs);
  32674. return [outputs[0], outputs.slice(1)];
  32675. };
  32676. var rnnOutputs = rnn(step, inputs, initialState, _this.goBackwards, null, null, _this.unroll, timesteps);
  32677. var lastOutput = rnnOutputs[0];
  32678. var outputs = rnnOutputs[1];
  32679. var states = rnnOutputs[2];
  32680. if (_this.stateful) {
  32681. throw new errors_1.NotImplementedError('stateful RNN layer is not implemented yet');
  32682. }
  32683. var output = _this.returnSequences ? outputs : lastOutput;
  32684. if (_this.returnState) {
  32685. return [output].concat(states);
  32686. }
  32687. else {
  32688. return output;
  32689. }
  32690. });
  32691. };
  32692. RNN.prototype.getInitialState = function (inputs) {
  32693. var _this = this;
  32694. return tfjs_core_1.tidy(function () {
  32695. var initialState = tfc.zeros(inputs.shape);
  32696. initialState = tfc.sum(initialState, [1, 2]);
  32697. initialState = K.expandDims(initialState);
  32698. if (Array.isArray(_this.cell.stateSize)) {
  32699. return _this.cell.stateSize.map(function (dim) { return dim > 1 ? K.tile(initialState, [1, dim]) : initialState; });
  32700. }
  32701. else {
  32702. return _this.cell.stateSize > 1 ?
  32703. [K.tile(initialState, [1, _this.cell.stateSize])] :
  32704. [initialState];
  32705. }
  32706. });
  32707. };
  32708. Object.defineProperty(RNN.prototype, "trainableWeights", {
  32709. get: function () {
  32710. if (!this.trainable) {
  32711. return [];
  32712. }
  32713. return this.cell.trainableWeights;
  32714. },
  32715. enumerable: true,
  32716. configurable: true
  32717. });
  32718. Object.defineProperty(RNN.prototype, "nonTrainableWeights", {
  32719. get: function () {
  32720. if (!this.trainable) {
  32721. return this.cell.weights;
  32722. }
  32723. return this.cell.nonTrainableWeights;
  32724. },
  32725. enumerable: true,
  32726. configurable: true
  32727. });
  32728. RNN.prototype.getConfig = function () {
  32729. var config = {
  32730. returnSequences: this.returnSequences,
  32731. returnState: this.returnState,
  32732. goBackwards: this.goBackwards,
  32733. stateful: this.stateful,
  32734. unroll: this.unroll,
  32735. };
  32736. if (this.numConstants != null) {
  32737. config.numConstants = this.numConstants;
  32738. }
  32739. var cellConfig = this.cell.getConfig();
  32740. config.cell = {
  32741. className: this.cell.getClassName(),
  32742. config: cellConfig,
  32743. };
  32744. var baseConfig = _super.prototype.getConfig.call(this);
  32745. Object.assign(config, baseConfig);
  32746. return config;
  32747. };
  32748. RNN.className = 'RNN';
  32749. return RNN;
  32750. }(topology_2.Layer));
  32751. exports.RNN = RNN;
  32752. tfjs_core_1.serialization.SerializationMap.register(RNN);
  32753. var RNNCell = (function (_super) {
  32754. __extends(RNNCell, _super);
  32755. function RNNCell() {
  32756. return _super !== null && _super.apply(this, arguments) || this;
  32757. }
  32758. RNNCell = __decorate([
  32759. tfjs_core_1.doc({ heading: 'Layers', subheading: 'Classes' })
  32760. ], RNNCell);
  32761. return RNNCell;
  32762. }(topology_2.Layer));
  32763. exports.RNNCell = RNNCell;
  32764. var SimpleRNNCell = (function (_super) {
  32765. __extends(SimpleRNNCell, _super);
  32766. function SimpleRNNCell(config) {
  32767. var _this = _super.call(this, config) || this;
  32768. _this.DEFAULT_ACTIVATION = 'tanh';
  32769. _this.DEFAULT_KERNEL_INITIALIZER = 'glorotNormal';
  32770. _this.DEFAULT_RECURRENT_INITIALIZER = 'orthogonal';
  32771. _this.DEFAULT_BIAS_INITIALIZER = 'zeros';
  32772. _this.units = config.units;
  32773. _this.activation = activations_1.getActivation(config.activation == null ? _this.DEFAULT_ACTIVATION :
  32774. config.activation);
  32775. _this.useBias = config.useBias == null ? true : config.useBias;
  32776. _this.kernelInitializer = initializers_1.getInitializer(config.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
  32777. _this.recurrentInitializer = initializers_1.getInitializer(config.recurrentInitializer || _this.DEFAULT_RECURRENT_INITIALIZER);
  32778. _this.biasInitializer =
  32779. initializers_1.getInitializer(config.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
  32780. _this.kernelRegularizer = regularizers_1.getRegularizer(config.kernelRegularizer);
  32781. _this.recurrentRegularizer = regularizers_1.getRegularizer(config.recurrentRegularizer);
  32782. _this.biasRegularizer = regularizers_1.getRegularizer(config.biasRegularizer);
  32783. _this.kernelConstraint = constraints_1.getConstraint(config.kernelConstraint);
  32784. _this.recurrentConstraint = constraints_1.getConstraint(config.recurrentConstraint);
  32785. _this.biasConstraint = constraints_1.getConstraint(config.biasConstraint);
  32786. _this.dropout = math_utils.min([1, math_utils.max([0, config.dropout == null ? 0 : config.dropout])]);
  32787. _this.recurrentDropout = math_utils.min([
  32788. 1,
  32789. math_utils.max([0, config.recurrentDropout == null ? 0 : config.recurrentDropout])
  32790. ]);
  32791. _this.stateSize = _this.units;
  32792. return _this;
  32793. }
  32794. SimpleRNNCell.prototype.build = function (inputShape) {
  32795. inputShape = generic_utils.getExactlyOneShape(inputShape);
  32796. this.kernel = this.addWeight('kernel', [inputShape[inputShape.length - 1], this.units], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
  32797. this.recurrentKernel = this.addWeight('recurrent_kernel', [this.units, this.units], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint);
  32798. if (this.useBias) {
  32799. this.bias = this.addWeight('bias', [this.units], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
  32800. }
  32801. else {
  32802. this.bias = null;
  32803. }
  32804. this.built = true;
  32805. };
  32806. SimpleRNNCell.prototype.call = function (inputs, kwargs) {
  32807. var _this = this;
  32808. return tfjs_core_1.tidy(function () {
  32809. inputs = inputs;
  32810. if (inputs.length !== 2) {
  32811. throw new errors_1.ValueError("SimpleRNNCell expects 2 input Tensors, got " + inputs.length + ".");
  32812. }
  32813. var prevOutput = inputs[1];
  32814. inputs = inputs[0];
  32815. if (_this.dropout !== 0 || _this.recurrentDropout !== 0) {
  32816. throw new errors_1.NotImplementedError('Dropout is not implemented for SimpleRNNCell yet');
  32817. }
  32818. var h = K.dot(inputs, _this.kernel.read());
  32819. if (_this.bias != null) {
  32820. h = K.biasAdd(h, _this.bias.read());
  32821. }
  32822. var output = tfc.add(h, K.dot(prevOutput, _this.recurrentKernel.read()));
  32823. if (_this.activation != null) {
  32824. output = _this.activation.apply(output);
  32825. }
  32826. return [output, output];
  32827. });
  32828. };
  32829. SimpleRNNCell.prototype.getConfig = function () {
  32830. var config = {
  32831. units: this.units,
  32832. activation: activations_1.serializeActivation(this.activation),
  32833. useBias: this.useBias,
  32834. kernelInitializer: initializers_1.serializeInitializer(this.kernelInitializer),
  32835. recurrentInitializer: initializers_1.serializeInitializer(this.recurrentInitializer),
  32836. biasInitializer: initializers_1.serializeInitializer(this.biasInitializer),
  32837. kernelRegularizer: regularizers_1.serializeRegularizer(this.kernelRegularizer),
  32838. recurrentRegularizer: regularizers_1.serializeRegularizer(this.recurrentRegularizer),
  32839. biasRegularizer: regularizers_1.serializeRegularizer(this.biasRegularizer),
  32840. activityRegularizer: regularizers_1.serializeRegularizer(this.activityRegularizer),
  32841. kernelConstraint: constraints_1.serializeConstraint(this.kernelConstraint),
  32842. recurrentConstraint: constraints_1.serializeConstraint(this.recurrentConstraint),
  32843. biasConstraint: constraints_1.serializeConstraint(this.biasConstraint),
  32844. dropout: this.dropout,
  32845. recurrentDropout: this.recurrentDropout,
  32846. };
  32847. var baseConfig = _super.prototype.getConfig.call(this);
  32848. Object.assign(config, baseConfig);
  32849. return config;
  32850. };
  32851. SimpleRNNCell.className = 'SimpleRNNCell';
  32852. return SimpleRNNCell;
  32853. }(RNNCell));
  32854. exports.SimpleRNNCell = SimpleRNNCell;
  32855. tfjs_core_1.serialization.SerializationMap.register(SimpleRNNCell);
  32856. var SimpleRNN = (function (_super) {
  32857. __extends(SimpleRNN, _super);
  32858. function SimpleRNN(config) {
  32859. var _this = this;
  32860. config.cell = new SimpleRNNCell(config);
  32861. _this = _super.call(this, config) || this;
  32862. return _this;
  32863. }
  32864. SimpleRNN.prototype.call = function (inputs, kwargs) {
  32865. var _this = this;
  32866. return tfjs_core_1.tidy(function () {
  32867. var mask = kwargs == null ? null : kwargs['mask'];
  32868. var training = kwargs == null ? null : kwargs['training'];
  32869. var initialState = kwargs == null ? null : kwargs['initialState'];
  32870. return _super.prototype.call.call(_this, inputs, { mask: mask, training: training, initialState: initialState });
  32871. });
  32872. };
  32873. Object.defineProperty(SimpleRNN.prototype, "units", {
  32874. get: function () {
  32875. return this.cell.units;
  32876. },
  32877. enumerable: true,
  32878. configurable: true
  32879. });
  32880. Object.defineProperty(SimpleRNN.prototype, "activation", {
  32881. get: function () {
  32882. return this.cell.activation;
  32883. },
  32884. enumerable: true,
  32885. configurable: true
  32886. });
  32887. Object.defineProperty(SimpleRNN.prototype, "useBias", {
  32888. get: function () {
  32889. return this.cell.useBias;
  32890. },
  32891. enumerable: true,
  32892. configurable: true
  32893. });
  32894. Object.defineProperty(SimpleRNN.prototype, "kernelInitializer", {
  32895. get: function () {
  32896. return this.cell.kernelInitializer;
  32897. },
  32898. enumerable: true,
  32899. configurable: true
  32900. });
  32901. Object.defineProperty(SimpleRNN.prototype, "recurrentInitializer", {
  32902. get: function () {
  32903. return this.cell.recurrentInitializer;
  32904. },
  32905. enumerable: true,
  32906. configurable: true
  32907. });
  32908. Object.defineProperty(SimpleRNN.prototype, "biasInitializer", {
  32909. get: function () {
  32910. return this.cell.biasInitializer;
  32911. },
  32912. enumerable: true,
  32913. configurable: true
  32914. });
  32915. Object.defineProperty(SimpleRNN.prototype, "kernelRegularizer", {
  32916. get: function () {
  32917. return this.cell.kernelRegularizer;
  32918. },
  32919. enumerable: true,
  32920. configurable: true
  32921. });
  32922. Object.defineProperty(SimpleRNN.prototype, "recurrentRegularizer", {
  32923. get: function () {
  32924. return this.cell.recurrentRegularizer;
  32925. },
  32926. enumerable: true,
  32927. configurable: true
  32928. });
  32929. Object.defineProperty(SimpleRNN.prototype, "biasRegularizer", {
  32930. get: function () {
  32931. return this.cell.biasRegularizer;
  32932. },
  32933. enumerable: true,
  32934. configurable: true
  32935. });
  32936. Object.defineProperty(SimpleRNN.prototype, "kernelConstraint", {
  32937. get: function () {
  32938. return this.cell.kernelConstraint;
  32939. },
  32940. enumerable: true,
  32941. configurable: true
  32942. });
  32943. Object.defineProperty(SimpleRNN.prototype, "recurrentConstraint", {
  32944. get: function () {
  32945. return this.cell.recurrentConstraint;
  32946. },
  32947. enumerable: true,
  32948. configurable: true
  32949. });
  32950. Object.defineProperty(SimpleRNN.prototype, "biasConstraint", {
  32951. get: function () {
  32952. return this.cell.biasConstraint;
  32953. },
  32954. enumerable: true,
  32955. configurable: true
  32956. });
  32957. Object.defineProperty(SimpleRNN.prototype, "dropout", {
  32958. get: function () {
  32959. return this.cell.dropout;
  32960. },
  32961. enumerable: true,
  32962. configurable: true
  32963. });
  32964. Object.defineProperty(SimpleRNN.prototype, "recurrentDropout", {
  32965. get: function () {
  32966. return this.cell.recurrentDropout;
  32967. },
  32968. enumerable: true,
  32969. configurable: true
  32970. });
  32971. SimpleRNN.prototype.getConfig = function () {
  32972. var config = {
  32973. units: this.units,
  32974. activation: activations_1.serializeActivation(this.activation),
  32975. useBias: this.useBias,
  32976. kernelInitializer: initializers_1.serializeInitializer(this.kernelInitializer),
  32977. recurrentInitializer: initializers_1.serializeInitializer(this.recurrentInitializer),
  32978. biasInitializer: initializers_1.serializeInitializer(this.biasInitializer),
  32979. kernelRegularizer: regularizers_1.serializeRegularizer(this.kernelRegularizer),
  32980. recurrentRegularizer: regularizers_1.serializeRegularizer(this.recurrentRegularizer),
  32981. biasRegularizer: regularizers_1.serializeRegularizer(this.biasRegularizer),
  32982. activityRegularizer: regularizers_1.serializeRegularizer(this.activityRegularizer),
  32983. kernelConstraint: constraints_1.serializeConstraint(this.kernelConstraint),
  32984. recurrentConstraint: constraints_1.serializeConstraint(this.recurrentConstraint),
  32985. biasConstraint: constraints_1.serializeConstraint(this.biasConstraint),
  32986. dropout: this.dropout,
  32987. recurrentDropout: this.recurrentDropout,
  32988. };
  32989. var baseConfig = _super.prototype.getConfig.call(this);
  32990. delete baseConfig['cell'];
  32991. Object.assign(config, baseConfig);
  32992. return config;
  32993. };
  32994. SimpleRNN.className = 'SimpleRNN';
  32995. return SimpleRNN;
  32996. }(RNN));
  32997. exports.SimpleRNN = SimpleRNN;
  32998. tfjs_core_1.serialization.SerializationMap.register(SimpleRNN);
  32999. var GRUCell = (function (_super) {
  33000. __extends(GRUCell, _super);
  33001. function GRUCell(config) {
  33002. var _this = _super.call(this, config) || this;
  33003. _this.DEFAULT_ACTIVATION = 'tanh';
  33004. _this.DEFAULT_RECURRENT_ACTIVATION = 'hardSigmoid';
  33005. _this.DEFAULT_KERNEL_INITIALIZER = 'glorotNormal';
  33006. _this.DEFAULT_RECURRENT_INITIALIZER = 'orthogonal';
  33007. _this.DEFAULT_BIAS_INITIALIZER = 'zeros';
  33008. _this.units = config.units;
  33009. _this.activation = activations_1.getActivation(config.activation === undefined ? _this.DEFAULT_ACTIVATION :
  33010. config.activation);
  33011. _this.recurrentActivation = activations_1.getActivation(config.recurrentActivation === undefined ?
  33012. _this.DEFAULT_RECURRENT_ACTIVATION :
  33013. config.recurrentActivation);
  33014. _this.useBias = config.useBias == null ? true : config.useBias;
  33015. _this.kernelInitializer = initializers_1.getInitializer(config.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
  33016. _this.recurrentInitializer = initializers_1.getInitializer(config.recurrentInitializer || _this.DEFAULT_RECURRENT_INITIALIZER);
  33017. _this.biasInitializer =
  33018. initializers_1.getInitializer(config.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
  33019. _this.kernelRegularizer = regularizers_1.getRegularizer(config.kernelRegularizer);
  33020. _this.recurrentRegularizer = regularizers_1.getRegularizer(config.recurrentRegularizer);
  33021. _this.biasRegularizer = regularizers_1.getRegularizer(config.biasRegularizer);
  33022. _this.kernelConstraint = constraints_1.getConstraint(config.kernelConstraint);
  33023. _this.recurrentConstraint = constraints_1.getConstraint(config.recurrentConstraint);
  33024. _this.biasConstraint = constraints_1.getConstraint(config.biasConstraint);
  33025. _this.dropout = math_utils.min([1, math_utils.max([0, config.dropout == null ? 0 : config.dropout])]);
  33026. _this.recurrentDropout = math_utils.min([
  33027. 1,
  33028. math_utils.max([0, config.recurrentDropout == null ? 0 : config.recurrentDropout])
  33029. ]);
  33030. _this.implementation = config.implementation;
  33031. _this.stateSize = _this.units;
  33032. return _this;
  33033. }
  33034. GRUCell.prototype.build = function (inputShape) {
  33035. inputShape = generic_utils.getExactlyOneShape(inputShape);
  33036. var inputDim = inputShape[inputShape.length - 1];
  33037. this.kernel = this.addWeight('kernel', [inputDim, this.units * 3], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
  33038. this.recurrentKernel = this.addWeight('recurrent_kernel', [this.units, this.units * 3], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint);
  33039. if (this.useBias) {
  33040. this.bias = this.addWeight('bias', [this.units * 3], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint);
  33041. }
  33042. else {
  33043. this.bias = null;
  33044. }
  33045. this.built = true;
  33046. };
  33047. GRUCell.prototype.call = function (inputs, kwargs) {
  33048. var _this = this;
  33049. return tfjs_core_1.tidy(function () {
  33050. if (_this.dropout !== 0 || _this.recurrentDropout !== 0) {
  33051. throw new errors_1.NotImplementedError('Dropout is not implemented for GRUCell yet');
  33052. }
  33053. inputs = inputs;
  33054. if (inputs.length !== 2) {
  33055. throw new errors_1.ValueError("GRUCell expects 2 input Tensors (inputs, h, c), got " +
  33056. (inputs.length + "."));
  33057. }
  33058. var hTMinus1 = inputs[1];
  33059. inputs = inputs[0];
  33060. var z;
  33061. var r;
  33062. var hh;
  33063. if (_this.implementation === 1) {
  33064. var kernelZ = K.sliceAlongLastAxis(_this.kernel.read(), 0, _this.units);
  33065. var kernelR = K.sliceAlongLastAxis(_this.kernel.read(), _this.units, _this.units);
  33066. var kernelH = K.sliceAlongLastAxis(_this.kernel.read(), _this.units * 2, _this.units);
  33067. var recurrentKernelZ = K.sliceAlongLastAxis(_this.recurrentKernel.read(), 0, _this.units);
  33068. var recurrentKernelR = K.sliceAlongLastAxis(_this.recurrentKernel.read(), _this.units, _this.units);
  33069. var recurrentKernelH = K.sliceAlongLastAxis(_this.recurrentKernel.read(), _this.units * 2, _this.units);
  33070. var inputsZ = inputs;
  33071. var inputsR = inputs;
  33072. var inputsH = inputs;
  33073. var xZ = K.dot(inputsZ, kernelZ);
  33074. var xR = K.dot(inputsR, kernelR);
  33075. var xH = K.dot(inputsH, kernelH);
  33076. if (_this.useBias) {
  33077. var biasZ = K.sliceAlongFirstAxis(_this.bias.read(), 0, _this.units);
  33078. var biasR = K.sliceAlongFirstAxis(_this.bias.read(), _this.units, _this.units);
  33079. var biasH = K.sliceAlongFirstAxis(_this.bias.read(), _this.units * 2, _this.units);
  33080. xZ = K.biasAdd(xZ, biasZ);
  33081. xR = K.biasAdd(xR, biasR);
  33082. xH = K.biasAdd(xH, biasH);
  33083. }
  33084. var hTMinus1Z = hTMinus1;
  33085. var hTMinus1R = hTMinus1;
  33086. var hTMinus1H = hTMinus1;
  33087. z = _this.recurrentActivation.apply(tfc.add(xZ, K.dot(hTMinus1Z, recurrentKernelZ)));
  33088. r = _this.recurrentActivation.apply(tfc.add(xR, K.dot(hTMinus1R, recurrentKernelR)));
  33089. hh = _this.activation.apply(tfc.add(xH, K.dot(tfc.mul(r, hTMinus1H), recurrentKernelH)));
  33090. }
  33091. else {
  33092. var matrixX = K.dot(inputs, _this.kernel.read());
  33093. if (_this.useBias) {
  33094. matrixX = K.biasAdd(matrixX, _this.bias.read());
  33095. }
  33096. var matrixInner = K.dot(hTMinus1, K.sliceAlongLastAxis(_this.recurrentKernel.read(), 0, 2 * _this.units));
  33097. var xZ = K.sliceAlongLastAxis(matrixX, 0, _this.units);
  33098. var xR = K.sliceAlongLastAxis(matrixX, _this.units, _this.units);
  33099. var recurrentZ = K.sliceAlongLastAxis(matrixInner, 0, _this.units);
  33100. var recurrentR = K.sliceAlongLastAxis(matrixInner, _this.units, _this.units);
  33101. z = _this.recurrentActivation.apply(tfc.add(xZ, recurrentZ));
  33102. r = _this.recurrentActivation.apply(tfc.add(xR, recurrentR));
  33103. var xH = K.sliceAlongLastAxis(matrixX, 2 * _this.units, _this.units);
  33104. var recurrentH = K.dot(tfc.mul(r, hTMinus1), K.sliceAlongLastAxis(_this.recurrentKernel.read(), 2 * _this.units, _this.units));
  33105. hh = _this.activation.apply(tfc.add(xH, recurrentH));
  33106. }
  33107. var h = tfc.add(tfc.mul(z, hTMinus1), tfc.mul(K.scalarPlusArray(K.getScalar(1), tfc.neg(z)), hh));
  33108. return [h, h];
  33109. });
  33110. };
  33111. GRUCell.prototype.getConfig = function () {
  33112. var config = {
  33113. units: this.units,
  33114. activation: activations_1.serializeActivation(this.activation),
  33115. recurrentActivation: activations_1.serializeActivation(this.recurrentActivation),
  33116. useBias: this.useBias,
  33117. kernelInitializer: initializers_1.serializeInitializer(this.kernelInitializer),
  33118. recurrentInitializer: initializers_1.serializeInitializer(this.recurrentInitializer),
  33119. biasInitializer: initializers_1.serializeInitializer(this.biasInitializer),
  33120. kernelRegularizer: regularizers_1.serializeRegularizer(this.kernelRegularizer),
  33121. recurrentRegularizer: regularizers_1.serializeRegularizer(this.recurrentRegularizer),
  33122. biasRegularizer: regularizers_1.serializeRegularizer(this.biasRegularizer),
  33123. activityRegularizer: regularizers_1.serializeRegularizer(this.activityRegularizer),
  33124. kernelConstraint: constraints_1.serializeConstraint(this.kernelConstraint),
  33125. recurrentConstraint: constraints_1.serializeConstraint(this.recurrentConstraint),
  33126. biasConstraint: constraints_1.serializeConstraint(this.biasConstraint),
  33127. dropout: this.dropout,
  33128. recurrentDropout: this.recurrentDropout,
  33129. implementation: this.implementation,
  33130. };
  33131. var baseConfig = _super.prototype.getConfig.call(this);
  33132. Object.assign(config, baseConfig);
  33133. return config;
  33134. };
  33135. GRUCell.className = 'GRUCell';
  33136. return GRUCell;
  33137. }(RNNCell));
  33138. exports.GRUCell = GRUCell;
  33139. tfjs_core_1.serialization.SerializationMap.register(GRUCell);
  33140. var GRU = (function (_super) {
  33141. __extends(GRU, _super);
  33142. function GRU(config) {
  33143. var _this = this;
  33144. if (config.implementation === 0) {
  33145. console.warn('`implementation=0` has been deprecated, and now defaults to ' +
  33146. '`implementation=1`. Please update your layer call.');
  33147. }
  33148. config.cell = new GRUCell(config);
  33149. _this = _super.call(this, config) || this;
  33150. return _this;
  33151. }
  33152. GRU.prototype.call = function (inputs, kwargs) {
  33153. var _this = this;
  33154. return tfjs_core_1.tidy(function () {
  33155. var mask = kwargs == null ? null : kwargs['mask'];
  33156. var training = kwargs == null ? null : kwargs['training'];
  33157. var initialState = kwargs == null ? null : kwargs['initialState'];
  33158. return _super.prototype.call.call(_this, inputs, { mask: mask, training: training, initialState: initialState });
  33159. });
  33160. };
  33161. Object.defineProperty(GRU.prototype, "units", {
  33162. get: function () {
  33163. return this.cell.units;
  33164. },
  33165. enumerable: true,
  33166. configurable: true
  33167. });
  33168. Object.defineProperty(GRU.prototype, "activation", {
  33169. get: function () {
  33170. return this.cell.activation;
  33171. },
  33172. enumerable: true,
  33173. configurable: true
  33174. });
  33175. Object.defineProperty(GRU.prototype, "recurrentActivation", {
  33176. get: function () {
  33177. return this.cell.recurrentActivation;
  33178. },
  33179. enumerable: true,
  33180. configurable: true
  33181. });
  33182. Object.defineProperty(GRU.prototype, "useBias", {
  33183. get: function () {
  33184. return this.cell.useBias;
  33185. },
  33186. enumerable: true,
  33187. configurable: true
  33188. });
  33189. Object.defineProperty(GRU.prototype, "kernelInitializer", {
  33190. get: function () {
  33191. return this.cell.kernelInitializer;
  33192. },
  33193. enumerable: true,
  33194. configurable: true
  33195. });
  33196. Object.defineProperty(GRU.prototype, "recurrentInitializer", {
  33197. get: function () {
  33198. return this.cell.recurrentInitializer;
  33199. },
  33200. enumerable: true,
  33201. configurable: true
  33202. });
  33203. Object.defineProperty(GRU.prototype, "biasInitializer", {
  33204. get: function () {
  33205. return this.cell.biasInitializer;
  33206. },
  33207. enumerable: true,
  33208. configurable: true
  33209. });
  33210. Object.defineProperty(GRU.prototype, "kernelRegularizer", {
  33211. get: function () {
  33212. return this.cell.kernelRegularizer;
  33213. },
  33214. enumerable: true,
  33215. configurable: true
  33216. });
  33217. Object.defineProperty(GRU.prototype, "recurrentRegularizer", {
  33218. get: function () {
  33219. return this.cell.recurrentRegularizer;
  33220. },
  33221. enumerable: true,
  33222. configurable: true
  33223. });
  33224. Object.defineProperty(GRU.prototype, "biasRegularizer", {
  33225. get: function () {
  33226. return this.cell.biasRegularizer;
  33227. },
  33228. enumerable: true,
  33229. configurable: true
  33230. });
  33231. Object.defineProperty(GRU.prototype, "kernelConstraint", {
  33232. get: function () {
  33233. return this.cell.kernelConstraint;
  33234. },
  33235. enumerable: true,
  33236. configurable: true
  33237. });
  33238. Object.defineProperty(GRU.prototype, "recurrentConstraint", {
  33239. get: function () {
  33240. return this.cell.recurrentConstraint;
  33241. },
  33242. enumerable: true,
  33243. configurable: true
  33244. });
  33245. Object.defineProperty(GRU.prototype, "biasConstraint", {
  33246. get: function () {
  33247. return this.cell.biasConstraint;
  33248. },
  33249. enumerable: true,
  33250. configurable: true
  33251. });
  33252. Object.defineProperty(GRU.prototype, "dropout", {
  33253. get: function () {
  33254. return this.cell.dropout;
  33255. },
  33256. enumerable: true,
  33257. configurable: true
  33258. });
  33259. Object.defineProperty(GRU.prototype, "recurrentDropout", {
  33260. get: function () {
  33261. return this.cell.recurrentDropout;
  33262. },
  33263. enumerable: true,
  33264. configurable: true
  33265. });
  33266. Object.defineProperty(GRU.prototype, "implementation", {
  33267. get: function () {
  33268. return this.cell.implementation;
  33269. },
  33270. enumerable: true,
  33271. configurable: true
  33272. });
  33273. GRU.prototype.getConfig = function () {
  33274. var config = {
  33275. units: this.units,
  33276. activation: activations_1.serializeActivation(this.activation),
  33277. recurrentActivation: activations_1.serializeActivation(this.recurrentActivation),
  33278. useBias: this.useBias,
  33279. kernelInitializer: initializers_1.serializeInitializer(this.kernelInitializer),
  33280. recurrentInitializer: initializers_1.serializeInitializer(this.recurrentInitializer),
  33281. biasInitializer: initializers_1.serializeInitializer(this.biasInitializer),
  33282. kernelRegularizer: regularizers_1.serializeRegularizer(this.kernelRegularizer),
  33283. recurrentRegularizer: regularizers_1.serializeRegularizer(this.recurrentRegularizer),
  33284. biasRegularizer: regularizers_1.serializeRegularizer(this.biasRegularizer),
  33285. activityRegularizer: regularizers_1.serializeRegularizer(this.activityRegularizer),
  33286. kernelConstraint: constraints_1.serializeConstraint(this.kernelConstraint),
  33287. recurrentConstraint: constraints_1.serializeConstraint(this.recurrentConstraint),
  33288. biasConstraint: constraints_1.serializeConstraint(this.biasConstraint),
  33289. dropout: this.dropout,
  33290. recurrentDropout: this.recurrentDropout,
  33291. implementation: this.implementation,
  33292. };
  33293. var baseConfig = _super.prototype.getConfig.call(this);
  33294. delete baseConfig['cell'];
  33295. Object.assign(config, baseConfig);
  33296. return config;
  33297. };
  33298. GRU.fromConfig = function (cls, config) {
  33299. if (config['implmentation'] === 0) {
  33300. config['implementation'] = 1;
  33301. }
  33302. return new cls(config);
  33303. };
  33304. GRU.className = 'GRU';
  33305. return GRU;
  33306. }(RNN));
  33307. exports.GRU = GRU;
  33308. tfjs_core_1.serialization.SerializationMap.register(GRU);
  33309. var LSTMCell = (function (_super) {
  33310. __extends(LSTMCell, _super);
  33311. function LSTMCell(config) {
  33312. var _this = _super.call(this, config) || this;
  33313. _this.DEFAULT_ACTIVATION = 'tanh';
  33314. _this.DEFAULT_RECURRENT_ACTIVATION = 'hardSigmoid';
  33315. _this.DEFAULT_KERNEL_INITIALIZER = 'glorotNormal';
  33316. _this.DEFAULT_RECURRENT_INITIALIZER = 'orthogonal';
  33317. _this.DEFAULT_BIAS_INITIALIZER = 'zeros';
  33318. _this.units = config.units;
  33319. _this.activation = activations_1.getActivation(config.activation === undefined ? _this.DEFAULT_ACTIVATION :
  33320. config.activation);
  33321. _this.recurrentActivation = activations_1.getActivation(config.recurrentActivation === undefined ?
  33322. _this.DEFAULT_RECURRENT_ACTIVATION :
  33323. config.recurrentActivation);
  33324. _this.useBias = config.useBias == null ? true : config.useBias;
  33325. _this.kernelInitializer = initializers_1.getInitializer(config.kernelInitializer || _this.DEFAULT_KERNEL_INITIALIZER);
  33326. _this.recurrentInitializer = initializers_1.getInitializer(config.recurrentInitializer || _this.DEFAULT_RECURRENT_INITIALIZER);
  33327. _this.biasInitializer =
  33328. initializers_1.getInitializer(config.biasInitializer || _this.DEFAULT_BIAS_INITIALIZER);
  33329. _this.unitForgetBias = config.unitForgetBias;
  33330. _this.kernelRegularizer = regularizers_1.getRegularizer(config.kernelRegularizer);
  33331. _this.recurrentRegularizer = regularizers_1.getRegularizer(config.recurrentRegularizer);
  33332. _this.biasRegularizer = regularizers_1.getRegularizer(config.biasRegularizer);
  33333. _this.kernelConstraint = constraints_1.getConstraint(config.kernelConstraint);
  33334. _this.recurrentConstraint = constraints_1.getConstraint(config.recurrentConstraint);
  33335. _this.biasConstraint = constraints_1.getConstraint(config.biasConstraint);
  33336. _this.dropout = math_utils.min([1, math_utils.max([0, config.dropout == null ? 0 : config.dropout])]);
  33337. _this.recurrentDropout = math_utils.min([
  33338. 1,
  33339. math_utils.max([0, config.recurrentDropout == null ? 0 : config.recurrentDropout])
  33340. ]);
  33341. _this.implementation = config.implementation;
  33342. _this.stateSize = [_this.units, _this.units];
  33343. return _this;
  33344. }
  33345. LSTMCell.prototype.build = function (inputShape) {
  33346. inputShape = generic_utils.getExactlyOneShape(inputShape);
  33347. var inputDim = inputShape[inputShape.length - 1];
  33348. this.kernel = this.addWeight('kernel', [inputDim, this.units * 4], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
  33349. this.recurrentKernel = this.addWeight('recurrent_kernel', [this.units, this.units * 4], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint);
  33350. var biasInitializer;
  33351. if (this.useBias) {
  33352. if (this.unitForgetBias) {
  33353. var capturedBiasInit_1 = this.biasInitializer;
  33354. var capturedUnits_1 = this.units;
  33355. biasInitializer = new (_a = (function (_super) {
  33356. __extends(CustomInit, _super);
  33357. function CustomInit() {
  33358. return _super !== null && _super.apply(this, arguments) || this;
  33359. }
  33360. CustomInit.prototype.apply = function (shape, dtype) {
  33361. var bI = capturedBiasInit_1.apply([capturedUnits_1]);
  33362. var bF = (new initializers_1.Ones()).apply([capturedUnits_1]);
  33363. var bCAndH = capturedBiasInit_1.apply([capturedUnits_1 * 2]);
  33364. return K.concatAlongFirstAxis(K.concatAlongFirstAxis(bI, bF), bCAndH);
  33365. };
  33366. return CustomInit;
  33367. }(initializers_1.Initializer)),
  33368. _a.className = 'CustomInit',
  33369. _a)();
  33370. }
  33371. else {
  33372. biasInitializer = this.biasInitializer;
  33373. }
  33374. this.bias = this.addWeight('bias', [this.units * 4], null, biasInitializer, this.biasRegularizer, true, this.biasConstraint);
  33375. }
  33376. else {
  33377. this.bias = null;
  33378. }
  33379. this.built = true;
  33380. var _a;
  33381. };
  33382. LSTMCell.prototype.call = function (inputs, kwargs) {
  33383. var _this = this;
  33384. return tfjs_core_1.tidy(function () {
  33385. if (_this.dropout !== 0 || _this.recurrentDropout !== 0) {
  33386. throw new errors_1.NotImplementedError('Dropout is not implemented for LSTMCell yet');
  33387. }
  33388. inputs = inputs;
  33389. if (inputs.length !== 3) {
  33390. throw new errors_1.ValueError("LSTMCell expects 3 input Tensors (inputs, h, c), got " +
  33391. (inputs.length + "."));
  33392. }
  33393. var hTMinus1 = inputs[1];
  33394. var cTMinus1 = inputs[2];
  33395. inputs = inputs[0];
  33396. var i;
  33397. var f;
  33398. var c;
  33399. var o;
  33400. if (_this.implementation === 1) {
  33401. var kernelI = K.sliceAlongLastAxis(_this.kernel.read(), 0, _this.units);
  33402. var kernelF = K.sliceAlongLastAxis(_this.kernel.read(), _this.units, _this.units);
  33403. var kernelC = K.sliceAlongLastAxis(_this.kernel.read(), _this.units * 2, _this.units);
  33404. var kernelO = K.sliceAlongLastAxis(_this.kernel.read(), _this.units * 3, _this.units);
  33405. var recurrentKernelI = K.sliceAlongLastAxis(_this.recurrentKernel.read(), 0, _this.units);
  33406. var recurrentKernelF = K.sliceAlongLastAxis(_this.recurrentKernel.read(), _this.units, _this.units);
  33407. var recurrentKernelC = K.sliceAlongLastAxis(_this.recurrentKernel.read(), _this.units * 2, _this.units);
  33408. var recurrentKernelO = K.sliceAlongLastAxis(_this.recurrentKernel.read(), _this.units * 3, _this.units);
  33409. var inputsI = inputs;
  33410. var inputsF = inputs;
  33411. var inputsC = inputs;
  33412. var inputsO = inputs;
  33413. var xI = K.dot(inputsI, kernelI);
  33414. var xF = K.dot(inputsF, kernelF);
  33415. var xC = K.dot(inputsC, kernelC);
  33416. var xO = K.dot(inputsO, kernelO);
  33417. if (_this.useBias) {
  33418. var biasI = K.sliceAlongFirstAxis(_this.bias.read(), 0, _this.units);
  33419. var biasF = K.sliceAlongFirstAxis(_this.bias.read(), _this.units, _this.units);
  33420. var biasC = K.sliceAlongFirstAxis(_this.bias.read(), _this.units * 2, _this.units);
  33421. var biasO = K.sliceAlongFirstAxis(_this.bias.read(), _this.units * 3, _this.units);
  33422. xI = K.biasAdd(xI, biasI);
  33423. xF = K.biasAdd(xF, biasF);
  33424. xC = K.biasAdd(xC, biasC);
  33425. xO = K.biasAdd(xO, biasO);
  33426. }
  33427. var hTMinus1I = hTMinus1;
  33428. var hTMinus1F = hTMinus1;
  33429. var hTMinus1C = hTMinus1;
  33430. var hTMinus1O = hTMinus1;
  33431. i = _this.recurrentActivation.apply(tfc.add(xI, K.dot(hTMinus1I, recurrentKernelI)));
  33432. f = _this.recurrentActivation.apply(tfc.add(xF, K.dot(hTMinus1F, recurrentKernelF)));
  33433. c = tfc.add(tfc.mul(f, cTMinus1), tfc.mul(i, _this.activation.apply(tfc.add(xC, K.dot(hTMinus1C, recurrentKernelC)))));
  33434. o = _this.recurrentActivation.apply(tfc.add(xO, K.dot(hTMinus1O, recurrentKernelO)));
  33435. }
  33436. else {
  33437. var z = K.dot(inputs, _this.kernel.read());
  33438. z = tfc.add(z, K.dot(hTMinus1, _this.recurrentKernel.read()));
  33439. if (_this.useBias) {
  33440. z = K.biasAdd(z, _this.bias.read());
  33441. }
  33442. var z0 = K.sliceAlongLastAxis(z, 0, _this.units);
  33443. var z1 = K.sliceAlongLastAxis(z, _this.units, _this.units);
  33444. var z2 = K.sliceAlongLastAxis(z, _this.units * 2, _this.units);
  33445. var z3 = K.sliceAlongLastAxis(z, _this.units * 3, _this.units);
  33446. i = _this.recurrentActivation.apply(z0);
  33447. f = _this.recurrentActivation.apply(z1);
  33448. c = tfc.add(tfc.mul(f, cTMinus1), tfc.mul(i, _this.activation.apply(z2)));
  33449. o = _this.recurrentActivation.apply(z3);
  33450. }
  33451. var h = tfc.mul(o, _this.activation.apply(c));
  33452. return [h, h, c];
  33453. });
  33454. };
  33455. LSTMCell.prototype.getConfig = function () {
  33456. var config = {
  33457. units: this.units,
  33458. activation: activations_1.serializeActivation(this.activation),
  33459. recurrentActivation: activations_1.serializeActivation(this.recurrentActivation),
  33460. useBias: this.useBias,
  33461. kernelInitializer: initializers_1.serializeInitializer(this.kernelInitializer),
  33462. recurrentInitializer: initializers_1.serializeInitializer(this.recurrentInitializer),
  33463. biasInitializer: initializers_1.serializeInitializer(this.biasInitializer),
  33464. unitForgetBias: this.unitForgetBias,
  33465. kernelRegularizer: regularizers_1.serializeRegularizer(this.kernelRegularizer),
  33466. recurrentRegularizer: regularizers_1.serializeRegularizer(this.recurrentRegularizer),
  33467. biasRegularizer: regularizers_1.serializeRegularizer(this.biasRegularizer),
  33468. activityRegularizer: regularizers_1.serializeRegularizer(this.activityRegularizer),
  33469. kernelConstraint: constraints_1.serializeConstraint(this.kernelConstraint),
  33470. recurrentConstraint: constraints_1.serializeConstraint(this.recurrentConstraint),
  33471. biasConstraint: constraints_1.serializeConstraint(this.biasConstraint),
  33472. dropout: this.dropout,
  33473. recurrentDropout: this.recurrentDropout,
  33474. implementation: this.implementation,
  33475. };
  33476. var baseConfig = _super.prototype.getConfig.call(this);
  33477. Object.assign(config, baseConfig);
  33478. return config;
  33479. };
  33480. LSTMCell.className = 'LSTMCell';
  33481. return LSTMCell;
  33482. }(RNNCell));
  33483. exports.LSTMCell = LSTMCell;
  33484. tfjs_core_1.serialization.SerializationMap.register(LSTMCell);
  33485. var LSTM = (function (_super) {
  33486. __extends(LSTM, _super);
  33487. function LSTM(config) {
  33488. var _this = this;
  33489. if (config.implementation === 0) {
  33490. console.warn('`implementation=0` has been deprecated, and now defaults to ' +
  33491. '`implementation=1`. Please update your layer call.');
  33492. }
  33493. config.cell = new LSTMCell(config);
  33494. _this = _super.call(this, config) || this;
  33495. return _this;
  33496. }
  33497. LSTM.prototype.call = function (inputs, kwargs) {
  33498. var _this = this;
  33499. return tfjs_core_1.tidy(function () {
  33500. var mask = kwargs == null ? null : kwargs['mask'];
  33501. var training = kwargs == null ? null : kwargs['training'];
  33502. var initialState = kwargs == null ? null : kwargs['initialState'];
  33503. return _super.prototype.call.call(_this, inputs, { mask: mask, training: training, initialState: initialState });
  33504. });
  33505. };
  33506. Object.defineProperty(LSTM.prototype, "units", {
  33507. get: function () {
  33508. return this.cell.units;
  33509. },
  33510. enumerable: true,
  33511. configurable: true
  33512. });
  33513. Object.defineProperty(LSTM.prototype, "activation", {
  33514. get: function () {
  33515. return this.cell.activation;
  33516. },
  33517. enumerable: true,
  33518. configurable: true
  33519. });
  33520. Object.defineProperty(LSTM.prototype, "recurrentActivation", {
  33521. get: function () {
  33522. return this.cell.recurrentActivation;
  33523. },
  33524. enumerable: true,
  33525. configurable: true
  33526. });
  33527. Object.defineProperty(LSTM.prototype, "useBias", {
  33528. get: function () {
  33529. return this.cell.useBias;
  33530. },
  33531. enumerable: true,
  33532. configurable: true
  33533. });
  33534. Object.defineProperty(LSTM.prototype, "kernelInitializer", {
  33535. get: function () {
  33536. return this.cell.kernelInitializer;
  33537. },
  33538. enumerable: true,
  33539. configurable: true
  33540. });
  33541. Object.defineProperty(LSTM.prototype, "recurrentInitializer", {
  33542. get: function () {
  33543. return this.cell.recurrentInitializer;
  33544. },
  33545. enumerable: true,
  33546. configurable: true
  33547. });
  33548. Object.defineProperty(LSTM.prototype, "biasInitializer", {
  33549. get: function () {
  33550. return this.cell.biasInitializer;
  33551. },
  33552. enumerable: true,
  33553. configurable: true
  33554. });
  33555. Object.defineProperty(LSTM.prototype, "unitForgetBias", {
  33556. get: function () {
  33557. return this.cell.unitForgetBias;
  33558. },
  33559. enumerable: true,
  33560. configurable: true
  33561. });
  33562. Object.defineProperty(LSTM.prototype, "kernelRegularizer", {
  33563. get: function () {
  33564. return this.cell.kernelRegularizer;
  33565. },
  33566. enumerable: true,
  33567. configurable: true
  33568. });
  33569. Object.defineProperty(LSTM.prototype, "recurrentRegularizer", {
  33570. get: function () {
  33571. return this.cell.recurrentRegularizer;
  33572. },
  33573. enumerable: true,
  33574. configurable: true
  33575. });
  33576. Object.defineProperty(LSTM.prototype, "biasRegularizer", {
  33577. get: function () {
  33578. return this.cell.biasRegularizer;
  33579. },
  33580. enumerable: true,
  33581. configurable: true
  33582. });
  33583. Object.defineProperty(LSTM.prototype, "kernelConstraint", {
  33584. get: function () {
  33585. return this.cell.kernelConstraint;
  33586. },
  33587. enumerable: true,
  33588. configurable: true
  33589. });
  33590. Object.defineProperty(LSTM.prototype, "recurrentConstraint", {
  33591. get: function () {
  33592. return this.cell.recurrentConstraint;
  33593. },
  33594. enumerable: true,
  33595. configurable: true
  33596. });
  33597. Object.defineProperty(LSTM.prototype, "biasConstraint", {
  33598. get: function () {
  33599. return this.cell.biasConstraint;
  33600. },
  33601. enumerable: true,
  33602. configurable: true
  33603. });
  33604. Object.defineProperty(LSTM.prototype, "dropout", {
  33605. get: function () {
  33606. return this.cell.dropout;
  33607. },
  33608. enumerable: true,
  33609. configurable: true
  33610. });
  33611. Object.defineProperty(LSTM.prototype, "recurrentDropout", {
  33612. get: function () {
  33613. return this.cell.recurrentDropout;
  33614. },
  33615. enumerable: true,
  33616. configurable: true
  33617. });
  33618. Object.defineProperty(LSTM.prototype, "implementation", {
  33619. get: function () {
  33620. return this.cell.implementation;
  33621. },
  33622. enumerable: true,
  33623. configurable: true
  33624. });
  33625. LSTM.prototype.getConfig = function () {
  33626. var config = {
  33627. units: this.units,
  33628. activation: activations_1.serializeActivation(this.activation),
  33629. recurrentActivation: activations_1.serializeActivation(this.recurrentActivation),
  33630. useBias: this.useBias,
  33631. kernelInitializer: initializers_1.serializeInitializer(this.kernelInitializer),
  33632. recurrentInitializer: initializers_1.serializeInitializer(this.recurrentInitializer),
  33633. biasInitializer: initializers_1.serializeInitializer(this.biasInitializer),
  33634. unitForgetBias: this.unitForgetBias,
  33635. kernelRegularizer: regularizers_1.serializeRegularizer(this.kernelRegularizer),
  33636. recurrentRegularizer: regularizers_1.serializeRegularizer(this.recurrentRegularizer),
  33637. biasRegularizer: regularizers_1.serializeRegularizer(this.biasRegularizer),
  33638. activityRegularizer: regularizers_1.serializeRegularizer(this.activityRegularizer),
  33639. kernelConstraint: constraints_1.serializeConstraint(this.kernelConstraint),
  33640. recurrentConstraint: constraints_1.serializeConstraint(this.recurrentConstraint),
  33641. biasConstraint: constraints_1.serializeConstraint(this.biasConstraint),
  33642. dropout: this.dropout,
  33643. recurrentDropout: this.recurrentDropout,
  33644. implementation: this.implementation,
  33645. };
  33646. var baseConfig = _super.prototype.getConfig.call(this);
  33647. delete baseConfig['cell'];
  33648. Object.assign(config, baseConfig);
  33649. return config;
  33650. };
  33651. LSTM.fromConfig = function (cls, config) {
  33652. if (config['implmentation'] === 0) {
  33653. config['implementation'] = 1;
  33654. }
  33655. return new cls(config);
  33656. };
  33657. LSTM.className = 'LSTM';
  33658. return LSTM;
  33659. }(RNN));
  33660. exports.LSTM = LSTM;
  33661. tfjs_core_1.serialization.SerializationMap.register(LSTM);
  33662. var StackedRNNCells = (function (_super) {
  33663. __extends(StackedRNNCells, _super);
  33664. function StackedRNNCells(config) {
  33665. var _this = _super.call(this, config) || this;
  33666. _this.cells = config.cells;
  33667. return _this;
  33668. }
  33669. Object.defineProperty(StackedRNNCells.prototype, "stateSize", {
  33670. get: function () {
  33671. var stateSize = [];
  33672. for (var _i = 0, _a = this.cells.slice().reverse(); _i < _a.length; _i++) {
  33673. var cell = _a[_i];
  33674. if (Array.isArray(cell.stateSize)) {
  33675. stateSize.push.apply(stateSize, cell.stateSize);
  33676. }
  33677. else {
  33678. stateSize.push(cell.stateSize);
  33679. }
  33680. }
  33681. return stateSize;
  33682. },
  33683. enumerable: true,
  33684. configurable: true
  33685. });
  33686. StackedRNNCells.prototype.call = function (inputs, kwargs) {
  33687. var _this = this;
  33688. return tfjs_core_1.tidy(function () {
  33689. inputs = inputs;
  33690. var states = inputs.slice(1);
  33691. var nestedStates = [];
  33692. for (var _i = 0, _a = _this.cells.slice().reverse(); _i < _a.length; _i++) {
  33693. var cell = _a[_i];
  33694. if (Array.isArray(cell.stateSize)) {
  33695. nestedStates.push(states.splice(0, cell.stateSize.length));
  33696. }
  33697. else {
  33698. nestedStates.push(states.splice(0, 1));
  33699. }
  33700. }
  33701. nestedStates.reverse();
  33702. var newNestedStates = [];
  33703. var callInputs;
  33704. for (var i = 0; i < _this.cells.length; ++i) {
  33705. var cell = _this.cells[i];
  33706. states = nestedStates[i];
  33707. if (i === 0) {
  33708. callInputs = [inputs[0]].concat(states);
  33709. }
  33710. else {
  33711. callInputs = [callInputs[0]].concat(states);
  33712. }
  33713. callInputs = cell.call(callInputs, kwargs);
  33714. newNestedStates.push(callInputs.slice(1));
  33715. }
  33716. states = [];
  33717. for (var _b = 0, _c = newNestedStates.slice().reverse(); _b < _c.length; _b++) {
  33718. var cellStates = _c[_b];
  33719. states.push.apply(states, cellStates);
  33720. }
  33721. return [callInputs[0]].concat(states);
  33722. });
  33723. };
  33724. StackedRNNCells.prototype.build = function (inputShape) {
  33725. if (generic_utils.isArrayOfShapes(inputShape)) {
  33726. inputShape = inputShape[0];
  33727. }
  33728. inputShape = inputShape;
  33729. var outputDim;
  33730. for (var _i = 0, _a = this.cells; _i < _a.length; _i++) {
  33731. var cell = _a[_i];
  33732. cell.build(inputShape);
  33733. if (Array.isArray(cell.stateSize)) {
  33734. outputDim = cell.stateSize[0];
  33735. }
  33736. else {
  33737. outputDim = cell.stateSize;
  33738. }
  33739. inputShape = [inputShape[0], outputDim];
  33740. }
  33741. this.built = true;
  33742. };
  33743. StackedRNNCells.prototype.getConfig = function () {
  33744. var cellConfigs = [];
  33745. for (var _i = 0, _a = this.cells; _i < _a.length; _i++) {
  33746. var cell = _a[_i];
  33747. cellConfigs.push({
  33748. 'className': this.getClassName(),
  33749. 'config': cell.getConfig(),
  33750. });
  33751. }
  33752. var config = { 'cells': cellConfigs };
  33753. var baseConfig = _super.prototype.getConfig.call(this);
  33754. Object.assign(config, baseConfig);
  33755. return config;
  33756. };
  33757. StackedRNNCells.fromConfig = function (cls, config, customObjects) {
  33758. if (customObjects === void 0) { customObjects = {}; }
  33759. var cells = [];
  33760. for (var _i = 0, _a = config['cells']; _i < _a.length; _i++) {
  33761. var cellConfig = _a[_i];
  33762. cells.push(serialization_1.deserialize(cellConfig, customObjects));
  33763. }
  33764. return new cls({ cells: cells });
  33765. };
  33766. Object.defineProperty(StackedRNNCells.prototype, "trainableWeights", {
  33767. get: function () {
  33768. if (!this.trainable) {
  33769. return [];
  33770. }
  33771. var weights = [];
  33772. for (var _i = 0, _a = this.cells; _i < _a.length; _i++) {
  33773. var cell = _a[_i];
  33774. weights.push.apply(weights, cell.trainableWeights);
  33775. }
  33776. return weights;
  33777. },
  33778. enumerable: true,
  33779. configurable: true
  33780. });
  33781. Object.defineProperty(StackedRNNCells.prototype, "nonTrainableWeights", {
  33782. get: function () {
  33783. var weights = [];
  33784. for (var _i = 0, _a = this.cells; _i < _a.length; _i++) {
  33785. var cell = _a[_i];
  33786. weights.push.apply(weights, cell.nonTrainableWeights);
  33787. }
  33788. if (!this.trainable) {
  33789. var trainableWeights = [];
  33790. for (var _b = 0, _c = this.cells; _b < _c.length; _b++) {
  33791. var cell = _c[_b];
  33792. trainableWeights.push.apply(trainableWeights, cell.trainableWeights);
  33793. }
  33794. return trainableWeights.concat(weights);
  33795. }
  33796. return weights;
  33797. },
  33798. enumerable: true,
  33799. configurable: true
  33800. });
  33801. StackedRNNCells.prototype.getWeights = function () {
  33802. var weights = [];
  33803. for (var _i = 0, _a = this.cells; _i < _a.length; _i++) {
  33804. var cell = _a[_i];
  33805. weights.push.apply(weights, cell.weights);
  33806. }
  33807. return variables_1.batchGetValue(weights);
  33808. };
  33809. StackedRNNCells.prototype.setWeights = function (weights) {
  33810. var tuples = [];
  33811. for (var _i = 0, _a = this.cells; _i < _a.length; _i++) {
  33812. var cell = _a[_i];
  33813. var numParams = cell.weights.length;
  33814. var inputWeights = weights.splice(numParams);
  33815. for (var i = 0; i < cell.weights.length; ++i) {
  33816. tuples.push([cell.weights[i], inputWeights[i]]);
  33817. }
  33818. }
  33819. variables_1.batchSetValue(tuples);
  33820. };
  33821. StackedRNNCells.className = 'StackedRNNCells';
  33822. return StackedRNNCells;
  33823. }(RNNCell));
  33824. exports.StackedRNNCells = StackedRNNCells;
  33825. tfjs_core_1.serialization.SerializationMap.register(StackedRNNCells);
  33826. },{"../activations":167,"../backend/tfjs_backend":169,"../constraints":172,"../engine/topology":174,"../errors":176,"../initializers":179,"../regularizers":196,"../types":197,"../utils/generic_utils":199,"../utils/math_utils":201,"../variables":203,"./serialization":190,"@tensorflow/tfjs-core":54}],190:[function(require,module,exports){
  33827. "use strict";
  33828. Object.defineProperty(exports, "__esModule", { value: true });
  33829. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  33830. var generic_utils_1 = require("../utils/generic_utils");
  33831. function deserialize(config, customObjects) {
  33832. if (customObjects === void 0) { customObjects = {}; }
  33833. return generic_utils_1.deserializeKerasObject(config, tfjs_core_1.serialization.SerializationMap.getMap().classNameMap, customObjects, 'layer');
  33834. }
  33835. exports.deserialize = deserialize;
  33836. },{"../utils/generic_utils":199,"@tensorflow/tfjs-core":54}],191:[function(require,module,exports){
  33837. "use strict";
  33838. var __extends = (this && this.__extends) || (function () {
  33839. var extendStatics = Object.setPrototypeOf ||
  33840. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  33841. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  33842. return function (d, b) {
  33843. extendStatics(d, b);
  33844. function __() { this.constructor = d; }
  33845. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  33846. };
  33847. })();
  33848. Object.defineProperty(exports, "__esModule", { value: true });
  33849. var tfc = require("@tensorflow/tfjs-core");
  33850. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  33851. var K = require("../backend/tfjs_backend");
  33852. var topology_1 = require("../engine/topology");
  33853. var errors_1 = require("../errors");
  33854. var generic_utils = require("../utils/generic_utils");
  33855. var recurrent_1 = require("./recurrent");
  33856. var serialization_1 = require("./serialization");
  33857. var Wrapper = (function (_super) {
  33858. __extends(Wrapper, _super);
  33859. function Wrapper(config) {
  33860. var _this = _super.call(this, config) || this;
  33861. _this.layer = config.layer;
  33862. return _this;
  33863. }
  33864. Wrapper.prototype.build = function (inputShape) {
  33865. this.built = true;
  33866. };
  33867. Object.defineProperty(Wrapper.prototype, "trainable", {
  33868. get: function () {
  33869. if (this.layer != null) {
  33870. return this.layer.trainable;
  33871. }
  33872. else {
  33873. return false;
  33874. }
  33875. },
  33876. set: function (value) {
  33877. if (this.layer != null) {
  33878. this.layer.trainable = value;
  33879. }
  33880. },
  33881. enumerable: true,
  33882. configurable: true
  33883. });
  33884. Object.defineProperty(Wrapper.prototype, "trainableWeights", {
  33885. get: function () {
  33886. return this.layer.trainableWeights;
  33887. },
  33888. enumerable: true,
  33889. configurable: true
  33890. });
  33891. Object.defineProperty(Wrapper.prototype, "nonTrainableWeights", {
  33892. get: function () {
  33893. return this.layer.nonTrainableWeights;
  33894. },
  33895. enumerable: true,
  33896. configurable: true
  33897. });
  33898. Object.defineProperty(Wrapper.prototype, "updates", {
  33899. get: function () {
  33900. return this.layer._updates;
  33901. },
  33902. enumerable: true,
  33903. configurable: true
  33904. });
  33905. Object.defineProperty(Wrapper.prototype, "losses", {
  33906. get: function () {
  33907. return this.layer.losses;
  33908. },
  33909. enumerable: true,
  33910. configurable: true
  33911. });
  33912. Wrapper.prototype.getWeights = function () {
  33913. return this.layer.getWeights();
  33914. };
  33915. Wrapper.prototype.setWeights = function (weights) {
  33916. this.layer.setWeights(weights);
  33917. };
  33918. Wrapper.prototype.getConfig = function () {
  33919. var config = {
  33920. 'layer': {
  33921. 'className': this.layer.getClassName(),
  33922. 'config': this.layer.getConfig(),
  33923. }
  33924. };
  33925. var baseConfig = _super.prototype.getConfig.call(this);
  33926. Object.assign(config, baseConfig);
  33927. return config;
  33928. };
  33929. Wrapper.fromConfig = function (cls, config, customObjects) {
  33930. if (customObjects === void 0) { customObjects = {}; }
  33931. var layerConfig = config['layer'];
  33932. var layer = serialization_1.deserialize(layerConfig, customObjects);
  33933. delete config['layer'];
  33934. var newConfig = { layer: layer };
  33935. Object.assign(newConfig, config);
  33936. return new cls(newConfig);
  33937. };
  33938. return Wrapper;
  33939. }(topology_1.Layer));
  33940. exports.Wrapper = Wrapper;
  33941. var TimeDistributed = (function (_super) {
  33942. __extends(TimeDistributed, _super);
  33943. function TimeDistributed(config) {
  33944. var _this = _super.call(this, config) || this;
  33945. _this.supportsMasking = true;
  33946. return _this;
  33947. }
  33948. TimeDistributed.prototype.build = function (inputShape) {
  33949. inputShape = generic_utils.getExactlyOneShape(inputShape);
  33950. if (inputShape.length < 3) {
  33951. throw new errors_1.ValueError("TimeDistributed layer expects an input shape >= 3D, but received " +
  33952. ("input shape " + JSON.stringify(inputShape)));
  33953. }
  33954. this.inputSpec = [{ shape: inputShape }];
  33955. var childInputShape = [inputShape[0]].concat(inputShape.slice(2));
  33956. if (!this.layer.built) {
  33957. this.layer.build(childInputShape);
  33958. this.layer.built = true;
  33959. }
  33960. _super.prototype.build.call(this, inputShape);
  33961. };
  33962. TimeDistributed.prototype.computeOutputShape = function (inputShape) {
  33963. inputShape = generic_utils.getExactlyOneShape(inputShape);
  33964. var childInputShape = [inputShape[0]].concat(inputShape.slice(2));
  33965. var childOutputShape = this.layer.computeOutputShape(childInputShape);
  33966. var timesteps = inputShape[1];
  33967. return [childOutputShape[0], timesteps].concat(childOutputShape.slice(1));
  33968. };
  33969. TimeDistributed.prototype.call = function (inputs, kwargs) {
  33970. var _this = this;
  33971. return tfjs_core_1.tidy(function () {
  33972. inputs = generic_utils.getExactlyOneTensor(inputs);
  33973. var step = function (inputs, states) {
  33974. var output = _this.layer.call(inputs, kwargs);
  33975. return [output, []];
  33976. };
  33977. var rnnOutputs = recurrent_1.rnn(step, inputs, [], false, null, null, false, inputs.shape[1]);
  33978. var y = rnnOutputs[1];
  33979. return y;
  33980. });
  33981. };
  33982. TimeDistributed.className = 'TimeDistributed';
  33983. return TimeDistributed;
  33984. }(Wrapper));
  33985. exports.TimeDistributed = TimeDistributed;
  33986. tfjs_core_1.serialization.SerializationMap.register(TimeDistributed);
  33987. exports.VALID_BIDIRECTIONAL_MERGE_MODES = ['sum', 'mul', 'concat', 'ave'];
  33988. function checkBidirectionalMergeMode(value) {
  33989. generic_utils.checkStringTypeUnionValue(exports.VALID_BIDIRECTIONAL_MERGE_MODES, 'BidirectionalMergeMode', value);
  33990. }
  33991. exports.checkBidirectionalMergeMode = checkBidirectionalMergeMode;
  33992. var Bidirectional = (function (_super) {
  33993. __extends(Bidirectional, _super);
  33994. function Bidirectional(config) {
  33995. var _this = _super.call(this, config) || this;
  33996. var layerConfig = config.layer.getConfig();
  33997. _this.forwardLayer =
  33998. serialization_1.deserialize({ className: config.layer.getClassName(), config: layerConfig });
  33999. layerConfig['goBackwards'] =
  34000. layerConfig['goBackwards'] === true ? false : true;
  34001. _this.backwardLayer =
  34002. serialization_1.deserialize({ className: config.layer.getClassName(), config: layerConfig });
  34003. _this.forwardLayer.name = 'forward_' + _this.forwardLayer.name;
  34004. _this.backwardLayer.name = 'backward_' + _this.backwardLayer.name;
  34005. checkBidirectionalMergeMode(config.mergeMode);
  34006. _this.mergeMode = config.mergeMode;
  34007. if (config.weights) {
  34008. throw new errors_1.NotImplementedError('weights support is not implemented for Bidirectional layer yet.');
  34009. }
  34010. _this._stateful = config.layer.stateful;
  34011. _this.returnSequences = config.layer.returnSequences;
  34012. _this.returnState = config.layer.returnState;
  34013. _this.supportsMasking = true;
  34014. _this._trainable = true;
  34015. _this.inputSpec = config.layer.inputSpec;
  34016. return _this;
  34017. }
  34018. Object.defineProperty(Bidirectional.prototype, "trainable", {
  34019. get: function () {
  34020. return this._trainable;
  34021. },
  34022. set: function (value) {
  34023. this._trainable = value;
  34024. if (this.forwardLayer != null) {
  34025. this.forwardLayer.trainable = value;
  34026. }
  34027. if (this.backwardLayer != null) {
  34028. this.backwardLayer.trainable = value;
  34029. }
  34030. },
  34031. enumerable: true,
  34032. configurable: true
  34033. });
  34034. Bidirectional.prototype.getWeights = function () {
  34035. return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights());
  34036. };
  34037. Bidirectional.prototype.setWeights = function (weights) {
  34038. var numWeights = weights.length;
  34039. var numeightsOver2 = Math.floor(numWeights / 2);
  34040. this.forwardLayer.setWeights(weights.slice(0, numeightsOver2));
  34041. this.backwardLayer.setWeights(weights.slice(numeightsOver2));
  34042. };
  34043. Bidirectional.prototype.computeOutputShape = function (inputShape) {
  34044. var layerShapes = this.forwardLayer.computeOutputShape(inputShape);
  34045. if (!(Array.isArray(layerShapes) && Array.isArray(layerShapes[0]))) {
  34046. layerShapes = [layerShapes];
  34047. }
  34048. layerShapes = layerShapes;
  34049. var outputShape;
  34050. var outputShapes;
  34051. var stateShape;
  34052. if (this.returnState) {
  34053. stateShape = layerShapes.slice(1);
  34054. outputShape = layerShapes[0];
  34055. }
  34056. else {
  34057. outputShape = layerShapes[0];
  34058. }
  34059. outputShape = outputShape;
  34060. if (this.mergeMode === 'concat') {
  34061. outputShape[outputShape.length - 1] *= 2;
  34062. outputShapes = [outputShape];
  34063. }
  34064. else if (this.mergeMode == null) {
  34065. outputShapes = [outputShape, outputShape.slice()];
  34066. }
  34067. else {
  34068. outputShapes = [outputShape];
  34069. }
  34070. if (this.returnState) {
  34071. if (this.mergeMode == null) {
  34072. return outputShapes.concat(stateShape).concat(stateShape.slice());
  34073. }
  34074. return [outputShape].concat(stateShape).concat(stateShape.slice());
  34075. }
  34076. return generic_utils.singletonOrArray(outputShapes);
  34077. };
  34078. Bidirectional.prototype.apply = function (inputs, kwargs) {
  34079. var initialState = null;
  34080. if (kwargs != null) {
  34081. initialState = kwargs['initialState'];
  34082. }
  34083. if (Array.isArray(inputs)) {
  34084. initialState = inputs.slice(1);
  34085. inputs = inputs[0];
  34086. }
  34087. if (initialState == null || initialState.length === 0) {
  34088. var applyOutputs = _super.prototype.apply.call(this, inputs, kwargs);
  34089. return applyOutputs;
  34090. }
  34091. else {
  34092. throw new errors_1.NotImplementedError('The support for initial states is not implemented for ' +
  34093. 'Bidirectional layers yet.');
  34094. }
  34095. };
  34096. Bidirectional.prototype.call = function (inputs, kwargs) {
  34097. var _this = this;
  34098. return tfjs_core_1.tidy(function () {
  34099. if (kwargs['mask'] != null) {
  34100. throw new errors_1.NotImplementedError('The support for masking is not implemented for ' +
  34101. 'Bidirectional layers yet.');
  34102. }
  34103. if (kwargs['initialState'] != null) {
  34104. throw new errors_1.NotImplementedError('The support for initial states is not implemented for ' +
  34105. 'Bidirectional layers yet.');
  34106. }
  34107. var y = _this.forwardLayer.call(inputs, kwargs);
  34108. var yRev = _this.backwardLayer.call(inputs, kwargs);
  34109. var states;
  34110. if (_this.returnState) {
  34111. if (Array.isArray(y)) {
  34112. states = y.slice(1).concat(yRev.slice(1));
  34113. }
  34114. else {
  34115. }
  34116. y = y[0];
  34117. yRev = yRev[0];
  34118. }
  34119. if (_this.returnSequences) {
  34120. yRev = tfc.reverse(yRev, 1);
  34121. }
  34122. var output;
  34123. if (_this.mergeMode === 'concat') {
  34124. output = K.concatenate([y, yRev]);
  34125. }
  34126. else if (_this.mergeMode === 'sum') {
  34127. output = tfc.add(y, yRev);
  34128. }
  34129. else if (_this.mergeMode === 'ave') {
  34130. output = K.scalarTimesArray(K.getScalar(0.5), tfc.add(y, yRev));
  34131. }
  34132. else if (_this.mergeMode === 'mul') {
  34133. output = tfc.mul(y, yRev);
  34134. }
  34135. else if (_this.mergeMode == null) {
  34136. output = [y, yRev];
  34137. }
  34138. if (_this.returnState) {
  34139. if (_this.mergeMode == null) {
  34140. return output.concat(states);
  34141. }
  34142. return [output].concat(states);
  34143. }
  34144. return output;
  34145. });
  34146. };
  34147. Bidirectional.prototype.resetStates = function (states) {
  34148. this.forwardLayer.resetStates();
  34149. this.backwardLayer.resetStates();
  34150. };
  34151. Bidirectional.prototype.build = function (inputShape) {
  34152. var _this = this;
  34153. K.nameScope(this.forwardLayer.name, function () {
  34154. _this.forwardLayer.build(inputShape);
  34155. });
  34156. K.nameScope(this.backwardLayer.name, function () {
  34157. _this.backwardLayer.build(inputShape);
  34158. });
  34159. this.built = true;
  34160. };
  34161. Object.defineProperty(Bidirectional.prototype, "trainableWeights", {
  34162. get: function () {
  34163. return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights);
  34164. },
  34165. enumerable: true,
  34166. configurable: true
  34167. });
  34168. Object.defineProperty(Bidirectional.prototype, "nonTrainableWeights", {
  34169. get: function () {
  34170. return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights);
  34171. },
  34172. enumerable: true,
  34173. configurable: true
  34174. });
  34175. Bidirectional.prototype.getConfig = function () {
  34176. var config = {
  34177. 'mergeMode': this.mergeMode,
  34178. };
  34179. var baseConfig = _super.prototype.getConfig.call(this);
  34180. Object.assign(config, baseConfig);
  34181. return config;
  34182. };
  34183. Bidirectional.fromConfig = function (cls, config) {
  34184. var rnnLayer = serialization_1.deserialize(config['layer']);
  34185. delete config['layer'];
  34186. if (config['numConstants'] != null) {
  34187. throw new errors_1.NotImplementedError("Deserialization of a Bidirectional layer with numConstants " +
  34188. "present is not supported yet.");
  34189. }
  34190. var newConfig = config;
  34191. newConfig['layer'] = rnnLayer;
  34192. return new cls(newConfig);
  34193. };
  34194. Bidirectional.className = 'Bidirectional';
  34195. return Bidirectional;
  34196. }(Wrapper));
  34197. exports.Bidirectional = Bidirectional;
  34198. tfjs_core_1.serialization.SerializationMap.register(Bidirectional);
  34199. },{"../backend/tfjs_backend":169,"../engine/topology":174,"../errors":176,"../utils/generic_utils":199,"./recurrent":189,"./serialization":190,"@tensorflow/tfjs-core":54}],192:[function(require,module,exports){
  34200. "use strict";
  34201. Object.defineProperty(exports, "__esModule", { value: true });
  34202. var tfc = require("@tensorflow/tfjs-core");
  34203. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  34204. var K = require("./backend/tfjs_backend");
  34205. var errors_1 = require("./errors");
  34206. function l2Normalize(x, axis) {
  34207. return tfjs_core_1.tidy(function () {
  34208. var squareSum = tfc.sum(K.square(x), axis, true);
  34209. var epsilonTensor = K.scalarTimesArray(tfjs_core_1.scalar(K.epsilon()), tfc.onesLike(x));
  34210. var norm = tfc.sqrt(tfc.maximum(squareSum, epsilonTensor));
  34211. return tfc.div(x, norm);
  34212. });
  34213. }
  34214. exports.l2Normalize = l2Normalize;
  34215. function meanSquaredError(yTrue, yPred) {
  34216. return tfjs_core_1.tidy(function () { return tfc.mean(K.square(tfc.sub(yPred, yTrue)), -1); });
  34217. }
  34218. exports.meanSquaredError = meanSquaredError;
  34219. function meanAbsoluteError(yTrue, yPred) {
  34220. return tfjs_core_1.tidy(function () { return tfc.mean(tfc.abs(tfc.sub(yPred, yTrue)), -1); });
  34221. }
  34222. exports.meanAbsoluteError = meanAbsoluteError;
  34223. function meanAbsolutePercentageError(yTrue, yPred) {
  34224. return tfjs_core_1.tidy(function () {
  34225. var diff = tfc.sub(yTrue, yPred);
  34226. var clippedTrue = tfc.clipByValue(tfc.abs(yTrue), K.epsilon(), Number.MAX_VALUE);
  34227. var absResult = tfc.abs(tfc.div(diff, clippedTrue));
  34228. return K.scalarTimesArray(K.getScalar(100.0), tfc.mean(absResult, -1));
  34229. });
  34230. }
  34231. exports.meanAbsolutePercentageError = meanAbsolutePercentageError;
  34232. function meanSquaredLogarithmicError(yTrue, yPred) {
  34233. return tfjs_core_1.tidy(function () {
  34234. var one = K.getScalar(1.0);
  34235. var clippedPred = tfc.clipByValue(yPred, K.epsilon(), Number.MAX_VALUE);
  34236. var firstLog = tfc.log(K.scalarPlusArray(one, clippedPred));
  34237. var clippedTrue = tfc.clipByValue(yTrue, K.epsilon(), Number.MAX_VALUE);
  34238. var secondLog = tfc.log(K.scalarPlusArray(one, clippedTrue));
  34239. return tfc.mean(K.square(tfc.sub(firstLog, secondLog)), -1);
  34240. });
  34241. }
  34242. exports.meanSquaredLogarithmicError = meanSquaredLogarithmicError;
  34243. function squaredHinge(yTrue, yPred) {
  34244. return tfjs_core_1.tidy(function () {
  34245. var zeroTensor = K.getScalar(0.0);
  34246. var one = K.getScalar(1.0);
  34247. var maxResult = tfc.maximum(zeroTensor, tfc.sub(one, tfc.mul(yTrue, yPred)));
  34248. return tfc.mean(K.square(maxResult), -1);
  34249. });
  34250. }
  34251. exports.squaredHinge = squaredHinge;
  34252. function hinge(yTrue, yPred) {
  34253. return tfjs_core_1.tidy(function () {
  34254. var zeroTensor = K.getScalar(0.0);
  34255. var one = K.getScalar(1.0);
  34256. var maxResult = tfc.maximum(zeroTensor, tfc.sub(one, tfc.mul(yTrue, yPred)));
  34257. return tfc.mean(maxResult, -1);
  34258. });
  34259. }
  34260. exports.hinge = hinge;
  34261. function categoricalHinge(yTrue, yPred) {
  34262. return tfjs_core_1.tidy(function () {
  34263. var zeroTensor = K.getScalar(0.0);
  34264. var one = K.getScalar(1.0);
  34265. var pos = tfc.sum(tfc.mul(yTrue, yPred), -1);
  34266. var neg = tfc.max(tfc.mul(tfc.sub(one, yTrue), yPred), -1);
  34267. return tfc.maximum(zeroTensor, K.scalarPlusArray(one, tfc.sub(neg, pos)));
  34268. });
  34269. }
  34270. exports.categoricalHinge = categoricalHinge;
  34271. function logcosh(yTrue, yPred) {
  34272. return tfjs_core_1.tidy(function () {
  34273. var log2 = K.getScalar(Math.log(2.0));
  34274. var predictionDiff = tfc.sub(yPred, yTrue);
  34275. var logcoshResult = tfc.sub(tfc.add(predictionDiff, tfc.softplus(K.scalarTimesArray(K.getScalar(-2.0), predictionDiff))), log2);
  34276. return tfc.mean(logcoshResult, -1);
  34277. });
  34278. }
  34279. exports.logcosh = logcosh;
  34280. function categoricalCrossentropy(target, output, fromLogits) {
  34281. if (fromLogits === void 0) { fromLogits = false; }
  34282. return tfjs_core_1.tidy(function () {
  34283. if (fromLogits) {
  34284. output = tfc.softmax(output);
  34285. }
  34286. else {
  34287. var outputSum = tfc.sum(output, K.shape(output).length - 1, true);
  34288. output = tfc.div(output, outputSum);
  34289. }
  34290. output = tfc.clipByValue(output, K.epsilon(), 1 - K.epsilon());
  34291. return tfc.neg(tfc.sum(tfc.mul(target.toFloat(), tfc.log(output)), K.shape(output).length - 1));
  34292. });
  34293. }
  34294. exports.categoricalCrossentropy = categoricalCrossentropy;
  34295. function sparseCategoricalCrossentropy(target, output, fromLogits) {
  34296. if (fromLogits === void 0) { fromLogits = false; }
  34297. return tfjs_core_1.tidy(function () {
  34298. var flatTarget = tfc.floor(K.flatten(target)).toInt();
  34299. var outputShape = K.shape(output);
  34300. var oneHotTarget = tfc.oneHot(flatTarget, outputShape[outputShape.length - 1])
  34301. .reshape(outputShape);
  34302. return categoricalCrossentropy(oneHotTarget, output, fromLogits);
  34303. });
  34304. }
  34305. exports.sparseCategoricalCrossentropy = sparseCategoricalCrossentropy;
  34306. function sigmoidCrossEntropyWithLogits(target, output) {
  34307. return tfjs_core_1.tidy(function () {
  34308. var maxOutput = tfc.maximum(output, tfc.zerosLike(output));
  34309. var outputXTarget = tfc.mul(output, target);
  34310. var sigmoidOutput = tfc.log(tfc.add(K.getScalar(1), tfc.exp(tfc.neg(tfc.abs(output)))));
  34311. var result = tfc.add(tfc.sub(maxOutput, outputXTarget), sigmoidOutput);
  34312. return result;
  34313. });
  34314. }
  34315. exports.sigmoidCrossEntropyWithLogits = sigmoidCrossEntropyWithLogits;
  34316. function binaryCrossentropy(yTrue, yPred) {
  34317. return tfjs_core_1.tidy(function () {
  34318. var y;
  34319. y = tfc.clipByValue(yPred, K.epsilon(), 1 - K.epsilon());
  34320. y = tfc.log(tfc.div(y, tfc.sub(tfc.onesLike(y), y)));
  34321. return tfc.mean(sigmoidCrossEntropyWithLogits(yTrue, y), -1);
  34322. });
  34323. }
  34324. exports.binaryCrossentropy = binaryCrossentropy;
  34325. function kullbackLeiblerDivergence(yTrue, yPred) {
  34326. return tfjs_core_1.tidy(function () {
  34327. var clippedTrue = tfc.clipByValue(yTrue, K.epsilon(), 1);
  34328. var clippedPred = tfc.clipByValue(yPred, K.epsilon(), 1);
  34329. return tfc.sum(tfc.mul(yTrue, tfc.log(tfc.div(clippedTrue, clippedPred))), -1);
  34330. });
  34331. }
  34332. exports.kullbackLeiblerDivergence = kullbackLeiblerDivergence;
  34333. function poisson(yTrue, yPred) {
  34334. return tfjs_core_1.tidy(function () {
  34335. var logPred = tfc.log(K.scalarPlusArray(K.getScalar(K.epsilon()), yPred));
  34336. return tfc.mean(tfc.sub(yPred, tfc.mul(yTrue, logPred)), -1);
  34337. });
  34338. }
  34339. exports.poisson = poisson;
  34340. function cosineProximity(yTrue, yPred) {
  34341. return tfjs_core_1.tidy(function () {
  34342. var trueNormalized = l2Normalize(yTrue, -1);
  34343. var predNormalized = l2Normalize(yPred, -1);
  34344. var trueXPred = tfc.mul(trueNormalized, predNormalized);
  34345. return tfc.neg(tfc.sum(trueXPred, -1));
  34346. });
  34347. }
  34348. exports.cosineProximity = cosineProximity;
  34349. exports.mse = meanSquaredError;
  34350. exports.MSE = meanSquaredError;
  34351. exports.mae = meanAbsoluteError;
  34352. exports.MAE = meanAbsoluteError;
  34353. exports.mape = meanAbsolutePercentageError;
  34354. exports.MAPE = meanAbsolutePercentageError;
  34355. exports.msle = meanSquaredLogarithmicError;
  34356. exports.MSLE = meanSquaredLogarithmicError;
  34357. exports.kld = kullbackLeiblerDivergence;
  34358. exports.KLD = kullbackLeiblerDivergence;
  34359. exports.cosine = cosineProximity;
  34360. function get(identifierOrFn) {
  34361. var lossesMap = {
  34362. meanSquaredError: meanSquaredError,
  34363. meanAbsoluteError: meanAbsoluteError,
  34364. meanAbsolutePercentageError: meanAbsolutePercentageError,
  34365. meanSquaredLogarithmicError: meanSquaredLogarithmicError,
  34366. squaredHinge: squaredHinge,
  34367. hinge: hinge,
  34368. categoricalHinge: categoricalHinge,
  34369. logcosh: logcosh,
  34370. categoricalCrossentropy: categoricalCrossentropy,
  34371. sparseCategoricalCrossentropy: sparseCategoricalCrossentropy,
  34372. binaryCrossentropy: binaryCrossentropy,
  34373. kullbackLeiblerDivergence: kullbackLeiblerDivergence,
  34374. poisson: poisson,
  34375. cosineProximity: cosineProximity
  34376. };
  34377. if (typeof identifierOrFn === 'string') {
  34378. if (identifierOrFn in lossesMap) {
  34379. return lossesMap[identifierOrFn];
  34380. }
  34381. throw new errors_1.ValueError("Unknown loss " + identifierOrFn);
  34382. }
  34383. else {
  34384. return identifierOrFn;
  34385. }
  34386. }
  34387. exports.get = get;
  34388. },{"./backend/tfjs_backend":169,"./errors":176,"@tensorflow/tfjs-core":54}],193:[function(require,module,exports){
  34389. "use strict";
  34390. Object.defineProperty(exports, "__esModule", { value: true });
  34391. var tfc = require("@tensorflow/tfjs-core");
  34392. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  34393. var K = require("./backend/tfjs_backend");
  34394. var errors_1 = require("./errors");
  34395. var losses_1 = require("./losses");
  34396. var losses_2 = require("./losses");
  34397. function binaryAccuracy(yTrue, yPred) {
  34398. return tfjs_core_1.tidy(function () {
  34399. var threshold = K.scalarTimesArray(K.getScalar(0.5), tfc.onesLike(yPred));
  34400. var yPredThresholded = K.cast(tfc.greater(yPred, threshold), yTrue.dtype);
  34401. return tfc.mean(tfc.equal(yTrue, yPredThresholded), -1);
  34402. });
  34403. }
  34404. exports.binaryAccuracy = binaryAccuracy;
  34405. function categoricalAccuracy(yTrue, yPred) {
  34406. return tfjs_core_1.tidy(function () { return K.cast(tfc.equal(tfc.argMax(yTrue, -1), tfc.argMax(yPred, -1)), 'float32'); });
  34407. }
  34408. exports.categoricalAccuracy = categoricalAccuracy;
  34409. function binaryCrossentropy(yTrue, yPred) {
  34410. return losses_2.binaryCrossentropy(yTrue, yPred);
  34411. }
  34412. exports.binaryCrossentropy = binaryCrossentropy;
  34413. function sparseCategoricalAccuracy(yTrue, yPred) {
  34414. throw new errors_1.NotImplementedError();
  34415. }
  34416. exports.sparseCategoricalAccuracy = sparseCategoricalAccuracy;
  34417. function topKCategoricalAccuracy(yTrue, yPred) {
  34418. throw new errors_1.NotImplementedError();
  34419. }
  34420. exports.topKCategoricalAccuracy = topKCategoricalAccuracy;
  34421. function sparseTopKCategoricalAccuracy(yTrue, yPred) {
  34422. throw new errors_1.NotImplementedError();
  34423. }
  34424. exports.sparseTopKCategoricalAccuracy = sparseTopKCategoricalAccuracy;
  34425. exports.mse = losses_1.meanSquaredError;
  34426. exports.MSE = losses_1.meanSquaredError;
  34427. exports.mae = losses_1.meanAbsoluteError;
  34428. exports.MAE = losses_1.meanAbsoluteError;
  34429. exports.mape = losses_1.meanAbsolutePercentageError;
  34430. exports.MAPE = losses_1.meanAbsolutePercentageError;
  34431. exports.categoricalCrossentropy = losses_1.categoricalCrossentropy;
  34432. exports.cosine = losses_1.cosineProximity;
  34433. exports.sparseCategoricalCrossentropy = losses_1.sparseCategoricalCrossentropy;
  34434. function get(identifier) {
  34435. var metricsMap = {
  34436. binaryAccuracy: binaryAccuracy,
  34437. categoricalAccuracy: categoricalAccuracy,
  34438. categoricalCrossentropy: exports.categoricalCrossentropy,
  34439. sparseCategoricalCrossentropy: exports.sparseCategoricalCrossentropy,
  34440. mse: exports.mse,
  34441. MSE: exports.MSE,
  34442. mae: exports.mae,
  34443. MAE: exports.MAE,
  34444. mape: exports.mape,
  34445. MAPE: exports.MAPE,
  34446. cosine: exports.cosine,
  34447. };
  34448. if (typeof identifier === 'string' && identifier in metricsMap) {
  34449. return metricsMap[identifier];
  34450. }
  34451. else if (typeof identifier !== 'string' && identifier != null) {
  34452. return identifier;
  34453. }
  34454. else {
  34455. throw new errors_1.ValueError("Unknown metric " + identifier);
  34456. }
  34457. }
  34458. exports.get = get;
  34459. },{"./backend/tfjs_backend":169,"./errors":176,"./losses":192,"@tensorflow/tfjs-core":54}],194:[function(require,module,exports){
  34460. "use strict";
  34461. var __extends = (this && this.__extends) || (function () {
  34462. var extendStatics = Object.setPrototypeOf ||
  34463. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  34464. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  34465. return function (d, b) {
  34466. extendStatics(d, b);
  34467. function __() { this.constructor = d; }
  34468. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  34469. };
  34470. })();
  34471. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  34472. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  34473. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  34474. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  34475. return c > 3 && r && Object.defineProperty(target, key, r), r;
  34476. };
  34477. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  34478. return new (P || (P = Promise))(function (resolve, reject) {
  34479. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  34480. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  34481. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  34482. step((generator = generator.apply(thisArg, _arguments || [])).next());
  34483. });
  34484. };
  34485. var __generator = (this && this.__generator) || function (thisArg, body) {
  34486. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  34487. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  34488. function verb(n) { return function (v) { return step([n, v]); }; }
  34489. function step(op) {
  34490. if (f) throw new TypeError("Generator is already executing.");
  34491. while (_) try {
  34492. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  34493. if (y = 0, t) op = [0, t.value];
  34494. switch (op[0]) {
  34495. case 0: case 1: t = op; break;
  34496. case 4: _.label++; return { value: op[1], done: false };
  34497. case 5: _.label++; y = op[1]; op = [0]; continue;
  34498. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  34499. default:
  34500. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  34501. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  34502. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  34503. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  34504. if (t[2]) _.ops.pop();
  34505. _.trys.pop(); continue;
  34506. }
  34507. op = body.call(thisArg, _);
  34508. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  34509. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  34510. }
  34511. };
  34512. Object.defineProperty(exports, "__esModule", { value: true });
  34513. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  34514. var K = require("./backend/tfjs_backend");
  34515. var topology_1 = require("./engine/topology");
  34516. var training_1 = require("./engine/training");
  34517. var errors_1 = require("./errors");
  34518. var serialization_1 = require("./layers/serialization");
  34519. var generic_utils = require("./utils/generic_utils");
  34520. var serialization_utils_1 = require("./utils/serialization_utils");
  34521. function modelFromJSON(modelAndWeightsConfig, customObjects) {
  34522. return __awaiter(this, void 0, void 0, function () {
  34523. var modelTopology, tsConfig, model, weightValues, uniqueWeightValues, _i, _a, weight, skipMismatches, isNamedTensorMap;
  34524. return __generator(this, function (_b) {
  34525. switch (_b.label) {
  34526. case 0:
  34527. modelTopology = modelAndWeightsConfig.modelTopology;
  34528. if (modelTopology['model_config'] != null) {
  34529. modelTopology = modelTopology['model_config'];
  34530. }
  34531. tsConfig = serialization_utils_1.convertPythonicToTs(modelTopology);
  34532. model = serialization_1.deserialize(tsConfig, customObjects);
  34533. if (!(modelAndWeightsConfig.weightsManifest != null)) return [3, 2];
  34534. return [4, tfjs_core_1.io.loadWeights(modelAndWeightsConfig.weightsManifest, modelAndWeightsConfig.pathPrefix, model.weights.map(function (weight) { return weight.originalName; }))];
  34535. case 1:
  34536. weightValues = _b.sent();
  34537. uniqueWeightValues = {};
  34538. for (_i = 0, _a = model.weights; _i < _a.length; _i++) {
  34539. weight = _a[_i];
  34540. uniqueWeightValues[weight.originalName] =
  34541. weightValues[weight.originalName];
  34542. }
  34543. skipMismatches = null;
  34544. isNamedTensorMap = true;
  34545. model.loadWeights(uniqueWeightValues, skipMismatches, isNamedTensorMap);
  34546. _b.label = 2;
  34547. case 2: return [2, model];
  34548. }
  34549. });
  34550. });
  34551. }
  34552. exports.modelFromJSON = modelFromJSON;
  34553. function loadModelInternal(pathOrIOHandler) {
  34554. return __awaiter(this, void 0, void 0, function () {
  34555. var handlers;
  34556. return __generator(this, function (_a) {
  34557. if (typeof pathOrIOHandler === 'string') {
  34558. handlers = tfjs_core_1.io.getLoadHandlers(pathOrIOHandler);
  34559. if (handlers.length === 0) {
  34560. handlers.push(tfjs_core_1.io.browserHTTPRequest(pathOrIOHandler));
  34561. }
  34562. else if (handlers.length > 1) {
  34563. throw new errors_1.ValueError("Found more than one (" + handlers.length + ") load handlers for " +
  34564. ("URL '" + pathOrIOHandler + "'"));
  34565. }
  34566. pathOrIOHandler = handlers[0];
  34567. }
  34568. return [2, loadModelFromIOHandler(pathOrIOHandler)];
  34569. });
  34570. });
  34571. }
  34572. exports.loadModelInternal = loadModelInternal;
  34573. function loadModelFromIOHandler(handler, customObjects) {
  34574. return __awaiter(this, void 0, void 0, function () {
  34575. var artifacts, modelTopology, model, skipMismatch, isNamedTensorMap;
  34576. return __generator(this, function (_a) {
  34577. switch (_a.label) {
  34578. case 0:
  34579. if (handler.load == null) {
  34580. throw new errors_1.ValueError('Cannot proceed with model loading because the IOHandler provided ' +
  34581. 'does not have the `load` method implemented.');
  34582. }
  34583. return [4, handler.load()];
  34584. case 1:
  34585. artifacts = _a.sent();
  34586. modelTopology = artifacts.modelTopology;
  34587. if (modelTopology['model_config'] != null) {
  34588. modelTopology = modelTopology['model_config'];
  34589. }
  34590. model = serialization_1.deserialize(serialization_utils_1.convertPythonicToTs(modelTopology), customObjects);
  34591. if (artifacts.weightData != null) {
  34592. if (artifacts.weightSpecs == null) {
  34593. throw new errors_1.ValueError('Model artifacts contains weight data, but not weight specs. ' +
  34594. 'Therefore loading of weights cannot proceed.');
  34595. }
  34596. skipMismatch = false;
  34597. isNamedTensorMap = true;
  34598. model.loadWeights(tfjs_core_1.io.decodeWeights(artifacts.weightData, artifacts.weightSpecs), skipMismatch, isNamedTensorMap);
  34599. }
  34600. return [2, model];
  34601. }
  34602. });
  34603. });
  34604. }
  34605. exports.loadModelFromIOHandler = loadModelFromIOHandler;
  34606. var Sequential = (function (_super) {
  34607. __extends(Sequential, _super);
  34608. function Sequential(config) {
  34609. var _this = _super.call(this, { inputs: [], outputs: [] }) || this;
  34610. config = config || {};
  34611. _this.trainable = true;
  34612. _this._updatable = true;
  34613. _this.built = false;
  34614. _this.name = (config.name != null) ? config.name : K.getUid('sequential_');
  34615. if (config.layers != null) {
  34616. for (var _i = 0, _a = config.layers; _i < _a.length; _i++) {
  34617. var layer = _a[_i];
  34618. _this.add(layer);
  34619. }
  34620. }
  34621. return _this;
  34622. }
  34623. Sequential_1 = Sequential;
  34624. Sequential.prototype.add = function (layer) {
  34625. var isLayerModelInstance = layer instanceof Sequential_1 || layer instanceof training_1.Model;
  34626. var modelLayer;
  34627. if (isLayerModelInstance) {
  34628. modelLayer = layer;
  34629. if (modelLayer.outputs.length !== 1) {
  34630. throw new errors_1.ValueError('All layers in a Sequential model ' +
  34631. 'should have a single output tensor. ' +
  34632. 'For multi-output layers, ' +
  34633. 'use the functional API.');
  34634. }
  34635. if (modelLayer.inputs.length !== 1) {
  34636. throw new errors_1.ValueError('All layers in a Sequential model ' +
  34637. 'should have a single input tensor. ' +
  34638. 'For multi-input layers, ' +
  34639. 'use the functional API.');
  34640. }
  34641. }
  34642. if (this.outputs.length === 0) {
  34643. if (layer.inboundNodes.length === 0) {
  34644. if (layer.batchInputShape == null) {
  34645. throw new errors_1.ValueError('The first layer in a Sequential model must ' +
  34646. 'get an `inputShape` or `batchInputShape` argument.');
  34647. }
  34648. var x = topology_1.Input({
  34649. batchShape: layer.batchInputShape,
  34650. dtype: layer.dtype,
  34651. name: layer.name + '_input'
  34652. });
  34653. layer.apply(x);
  34654. }
  34655. if (isLayerModelInstance) {
  34656. this.outputs = modelLayer.outputs;
  34657. this.inputs = modelLayer.inputs;
  34658. }
  34659. else {
  34660. if (layer.inboundNodes.length !== 1) {
  34661. throw new errors_1.ValueError('A layer added to a Sequential model must not already be ' +
  34662. ("connected somewhere else. Model received layer " + layer.name + " ") +
  34663. ("which has " + layer.inboundNodes.length + " pre-existing inbound ") +
  34664. 'connections.');
  34665. }
  34666. if (layer.inboundNodes[0].outputTensors.length !== 1) {
  34667. throw new errors_1.ValueError('All layers in a Sequential model ' +
  34668. 'should have a single output tensor. ' +
  34669. 'For multi-output layers, ' +
  34670. 'use the functional API.');
  34671. }
  34672. this.outputs = [layer.inboundNodes[0].outputTensors[0]];
  34673. this.inputs = topology_1.getSourceInputs(this.outputs[0]);
  34674. }
  34675. this.inboundNodes = [];
  34676. new topology_1.Node({
  34677. outboundLayer: this,
  34678. inboundLayers: [],
  34679. nodeIndices: [],
  34680. tensorIndices: [],
  34681. inputTensors: this.inputs,
  34682. outputTensors: this.outputs,
  34683. inputMasks: generic_utils.pyListRepeat(null, this.inputs.length),
  34684. outputMasks: [null],
  34685. inputShapes: this.inputs.map(function (x) { return x.shape; }),
  34686. outputShapes: this.outputs[0].shape
  34687. });
  34688. }
  34689. else {
  34690. var outputTensor = layer.apply(this.outputs[0]);
  34691. if (Array.isArray(outputTensor)) {
  34692. throw new TypeError('All layers in a Sequential model ' +
  34693. 'should have a single output tensor. ' +
  34694. 'For multi-output layers, ' +
  34695. 'use the functional API.');
  34696. }
  34697. this.outputs = [outputTensor];
  34698. this.inboundNodes[0].outputTensors = this.outputs;
  34699. this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
  34700. }
  34701. this.layers.push(layer);
  34702. this.built = false;
  34703. };
  34704. Sequential.prototype.pop = function () {
  34705. if (this.layers.length === 0) {
  34706. throw new TypeError('There are no layers in the model.');
  34707. }
  34708. this.layers.pop();
  34709. if (this.layers.length === 0) {
  34710. this.outputs = [];
  34711. this.inboundNodes = [];
  34712. this.outboundNodes = [];
  34713. }
  34714. else {
  34715. var lastLayerIndex = this.layers.length - 1;
  34716. this.layers[lastLayerIndex].outboundNodes = [];
  34717. this.outputs = [this.layers[lastLayerIndex].output];
  34718. this.inboundNodes[0].outputTensors = this.outputs;
  34719. this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
  34720. }
  34721. };
  34722. Sequential.prototype.call = function (inputs, kwargs) {
  34723. if (this.model == null) {
  34724. this.build();
  34725. }
  34726. return this.model.call(inputs, kwargs);
  34727. };
  34728. Sequential.prototype.build = function (inputShape) {
  34729. generic_utils.getExactlyOneShape(inputShape);
  34730. if (this.inputs.length === 0 || this.outputs.length === 0) {
  34731. throw new TypeError('Sequential model cannot be built: model is empty.' +
  34732. ' Add some layers first.');
  34733. }
  34734. this.model = new training_1.Model({
  34735. inputs: this.inputs,
  34736. outputs: this.outputs[0],
  34737. name: this.name + '_model'
  34738. });
  34739. this.model.trainable = this.trainable;
  34740. this.model.updatable = this.updatable;
  34741. this.supportsMasking = this.model.supportsMasking;
  34742. this.inputLayers = this.model.inputLayers;
  34743. this.inputLayersNodeIndices = this.model.inputLayersNodeIndices;
  34744. this.inputLayersTensorIndices = this.model.inputLayersTensorIndices;
  34745. this.outputLayers = this.model.outputLayers;
  34746. this.outputLayersNodeIndices = this.model.outputLayersNodeIndices;
  34747. this.outputLayersTensorIndices = this.model.outputLayersTensorIndices;
  34748. this.nodesByDepth = this.model.nodesByDepth;
  34749. this.containerNodes = this.model.containerNodes;
  34750. this.outputNames = this.model.outputNames;
  34751. this.inputNames = this.model.inputNames;
  34752. this.built = true;
  34753. };
  34754. Sequential.prototype.countParams = function () {
  34755. if (!this.built) {
  34756. this.build();
  34757. }
  34758. return _super.prototype.countParams.call(this);
  34759. };
  34760. Sequential.prototype.summary = function (lineLength, positions, printFn) {
  34761. if (printFn === void 0) { printFn = console.log; }
  34762. if (!this.built) {
  34763. this.build();
  34764. }
  34765. _super.prototype.summary.call(this, lineLength, positions, printFn);
  34766. };
  34767. Sequential.prototype.setWeights = function (weights) {
  34768. if (this.model == null) {
  34769. this.build();
  34770. }
  34771. this.model.setWeights(weights);
  34772. };
  34773. Object.defineProperty(Sequential.prototype, "updatable", {
  34774. get: function () {
  34775. return this._updatable;
  34776. },
  34777. set: function (value) {
  34778. if (this.built) {
  34779. this.model.updatable = value;
  34780. }
  34781. this._updatable = value;
  34782. },
  34783. enumerable: true,
  34784. configurable: true
  34785. });
  34786. Sequential.prototype.evaluate = function (x, y, config) {
  34787. if (config === void 0) { config = {}; }
  34788. if (!this.built) {
  34789. throw new errors_1.RuntimeError('The model needs to be compiled before being used.');
  34790. }
  34791. return this.model.evaluate(x, y, config);
  34792. };
  34793. Sequential.prototype.predict = function (x, config) {
  34794. if (config === void 0) { config = {}; }
  34795. if (this.model == null) {
  34796. this.build();
  34797. }
  34798. return this.model.predict(x, config);
  34799. };
  34800. Sequential.prototype.predictOnBatch = function (x) {
  34801. if (this.model == null) {
  34802. this.build();
  34803. }
  34804. return this.model.predictOnBatch(x);
  34805. };
  34806. Sequential.prototype.compile = function (config) {
  34807. this.build();
  34808. this.model.compile(config);
  34809. this.optimizer = this.model.optimizer;
  34810. this.loss = this.model.loss;
  34811. this.metrics = this.model.metrics;
  34812. this.metricsTensors = this.model.metricsTensors;
  34813. this.metricsNames = this.model.metricsNames;
  34814. };
  34815. Sequential.prototype.fit = function (x, y, config) {
  34816. if (config === void 0) { config = {}; }
  34817. return __awaiter(this, void 0, void 0, function () {
  34818. return __generator(this, function (_a) {
  34819. if (!this.built) {
  34820. throw new errors_1.RuntimeError('The model needs to be compiled before ' +
  34821. 'being used.');
  34822. }
  34823. return [2, this.model.fit(x, y, config)];
  34824. });
  34825. });
  34826. };
  34827. Sequential.fromConfig = function (cls, config) {
  34828. var model = new cls({});
  34829. if (!(model instanceof Sequential_1)) {
  34830. throw new errors_1.ValueError("Sequential.fromConfig called on non-Sequential input: " + model);
  34831. }
  34832. if (!(config instanceof Array)) {
  34833. throw new errors_1.ValueError("Sequential.fromConfig called without an array of configs");
  34834. }
  34835. if (!(config[0].className != null) || config[0]['className'] === 'Merge') {
  34836. throw new errors_1.ValueError('Legacy serialization format not supported yet.');
  34837. }
  34838. for (var _i = 0, _a = config; _i < _a.length; _i++) {
  34839. var conf = _a[_i];
  34840. var layer = serialization_1.deserialize(conf);
  34841. model.add(layer);
  34842. }
  34843. return model;
  34844. };
  34845. Sequential.prototype.getConfig = function () {
  34846. var config = [];
  34847. for (var _i = 0, _a = this.layers; _i < _a.length; _i++) {
  34848. var layer = _a[_i];
  34849. config.push({
  34850. className: layer.getClassName(),
  34851. config: layer.getConfig(),
  34852. });
  34853. }
  34854. return config;
  34855. };
  34856. Sequential.className = 'Sequential';
  34857. __decorate([
  34858. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes' })
  34859. ], Sequential.prototype, "add", null);
  34860. __decorate([
  34861. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes' })
  34862. ], Sequential.prototype, "summary", null);
  34863. __decorate([
  34864. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes', configParamIndices: [2] })
  34865. ], Sequential.prototype, "evaluate", null);
  34866. __decorate([
  34867. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes', configParamIndices: [1] })
  34868. ], Sequential.prototype, "predict", null);
  34869. __decorate([
  34870. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes', configParamIndices: [2] })
  34871. ], Sequential.prototype, "fit", null);
  34872. Sequential = Sequential_1 = __decorate([
  34873. tfjs_core_1.doc({ heading: 'Models', subheading: 'Classes' })
  34874. ], Sequential);
  34875. return Sequential;
  34876. var Sequential_1;
  34877. }(training_1.Model));
  34878. exports.Sequential = Sequential;
  34879. tfjs_core_1.serialization.SerializationMap.register(Sequential);
  34880. },{"./backend/tfjs_backend":169,"./engine/topology":174,"./engine/training":175,"./errors":176,"./layers/serialization":190,"./utils/generic_utils":199,"./utils/serialization_utils":202,"@tensorflow/tfjs-core":54}],195:[function(require,module,exports){
  34881. "use strict";
  34882. Object.defineProperty(exports, "__esModule", { value: true });
  34883. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  34884. var K = require("./backend/tfjs_backend");
  34885. var errors_1 = require("./errors");
  34886. function getOptimizer(identifier) {
  34887. var optimizerMap = {
  34888. 'Adagrad': function () { return tfjs_core_1.train.adagrad(.01); },
  34889. 'Adadelta': function () { return tfjs_core_1.train.adadelta(1.0, 0.95, K.epsilon()); },
  34890. 'Adam': function () { return tfjs_core_1.train.adam(.001, .9, .999, K.epsilon()); },
  34891. 'Adamax': function () { return tfjs_core_1.train.adamax(0.002, .9, .999, K.epsilon(), 0.0); },
  34892. 'RMSProp': function () { return tfjs_core_1.train.rmsprop(.001, .9, null, K.epsilon()); },
  34893. 'SGD': function () { return tfjs_core_1.train.sgd(.01); }
  34894. };
  34895. optimizerMap['adagrad'] = optimizerMap['Adagrad'];
  34896. optimizerMap['adadelta'] = optimizerMap['Adadelta'];
  34897. optimizerMap['adam'] = optimizerMap['Adam'];
  34898. optimizerMap['adamax'] = optimizerMap['Adamax'];
  34899. optimizerMap['rmsprop'] = optimizerMap['RMSProp'];
  34900. optimizerMap['sgd'] = optimizerMap['SGD'];
  34901. if (identifier in optimizerMap) {
  34902. return optimizerMap[identifier]();
  34903. }
  34904. throw new errors_1.ValueError("Unknown Optimizer " + identifier);
  34905. }
  34906. exports.getOptimizer = getOptimizer;
  34907. },{"./backend/tfjs_backend":169,"./errors":176,"@tensorflow/tfjs-core":54}],196:[function(require,module,exports){
  34908. "use strict";
  34909. var __extends = (this && this.__extends) || (function () {
  34910. var extendStatics = Object.setPrototypeOf ||
  34911. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  34912. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  34913. return function (d, b) {
  34914. extendStatics(d, b);
  34915. function __() { this.constructor = d; }
  34916. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  34917. };
  34918. })();
  34919. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  34920. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  34921. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  34922. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  34923. return c > 3 && r && Object.defineProperty(target, key, r), r;
  34924. };
  34925. Object.defineProperty(exports, "__esModule", { value: true });
  34926. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  34927. var K = require("./backend/tfjs_backend");
  34928. var generic_utils_1 = require("./utils/generic_utils");
  34929. var Regularizer = (function (_super) {
  34930. __extends(Regularizer, _super);
  34931. function Regularizer() {
  34932. return _super !== null && _super.apply(this, arguments) || this;
  34933. }
  34934. return Regularizer;
  34935. }(tfjs_core_1.serialization.Serializable));
  34936. exports.Regularizer = Regularizer;
  34937. var L1L2 = (function (_super) {
  34938. __extends(L1L2, _super);
  34939. function L1L2(config) {
  34940. var _this = _super.call(this) || this;
  34941. var l1 = config == null || config.l1 == null ? 0.01 : config.l1;
  34942. var l2 = config == null || config.l2 == null ? 0.01 : config.l2;
  34943. _this.hasL1 = l1 !== 0;
  34944. _this.hasL2 = l2 !== 0;
  34945. _this.l1 = K.getScalar(l1);
  34946. _this.l2 = K.getScalar(l2);
  34947. return _this;
  34948. }
  34949. L1L2.prototype.apply = function (x) {
  34950. var _this = this;
  34951. return tfjs_core_1.tidy(function () {
  34952. var regularization = tfjs_core_1.zeros([1]);
  34953. if (_this.hasL1) {
  34954. regularization =
  34955. tfjs_core_1.add(regularization, tfjs_core_1.sum(K.scalarTimesArray(_this.l1, tfjs_core_1.abs(x))));
  34956. }
  34957. if (_this.hasL2) {
  34958. regularization =
  34959. tfjs_core_1.add(regularization, tfjs_core_1.sum(K.scalarTimesArray(_this.l2, K.square(x))));
  34960. }
  34961. return regularization.asScalar();
  34962. });
  34963. };
  34964. L1L2.prototype.getConfig = function () {
  34965. return { 'l1': this.l1.dataSync()[0], 'l2': this.l2.dataSync()[0] };
  34966. };
  34967. L1L2.fromConfig = function (cls, config) {
  34968. return new cls({ l1: config.l1, l2: config.l2 });
  34969. };
  34970. L1L2.className = 'L1L2';
  34971. L1L2 = __decorate([
  34972. tfjs_core_1.doc({ heading: 'Regularizers', namespace: 'regularizers' })
  34973. ], L1L2);
  34974. return L1L2;
  34975. }(Regularizer));
  34976. exports.L1L2 = L1L2;
  34977. tfjs_core_1.serialization.SerializationMap.register(L1L2);
  34978. function l1(config) {
  34979. return new L1L2({ l1: config != null ? config.l1 : null, l2: 0 });
  34980. }
  34981. exports.l1 = l1;
  34982. function l2(config) {
  34983. return new L1L2({ l2: config != null ? config.l2 : null, l1: 0 });
  34984. }
  34985. exports.l2 = l2;
  34986. exports.REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP = {
  34987. 'l1l2': 'L1L2'
  34988. };
  34989. function serializeRegularizer(constraint) {
  34990. return generic_utils_1.serializeKerasObject(constraint);
  34991. }
  34992. exports.serializeRegularizer = serializeRegularizer;
  34993. function deserializeRegularizer(config, customObjects) {
  34994. if (customObjects === void 0) { customObjects = {}; }
  34995. return generic_utils_1.deserializeKerasObject(config, tfjs_core_1.serialization.SerializationMap.getMap().classNameMap, customObjects, 'regularizer');
  34996. }
  34997. exports.deserializeRegularizer = deserializeRegularizer;
  34998. function getRegularizer(identifier) {
  34999. if (identifier == null) {
  35000. return null;
  35001. }
  35002. if (typeof identifier === 'string') {
  35003. var className = identifier in exports.REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP ?
  35004. exports.REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] :
  35005. identifier;
  35006. var config = { className: className, config: {} };
  35007. return deserializeRegularizer(config);
  35008. }
  35009. else if (identifier instanceof Regularizer) {
  35010. return identifier;
  35011. }
  35012. else {
  35013. return deserializeRegularizer(identifier);
  35014. }
  35015. }
  35016. exports.getRegularizer = getRegularizer;
  35017. },{"./backend/tfjs_backend":169,"./utils/generic_utils":199,"@tensorflow/tfjs-core":54}],197:[function(require,module,exports){
  35018. "use strict";
  35019. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  35020. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  35021. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  35022. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  35023. return c > 3 && r && Object.defineProperty(target, key, r), r;
  35024. };
  35025. Object.defineProperty(exports, "__esModule", { value: true });
  35026. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  35027. var common_1 = require("./common");
  35028. var _nextUniqueTensorId = 0;
  35029. function getNextUniqueTensorId() {
  35030. return _nextUniqueTensorId++;
  35031. }
  35032. exports.getNextUniqueTensorId = getNextUniqueTensorId;
  35033. var SymbolicTensor = (function () {
  35034. function SymbolicTensor(dtype, shape, sourceLayer, inputs, callArgs, name, outputTensorIndex) {
  35035. this.dtype = dtype;
  35036. this.shape = shape;
  35037. this.sourceLayer = sourceLayer;
  35038. this.inputs = inputs;
  35039. this.callArgs = callArgs;
  35040. this.outputTensorIndex = outputTensorIndex;
  35041. this.id = getNextUniqueTensorId();
  35042. if (name != null) {
  35043. this.originalName = common_1.getScopedTensorName(name);
  35044. this.name = common_1.getUniqueTensorName(this.originalName);
  35045. }
  35046. this.rank = shape.length;
  35047. }
  35048. SymbolicTensor = __decorate([
  35049. tfjs_core_1.doc({ heading: 'Models', 'subheading': 'Classes' })
  35050. ], SymbolicTensor);
  35051. return SymbolicTensor;
  35052. }());
  35053. exports.SymbolicTensor = SymbolicTensor;
  35054. },{"./common":171,"@tensorflow/tfjs-core":54}],198:[function(require,module,exports){
  35055. "use strict";
  35056. Object.defineProperty(exports, "__esModule", { value: true });
  35057. var errors_1 = require("../errors");
  35058. var generic_utils_1 = require("./generic_utils");
  35059. var math_utils_1 = require("./math_utils");
  35060. function normalizeArray(value, n, name) {
  35061. if (typeof value === 'number') {
  35062. return generic_utils_1.pyListRepeat(value, n);
  35063. }
  35064. else {
  35065. if (value.length !== n) {
  35066. throw new errors_1.ValueError("The " + name + " argument must be a tuple of " + n + " integers. Received: " +
  35067. (value.length + " elements."));
  35068. }
  35069. for (var i = 0; i < n; ++i) {
  35070. var singleValue = value[i];
  35071. if (!math_utils_1.isInteger(singleValue)) {
  35072. throw new errors_1.ValueError("The " + name + " argument must be a tuple of " + n + " integers. Received: " +
  35073. (JSON.stringify(value) + " including a non-integer number ") +
  35074. ("" + singleValue));
  35075. }
  35076. }
  35077. return value;
  35078. }
  35079. }
  35080. exports.normalizeArray = normalizeArray;
  35081. function convOutputLength(inputLength, filterSize, padding, stride, dilation) {
  35082. if (dilation === void 0) { dilation = 1; }
  35083. if (inputLength == null) {
  35084. return inputLength;
  35085. }
  35086. var dilatedFilterSize = filterSize + (filterSize - 1) * (dilation - 1);
  35087. var outputLength;
  35088. if (padding === 'same') {
  35089. outputLength = inputLength;
  35090. }
  35091. else {
  35092. outputLength = inputLength - dilatedFilterSize + 1;
  35093. }
  35094. return Math.floor((outputLength + stride - 1) / stride);
  35095. }
  35096. exports.convOutputLength = convOutputLength;
  35097. function deconvLength(dimSize, strideSize, kernelSize, padding) {
  35098. if (dimSize == null) {
  35099. return null;
  35100. }
  35101. if (padding === 'valid') {
  35102. dimSize = dimSize * strideSize + math_utils_1.max([kernelSize - strideSize, 0]);
  35103. }
  35104. else if (padding === 'same') {
  35105. dimSize = dimSize * strideSize;
  35106. }
  35107. else {
  35108. throw new errors_1.ValueError("Unsupport padding mode: " + padding + ".");
  35109. }
  35110. return dimSize;
  35111. }
  35112. exports.deconvLength = deconvLength;
  35113. },{"../errors":176,"./generic_utils":199,"./math_utils":201}],199:[function(require,module,exports){
  35114. "use strict";
  35115. var __assign = (this && this.__assign) || Object.assign || function(t) {
  35116. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35117. s = arguments[i];
  35118. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35119. t[p] = s[p];
  35120. }
  35121. return t;
  35122. };
  35123. Object.defineProperty(exports, "__esModule", { value: true });
  35124. var errors_1 = require("../errors");
  35125. function pyListRepeat(value, numValues) {
  35126. if (Array.isArray(value)) {
  35127. var newArray = [];
  35128. for (var i = 0; i < numValues; i++) {
  35129. newArray = newArray.concat(value);
  35130. }
  35131. return newArray;
  35132. }
  35133. else {
  35134. var newArray = new Array(numValues);
  35135. newArray.fill(value);
  35136. return newArray;
  35137. }
  35138. }
  35139. exports.pyListRepeat = pyListRepeat;
  35140. function assert(val, message) {
  35141. if (!val) {
  35142. throw new errors_1.AssertionError(message);
  35143. }
  35144. }
  35145. exports.assert = assert;
  35146. function count(array, refernce) {
  35147. var counter = 0;
  35148. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  35149. var item = array_1[_i];
  35150. if (item === refernce) {
  35151. counter++;
  35152. }
  35153. }
  35154. return counter;
  35155. }
  35156. exports.count = count;
  35157. function singletonOrArray(xs) {
  35158. if (xs.length === 1) {
  35159. return xs[0];
  35160. }
  35161. return xs;
  35162. }
  35163. exports.singletonOrArray = singletonOrArray;
  35164. function toList(x) {
  35165. if (Array.isArray(x)) {
  35166. return x;
  35167. }
  35168. return [x];
  35169. }
  35170. exports.toList = toList;
  35171. function objectListUid(objs) {
  35172. var objectList = toList(objs);
  35173. var retVal = '';
  35174. for (var _i = 0, objectList_1 = objectList; _i < objectList_1.length; _i++) {
  35175. var obj = objectList_1[_i];
  35176. if (obj.id == null) {
  35177. throw new errors_1.ValueError("Object " + obj + " passed to objectListUid without an id");
  35178. }
  35179. if (retVal !== '') {
  35180. retVal = retVal + ', ';
  35181. }
  35182. retVal = retVal + Math.abs(obj.id);
  35183. }
  35184. return retVal;
  35185. }
  35186. exports.objectListUid = objectListUid;
  35187. function isArrayOfShapes(x) {
  35188. return Array.isArray(x) && Array.isArray(x[0]);
  35189. }
  35190. exports.isArrayOfShapes = isArrayOfShapes;
  35191. function normalizeShapeList(x) {
  35192. if (x.length === 0) {
  35193. return [];
  35194. }
  35195. if (!Array.isArray(x[0])) {
  35196. return [x];
  35197. }
  35198. return x;
  35199. }
  35200. exports.normalizeShapeList = normalizeShapeList;
  35201. function toSnakeCase(name) {
  35202. var intermediate = name.replace(/(.)([A-Z][a-z0-9]+)/g, '$1_$2');
  35203. var insecure = intermediate.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
  35204. if (insecure[0] !== '_') {
  35205. return insecure;
  35206. }
  35207. return 'private' + insecure;
  35208. }
  35209. exports.toSnakeCase = toSnakeCase;
  35210. function toCamelCase(identifier) {
  35211. if (identifier.length <= 1) {
  35212. return identifier;
  35213. }
  35214. if (identifier.indexOf('_') === -1) {
  35215. return identifier;
  35216. }
  35217. return identifier.replace(/[_]+(\w|$)/g, function (m, p1) { return p1.toUpperCase(); });
  35218. }
  35219. exports.toCamelCase = toCamelCase;
  35220. var _GLOBAL_CUSTOM_OBJECTS = {};
  35221. function serializeKerasObject(instance) {
  35222. if (instance === null || instance === undefined) {
  35223. return null;
  35224. }
  35225. return { className: instance.getClassName(), config: instance.getConfig() };
  35226. }
  35227. exports.serializeKerasObject = serializeKerasObject;
  35228. function deserializeKerasObject(identifier, moduleObjects, customObjects, printableModuleName) {
  35229. if (moduleObjects === void 0) { moduleObjects = {}; }
  35230. if (customObjects === void 0) { customObjects = {}; }
  35231. if (printableModuleName === void 0) { printableModuleName = 'object'; }
  35232. if (typeof identifier === 'string') {
  35233. var functionName = identifier;
  35234. var fn = void 0;
  35235. if (functionName in customObjects) {
  35236. fn = customObjects[functionName];
  35237. }
  35238. else if (functionName in _GLOBAL_CUSTOM_OBJECTS) {
  35239. fn = _GLOBAL_CUSTOM_OBJECTS[functionName];
  35240. }
  35241. else {
  35242. fn = moduleObjects[functionName];
  35243. if (fn == null) {
  35244. throw new errors_1.ValueError("Unknown " + printableModuleName + ": " + identifier);
  35245. }
  35246. }
  35247. return fn;
  35248. }
  35249. else {
  35250. var config = identifier;
  35251. if (config.className == null || config.config == null) {
  35252. throw new errors_1.ValueError(printableModuleName + ": Improper config format: " +
  35253. (JSON.stringify(config) + ".\n") +
  35254. "'className' and 'config' must set.");
  35255. }
  35256. var className = config.className;
  35257. var cls = void 0, fromConfig = void 0;
  35258. if (className in customObjects) {
  35259. _a = customObjects.get(className), cls = _a[0], fromConfig = _a[1];
  35260. }
  35261. else if (className in _GLOBAL_CUSTOM_OBJECTS) {
  35262. _b = _GLOBAL_CUSTOM_OBJECTS.className, cls = _b[0], fromConfig = _b[1];
  35263. }
  35264. else if (className in moduleObjects) {
  35265. _c = moduleObjects[className], cls = _c[0], fromConfig = _c[1];
  35266. }
  35267. if (cls == null) {
  35268. throw new errors_1.ValueError("Unknown " + printableModuleName + ": " + className);
  35269. }
  35270. if (fromConfig != null) {
  35271. var customObjectsCombined = {};
  35272. for (var _i = 0, _d = Object.keys(_GLOBAL_CUSTOM_OBJECTS); _i < _d.length; _i++) {
  35273. var key = _d[_i];
  35274. customObjectsCombined[key] = _GLOBAL_CUSTOM_OBJECTS[key];
  35275. }
  35276. for (var _e = 0, _f = Object.keys(customObjects); _e < _f.length; _e++) {
  35277. var key = _f[_e];
  35278. customObjectsCombined[key] = customObjects[key];
  35279. }
  35280. var nestedConfig = config.config;
  35281. nestedConfig.customObjects = customObjectsCombined;
  35282. var backupCustomObjects = __assign({}, _GLOBAL_CUSTOM_OBJECTS);
  35283. for (var _g = 0, _h = Object.keys(customObjects); _g < _h.length; _g++) {
  35284. var key = _h[_g];
  35285. _GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key];
  35286. }
  35287. var returnObj = fromConfig(cls, config.config);
  35288. _GLOBAL_CUSTOM_OBJECTS = __assign({}, backupCustomObjects);
  35289. return returnObj;
  35290. }
  35291. else {
  35292. var backupCustomObjects = __assign({}, _GLOBAL_CUSTOM_OBJECTS);
  35293. for (var _j = 0, _k = Object.keys(customObjects); _j < _k.length; _j++) {
  35294. var key = _k[_j];
  35295. _GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key];
  35296. }
  35297. var returnObj = new cls(config.config);
  35298. _GLOBAL_CUSTOM_OBJECTS = __assign({}, backupCustomObjects);
  35299. return returnObj;
  35300. }
  35301. }
  35302. var _a, _b, _c;
  35303. }
  35304. exports.deserializeKerasObject = deserializeKerasObject;
  35305. function getExactlyOneTensor(xs) {
  35306. var x;
  35307. if (Array.isArray(xs)) {
  35308. if (xs.length !== 1) {
  35309. throw new errors_1.ValueError("Expected Tensor length to be 1; got " + xs.length);
  35310. }
  35311. x = xs[0];
  35312. }
  35313. else {
  35314. x = xs;
  35315. }
  35316. return x;
  35317. }
  35318. exports.getExactlyOneTensor = getExactlyOneTensor;
  35319. function getExactlyOneShape(shapes) {
  35320. if (Array.isArray(shapes) && Array.isArray(shapes[0])) {
  35321. if (shapes.length === 1) {
  35322. shapes = shapes;
  35323. return shapes[0];
  35324. }
  35325. else {
  35326. throw new errors_1.ValueError("Expected exactly 1 Shape; got " + shapes.length);
  35327. }
  35328. }
  35329. else {
  35330. return shapes;
  35331. }
  35332. }
  35333. exports.getExactlyOneShape = getExactlyOneShape;
  35334. function numberCompare(a, b) {
  35335. return (a < b) ? -1 : ((a > b) ? 1 : 0);
  35336. }
  35337. exports.numberCompare = numberCompare;
  35338. function reverseNumberCompare(a, b) {
  35339. return -1 * numberCompare(a, b);
  35340. }
  35341. exports.reverseNumberCompare = reverseNumberCompare;
  35342. function stringToDType(dtype) {
  35343. switch (dtype) {
  35344. case 'float32':
  35345. return 'float32';
  35346. default:
  35347. throw new errors_1.ValueError("Invalid dtype: " + dtype);
  35348. }
  35349. }
  35350. exports.stringToDType = stringToDType;
  35351. function stringsEqual(xs, ys) {
  35352. if (xs == null || ys == null) {
  35353. return xs === ys;
  35354. }
  35355. if (xs.length !== ys.length) {
  35356. return false;
  35357. }
  35358. for (var i = 0; i < xs.length; ++i) {
  35359. if (xs[i] !== ys[i]) {
  35360. return false;
  35361. }
  35362. }
  35363. return true;
  35364. }
  35365. exports.stringsEqual = stringsEqual;
  35366. function unique(xs) {
  35367. if (xs == null) {
  35368. return xs;
  35369. }
  35370. var out = [];
  35371. for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
  35372. var x = xs_1[_i];
  35373. if (out.indexOf(x) === -1) {
  35374. out.push(x);
  35375. }
  35376. }
  35377. return out;
  35378. }
  35379. exports.unique = unique;
  35380. function isObjectEmpty(obj) {
  35381. if (obj == null) {
  35382. throw new errors_1.ValueError("Invalid value in obj: " + JSON.stringify(obj));
  35383. }
  35384. for (var key in obj) {
  35385. if (obj.hasOwnProperty(key)) {
  35386. return false;
  35387. }
  35388. }
  35389. return true;
  35390. }
  35391. exports.isObjectEmpty = isObjectEmpty;
  35392. function checkStringTypeUnionValue(values, label, value) {
  35393. if (value == null) {
  35394. return;
  35395. }
  35396. if (values.indexOf(value) < 0) {
  35397. throw new errors_1.ValueError(value + " is not a valid " + label + ". Valid values are " + values + " or null/undefined.");
  35398. }
  35399. }
  35400. exports.checkStringTypeUnionValue = checkStringTypeUnionValue;
  35401. function checkArrayTypeAndLength(x, expectedType, minLength, maxLength) {
  35402. if (minLength === void 0) { minLength = 0; }
  35403. if (maxLength === void 0) { maxLength = Infinity; }
  35404. assert(minLength >= 0);
  35405. assert(maxLength >= minLength);
  35406. return (Array.isArray(x) && x.length >= minLength && x.length <= maxLength &&
  35407. x.every(function (e) { return typeof e === expectedType; }));
  35408. }
  35409. exports.checkArrayTypeAndLength = checkArrayTypeAndLength;
  35410. function countParamsInWeights(weights) {
  35411. var count = 0;
  35412. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  35413. var weight = weights_1[_i];
  35414. if (weight.shape.length === 0) {
  35415. count += 1;
  35416. }
  35417. else {
  35418. count += weight.shape.reduce(function (a, b) { return a * b; });
  35419. }
  35420. }
  35421. return count;
  35422. }
  35423. exports.countParamsInWeights = countParamsInWeights;
  35424. },{"../errors":176}],200:[function(require,module,exports){
  35425. "use strict";
  35426. Object.defineProperty(exports, "__esModule", { value: true });
  35427. var generic_utils_1 = require("./generic_utils");
  35428. function printSummary(model, lineLength, positions, printFn) {
  35429. if (printFn === void 0) { printFn = console.log; }
  35430. var sequentialLike = isModelSequentialLike(model);
  35431. var toDisplay = ['Layer (type)', 'Output shape', 'Param #'];
  35432. if (sequentialLike) {
  35433. lineLength = lineLength || 65;
  35434. positions = positions || [0.45, 0.85, 1];
  35435. }
  35436. else {
  35437. lineLength = lineLength || 98;
  35438. positions = positions || [0.33, 0.55, 0.67, 1];
  35439. }
  35440. if (positions[positions.length - 1] <= 1) {
  35441. positions = positions.map(function (p) { return Math.floor(lineLength * p); });
  35442. }
  35443. var relevantNodes;
  35444. if (!sequentialLike) {
  35445. toDisplay.push('Receives inputs');
  35446. relevantNodes = [];
  35447. for (var depth in model.nodesByDepth) {
  35448. relevantNodes.push.apply(relevantNodes, model.nodesByDepth[depth]);
  35449. }
  35450. }
  35451. printFn('_'.repeat(lineLength));
  35452. printRow(toDisplay, positions, printFn);
  35453. printFn('='.repeat(lineLength));
  35454. var layers = model.layers;
  35455. for (var i = 0; i < layers.length; ++i) {
  35456. if (sequentialLike) {
  35457. printLayerSummary(layers[i], positions, printFn);
  35458. }
  35459. else {
  35460. printLayerSummaryWithConnections(layers[i], positions, relevantNodes, printFn);
  35461. }
  35462. printFn((i === layers.length - 1 ? '=' : '_').repeat(lineLength));
  35463. }
  35464. model.checkTrainableWeightsConsistency();
  35465. var trainableCount;
  35466. if (model.collectedTrainableWeights != null) {
  35467. trainableCount =
  35468. generic_utils_1.countParamsInWeights(model.collectedTrainableWeights);
  35469. }
  35470. else {
  35471. trainableCount = generic_utils_1.countParamsInWeights(model.trainableWeights);
  35472. }
  35473. var nonTrainableCount = generic_utils_1.countParamsInWeights(model.nonTrainableWeights);
  35474. printFn("Total params: " + (trainableCount + nonTrainableCount));
  35475. printFn("Trainable params: " + trainableCount);
  35476. printFn("Non-trainable params: " + nonTrainableCount);
  35477. printFn('_'.repeat(lineLength));
  35478. }
  35479. exports.printSummary = printSummary;
  35480. function isModelSequentialLike(model) {
  35481. var sequentialLike = true;
  35482. var nodesByDepth = [];
  35483. var nodes = [];
  35484. for (var depth in model.nodesByDepth) {
  35485. nodesByDepth.push(model.nodesByDepth[depth]);
  35486. }
  35487. for (var _i = 0, nodesByDepth_1 = nodesByDepth; _i < nodesByDepth_1.length; _i++) {
  35488. var depthNodes = nodesByDepth_1[_i];
  35489. if (depthNodes.length > 1 ||
  35490. depthNodes.length === 1 && depthNodes[0].inboundLayers.length > 1) {
  35491. sequentialLike = false;
  35492. break;
  35493. }
  35494. nodes.push.apply(nodes, depthNodes);
  35495. }
  35496. if (sequentialLike) {
  35497. for (var _a = 0, _b = model.layers; _a < _b.length; _a++) {
  35498. var layer = _b[_a];
  35499. var flag = false;
  35500. for (var _c = 0, _d = layer.inboundNodes; _c < _d.length; _c++) {
  35501. var node = _d[_c];
  35502. if (nodes.indexOf(node) !== -1) {
  35503. if (flag) {
  35504. sequentialLike = false;
  35505. break;
  35506. }
  35507. else {
  35508. flag = true;
  35509. }
  35510. }
  35511. }
  35512. if (!sequentialLike) {
  35513. break;
  35514. }
  35515. }
  35516. }
  35517. return sequentialLike;
  35518. }
  35519. function printRow(fields, positions, printFn) {
  35520. if (printFn === void 0) { printFn = console.log; }
  35521. var line = '';
  35522. for (var i = 0; i < fields.length; ++i) {
  35523. if (i > 0) {
  35524. line = line.slice(0, line.length - 1) + ' ';
  35525. }
  35526. line += fields[i];
  35527. line = line.slice(0, positions[i]);
  35528. line += ' '.repeat(positions[i] - line.length);
  35529. }
  35530. printFn(line);
  35531. }
  35532. function printLayerSummary(layer, positions, printFn) {
  35533. var outputShape;
  35534. try {
  35535. outputShape = JSON.stringify(layer.outputShape);
  35536. }
  35537. catch (err) {
  35538. outputShape = 'multiple';
  35539. }
  35540. var name = layer.name;
  35541. var className = layer.getClassName();
  35542. var fields = [name + " (" + className + ")", outputShape, layer.countParams().toString()];
  35543. printRow(fields, positions, printFn);
  35544. }
  35545. function printLayerSummaryWithConnections(layer, positions, relevantNodes, printFn) {
  35546. var outputShape;
  35547. try {
  35548. outputShape = JSON.stringify(layer.outputShape);
  35549. }
  35550. catch (err) {
  35551. outputShape = 'multiple';
  35552. }
  35553. var connections = [];
  35554. for (var _i = 0, _a = layer.inboundNodes; _i < _a.length; _i++) {
  35555. var node = _a[_i];
  35556. if (relevantNodes != null && relevantNodes.length > 0 &&
  35557. relevantNodes.indexOf(node) === -1) {
  35558. continue;
  35559. }
  35560. for (var i = 0; i < node.inboundLayers.length; ++i) {
  35561. var inboundLayer = node.inboundLayers[i].name;
  35562. var inboundLayerIndex = node.nodeIndices[i];
  35563. var inboundTensorIndex = node.tensorIndices[i];
  35564. connections.push(inboundLayer + "[" + inboundLayerIndex + "][" + inboundTensorIndex + "]");
  35565. }
  35566. }
  35567. var name = layer.name;
  35568. var className = layer.getClassName();
  35569. var firstConnection = connections.length === 0 ? '' : connections[0];
  35570. var fields = [
  35571. name + " (" + className + ")", outputShape, layer.countParams().toString(),
  35572. firstConnection
  35573. ];
  35574. printRow(fields, positions, printFn);
  35575. for (var i = 1; i < connections.length; ++i) {
  35576. printRow(['', '', '', connections[i]], positions, printFn);
  35577. }
  35578. }
  35579. },{"./generic_utils":199}],201:[function(require,module,exports){
  35580. "use strict";
  35581. Object.defineProperty(exports, "__esModule", { value: true });
  35582. var tfc = require("@tensorflow/tfjs-core");
  35583. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  35584. var errors_1 = require("../errors");
  35585. function isInteger(x) {
  35586. return x === parseInt(x.toString(), 10);
  35587. }
  35588. exports.isInteger = isInteger;
  35589. function arrayProd(array, begin, end) {
  35590. if (begin == null) {
  35591. begin = 0;
  35592. }
  35593. if (end == null) {
  35594. end = array.length;
  35595. }
  35596. var prod = 1;
  35597. for (var i = begin; i < end; ++i) {
  35598. prod *= array[i];
  35599. }
  35600. return prod;
  35601. }
  35602. exports.arrayProd = arrayProd;
  35603. function toArray1D(array) {
  35604. array = Array.isArray(array) ? new Float32Array(array) : array;
  35605. return tfjs_core_1.tensor1d(array);
  35606. }
  35607. function min(array) {
  35608. return tfc.min(toArray1D(array)).dataSync()[0];
  35609. }
  35610. exports.min = min;
  35611. function max(array) {
  35612. return tfc.max(toArray1D(array)).dataSync()[0];
  35613. }
  35614. exports.max = max;
  35615. function sum(array) {
  35616. return tfc.sum(toArray1D(array)).dataSync()[0];
  35617. }
  35618. exports.sum = sum;
  35619. function mean(array) {
  35620. return sum(array) / array.length;
  35621. }
  35622. exports.mean = mean;
  35623. function variance(array) {
  35624. var demeaned = tfc.sub(toArray1D(array), tfjs_core_1.scalar(mean(array)));
  35625. var sumSquare = tfc.sum(tfc.mulStrict(demeaned, demeaned)).dataSync()[0];
  35626. return sumSquare / array.length;
  35627. }
  35628. exports.variance = variance;
  35629. function median(array) {
  35630. var arraySorted = array.slice().sort(function (a, b) { return a - b; });
  35631. var lowIdx = Math.floor((arraySorted.length - 1) / 2);
  35632. var highIdx = Math.ceil((arraySorted.length - 1) / 2);
  35633. if (lowIdx === highIdx) {
  35634. return arraySorted[lowIdx];
  35635. }
  35636. return (arraySorted[lowIdx] + arraySorted[highIdx]) / 2;
  35637. }
  35638. exports.median = median;
  35639. function range(begin, end) {
  35640. if (end < begin) {
  35641. throw new errors_1.ValueError("end (" + end + ") < begin (" + begin + ") is forbidden.");
  35642. }
  35643. var out = [];
  35644. for (var i = begin; i < end; ++i) {
  35645. out.push(i);
  35646. }
  35647. return out;
  35648. }
  35649. exports.range = range;
  35650. },{"../errors":176,"@tensorflow/tfjs-core":54}],202:[function(require,module,exports){
  35651. "use strict";
  35652. Object.defineProperty(exports, "__esModule", { value: true });
  35653. var generic_utils = require("../utils/generic_utils");
  35654. function isArrayItemInputOrOutputName(key, index, value) {
  35655. return (key === 'inboundNodes' || key === 'outputLayers' ||
  35656. key === 'inputLayers') &&
  35657. index === 0 && typeof value === 'string';
  35658. }
  35659. function convertPythonicToTs(pythonicConfig, key) {
  35660. if (pythonicConfig === null) {
  35661. return null;
  35662. }
  35663. else if (typeof pythonicConfig === 'string') {
  35664. return generic_utils.toCamelCase(pythonicConfig);
  35665. }
  35666. else if ((typeof pythonicConfig === 'number') ||
  35667. (typeof pythonicConfig === 'boolean')) {
  35668. return pythonicConfig;
  35669. }
  35670. else if (pythonicConfig instanceof Array) {
  35671. var tsArray = [];
  35672. var arrayLength = pythonicConfig.length;
  35673. for (var i = 0; i < arrayLength; ++i) {
  35674. var item = pythonicConfig[i];
  35675. if (isArrayItemInputOrOutputName(key, i, item)) {
  35676. tsArray.push(item);
  35677. }
  35678. else {
  35679. tsArray.push(convertPythonicToTs(item, key));
  35680. }
  35681. }
  35682. return tsArray;
  35683. }
  35684. else {
  35685. var tsDict = {};
  35686. for (var _i = 0, _a = Object.keys(pythonicConfig); _i < _a.length; _i++) {
  35687. var pythonicKey = _a[_i];
  35688. var pythonicValue = pythonicConfig[pythonicKey];
  35689. if (pythonicKey === 'name' && typeof pythonicValue === 'string') {
  35690. tsDict[pythonicKey] = pythonicValue;
  35691. }
  35692. else {
  35693. var tsKey = generic_utils.toCamelCase(pythonicKey);
  35694. tsDict[tsKey] = convertPythonicToTs(pythonicValue, tsKey);
  35695. }
  35696. }
  35697. return tsDict;
  35698. }
  35699. }
  35700. exports.convertPythonicToTs = convertPythonicToTs;
  35701. function convertTsToPythonic(tsConfig, key) {
  35702. if (tsConfig === null || tsConfig === undefined) {
  35703. return null;
  35704. }
  35705. else if (typeof tsConfig === 'string') {
  35706. return generic_utils.toSnakeCase(tsConfig);
  35707. }
  35708. else if ((typeof tsConfig === 'number') || (typeof tsConfig === 'boolean')) {
  35709. return tsConfig;
  35710. }
  35711. else if (tsConfig instanceof Array) {
  35712. var pyArray = [];
  35713. var arrayLength = tsConfig.length;
  35714. for (var i = 0; i < arrayLength; ++i) {
  35715. var item = tsConfig[i];
  35716. if (isArrayItemInputOrOutputName(key, i, item)) {
  35717. pyArray.push(item);
  35718. }
  35719. else {
  35720. pyArray.push(convertTsToPythonic(item, key));
  35721. }
  35722. }
  35723. return pyArray;
  35724. }
  35725. else {
  35726. var pyDict = {};
  35727. for (var _i = 0, _a = Object.keys(tsConfig); _i < _a.length; _i++) {
  35728. var tsKey = _a[_i];
  35729. var tsValue = tsConfig[tsKey];
  35730. var pyKey = generic_utils.toSnakeCase(tsKey);
  35731. if ((tsKey === 'name' || tsKey === 'className') &&
  35732. typeof tsValue === 'string') {
  35733. pyDict[pyKey] = tsValue;
  35734. }
  35735. else {
  35736. pyDict[pyKey] = convertTsToPythonic(tsValue, tsKey);
  35737. }
  35738. }
  35739. return pyDict;
  35740. }
  35741. }
  35742. exports.convertTsToPythonic = convertTsToPythonic;
  35743. },{"../utils/generic_utils":199}],203:[function(require,module,exports){
  35744. "use strict";
  35745. Object.defineProperty(exports, "__esModule", { value: true });
  35746. var tfc = require("@tensorflow/tfjs-core");
  35747. var tfjs_backend_1 = require("./backend/tfjs_backend");
  35748. var common_1 = require("./common");
  35749. var errors_1 = require("./errors");
  35750. var types_1 = require("./types");
  35751. var DEFAULT_VARIABLE_NAME_PREFIX = 'Variable';
  35752. var LayerVariable = (function () {
  35753. function LayerVariable(val, dtype, name, trainable, constraint) {
  35754. if (dtype === void 0) { dtype = 'float32'; }
  35755. if (name === void 0) { name = DEFAULT_VARIABLE_NAME_PREFIX; }
  35756. if (trainable === void 0) { trainable = true; }
  35757. if (constraint === void 0) { constraint = null; }
  35758. this.dtype = dtype == null ? 'float32' : dtype;
  35759. this.shape = val.shape;
  35760. this.id = types_1.getNextUniqueTensorId();
  35761. name = name == null ? DEFAULT_VARIABLE_NAME_PREFIX : name;
  35762. this.originalName = common_1.getScopedTensorName(name);
  35763. this.name = common_1.getUniqueTensorName(this.originalName);
  35764. this.trainable = trainable;
  35765. this.constraint = constraint;
  35766. this.val = tfc.variable(val, this.trainable, this.name, this.dtype);
  35767. }
  35768. LayerVariable.prototype.read = function () {
  35769. return this.val;
  35770. };
  35771. LayerVariable.prototype.write = function (newVal) {
  35772. checkShapesMatch(this.val, newVal);
  35773. this.val.assign(newVal);
  35774. if (this.constraint != null) {
  35775. this.val.assign(this.constraint.apply(this.val));
  35776. }
  35777. return this;
  35778. };
  35779. return LayerVariable;
  35780. }());
  35781. exports.LayerVariable = LayerVariable;
  35782. function checkShapesMatch(x, y) {
  35783. if (x.shape.toString() !== y.shape.toString()) {
  35784. throw new Error('Shape mismatch: ' + JSON.stringify(x.shape) + ' vs. ' +
  35785. JSON.stringify(y.shape));
  35786. }
  35787. }
  35788. function variable(x, dtype, name, constraint) {
  35789. return new LayerVariable(x, dtype, name, true, constraint);
  35790. }
  35791. exports.variable = variable;
  35792. function zerosVariable(shape, dtype, name) {
  35793. return new LayerVariable(tfc.zeros(shape), dtype, name);
  35794. }
  35795. exports.zerosVariable = zerosVariable;
  35796. function zerosLike(x, dtype, name) {
  35797. return new LayerVariable(tfc.zerosLike(x), dtype, name);
  35798. }
  35799. exports.zerosLike = zerosLike;
  35800. function onesVariable(shape, dtype, name) {
  35801. var allocated = tfc.ones(shape);
  35802. return new LayerVariable(allocated, dtype, name);
  35803. }
  35804. exports.onesVariable = onesVariable;
  35805. function onesLike(x, dtype, name) {
  35806. var allocated = tfc.onesLike(x);
  35807. return new LayerVariable(allocated, dtype, name);
  35808. }
  35809. exports.onesLike = onesLike;
  35810. function eyeVariable(size, dtype, name) {
  35811. return new LayerVariable(tfc.eye(size), dtype, name);
  35812. }
  35813. exports.eyeVariable = eyeVariable;
  35814. function randomUniformVariable(shape, minval, maxval, dtype, seed, name) {
  35815. if (name === void 0) { name = 'randomUniform'; }
  35816. return new LayerVariable(tfc.randomUniform(shape, minval, maxval, dtype), dtype, name);
  35817. }
  35818. exports.randomUniformVariable = randomUniformVariable;
  35819. function truncatedNormalVariable(shape, mean, stddev, dtype, seed, name) {
  35820. if (mean === void 0) { mean = 0.0; }
  35821. if (stddev === void 0) { stddev = 1.0; }
  35822. if (name === void 0) { name = 'truncatedNormal'; }
  35823. if (dtype === 'bool') {
  35824. throw new errors_1.NotImplementedError("randomNormal does not support dType bool.");
  35825. }
  35826. return new LayerVariable(tfc.truncatedNormal(shape, mean, stddev, dtype, seed), dtype, name);
  35827. }
  35828. exports.truncatedNormalVariable = truncatedNormalVariable;
  35829. function randomNormalVariable(shape, mean, stddev, dtype, seed, name) {
  35830. if (mean === void 0) { mean = 0.0; }
  35831. if (stddev === void 0) { stddev = 1.0; }
  35832. if (name === void 0) { name = 'randomNormal'; }
  35833. if (dtype === 'bool') {
  35834. throw new errors_1.NotImplementedError("randomNormalVariable does not support dType bool.");
  35835. }
  35836. return new LayerVariable(tfjs_backend_1.randomNormal(shape, mean, stddev, dtype, seed), dtype, name);
  35837. }
  35838. exports.randomNormalVariable = randomNormalVariable;
  35839. function update(x, xNew) {
  35840. return x.write(xNew);
  35841. }
  35842. exports.update = update;
  35843. function updateAdd(x, increment) {
  35844. return x.write(tfc.add(x.read(), increment));
  35845. }
  35846. exports.updateAdd = updateAdd;
  35847. function updateSub(x, decrement) {
  35848. return x.write(tfc.sub(x.read(), decrement));
  35849. }
  35850. exports.updateSub = updateSub;
  35851. function batchGetValue(xs) {
  35852. return xs.map(function (x) { return x.read(); });
  35853. }
  35854. exports.batchGetValue = batchGetValue;
  35855. function batchSetValue(variablesAndValues) {
  35856. variablesAndValues.map(function (variableAndValue) {
  35857. var variable = variableAndValue[0];
  35858. variable.write(variableAndValue[1]);
  35859. });
  35860. }
  35861. exports.batchSetValue = batchSetValue;
  35862. },{"./backend/tfjs_backend":169,"./common":171,"./errors":176,"./types":197,"@tensorflow/tfjs-core":54}],204:[function(require,module,exports){
  35863. "use strict";
  35864. Object.defineProperty(exports, "__esModule", { value: true });
  35865. var version = '0.6.7';
  35866. exports.version = version;
  35867. },{}],205:[function(require,module,exports){
  35868. "use strict";
  35869. function __export(m) {
  35870. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  35871. }
  35872. Object.defineProperty(exports, "__esModule", { value: true });
  35873. __export(require("@tensorflow/tfjs-core"));
  35874. __export(require("@tensorflow/tfjs-layers"));
  35875. __export(require("@tensorflow/tfjs-converter"));
  35876. var tfjs_core_1 = require("@tensorflow/tfjs-core");
  35877. var tfjs_layers_1 = require("@tensorflow/tfjs-layers");
  35878. var tfjs_converter_1 = require("@tensorflow/tfjs-converter");
  35879. var version_1 = require("./version");
  35880. exports.version = {
  35881. 'tfjs-core': tfjs_core_1.version_core,
  35882. 'tfjs-layers': tfjs_layers_1.version_layers,
  35883. 'tfjs-converter': tfjs_converter_1.version_converter,
  35884. 'tfjs': version_1.version
  35885. };
  35886. },{"./version":206,"@tensorflow/tfjs-converter":16,"@tensorflow/tfjs-core":54,"@tensorflow/tfjs-layers":178}],206:[function(require,module,exports){
  35887. "use strict";
  35888. Object.defineProperty(exports, "__esModule", { value: true });
  35889. var version = '0.11.7';
  35890. exports.version = version;
  35891. },{}],207:[function(require,module,exports){
  35892. (function (process,global){
  35893. /* @preserve
  35894. * The MIT License (MIT)
  35895. *
  35896. * Copyright (c) 2013-2015 Petka Antonov
  35897. *
  35898. * Permission is hereby granted, free of charge, to any person obtaining a copy
  35899. * of this software and associated documentation files (the "Software"), to deal
  35900. * in the Software without restriction, including without limitation the rights
  35901. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  35902. * copies of the Software, and to permit persons to whom the Software is
  35903. * furnished to do so, subject to the following conditions:
  35904. *
  35905. * The above copyright notice and this permission notice shall be included in
  35906. * all copies or substantial portions of the Software.
  35907. *
  35908. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  35909. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  35910. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  35911. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  35912. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  35913. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  35914. * THE SOFTWARE.
  35915. *
  35916. */
  35917. /**
  35918. * bluebird build version 3.0.2
  35919. * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
  35920. */
  35921. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  35922. "use strict";
  35923. module.exports = function(Promise) {
  35924. var SomePromiseArray = Promise._SomePromiseArray;
  35925. function any(promises) {
  35926. var ret = new SomePromiseArray(promises);
  35927. var promise = ret.promise();
  35928. ret.setHowMany(1);
  35929. ret.setUnwrap();
  35930. ret.init();
  35931. return promise;
  35932. }
  35933. Promise.any = function (promises) {
  35934. return any(promises);
  35935. };
  35936. Promise.prototype.any = function () {
  35937. return any(this);
  35938. };
  35939. };
  35940. },{}],2:[function(_dereq_,module,exports){
  35941. "use strict";
  35942. var firstLineError;
  35943. try {throw new Error(); } catch (e) {firstLineError = e;}
  35944. var schedule = _dereq_("./schedule");
  35945. var Queue = _dereq_("./queue");
  35946. var util = _dereq_("./util");
  35947. function Async() {
  35948. this._isTickUsed = false;
  35949. this._lateQueue = new Queue(16);
  35950. this._normalQueue = new Queue(16);
  35951. this._haveDrainedQueues = false;
  35952. this._trampolineEnabled = true;
  35953. var self = this;
  35954. this.drainQueues = function () {
  35955. self._drainQueues();
  35956. };
  35957. this._schedule =
  35958. schedule.isStatic ? schedule(this.drainQueues) : schedule;
  35959. }
  35960. Async.prototype.disableTrampolineIfNecessary = function() {
  35961. if (util.hasDevTools) {
  35962. this._trampolineEnabled = false;
  35963. }
  35964. };
  35965. Async.prototype.haveItemsQueued = function () {
  35966. return this._isTickUsed || this._haveDrainedQueues;
  35967. };
  35968. Async.prototype.fatalError = function(e, isNode) {
  35969. if (isNode) {
  35970. process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e));
  35971. process.exit(2);
  35972. } else {
  35973. this.throwLater(e);
  35974. }
  35975. };
  35976. Async.prototype.throwLater = function(fn, arg) {
  35977. if (arguments.length === 1) {
  35978. arg = fn;
  35979. fn = function () { throw arg; };
  35980. }
  35981. if (typeof setTimeout !== "undefined") {
  35982. setTimeout(function() {
  35983. fn(arg);
  35984. }, 0);
  35985. } else try {
  35986. this._schedule(function() {
  35987. fn(arg);
  35988. });
  35989. } catch (e) {
  35990. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  35991. }
  35992. };
  35993. function AsyncInvokeLater(fn, receiver, arg) {
  35994. this._lateQueue.push(fn, receiver, arg);
  35995. this._queueTick();
  35996. }
  35997. function AsyncInvoke(fn, receiver, arg) {
  35998. this._normalQueue.push(fn, receiver, arg);
  35999. this._queueTick();
  36000. }
  36001. function AsyncSettlePromises(promise) {
  36002. this._normalQueue._pushOne(promise);
  36003. this._queueTick();
  36004. }
  36005. if (!util.hasDevTools) {
  36006. Async.prototype.invokeLater = AsyncInvokeLater;
  36007. Async.prototype.invoke = AsyncInvoke;
  36008. Async.prototype.settlePromises = AsyncSettlePromises;
  36009. } else {
  36010. if (schedule.isStatic) {
  36011. schedule = function(fn) { setTimeout(fn, 0); };
  36012. }
  36013. Async.prototype.invokeLater = function (fn, receiver, arg) {
  36014. if (this._trampolineEnabled) {
  36015. AsyncInvokeLater.call(this, fn, receiver, arg);
  36016. } else {
  36017. this._schedule(function() {
  36018. setTimeout(function() {
  36019. fn.call(receiver, arg);
  36020. }, 100);
  36021. });
  36022. }
  36023. };
  36024. Async.prototype.invoke = function (fn, receiver, arg) {
  36025. if (this._trampolineEnabled) {
  36026. AsyncInvoke.call(this, fn, receiver, arg);
  36027. } else {
  36028. this._schedule(function() {
  36029. fn.call(receiver, arg);
  36030. });
  36031. }
  36032. };
  36033. Async.prototype.settlePromises = function(promise) {
  36034. if (this._trampolineEnabled) {
  36035. AsyncSettlePromises.call(this, promise);
  36036. } else {
  36037. this._schedule(function() {
  36038. promise._settlePromises();
  36039. });
  36040. }
  36041. };
  36042. }
  36043. Async.prototype.invokeFirst = function (fn, receiver, arg) {
  36044. this._normalQueue.unshift(fn, receiver, arg);
  36045. this._queueTick();
  36046. };
  36047. Async.prototype._drainQueue = function(queue) {
  36048. while (queue.length() > 0) {
  36049. var fn = queue.shift();
  36050. if (typeof fn !== "function") {
  36051. fn._settlePromises();
  36052. continue;
  36053. }
  36054. var receiver = queue.shift();
  36055. var arg = queue.shift();
  36056. fn.call(receiver, arg);
  36057. }
  36058. };
  36059. Async.prototype._drainQueues = function () {
  36060. this._drainQueue(this._normalQueue);
  36061. this._reset();
  36062. this._haveDrainedQueues = true;
  36063. this._drainQueue(this._lateQueue);
  36064. };
  36065. Async.prototype._queueTick = function () {
  36066. if (!this._isTickUsed) {
  36067. this._isTickUsed = true;
  36068. this._schedule(this.drainQueues);
  36069. }
  36070. };
  36071. Async.prototype._reset = function () {
  36072. this._isTickUsed = false;
  36073. };
  36074. module.exports = Async;
  36075. module.exports.firstLineError = firstLineError;
  36076. },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
  36077. "use strict";
  36078. module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
  36079. var calledBind = false;
  36080. var rejectThis = function(_, e) {
  36081. this._reject(e);
  36082. };
  36083. var targetRejected = function(e, context) {
  36084. context.promiseRejectionQueued = true;
  36085. context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
  36086. };
  36087. var bindingResolved = function(thisArg, context) {
  36088. if (((this._bitField & 50397184) === 0)) {
  36089. this._resolveCallback(context.target);
  36090. }
  36091. };
  36092. var bindingRejected = function(e, context) {
  36093. if (!context.promiseRejectionQueued) this._reject(e);
  36094. };
  36095. Promise.prototype.bind = function (thisArg) {
  36096. if (!calledBind) {
  36097. calledBind = true;
  36098. Promise.prototype._propagateFrom = debug.propagateFromFunction();
  36099. Promise.prototype._boundValue = debug.boundValueFunction();
  36100. }
  36101. var maybePromise = tryConvertToPromise(thisArg);
  36102. var ret = new Promise(INTERNAL);
  36103. ret._propagateFrom(this, 1);
  36104. var target = this._target();
  36105. ret._setBoundTo(maybePromise);
  36106. if (maybePromise instanceof Promise) {
  36107. var context = {
  36108. promiseRejectionQueued: false,
  36109. promise: ret,
  36110. target: target,
  36111. bindingPromise: maybePromise
  36112. };
  36113. target._then(INTERNAL, targetRejected, undefined, ret, context);
  36114. maybePromise._then(
  36115. bindingResolved, bindingRejected, undefined, ret, context);
  36116. ret._setOnCancel(maybePromise);
  36117. } else {
  36118. ret._resolveCallback(target);
  36119. }
  36120. return ret;
  36121. };
  36122. Promise.prototype._setBoundTo = function (obj) {
  36123. if (obj !== undefined) {
  36124. this._bitField = this._bitField | 2097152;
  36125. this._boundTo = obj;
  36126. } else {
  36127. this._bitField = this._bitField & (~2097152);
  36128. }
  36129. };
  36130. Promise.prototype._isBound = function () {
  36131. return (this._bitField & 2097152) === 2097152;
  36132. };
  36133. Promise.bind = function (thisArg, value) {
  36134. return Promise.resolve(value).bind(thisArg);
  36135. };
  36136. };
  36137. },{}],4:[function(_dereq_,module,exports){
  36138. "use strict";
  36139. var old;
  36140. if (typeof Promise !== "undefined") old = Promise;
  36141. function noConflict() {
  36142. try { if (Promise === bluebird) Promise = old; }
  36143. catch (e) {}
  36144. return bluebird;
  36145. }
  36146. var bluebird = _dereq_("./promise")();
  36147. bluebird.noConflict = noConflict;
  36148. module.exports = bluebird;
  36149. },{"./promise":22}],5:[function(_dereq_,module,exports){
  36150. "use strict";
  36151. var cr = Object.create;
  36152. if (cr) {
  36153. var callerCache = cr(null);
  36154. var getterCache = cr(null);
  36155. callerCache[" size"] = getterCache[" size"] = 0;
  36156. }
  36157. module.exports = function(Promise) {
  36158. var util = _dereq_("./util");
  36159. var canEvaluate = util.canEvaluate;
  36160. var isIdentifier = util.isIdentifier;
  36161. var getMethodCaller;
  36162. var getGetter;
  36163. if (!true) {
  36164. var makeMethodCaller = function (methodName) {
  36165. return new Function("ensureMethod", " \n\
  36166. return function(obj) { \n\
  36167. 'use strict' \n\
  36168. var len = this.length; \n\
  36169. ensureMethod(obj, 'methodName'); \n\
  36170. switch(len) { \n\
  36171. case 1: return obj.methodName(this[0]); \n\
  36172. case 2: return obj.methodName(this[0], this[1]); \n\
  36173. case 3: return obj.methodName(this[0], this[1], this[2]); \n\
  36174. case 0: return obj.methodName(); \n\
  36175. default: \n\
  36176. return obj.methodName.apply(obj, this); \n\
  36177. } \n\
  36178. }; \n\
  36179. ".replace(/methodName/g, methodName))(ensureMethod);
  36180. };
  36181. var makeGetter = function (propertyName) {
  36182. return new Function("obj", " \n\
  36183. 'use strict'; \n\
  36184. return obj.propertyName; \n\
  36185. ".replace("propertyName", propertyName));
  36186. };
  36187. var getCompiled = function(name, compiler, cache) {
  36188. var ret = cache[name];
  36189. if (typeof ret !== "function") {
  36190. if (!isIdentifier(name)) {
  36191. return null;
  36192. }
  36193. ret = compiler(name);
  36194. cache[name] = ret;
  36195. cache[" size"]++;
  36196. if (cache[" size"] > 512) {
  36197. var keys = Object.keys(cache);
  36198. for (var i = 0; i < 256; ++i) delete cache[keys[i]];
  36199. cache[" size"] = keys.length - 256;
  36200. }
  36201. }
  36202. return ret;
  36203. };
  36204. getMethodCaller = function(name) {
  36205. return getCompiled(name, makeMethodCaller, callerCache);
  36206. };
  36207. getGetter = function(name) {
  36208. return getCompiled(name, makeGetter, getterCache);
  36209. };
  36210. }
  36211. function ensureMethod(obj, methodName) {
  36212. var fn;
  36213. if (obj != null) fn = obj[methodName];
  36214. if (typeof fn !== "function") {
  36215. var message = "Object " + util.classString(obj) + " has no method '" +
  36216. util.toString(methodName) + "'";
  36217. throw new Promise.TypeError(message);
  36218. }
  36219. return fn;
  36220. }
  36221. function caller(obj) {
  36222. var methodName = this.pop();
  36223. var fn = ensureMethod(obj, methodName);
  36224. return fn.apply(obj, this);
  36225. }
  36226. Promise.prototype.call = function (methodName) {
  36227. var args = [].slice.call(arguments, 1);;
  36228. if (!true) {
  36229. if (canEvaluate) {
  36230. var maybeCaller = getMethodCaller(methodName);
  36231. if (maybeCaller !== null) {
  36232. return this._then(
  36233. maybeCaller, undefined, undefined, args, undefined);
  36234. }
  36235. }
  36236. }
  36237. args.push(methodName);
  36238. return this._then(caller, undefined, undefined, args, undefined);
  36239. };
  36240. function namedGetter(obj) {
  36241. return obj[this];
  36242. }
  36243. function indexedGetter(obj) {
  36244. var index = +this;
  36245. if (index < 0) index = Math.max(0, index + obj.length);
  36246. return obj[index];
  36247. }
  36248. Promise.prototype.get = function (propertyName) {
  36249. var isIndex = (typeof propertyName === "number");
  36250. var getter;
  36251. if (!isIndex) {
  36252. if (canEvaluate) {
  36253. var maybeGetter = getGetter(propertyName);
  36254. getter = maybeGetter !== null ? maybeGetter : namedGetter;
  36255. } else {
  36256. getter = namedGetter;
  36257. }
  36258. } else {
  36259. getter = indexedGetter;
  36260. }
  36261. return this._then(getter, undefined, undefined, propertyName, undefined);
  36262. };
  36263. };
  36264. },{"./util":36}],6:[function(_dereq_,module,exports){
  36265. "use strict";
  36266. module.exports = function(Promise, PromiseArray, apiRejection, debug) {
  36267. var util = _dereq_("./util");
  36268. var tryCatch = util.tryCatch;
  36269. var errorObj = util.errorObj;
  36270. var async = Promise._async;
  36271. Promise.prototype["break"] = Promise.prototype.cancel = function() {
  36272. if (!debug.cancellation()) return this._warn("cancellation is disabled");
  36273. var promise = this;
  36274. var child = promise;
  36275. while (promise.isCancellable()) {
  36276. if (!promise._cancelBy(child)) {
  36277. if (child._isFollowing()) {
  36278. child._followee().cancel();
  36279. } else {
  36280. child._cancelBranched();
  36281. }
  36282. break;
  36283. }
  36284. var parent = promise._cancellationParent;
  36285. if (parent == null || !parent.isCancellable()) {
  36286. if (promise._isFollowing()) {
  36287. promise._followee().cancel();
  36288. } else {
  36289. promise._cancelBranched();
  36290. }
  36291. break;
  36292. } else {
  36293. if (promise._isFollowing()) promise._followee().cancel();
  36294. child = promise;
  36295. promise = parent;
  36296. }
  36297. }
  36298. };
  36299. Promise.prototype._branchHasCancelled = function() {
  36300. this._branchesRemainingToCancel--;
  36301. };
  36302. Promise.prototype._enoughBranchesHaveCancelled = function() {
  36303. return this._branchesRemainingToCancel === undefined ||
  36304. this._branchesRemainingToCancel <= 0;
  36305. };
  36306. Promise.prototype._cancelBy = function(canceller) {
  36307. if (canceller === this) {
  36308. this._branchesRemainingToCancel = 0;
  36309. this._invokeOnCancel();
  36310. return true;
  36311. } else {
  36312. this._branchHasCancelled();
  36313. if (this._enoughBranchesHaveCancelled()) {
  36314. this._invokeOnCancel();
  36315. return true;
  36316. }
  36317. }
  36318. return false;
  36319. };
  36320. Promise.prototype._cancelBranched = function() {
  36321. if (this._enoughBranchesHaveCancelled()) {
  36322. this._cancel();
  36323. }
  36324. };
  36325. Promise.prototype._cancel = function() {
  36326. if (!this.isCancellable()) return;
  36327. this._setCancelled();
  36328. async.invoke(this._cancelPromises, this, undefined);
  36329. };
  36330. Promise.prototype._cancelPromises = function() {
  36331. if (this._length() > 0) this._settlePromises();
  36332. };
  36333. Promise.prototype._unsetOnCancel = function() {
  36334. this._onCancelField = undefined;
  36335. };
  36336. Promise.prototype.isCancellable = function() {
  36337. return this.isPending() && !this.isCancelled();
  36338. };
  36339. Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
  36340. if (util.isArray(onCancelCallback)) {
  36341. for (var i = 0; i < onCancelCallback.length; ++i) {
  36342. this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
  36343. }
  36344. } else if (onCancelCallback !== undefined) {
  36345. if (typeof onCancelCallback === "function") {
  36346. if (!internalOnly) {
  36347. var e = tryCatch(onCancelCallback).call(this._boundValue());
  36348. if (e === errorObj) {
  36349. this._attachExtraTrace(e.e);
  36350. async.throwLater(e.e);
  36351. }
  36352. }
  36353. } else {
  36354. onCancelCallback._resultCancelled(this);
  36355. }
  36356. }
  36357. };
  36358. Promise.prototype._invokeOnCancel = function() {
  36359. var onCancelCallback = this._onCancel();
  36360. this._unsetOnCancel();
  36361. async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
  36362. };
  36363. Promise.prototype._invokeInternalOnCancel = function() {
  36364. if (this.isCancellable()) {
  36365. this._doInvokeOnCancel(this._onCancel(), true);
  36366. this._unsetOnCancel();
  36367. }
  36368. };
  36369. Promise.prototype._resultCancelled = function() {
  36370. this.cancel();
  36371. };
  36372. };
  36373. },{"./util":36}],7:[function(_dereq_,module,exports){
  36374. "use strict";
  36375. module.exports = function(NEXT_FILTER) {
  36376. var util = _dereq_("./util");
  36377. var getKeys = _dereq_("./es5").keys;
  36378. var tryCatch = util.tryCatch;
  36379. var errorObj = util.errorObj;
  36380. function catchFilter(instances, cb, promise) {
  36381. return function(e) {
  36382. var boundTo = promise._boundValue();
  36383. predicateLoop: for (var i = 0; i < instances.length; ++i) {
  36384. var item = instances[i];
  36385. if (item === Error ||
  36386. (item != null && item.prototype instanceof Error)) {
  36387. if (e instanceof item) {
  36388. return tryCatch(cb).call(boundTo, e);
  36389. }
  36390. } else if (typeof item === "function") {
  36391. var matchesPredicate = tryCatch(item).call(boundTo, e);
  36392. if (matchesPredicate === errorObj) {
  36393. return matchesPredicate;
  36394. } else if (matchesPredicate) {
  36395. return tryCatch(cb).call(boundTo, e);
  36396. }
  36397. } else if (util.isObject(e)) {
  36398. var keys = getKeys(item);
  36399. for (var j = 0; j < keys.length; ++j) {
  36400. var key = keys[j];
  36401. if (item[key] != e[key]) {
  36402. continue predicateLoop;
  36403. }
  36404. }
  36405. return tryCatch(cb).call(boundTo, e);
  36406. }
  36407. }
  36408. return NEXT_FILTER;
  36409. };
  36410. }
  36411. return catchFilter;
  36412. };
  36413. },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
  36414. "use strict";
  36415. module.exports = function(Promise) {
  36416. var longStackTraces = false;
  36417. var contextStack = [];
  36418. Promise.prototype._promiseCreated = function() {};
  36419. Promise.prototype._pushContext = function() {};
  36420. Promise.prototype._popContext = function() {return 0;};
  36421. Promise._peekContext = Promise.prototype._peekContext = function() {};
  36422. function Context() {
  36423. this._trace = new Context.CapturedTrace(peekContext());
  36424. }
  36425. Context.prototype._pushContext = function () {
  36426. if (this._trace !== undefined) {
  36427. this._trace._promisesCreated = 0;
  36428. contextStack.push(this._trace);
  36429. }
  36430. };
  36431. Context.prototype._popContext = function () {
  36432. if (this._trace !== undefined) {
  36433. var trace = contextStack.pop();
  36434. var ret = trace._promisesCreated;
  36435. trace._promisesCreated = 0;
  36436. return ret;
  36437. }
  36438. return 0;
  36439. };
  36440. function createContext() {
  36441. if (longStackTraces) return new Context();
  36442. }
  36443. function peekContext() {
  36444. var lastIndex = contextStack.length - 1;
  36445. if (lastIndex >= 0) {
  36446. return contextStack[lastIndex];
  36447. }
  36448. return undefined;
  36449. }
  36450. Context.CapturedTrace = null;
  36451. Context.create = createContext;
  36452. Context.activateLongStackTraces = function() {
  36453. longStackTraces = true;
  36454. Promise.prototype._pushContext = Context.prototype._pushContext;
  36455. Promise.prototype._popContext = Context.prototype._popContext;
  36456. Promise._peekContext = Promise.prototype._peekContext = peekContext;
  36457. Promise.prototype._promiseCreated = function() {
  36458. var ctx = this._peekContext();
  36459. if (ctx) ctx._promisesCreated++;
  36460. };
  36461. };
  36462. return Context;
  36463. };
  36464. },{}],9:[function(_dereq_,module,exports){
  36465. "use strict";
  36466. module.exports = function(Promise, Context) {
  36467. var getDomain = Promise._getDomain;
  36468. var async = Promise._async;
  36469. var Warning = _dereq_("./errors").Warning;
  36470. var util = _dereq_("./util");
  36471. var canAttachTrace = util.canAttachTrace;
  36472. var unhandledRejectionHandled;
  36473. var possiblyUnhandledRejection;
  36474. var bluebirdFramePattern =
  36475. /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
  36476. var stackFramePattern = null;
  36477. var formatStack = null;
  36478. var indentStackFrames = false;
  36479. var printWarning;
  36480. var debugging =!!(true || util.env("BLUEBIRD_DEBUG") ||
  36481. util.env("NODE_ENV") === "development");
  36482. var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
  36483. (debugging || util.env("BLUEBIRD_WARNINGS")));
  36484. var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
  36485. (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
  36486. Promise.prototype.suppressUnhandledRejections = function() {
  36487. var target = this._target();
  36488. target._bitField = ((target._bitField & (~1048576)) |
  36489. 2097152);
  36490. };
  36491. Promise.prototype._ensurePossibleRejectionHandled = function () {
  36492. if ((this._bitField & 2097152) !== 0) return;
  36493. this._setRejectionIsUnhandled();
  36494. async.invokeLater(this._notifyUnhandledRejection, this, undefined);
  36495. };
  36496. Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
  36497. fireRejectionEvent("rejectionHandled",
  36498. unhandledRejectionHandled, undefined, this);
  36499. };
  36500. Promise.prototype._notifyUnhandledRejection = function () {
  36501. if (this._isRejectionUnhandled()) {
  36502. var reason = this._settledValue();
  36503. this._setUnhandledRejectionIsNotified();
  36504. fireRejectionEvent("unhandledRejection",
  36505. possiblyUnhandledRejection, reason, this);
  36506. }
  36507. };
  36508. Promise.prototype._setUnhandledRejectionIsNotified = function () {
  36509. this._bitField = this._bitField | 262144;
  36510. };
  36511. Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
  36512. this._bitField = this._bitField & (~262144);
  36513. };
  36514. Promise.prototype._isUnhandledRejectionNotified = function () {
  36515. return (this._bitField & 262144) > 0;
  36516. };
  36517. Promise.prototype._setRejectionIsUnhandled = function () {
  36518. this._bitField = this._bitField | 1048576;
  36519. };
  36520. Promise.prototype._unsetRejectionIsUnhandled = function () {
  36521. this._bitField = this._bitField & (~1048576);
  36522. if (this._isUnhandledRejectionNotified()) {
  36523. this._unsetUnhandledRejectionIsNotified();
  36524. this._notifyUnhandledRejectionIsHandled();
  36525. }
  36526. };
  36527. Promise.prototype._isRejectionUnhandled = function () {
  36528. return (this._bitField & 1048576) > 0;
  36529. };
  36530. Promise.prototype._warn = function(message, shouldUseOwnTrace) {
  36531. return warn(message, shouldUseOwnTrace, this);
  36532. };
  36533. Promise.onPossiblyUnhandledRejection = function (fn) {
  36534. var domain = getDomain();
  36535. possiblyUnhandledRejection =
  36536. typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
  36537. : undefined;
  36538. };
  36539. Promise.onUnhandledRejectionHandled = function (fn) {
  36540. var domain = getDomain();
  36541. unhandledRejectionHandled =
  36542. typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
  36543. : undefined;
  36544. };
  36545. Promise.longStackTraces = function () {
  36546. if (async.haveItemsQueued() && !config.longStackTraces) {
  36547. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  36548. }
  36549. if (!config.longStackTraces && longStackTracesIsSupported()) {
  36550. config.longStackTraces = true;
  36551. Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
  36552. Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
  36553. Context.activateLongStackTraces();
  36554. async.disableTrampolineIfNecessary();
  36555. }
  36556. };
  36557. Promise.hasLongStackTraces = function () {
  36558. return config.longStackTraces && longStackTracesIsSupported();
  36559. };
  36560. Promise.config = function(opts) {
  36561. opts = Object(opts);
  36562. if ("longStackTraces" in opts && opts.longStackTraces) {
  36563. Promise.longStackTraces();
  36564. }
  36565. if ("warnings" in opts) {
  36566. config.warnings = !!opts.warnings;
  36567. }
  36568. if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
  36569. if (async.haveItemsQueued()) {
  36570. throw new Error(
  36571. "cannot enable cancellation after promises are in use");
  36572. }
  36573. Promise.prototype._clearCancellationData =
  36574. cancellationClearCancellationData;
  36575. Promise.prototype._propagateFrom = cancellationPropagateFrom;
  36576. Promise.prototype._onCancel = cancellationOnCancel;
  36577. Promise.prototype._setOnCancel = cancellationSetOnCancel;
  36578. Promise.prototype._attachCancellationCallback =
  36579. cancellationAttachCancellationCallback;
  36580. Promise.prototype._execute = cancellationExecute;
  36581. propagateFromFunction = cancellationPropagateFrom;
  36582. config.cancellation = true;
  36583. }
  36584. };
  36585. Promise.prototype._execute = function(executor, resolve, reject) {
  36586. try {
  36587. executor(resolve, reject);
  36588. } catch (e) {
  36589. return e;
  36590. }
  36591. };
  36592. Promise.prototype._onCancel = function () {};
  36593. Promise.prototype._setOnCancel = function (handler) { ; };
  36594. Promise.prototype._attachCancellationCallback = function(onCancel) {
  36595. ;
  36596. };
  36597. Promise.prototype._captureStackTrace = function () {};
  36598. Promise.prototype._attachExtraTrace = function () {};
  36599. Promise.prototype._clearCancellationData = function() {};
  36600. Promise.prototype._propagateFrom = function (parent, flags) {
  36601. ;
  36602. ;
  36603. };
  36604. function cancellationExecute(executor, resolve, reject) {
  36605. var promise = this;
  36606. try {
  36607. executor(resolve, reject, function(onCancel) {
  36608. if (typeof onCancel !== "function") {
  36609. throw new TypeError("onCancel must be a function, got: " +
  36610. util.toString(onCancel));
  36611. }
  36612. promise._attachCancellationCallback(onCancel);
  36613. });
  36614. } catch (e) {
  36615. return e;
  36616. }
  36617. }
  36618. function cancellationAttachCancellationCallback(onCancel) {
  36619. if (!this.isCancellable()) return this;
  36620. var previousOnCancel = this._onCancel();
  36621. if (previousOnCancel !== undefined) {
  36622. if (util.isArray(previousOnCancel)) {
  36623. previousOnCancel.push(onCancel);
  36624. } else {
  36625. this._setOnCancel([previousOnCancel, onCancel]);
  36626. }
  36627. } else {
  36628. this._setOnCancel(onCancel);
  36629. }
  36630. }
  36631. function cancellationOnCancel() {
  36632. return this._onCancelField;
  36633. }
  36634. function cancellationSetOnCancel(onCancel) {
  36635. this._onCancelField = onCancel;
  36636. }
  36637. function cancellationClearCancellationData() {
  36638. this._cancellationParent = undefined;
  36639. this._onCancelField = undefined;
  36640. }
  36641. function cancellationPropagateFrom(parent, flags) {
  36642. if ((flags & 1) !== 0) {
  36643. this._cancellationParent = parent;
  36644. var branchesRemainingToCancel = parent._branchesRemainingToCancel;
  36645. if (branchesRemainingToCancel === undefined) {
  36646. branchesRemainingToCancel = 0;
  36647. }
  36648. parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
  36649. }
  36650. if ((flags & 2) !== 0 && parent._isBound()) {
  36651. this._setBoundTo(parent._boundTo);
  36652. }
  36653. }
  36654. function bindingPropagateFrom(parent, flags) {
  36655. if ((flags & 2) !== 0 && parent._isBound()) {
  36656. this._setBoundTo(parent._boundTo);
  36657. }
  36658. }
  36659. var propagateFromFunction = bindingPropagateFrom;
  36660. function boundValueFunction() {
  36661. var ret = this._boundTo;
  36662. if (ret !== undefined) {
  36663. if (ret instanceof Promise) {
  36664. if (ret.isFulfilled()) {
  36665. return ret.value();
  36666. } else {
  36667. return undefined;
  36668. }
  36669. }
  36670. }
  36671. return ret;
  36672. }
  36673. function longStackTracesCaptureStackTrace() {
  36674. this._trace = new CapturedTrace(this._peekContext());
  36675. }
  36676. function longStackTracesAttachExtraTrace(error, ignoreSelf) {
  36677. if (canAttachTrace(error)) {
  36678. var trace = this._trace;
  36679. if (trace !== undefined) {
  36680. if (ignoreSelf) trace = trace._parent;
  36681. }
  36682. if (trace !== undefined) {
  36683. trace.attachExtraTrace(error);
  36684. } else if (!error.__stackCleaned__) {
  36685. var parsed = parseStackAndMessage(error);
  36686. util.notEnumerableProp(error, "stack",
  36687. parsed.message + "\n" + parsed.stack.join("\n"));
  36688. util.notEnumerableProp(error, "__stackCleaned__", true);
  36689. }
  36690. }
  36691. }
  36692. function checkForgottenReturns(returnValue, promisesCreated, name, promise) {
  36693. if (returnValue === undefined &&
  36694. promisesCreated > 0 &&
  36695. config.longStackTraces &&
  36696. config.warnings) {
  36697. var msg = "a promise was created in a " + name +
  36698. " handler but was not returned from it";
  36699. promise._warn(msg);
  36700. }
  36701. }
  36702. function deprecated(name, replacement) {
  36703. var message = name +
  36704. " is deprecated and will be removed in a future version.";
  36705. if (replacement) message += " Use " + replacement + " instead.";
  36706. return warn(message);
  36707. }
  36708. function warn(message, shouldUseOwnTrace, promise) {
  36709. if (!config.warnings) return;
  36710. var warning = new Warning(message);
  36711. var ctx;
  36712. if (shouldUseOwnTrace) {
  36713. promise._attachExtraTrace(warning);
  36714. } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
  36715. ctx.attachExtraTrace(warning);
  36716. } else {
  36717. var parsed = parseStackAndMessage(warning);
  36718. warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
  36719. }
  36720. formatAndLogError(warning, "", true);
  36721. }
  36722. function reconstructStack(message, stacks) {
  36723. for (var i = 0; i < stacks.length - 1; ++i) {
  36724. stacks[i].push("From previous event:");
  36725. stacks[i] = stacks[i].join("\n");
  36726. }
  36727. if (i < stacks.length) {
  36728. stacks[i] = stacks[i].join("\n");
  36729. }
  36730. return message + "\n" + stacks.join("\n");
  36731. }
  36732. function removeDuplicateOrEmptyJumps(stacks) {
  36733. for (var i = 0; i < stacks.length; ++i) {
  36734. if (stacks[i].length === 0 ||
  36735. ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
  36736. stacks.splice(i, 1);
  36737. i--;
  36738. }
  36739. }
  36740. }
  36741. function removeCommonRoots(stacks) {
  36742. var current = stacks[0];
  36743. for (var i = 1; i < stacks.length; ++i) {
  36744. var prev = stacks[i];
  36745. var currentLastIndex = current.length - 1;
  36746. var currentLastLine = current[currentLastIndex];
  36747. var commonRootMeetPoint = -1;
  36748. for (var j = prev.length - 1; j >= 0; --j) {
  36749. if (prev[j] === currentLastLine) {
  36750. commonRootMeetPoint = j;
  36751. break;
  36752. }
  36753. }
  36754. for (var j = commonRootMeetPoint; j >= 0; --j) {
  36755. var line = prev[j];
  36756. if (current[currentLastIndex] === line) {
  36757. current.pop();
  36758. currentLastIndex--;
  36759. } else {
  36760. break;
  36761. }
  36762. }
  36763. current = prev;
  36764. }
  36765. }
  36766. function cleanStack(stack) {
  36767. var ret = [];
  36768. for (var i = 0; i < stack.length; ++i) {
  36769. var line = stack[i];
  36770. var isTraceLine = " (No stack trace)" === line ||
  36771. stackFramePattern.test(line);
  36772. var isInternalFrame = isTraceLine && shouldIgnore(line);
  36773. if (isTraceLine && !isInternalFrame) {
  36774. if (indentStackFrames && line.charAt(0) !== " ") {
  36775. line = " " + line;
  36776. }
  36777. ret.push(line);
  36778. }
  36779. }
  36780. return ret;
  36781. }
  36782. function stackFramesAsArray(error) {
  36783. var stack = error.stack.replace(/\s+$/g, "").split("\n");
  36784. for (var i = 0; i < stack.length; ++i) {
  36785. var line = stack[i];
  36786. if (" (No stack trace)" === line || stackFramePattern.test(line)) {
  36787. break;
  36788. }
  36789. }
  36790. if (i > 0) {
  36791. stack = stack.slice(i);
  36792. }
  36793. return stack;
  36794. }
  36795. function parseStackAndMessage(error) {
  36796. var stack = error.stack;
  36797. var message = error.toString();
  36798. stack = typeof stack === "string" && stack.length > 0
  36799. ? stackFramesAsArray(error) : [" (No stack trace)"];
  36800. return {
  36801. message: message,
  36802. stack: cleanStack(stack)
  36803. };
  36804. }
  36805. function formatAndLogError(error, title, isSoft) {
  36806. if (typeof console !== "undefined") {
  36807. var message;
  36808. if (util.isObject(error)) {
  36809. var stack = error.stack;
  36810. message = title + formatStack(stack, error);
  36811. } else {
  36812. message = title + String(error);
  36813. }
  36814. if (typeof printWarning === "function") {
  36815. printWarning(message, isSoft);
  36816. } else if (typeof console.log === "function" ||
  36817. typeof console.log === "object") {
  36818. console.log(message);
  36819. }
  36820. }
  36821. }
  36822. function fireRejectionEvent(name, localHandler, reason, promise) {
  36823. var localEventFired = false;
  36824. try {
  36825. if (typeof localHandler === "function") {
  36826. localEventFired = true;
  36827. if (name === "rejectionHandled") {
  36828. localHandler(promise);
  36829. } else {
  36830. localHandler(reason, promise);
  36831. }
  36832. }
  36833. } catch (e) {
  36834. async.throwLater(e);
  36835. }
  36836. var globalEventFired = false;
  36837. try {
  36838. globalEventFired = fireGlobalEvent(name, reason, promise);
  36839. } catch (e) {
  36840. globalEventFired = true;
  36841. async.throwLater(e);
  36842. }
  36843. var domEventFired = false;
  36844. if (fireDomEvent) {
  36845. try {
  36846. domEventFired = fireDomEvent(name.toLowerCase(), {
  36847. reason: reason,
  36848. promise: promise
  36849. });
  36850. } catch (e) {
  36851. domEventFired = true;
  36852. async.throwLater(e);
  36853. }
  36854. }
  36855. if (!globalEventFired && !localEventFired && !domEventFired &&
  36856. name === "unhandledRejection") {
  36857. formatAndLogError(reason, "Unhandled rejection ");
  36858. }
  36859. }
  36860. function formatNonError(obj) {
  36861. var str;
  36862. if (typeof obj === "function") {
  36863. str = "[function " +
  36864. (obj.name || "anonymous") +
  36865. "]";
  36866. } else {
  36867. str = obj && typeof obj.toString === "function"
  36868. ? obj.toString() : util.toString(obj);
  36869. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  36870. if (ruselessToString.test(str)) {
  36871. try {
  36872. var newStr = JSON.stringify(obj);
  36873. str = newStr;
  36874. }
  36875. catch(e) {
  36876. }
  36877. }
  36878. if (str.length === 0) {
  36879. str = "(empty array)";
  36880. }
  36881. }
  36882. return ("(<" + snip(str) + ">, no stack trace)");
  36883. }
  36884. function snip(str) {
  36885. var maxChars = 41;
  36886. if (str.length < maxChars) {
  36887. return str;
  36888. }
  36889. return str.substr(0, maxChars - 3) + "...";
  36890. }
  36891. function longStackTracesIsSupported() {
  36892. return typeof captureStackTrace === "function";
  36893. }
  36894. var shouldIgnore = function() { return false; };
  36895. var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
  36896. function parseLineInfo(line) {
  36897. var matches = line.match(parseLineInfoRegex);
  36898. if (matches) {
  36899. return {
  36900. fileName: matches[1],
  36901. line: parseInt(matches[2], 10)
  36902. };
  36903. }
  36904. }
  36905. function setBounds(firstLineError, lastLineError) {
  36906. if (!longStackTracesIsSupported()) return;
  36907. var firstStackLines = firstLineError.stack.split("\n");
  36908. var lastStackLines = lastLineError.stack.split("\n");
  36909. var firstIndex = -1;
  36910. var lastIndex = -1;
  36911. var firstFileName;
  36912. var lastFileName;
  36913. for (var i = 0; i < firstStackLines.length; ++i) {
  36914. var result = parseLineInfo(firstStackLines[i]);
  36915. if (result) {
  36916. firstFileName = result.fileName;
  36917. firstIndex = result.line;
  36918. break;
  36919. }
  36920. }
  36921. for (var i = 0; i < lastStackLines.length; ++i) {
  36922. var result = parseLineInfo(lastStackLines[i]);
  36923. if (result) {
  36924. lastFileName = result.fileName;
  36925. lastIndex = result.line;
  36926. break;
  36927. }
  36928. }
  36929. if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
  36930. firstFileName !== lastFileName || firstIndex >= lastIndex) {
  36931. return;
  36932. }
  36933. shouldIgnore = function(line) {
  36934. if (bluebirdFramePattern.test(line)) return true;
  36935. var info = parseLineInfo(line);
  36936. if (info) {
  36937. if (info.fileName === firstFileName &&
  36938. (firstIndex <= info.line && info.line <= lastIndex)) {
  36939. return true;
  36940. }
  36941. }
  36942. return false;
  36943. };
  36944. }
  36945. function CapturedTrace(parent) {
  36946. this._parent = parent;
  36947. this._promisesCreated = 0;
  36948. var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
  36949. captureStackTrace(this, CapturedTrace);
  36950. if (length > 32) this.uncycle();
  36951. }
  36952. util.inherits(CapturedTrace, Error);
  36953. Context.CapturedTrace = CapturedTrace;
  36954. CapturedTrace.prototype.uncycle = function() {
  36955. var length = this._length;
  36956. if (length < 2) return;
  36957. var nodes = [];
  36958. var stackToIndex = {};
  36959. for (var i = 0, node = this; node !== undefined; ++i) {
  36960. nodes.push(node);
  36961. node = node._parent;
  36962. }
  36963. length = this._length = i;
  36964. for (var i = length - 1; i >= 0; --i) {
  36965. var stack = nodes[i].stack;
  36966. if (stackToIndex[stack] === undefined) {
  36967. stackToIndex[stack] = i;
  36968. }
  36969. }
  36970. for (var i = 0; i < length; ++i) {
  36971. var currentStack = nodes[i].stack;
  36972. var index = stackToIndex[currentStack];
  36973. if (index !== undefined && index !== i) {
  36974. if (index > 0) {
  36975. nodes[index - 1]._parent = undefined;
  36976. nodes[index - 1]._length = 1;
  36977. }
  36978. nodes[i]._parent = undefined;
  36979. nodes[i]._length = 1;
  36980. var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
  36981. if (index < length - 1) {
  36982. cycleEdgeNode._parent = nodes[index + 1];
  36983. cycleEdgeNode._parent.uncycle();
  36984. cycleEdgeNode._length =
  36985. cycleEdgeNode._parent._length + 1;
  36986. } else {
  36987. cycleEdgeNode._parent = undefined;
  36988. cycleEdgeNode._length = 1;
  36989. }
  36990. var currentChildLength = cycleEdgeNode._length + 1;
  36991. for (var j = i - 2; j >= 0; --j) {
  36992. nodes[j]._length = currentChildLength;
  36993. currentChildLength++;
  36994. }
  36995. return;
  36996. }
  36997. }
  36998. };
  36999. CapturedTrace.prototype.attachExtraTrace = function(error) {
  37000. if (error.__stackCleaned__) return;
  37001. this.uncycle();
  37002. var parsed = parseStackAndMessage(error);
  37003. var message = parsed.message;
  37004. var stacks = [parsed.stack];
  37005. var trace = this;
  37006. while (trace !== undefined) {
  37007. stacks.push(cleanStack(trace.stack.split("\n")));
  37008. trace = trace._parent;
  37009. }
  37010. removeCommonRoots(stacks);
  37011. removeDuplicateOrEmptyJumps(stacks);
  37012. util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
  37013. util.notEnumerableProp(error, "__stackCleaned__", true);
  37014. };
  37015. var captureStackTrace = (function stackDetection() {
  37016. var v8stackFramePattern = /^\s*at\s*/;
  37017. var v8stackFormatter = function(stack, error) {
  37018. if (typeof stack === "string") return stack;
  37019. if (error.name !== undefined &&
  37020. error.message !== undefined) {
  37021. return error.toString();
  37022. }
  37023. return formatNonError(error);
  37024. };
  37025. if (typeof Error.stackTraceLimit === "number" &&
  37026. typeof Error.captureStackTrace === "function") {
  37027. Error.stackTraceLimit += 6;
  37028. stackFramePattern = v8stackFramePattern;
  37029. formatStack = v8stackFormatter;
  37030. var captureStackTrace = Error.captureStackTrace;
  37031. shouldIgnore = function(line) {
  37032. return bluebirdFramePattern.test(line);
  37033. };
  37034. return function(receiver, ignoreUntil) {
  37035. Error.stackTraceLimit += 6;
  37036. captureStackTrace(receiver, ignoreUntil);
  37037. Error.stackTraceLimit -= 6;
  37038. };
  37039. }
  37040. var err = new Error();
  37041. if (typeof err.stack === "string" &&
  37042. err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
  37043. stackFramePattern = /@/;
  37044. formatStack = v8stackFormatter;
  37045. indentStackFrames = true;
  37046. return function captureStackTrace(o) {
  37047. o.stack = new Error().stack;
  37048. };
  37049. }
  37050. var hasStackAfterThrow;
  37051. try { throw new Error(); }
  37052. catch(e) {
  37053. hasStackAfterThrow = ("stack" in e);
  37054. }
  37055. if (!("stack" in err) && hasStackAfterThrow &&
  37056. typeof Error.stackTraceLimit === "number") {
  37057. stackFramePattern = v8stackFramePattern;
  37058. formatStack = v8stackFormatter;
  37059. return function captureStackTrace(o) {
  37060. Error.stackTraceLimit += 6;
  37061. try { throw new Error(); }
  37062. catch(e) { o.stack = e.stack; }
  37063. Error.stackTraceLimit -= 6;
  37064. };
  37065. }
  37066. formatStack = function(stack, error) {
  37067. if (typeof stack === "string") return stack;
  37068. if ((typeof error === "object" ||
  37069. typeof error === "function") &&
  37070. error.name !== undefined &&
  37071. error.message !== undefined) {
  37072. return error.toString();
  37073. }
  37074. return formatNonError(error);
  37075. };
  37076. return null;
  37077. })([]);
  37078. var fireDomEvent;
  37079. var fireGlobalEvent = (function() {
  37080. if (util.isNode) {
  37081. return function(name, reason, promise) {
  37082. if (name === "rejectionHandled") {
  37083. return process.emit(name, promise);
  37084. } else {
  37085. return process.emit(name, reason, promise);
  37086. }
  37087. };
  37088. } else {
  37089. var customEventWorks = false;
  37090. var anyEventWorks = true;
  37091. try {
  37092. var ev = new self.CustomEvent("test");
  37093. customEventWorks = ev instanceof CustomEvent;
  37094. } catch (e) {}
  37095. if (!customEventWorks) {
  37096. try {
  37097. var event = document.createEvent("CustomEvent");
  37098. event.initCustomEvent("testingtheevent", false, true, {});
  37099. self.dispatchEvent(event);
  37100. } catch (e) {
  37101. anyEventWorks = false;
  37102. }
  37103. }
  37104. if (anyEventWorks) {
  37105. fireDomEvent = function(type, detail) {
  37106. var event;
  37107. if (customEventWorks) {
  37108. event = new self.CustomEvent(type, {
  37109. detail: detail,
  37110. bubbles: false,
  37111. cancelable: true
  37112. });
  37113. } else if (self.dispatchEvent) {
  37114. event = document.createEvent("CustomEvent");
  37115. event.initCustomEvent(type, false, true, detail);
  37116. }
  37117. return event ? !self.dispatchEvent(event) : false;
  37118. };
  37119. }
  37120. var toWindowMethodNameMap = {};
  37121. toWindowMethodNameMap["unhandledRejection"] = ("on" +
  37122. "unhandledRejection").toLowerCase();
  37123. toWindowMethodNameMap["rejectionHandled"] = ("on" +
  37124. "rejectionHandled").toLowerCase();
  37125. return function(name, reason, promise) {
  37126. var methodName = toWindowMethodNameMap[name];
  37127. var method = self[methodName];
  37128. if (!method) return false;
  37129. if (name === "rejectionHandled") {
  37130. method.call(self, promise);
  37131. } else {
  37132. method.call(self, reason, promise);
  37133. }
  37134. return true;
  37135. };
  37136. }
  37137. })();
  37138. if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
  37139. printWarning = function (message) {
  37140. console.warn(message);
  37141. };
  37142. if (util.isNode && process.stderr.isTTY) {
  37143. printWarning = function(message, isSoft) {
  37144. var color = isSoft ? "\u001b[33m" : "\u001b[31m";
  37145. process.stderr.write(color + message + "\u001b[0m\n");
  37146. };
  37147. } else if (!util.isNode && typeof (new Error().stack) === "string") {
  37148. printWarning = function(message, isSoft) {
  37149. console.warn("%c" + message,
  37150. isSoft ? "color: darkorange" : "color: red");
  37151. };
  37152. }
  37153. }
  37154. var config = {
  37155. warnings: warnings,
  37156. longStackTraces: false,
  37157. cancellation: false
  37158. };
  37159. if (longStackTraces) Promise.longStackTraces();
  37160. return {
  37161. longStackTraces: function() {
  37162. return config.longStackTraces;
  37163. },
  37164. warnings: function() {
  37165. return config.warnings;
  37166. },
  37167. cancellation: function() {
  37168. return config.cancellation;
  37169. },
  37170. propagateFromFunction: function() {
  37171. return propagateFromFunction;
  37172. },
  37173. boundValueFunction: function() {
  37174. return boundValueFunction;
  37175. },
  37176. checkForgottenReturns: checkForgottenReturns,
  37177. setBounds: setBounds,
  37178. warn: warn,
  37179. deprecated: deprecated,
  37180. CapturedTrace: CapturedTrace
  37181. };
  37182. };
  37183. },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){
  37184. "use strict";
  37185. module.exports = function(Promise) {
  37186. function returner() {
  37187. return this.value;
  37188. }
  37189. function thrower() {
  37190. throw this.reason;
  37191. }
  37192. Promise.prototype["return"] =
  37193. Promise.prototype.thenReturn = function (value) {
  37194. if (value instanceof Promise) value.suppressUnhandledRejections();
  37195. return this._then(
  37196. returner, undefined, undefined, {value: value}, undefined);
  37197. };
  37198. Promise.prototype["throw"] =
  37199. Promise.prototype.thenThrow = function (reason) {
  37200. return this._then(
  37201. thrower, undefined, undefined, {reason: reason}, undefined);
  37202. };
  37203. Promise.prototype.catchThrow = function (reason) {
  37204. if (arguments.length <= 1) {
  37205. return this._then(
  37206. undefined, thrower, undefined, {reason: reason}, undefined);
  37207. } else {
  37208. var _reason = arguments[1];
  37209. var handler = function() {throw _reason;};
  37210. return this.caught(reason, handler);
  37211. }
  37212. };
  37213. Promise.prototype.catchReturn = function (value) {
  37214. if (arguments.length <= 1) {
  37215. if (value instanceof Promise) value.suppressUnhandledRejections();
  37216. return this._then(
  37217. undefined, returner, undefined, {value: value}, undefined);
  37218. } else {
  37219. var _value = arguments[1];
  37220. if (_value instanceof Promise) _value.suppressUnhandledRejections();
  37221. var handler = function() {return _value;};
  37222. return this.caught(value, handler);
  37223. }
  37224. };
  37225. };
  37226. },{}],11:[function(_dereq_,module,exports){
  37227. "use strict";
  37228. module.exports = function(Promise, INTERNAL) {
  37229. var PromiseReduce = Promise.reduce;
  37230. var PromiseAll = Promise.all;
  37231. function promiseAllThis() {
  37232. return PromiseAll(this);
  37233. }
  37234. function PromiseMapSeries(promises, fn) {
  37235. return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
  37236. }
  37237. Promise.prototype.each = function (fn) {
  37238. return this.mapSeries(fn)
  37239. ._then(promiseAllThis, undefined, undefined, this, undefined);
  37240. };
  37241. Promise.prototype.mapSeries = function (fn) {
  37242. return PromiseReduce(this, fn, INTERNAL, INTERNAL);
  37243. };
  37244. Promise.each = function (promises, fn) {
  37245. return PromiseMapSeries(promises, fn)
  37246. ._then(promiseAllThis, undefined, undefined, promises, undefined);
  37247. };
  37248. Promise.mapSeries = PromiseMapSeries;
  37249. };
  37250. },{}],12:[function(_dereq_,module,exports){
  37251. "use strict";
  37252. var es5 = _dereq_("./es5");
  37253. var Objectfreeze = es5.freeze;
  37254. var util = _dereq_("./util");
  37255. var inherits = util.inherits;
  37256. var notEnumerableProp = util.notEnumerableProp;
  37257. function subError(nameProperty, defaultMessage) {
  37258. function SubError(message) {
  37259. if (!(this instanceof SubError)) return new SubError(message);
  37260. notEnumerableProp(this, "message",
  37261. typeof message === "string" ? message : defaultMessage);
  37262. notEnumerableProp(this, "name", nameProperty);
  37263. if (Error.captureStackTrace) {
  37264. Error.captureStackTrace(this, this.constructor);
  37265. } else {
  37266. Error.call(this);
  37267. }
  37268. }
  37269. inherits(SubError, Error);
  37270. return SubError;
  37271. }
  37272. var _TypeError, _RangeError;
  37273. var Warning = subError("Warning", "warning");
  37274. var CancellationError = subError("CancellationError", "cancellation error");
  37275. var TimeoutError = subError("TimeoutError", "timeout error");
  37276. var AggregateError = subError("AggregateError", "aggregate error");
  37277. try {
  37278. _TypeError = TypeError;
  37279. _RangeError = RangeError;
  37280. } catch(e) {
  37281. _TypeError = subError("TypeError", "type error");
  37282. _RangeError = subError("RangeError", "range error");
  37283. }
  37284. var methods = ("join pop push shift unshift slice filter forEach some " +
  37285. "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
  37286. for (var i = 0; i < methods.length; ++i) {
  37287. if (typeof Array.prototype[methods[i]] === "function") {
  37288. AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
  37289. }
  37290. }
  37291. es5.defineProperty(AggregateError.prototype, "length", {
  37292. value: 0,
  37293. configurable: false,
  37294. writable: true,
  37295. enumerable: true
  37296. });
  37297. AggregateError.prototype["isOperational"] = true;
  37298. var level = 0;
  37299. AggregateError.prototype.toString = function() {
  37300. var indent = Array(level * 4 + 1).join(" ");
  37301. var ret = "\n" + indent + "AggregateError of:" + "\n";
  37302. level++;
  37303. indent = Array(level * 4 + 1).join(" ");
  37304. for (var i = 0; i < this.length; ++i) {
  37305. var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
  37306. var lines = str.split("\n");
  37307. for (var j = 0; j < lines.length; ++j) {
  37308. lines[j] = indent + lines[j];
  37309. }
  37310. str = lines.join("\n");
  37311. ret += str + "\n";
  37312. }
  37313. level--;
  37314. return ret;
  37315. };
  37316. function OperationalError(message) {
  37317. if (!(this instanceof OperationalError))
  37318. return new OperationalError(message);
  37319. notEnumerableProp(this, "name", "OperationalError");
  37320. notEnumerableProp(this, "message", message);
  37321. this.cause = message;
  37322. this["isOperational"] = true;
  37323. if (message instanceof Error) {
  37324. notEnumerableProp(this, "message", message.message);
  37325. notEnumerableProp(this, "stack", message.stack);
  37326. } else if (Error.captureStackTrace) {
  37327. Error.captureStackTrace(this, this.constructor);
  37328. }
  37329. }
  37330. inherits(OperationalError, Error);
  37331. var errorTypes = Error["__BluebirdErrorTypes__"];
  37332. if (!errorTypes) {
  37333. errorTypes = Objectfreeze({
  37334. CancellationError: CancellationError,
  37335. TimeoutError: TimeoutError,
  37336. OperationalError: OperationalError,
  37337. RejectionError: OperationalError,
  37338. AggregateError: AggregateError
  37339. });
  37340. notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
  37341. }
  37342. module.exports = {
  37343. Error: Error,
  37344. TypeError: _TypeError,
  37345. RangeError: _RangeError,
  37346. CancellationError: errorTypes.CancellationError,
  37347. OperationalError: errorTypes.OperationalError,
  37348. TimeoutError: errorTypes.TimeoutError,
  37349. AggregateError: errorTypes.AggregateError,
  37350. Warning: Warning
  37351. };
  37352. },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
  37353. var isES5 = (function(){
  37354. "use strict";
  37355. return this === undefined;
  37356. })();
  37357. if (isES5) {
  37358. module.exports = {
  37359. freeze: Object.freeze,
  37360. defineProperty: Object.defineProperty,
  37361. getDescriptor: Object.getOwnPropertyDescriptor,
  37362. keys: Object.keys,
  37363. names: Object.getOwnPropertyNames,
  37364. getPrototypeOf: Object.getPrototypeOf,
  37365. isArray: Array.isArray,
  37366. isES5: isES5,
  37367. propertyIsWritable: function(obj, prop) {
  37368. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  37369. return !!(!descriptor || descriptor.writable || descriptor.set);
  37370. }
  37371. };
  37372. } else {
  37373. var has = {}.hasOwnProperty;
  37374. var str = {}.toString;
  37375. var proto = {}.constructor.prototype;
  37376. var ObjectKeys = function (o) {
  37377. var ret = [];
  37378. for (var key in o) {
  37379. if (has.call(o, key)) {
  37380. ret.push(key);
  37381. }
  37382. }
  37383. return ret;
  37384. };
  37385. var ObjectGetDescriptor = function(o, key) {
  37386. return {value: o[key]};
  37387. };
  37388. var ObjectDefineProperty = function (o, key, desc) {
  37389. o[key] = desc.value;
  37390. return o;
  37391. };
  37392. var ObjectFreeze = function (obj) {
  37393. return obj;
  37394. };
  37395. var ObjectGetPrototypeOf = function (obj) {
  37396. try {
  37397. return Object(obj).constructor.prototype;
  37398. }
  37399. catch (e) {
  37400. return proto;
  37401. }
  37402. };
  37403. var ArrayIsArray = function (obj) {
  37404. try {
  37405. return str.call(obj) === "[object Array]";
  37406. }
  37407. catch(e) {
  37408. return false;
  37409. }
  37410. };
  37411. module.exports = {
  37412. isArray: ArrayIsArray,
  37413. keys: ObjectKeys,
  37414. names: ObjectKeys,
  37415. defineProperty: ObjectDefineProperty,
  37416. getDescriptor: ObjectGetDescriptor,
  37417. freeze: ObjectFreeze,
  37418. getPrototypeOf: ObjectGetPrototypeOf,
  37419. isES5: isES5,
  37420. propertyIsWritable: function() {
  37421. return true;
  37422. }
  37423. };
  37424. }
  37425. },{}],14:[function(_dereq_,module,exports){
  37426. "use strict";
  37427. module.exports = function(Promise, INTERNAL) {
  37428. var PromiseMap = Promise.map;
  37429. Promise.prototype.filter = function (fn, options) {
  37430. return PromiseMap(this, fn, options, INTERNAL);
  37431. };
  37432. Promise.filter = function (promises, fn, options) {
  37433. return PromiseMap(promises, fn, options, INTERNAL);
  37434. };
  37435. };
  37436. },{}],15:[function(_dereq_,module,exports){
  37437. "use strict";
  37438. module.exports = function(Promise, tryConvertToPromise) {
  37439. var util = _dereq_("./util");
  37440. var CancellationError = Promise.CancellationError;
  37441. var errorObj = util.errorObj;
  37442. function FinallyHandlerCancelReaction(finallyHandler) {
  37443. this.finallyHandler = finallyHandler;
  37444. }
  37445. FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
  37446. checkCancel(this.finallyHandler);
  37447. };
  37448. function checkCancel(ctx, reason) {
  37449. if (ctx.cancelPromise != null) {
  37450. if (arguments.length > 1) {
  37451. ctx.cancelPromise._reject(reason);
  37452. } else {
  37453. ctx.cancelPromise._cancel();
  37454. }
  37455. ctx.cancelPromise = null;
  37456. return true;
  37457. }
  37458. return false;
  37459. }
  37460. function succeed() {
  37461. return finallyHandler.call(this, this.promise._target()._settledValue());
  37462. }
  37463. function fail(reason) {
  37464. if (checkCancel(this, reason)) return;
  37465. errorObj.e = reason;
  37466. return errorObj;
  37467. }
  37468. function finallyHandler(reasonOrValue) {
  37469. var promise = this.promise;
  37470. var handler = this.handler;
  37471. if (!this.called) {
  37472. this.called = true;
  37473. var ret = this.type === 0
  37474. ? handler.call(promise._boundValue())
  37475. : handler.call(promise._boundValue(), reasonOrValue);
  37476. if (ret !== undefined) {
  37477. var maybePromise = tryConvertToPromise(ret, promise);
  37478. if (maybePromise instanceof Promise) {
  37479. if (this.cancelPromise != null) {
  37480. if (maybePromise.isCancelled()) {
  37481. var reason =
  37482. new CancellationError("late cancellation observer");
  37483. promise._attachExtraTrace(reason);
  37484. errorObj.e = reason;
  37485. return errorObj;
  37486. } else if (maybePromise.isPending()) {
  37487. maybePromise._attachCancellationCallback(
  37488. new FinallyHandlerCancelReaction(this));
  37489. }
  37490. }
  37491. return maybePromise._then(
  37492. succeed, fail, undefined, this, undefined);
  37493. }
  37494. }
  37495. }
  37496. if (promise.isRejected()) {
  37497. checkCancel(this);
  37498. errorObj.e = reasonOrValue;
  37499. return errorObj;
  37500. } else {
  37501. checkCancel(this);
  37502. return reasonOrValue;
  37503. }
  37504. }
  37505. Promise.prototype._passThrough = function(handler, type, success, fail) {
  37506. if (typeof handler !== "function") return this.then();
  37507. return this._then(success, fail, undefined, {
  37508. promise: this,
  37509. handler: handler,
  37510. called: false,
  37511. cancelPromise: null,
  37512. type: type
  37513. }, undefined);
  37514. };
  37515. Promise.prototype.lastly =
  37516. Promise.prototype["finally"] = function (handler) {
  37517. return this._passThrough(handler,
  37518. 0,
  37519. finallyHandler,
  37520. finallyHandler);
  37521. };
  37522. Promise.prototype.tap = function (handler) {
  37523. return this._passThrough(handler, 1, finallyHandler);
  37524. };
  37525. return finallyHandler;
  37526. };
  37527. },{"./util":36}],16:[function(_dereq_,module,exports){
  37528. "use strict";
  37529. module.exports = function(Promise,
  37530. apiRejection,
  37531. INTERNAL,
  37532. tryConvertToPromise,
  37533. Proxyable,
  37534. debug) {
  37535. var errors = _dereq_("./errors");
  37536. var TypeError = errors.TypeError;
  37537. var util = _dereq_("./util");
  37538. var errorObj = util.errorObj;
  37539. var tryCatch = util.tryCatch;
  37540. var yieldHandlers = [];
  37541. function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
  37542. for (var i = 0; i < yieldHandlers.length; ++i) {
  37543. traceParent._pushContext();
  37544. var result = tryCatch(yieldHandlers[i])(value);
  37545. traceParent._popContext();
  37546. if (result === errorObj) {
  37547. traceParent._pushContext();
  37548. var ret = Promise.reject(errorObj.e);
  37549. traceParent._popContext();
  37550. return ret;
  37551. }
  37552. var maybePromise = tryConvertToPromise(result, traceParent);
  37553. if (maybePromise instanceof Promise) return maybePromise;
  37554. }
  37555. return null;
  37556. }
  37557. function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
  37558. var promise = this._promise = new Promise(INTERNAL);
  37559. promise._captureStackTrace();
  37560. promise._setOnCancel(this);
  37561. this._stack = stack;
  37562. this._generatorFunction = generatorFunction;
  37563. this._receiver = receiver;
  37564. this._generator = undefined;
  37565. this._yieldHandlers = typeof yieldHandler === "function"
  37566. ? [yieldHandler].concat(yieldHandlers)
  37567. : yieldHandlers;
  37568. this._yieldedPromise = null;
  37569. }
  37570. util.inherits(PromiseSpawn, Proxyable);
  37571. PromiseSpawn.prototype._isResolved = function() {
  37572. return this.promise === null;
  37573. };
  37574. PromiseSpawn.prototype._cleanup = function() {
  37575. this._promise = this._generator = null;
  37576. };
  37577. PromiseSpawn.prototype._promiseCancelled = function() {
  37578. if (this._isResolved()) return;
  37579. var implementsReturn = typeof this._generator["return"] !== "undefined";
  37580. var result;
  37581. if (!implementsReturn) {
  37582. var reason = new Promise.CancellationError(
  37583. "generator .return() sentinel");
  37584. Promise.coroutine.returnSentinel = reason;
  37585. this._promise._attachExtraTrace(reason);
  37586. this._promise._pushContext();
  37587. result = tryCatch(this._generator["throw"]).call(this._generator,
  37588. reason);
  37589. this._promise._popContext();
  37590. if (result === errorObj && result.e === reason) {
  37591. result = null;
  37592. }
  37593. } else {
  37594. this._promise._pushContext();
  37595. result = tryCatch(this._generator["return"]).call(this._generator,
  37596. undefined);
  37597. this._promise._popContext();
  37598. }
  37599. var promise = this._promise;
  37600. this._cleanup();
  37601. if (result === errorObj) {
  37602. promise._rejectCallback(result.e, false);
  37603. } else {
  37604. promise.cancel();
  37605. }
  37606. };
  37607. PromiseSpawn.prototype._promiseFulfilled = function(value) {
  37608. this._yieldedPromise = null;
  37609. this._promise._pushContext();
  37610. var result = tryCatch(this._generator.next).call(this._generator, value);
  37611. this._promise._popContext();
  37612. this._continue(result);
  37613. };
  37614. PromiseSpawn.prototype._promiseRejected = function(reason) {
  37615. this._yieldedPromise = null;
  37616. this._promise._attachExtraTrace(reason);
  37617. this._promise._pushContext();
  37618. var result = tryCatch(this._generator["throw"])
  37619. .call(this._generator, reason);
  37620. this._promise._popContext();
  37621. this._continue(result);
  37622. };
  37623. PromiseSpawn.prototype._resultCancelled = function() {
  37624. if (this._yieldedPromise instanceof Promise) {
  37625. var promise = this._yieldedPromise;
  37626. this._yieldedPromise = null;
  37627. promise.cancel();
  37628. }
  37629. };
  37630. PromiseSpawn.prototype.promise = function () {
  37631. return this._promise;
  37632. };
  37633. PromiseSpawn.prototype._run = function () {
  37634. this._generator = this._generatorFunction.call(this._receiver);
  37635. this._receiver =
  37636. this._generatorFunction = undefined;
  37637. this._promiseFulfilled(undefined);
  37638. };
  37639. PromiseSpawn.prototype._continue = function (result) {
  37640. var promise = this._promise;
  37641. if (result === errorObj) {
  37642. this._cleanup();
  37643. return promise._rejectCallback(result.e, false);
  37644. }
  37645. var value = result.value;
  37646. if (result.done === true) {
  37647. this._cleanup();
  37648. return promise._resolveCallback(value);
  37649. } else {
  37650. var maybePromise = tryConvertToPromise(value, this._promise);
  37651. if (!(maybePromise instanceof Promise)) {
  37652. maybePromise =
  37653. promiseFromYieldHandler(maybePromise,
  37654. this._yieldHandlers,
  37655. this._promise);
  37656. if (maybePromise === null) {
  37657. this._promiseRejected(
  37658. new TypeError(
  37659. "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
  37660. "From coroutine:\u000a" +
  37661. this._stack.split("\n").slice(1, -7).join("\n")
  37662. )
  37663. );
  37664. return;
  37665. }
  37666. }
  37667. maybePromise = maybePromise._target();
  37668. var bitField = maybePromise._bitField;
  37669. ;
  37670. if (((bitField & 50397184) === 0)) {
  37671. this._yieldedPromise = maybePromise;
  37672. maybePromise._proxy(this, null);
  37673. } else if (((bitField & 33554432) !== 0)) {
  37674. this._promiseFulfilled(maybePromise._value());
  37675. } else if (((bitField & 16777216) !== 0)) {
  37676. this._promiseRejected(maybePromise._reason());
  37677. } else {
  37678. this._promiseCancelled();
  37679. }
  37680. }
  37681. };
  37682. Promise.coroutine = function (generatorFunction, options) {
  37683. if (typeof generatorFunction !== "function") {
  37684. throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  37685. }
  37686. var yieldHandler = Object(options).yieldHandler;
  37687. var PromiseSpawn$ = PromiseSpawn;
  37688. var stack = new Error().stack;
  37689. return function () {
  37690. var generator = generatorFunction.apply(this, arguments);
  37691. var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
  37692. stack);
  37693. var ret = spawn.promise();
  37694. spawn._generator = generator;
  37695. spawn._promiseFulfilled(undefined);
  37696. return ret;
  37697. };
  37698. };
  37699. Promise.coroutine.addYieldHandler = function(fn) {
  37700. if (typeof fn !== "function") {
  37701. throw new TypeError("expecting a function but got " + util.classString(fn));
  37702. }
  37703. yieldHandlers.push(fn);
  37704. };
  37705. Promise.spawn = function (generatorFunction) {
  37706. debug.deprecated("Promise.spawn()", "Promise.coroutine()");
  37707. if (typeof generatorFunction !== "function") {
  37708. return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  37709. }
  37710. var spawn = new PromiseSpawn(generatorFunction, this);
  37711. var ret = spawn.promise();
  37712. spawn._run(Promise.spawn);
  37713. return ret;
  37714. };
  37715. };
  37716. },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
  37717. "use strict";
  37718. module.exports =
  37719. function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
  37720. var util = _dereq_("./util");
  37721. var canEvaluate = util.canEvaluate;
  37722. var tryCatch = util.tryCatch;
  37723. var errorObj = util.errorObj;
  37724. var reject;
  37725. if (!true) {
  37726. if (canEvaluate) {
  37727. var thenCallback = function(i) {
  37728. return new Function("value", "holder", " \n\
  37729. 'use strict'; \n\
  37730. holder.pIndex = value; \n\
  37731. holder.checkFulfillment(this); \n\
  37732. ".replace(/Index/g, i));
  37733. };
  37734. var promiseSetter = function(i) {
  37735. return new Function("promise", "holder", " \n\
  37736. 'use strict'; \n\
  37737. holder.pIndex = promise; \n\
  37738. ".replace(/Index/g, i));
  37739. };
  37740. var generateHolderClass = function(total) {
  37741. var props = new Array(total);
  37742. for (var i = 0; i < props.length; ++i) {
  37743. props[i] = "this.p" + (i+1);
  37744. }
  37745. var assignment = props.join(" = ") + " = null;";
  37746. var cancellationCode= "var promise;\n" + props.map(function(prop) {
  37747. return " \n\
  37748. promise = " + prop + "; \n\
  37749. if (promise instanceof Promise) { \n\
  37750. promise.cancel(); \n\
  37751. } \n\
  37752. ";
  37753. }).join("\n");
  37754. var passedArguments = props.join(", ");
  37755. var name = "Holder$" + total;
  37756. var code = "return function(tryCatch, errorObj, Promise) { \n\
  37757. 'use strict'; \n\
  37758. function [TheName](fn) { \n\
  37759. [TheProperties] \n\
  37760. this.fn = fn; \n\
  37761. this.now = 0; \n\
  37762. } \n\
  37763. [TheName].prototype.checkFulfillment = function(promise) { \n\
  37764. var now = ++this.now; \n\
  37765. if (now === [TheTotal]) { \n\
  37766. promise._pushContext(); \n\
  37767. var callback = this.fn; \n\
  37768. var ret = tryCatch(callback)([ThePassedArguments]); \n\
  37769. promise._popContext(); \n\
  37770. if (ret === errorObj) { \n\
  37771. promise._rejectCallback(ret.e, false); \n\
  37772. } else { \n\
  37773. promise._resolveCallback(ret); \n\
  37774. } \n\
  37775. } \n\
  37776. }; \n\
  37777. \n\
  37778. [TheName].prototype._resultCancelled = function() { \n\
  37779. [CancellationCode] \n\
  37780. }; \n\
  37781. \n\
  37782. return [TheName]; \n\
  37783. }(tryCatch, errorObj, Promise); \n\
  37784. ";
  37785. code = code.replace(/\[TheName\]/g, name)
  37786. .replace(/\[TheTotal\]/g, total)
  37787. .replace(/\[ThePassedArguments\]/g, passedArguments)
  37788. .replace(/\[TheProperties\]/g, assignment)
  37789. .replace(/\[CancellationCode\]/g, cancellationCode);
  37790. return new Function("tryCatch", "errorObj", "Promise", code)
  37791. (tryCatch, errorObj, Promise);
  37792. };
  37793. var holderClasses = [];
  37794. var thenCallbacks = [];
  37795. var promiseSetters = [];
  37796. for (var i = 0; i < 8; ++i) {
  37797. holderClasses.push(generateHolderClass(i + 1));
  37798. thenCallbacks.push(thenCallback(i + 1));
  37799. promiseSetters.push(promiseSetter(i + 1));
  37800. }
  37801. reject = function (reason) {
  37802. this._reject(reason);
  37803. };
  37804. }}
  37805. Promise.join = function () {
  37806. var last = arguments.length - 1;
  37807. var fn;
  37808. if (last > 0 && typeof arguments[last] === "function") {
  37809. fn = arguments[last];
  37810. if (!true) {
  37811. if (last <= 8 && canEvaluate) {
  37812. var ret = new Promise(INTERNAL);
  37813. ret._captureStackTrace();
  37814. var HolderClass = holderClasses[last - 1];
  37815. var holder = new HolderClass(fn);
  37816. var callbacks = thenCallbacks;
  37817. for (var i = 0; i < last; ++i) {
  37818. var maybePromise = tryConvertToPromise(arguments[i], ret);
  37819. if (maybePromise instanceof Promise) {
  37820. maybePromise = maybePromise._target();
  37821. var bitField = maybePromise._bitField;
  37822. ;
  37823. if (((bitField & 50397184) === 0)) {
  37824. maybePromise._then(callbacks[i], reject,
  37825. undefined, ret, holder);
  37826. promiseSetters[i](maybePromise, holder);
  37827. } else if (((bitField & 33554432) !== 0)) {
  37828. callbacks[i].call(ret,
  37829. maybePromise._value(), holder);
  37830. } else if (((bitField & 16777216) !== 0)) {
  37831. ret._reject(maybePromise._reason());
  37832. } else {
  37833. ret._cancel();
  37834. }
  37835. } else {
  37836. callbacks[i].call(ret, maybePromise, holder);
  37837. }
  37838. }
  37839. if (!ret._isFateSealed()) {
  37840. ret._setAsyncGuaranteed();
  37841. ret._setOnCancel(holder);
  37842. }
  37843. return ret;
  37844. }
  37845. }
  37846. }
  37847. var args = [].slice.call(arguments);;
  37848. if (fn) args.pop();
  37849. var ret = new PromiseArray(args).promise();
  37850. return fn !== undefined ? ret.spread(fn) : ret;
  37851. };
  37852. };
  37853. },{"./util":36}],18:[function(_dereq_,module,exports){
  37854. "use strict";
  37855. module.exports = function(Promise,
  37856. PromiseArray,
  37857. apiRejection,
  37858. tryConvertToPromise,
  37859. INTERNAL,
  37860. debug) {
  37861. var getDomain = Promise._getDomain;
  37862. var util = _dereq_("./util");
  37863. var tryCatch = util.tryCatch;
  37864. var errorObj = util.errorObj;
  37865. var EMPTY_ARRAY = [];
  37866. function MappingPromiseArray(promises, fn, limit, _filter) {
  37867. this.constructor$(promises);
  37868. this._promise._captureStackTrace();
  37869. var domain = getDomain();
  37870. this._callback = domain === null ? fn : domain.bind(fn);
  37871. this._preservedValues = _filter === INTERNAL
  37872. ? new Array(this.length())
  37873. : null;
  37874. this._limit = limit;
  37875. this._inFlight = 0;
  37876. this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
  37877. this._init$(undefined, -2);
  37878. }
  37879. util.inherits(MappingPromiseArray, PromiseArray);
  37880. MappingPromiseArray.prototype._init = function () {};
  37881. MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
  37882. var values = this._values;
  37883. var length = this.length();
  37884. var preservedValues = this._preservedValues;
  37885. var limit = this._limit;
  37886. if (index < 0) {
  37887. index = (index * -1) - 1;
  37888. values[index] = value;
  37889. if (limit >= 1) {
  37890. this._inFlight--;
  37891. this._drainQueue();
  37892. if (this._isResolved()) return true;
  37893. }
  37894. } else {
  37895. if (limit >= 1 && this._inFlight >= limit) {
  37896. values[index] = value;
  37897. this._queue.push(index);
  37898. return false;
  37899. }
  37900. if (preservedValues !== null) preservedValues[index] = value;
  37901. var promise = this._promise;
  37902. var callback = this._callback;
  37903. var receiver = promise._boundValue();
  37904. promise._pushContext();
  37905. var ret = tryCatch(callback).call(receiver, value, index, length);
  37906. var promisesCreated = promise._popContext();
  37907. debug.checkForgottenReturns(
  37908. ret,
  37909. promisesCreated,
  37910. preservedValues !== null ? "Promise.filter" : "Promise.map",
  37911. promise
  37912. );
  37913. if (ret === errorObj) {
  37914. this._reject(ret.e);
  37915. return true;
  37916. }
  37917. var maybePromise = tryConvertToPromise(ret, this._promise);
  37918. if (maybePromise instanceof Promise) {
  37919. maybePromise = maybePromise._target();
  37920. var bitField = maybePromise._bitField;
  37921. ;
  37922. if (((bitField & 50397184) === 0)) {
  37923. if (limit >= 1) this._inFlight++;
  37924. values[index] = maybePromise;
  37925. maybePromise._proxy(this, (index + 1) * -1);
  37926. return false;
  37927. } else if (((bitField & 33554432) !== 0)) {
  37928. ret = maybePromise._value();
  37929. } else if (((bitField & 16777216) !== 0)) {
  37930. this._reject(maybePromise._reason());
  37931. return true;
  37932. } else {
  37933. this._cancel();
  37934. return true;
  37935. }
  37936. }
  37937. values[index] = ret;
  37938. }
  37939. var totalResolved = ++this._totalResolved;
  37940. if (totalResolved >= length) {
  37941. if (preservedValues !== null) {
  37942. this._filter(values, preservedValues);
  37943. } else {
  37944. this._resolve(values);
  37945. }
  37946. return true;
  37947. }
  37948. return false;
  37949. };
  37950. MappingPromiseArray.prototype._drainQueue = function () {
  37951. var queue = this._queue;
  37952. var limit = this._limit;
  37953. var values = this._values;
  37954. while (queue.length > 0 && this._inFlight < limit) {
  37955. if (this._isResolved()) return;
  37956. var index = queue.pop();
  37957. this._promiseFulfilled(values[index], index);
  37958. }
  37959. };
  37960. MappingPromiseArray.prototype._filter = function (booleans, values) {
  37961. var len = values.length;
  37962. var ret = new Array(len);
  37963. var j = 0;
  37964. for (var i = 0; i < len; ++i) {
  37965. if (booleans[i]) ret[j++] = values[i];
  37966. }
  37967. ret.length = j;
  37968. this._resolve(ret);
  37969. };
  37970. MappingPromiseArray.prototype.preservedValues = function () {
  37971. return this._preservedValues;
  37972. };
  37973. function map(promises, fn, options, _filter) {
  37974. if (typeof fn !== "function") {
  37975. return apiRejection("expecting a function but got " + util.classString(fn));
  37976. }
  37977. var limit = typeof options === "object" && options !== null
  37978. ? options.concurrency
  37979. : 0;
  37980. limit = typeof limit === "number" &&
  37981. isFinite(limit) && limit >= 1 ? limit : 0;
  37982. return new MappingPromiseArray(promises, fn, limit, _filter).promise();
  37983. }
  37984. Promise.prototype.map = function (fn, options) {
  37985. return map(this, fn, options, null);
  37986. };
  37987. Promise.map = function (promises, fn, options, _filter) {
  37988. return map(promises, fn, options, _filter);
  37989. };
  37990. };
  37991. },{"./util":36}],19:[function(_dereq_,module,exports){
  37992. "use strict";
  37993. module.exports =
  37994. function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
  37995. var util = _dereq_("./util");
  37996. var tryCatch = util.tryCatch;
  37997. Promise.method = function (fn) {
  37998. if (typeof fn !== "function") {
  37999. throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
  38000. }
  38001. return function () {
  38002. var ret = new Promise(INTERNAL);
  38003. ret._captureStackTrace();
  38004. ret._pushContext();
  38005. var value = tryCatch(fn).apply(this, arguments);
  38006. ret._popContext();
  38007. ret._resolveFromSyncValue(value);
  38008. return ret;
  38009. };
  38010. };
  38011. Promise.attempt = Promise["try"] = function (fn) {
  38012. if (typeof fn !== "function") {
  38013. return apiRejection("expecting a function but got " + util.classString(fn));
  38014. }
  38015. var ret = new Promise(INTERNAL);
  38016. ret._captureStackTrace();
  38017. ret._pushContext();
  38018. var value;
  38019. if (arguments.length > 1) {
  38020. debug.deprecated("calling Promise.try with more than 1 argument");
  38021. var arg = arguments[1];
  38022. var ctx = arguments[2];
  38023. value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
  38024. : tryCatch(fn).call(ctx, arg);
  38025. } else {
  38026. value = tryCatch(fn)();
  38027. }
  38028. ret._popContext();
  38029. ret._resolveFromSyncValue(value);
  38030. return ret;
  38031. };
  38032. Promise.prototype._resolveFromSyncValue = function (value) {
  38033. if (value === util.errorObj) {
  38034. this._rejectCallback(value.e, false);
  38035. } else {
  38036. this._resolveCallback(value, true);
  38037. }
  38038. };
  38039. };
  38040. },{"./util":36}],20:[function(_dereq_,module,exports){
  38041. "use strict";
  38042. var util = _dereq_("./util");
  38043. var maybeWrapAsError = util.maybeWrapAsError;
  38044. var errors = _dereq_("./errors");
  38045. var OperationalError = errors.OperationalError;
  38046. var es5 = _dereq_("./es5");
  38047. function isUntypedError(obj) {
  38048. return obj instanceof Error &&
  38049. es5.getPrototypeOf(obj) === Error.prototype;
  38050. }
  38051. var rErrorKey = /^(?:name|message|stack|cause)$/;
  38052. function wrapAsOperationalError(obj) {
  38053. var ret;
  38054. if (isUntypedError(obj)) {
  38055. ret = new OperationalError(obj);
  38056. ret.name = obj.name;
  38057. ret.message = obj.message;
  38058. ret.stack = obj.stack;
  38059. var keys = es5.keys(obj);
  38060. for (var i = 0; i < keys.length; ++i) {
  38061. var key = keys[i];
  38062. if (!rErrorKey.test(key)) {
  38063. ret[key] = obj[key];
  38064. }
  38065. }
  38066. return ret;
  38067. }
  38068. util.markAsOriginatingFromRejection(obj);
  38069. return obj;
  38070. }
  38071. function nodebackForPromise(promise, multiArgs) {
  38072. return function(err, value) {
  38073. if (promise === null) return;
  38074. if (err) {
  38075. var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
  38076. promise._attachExtraTrace(wrapped);
  38077. promise._reject(wrapped);
  38078. } else if (!multiArgs) {
  38079. promise._fulfill(value);
  38080. } else {
  38081. var args = [].slice.call(arguments, 1);;
  38082. promise._fulfill(args);
  38083. }
  38084. promise = null;
  38085. };
  38086. }
  38087. module.exports = nodebackForPromise;
  38088. },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
  38089. "use strict";
  38090. module.exports = function(Promise) {
  38091. var util = _dereq_("./util");
  38092. var async = Promise._async;
  38093. var tryCatch = util.tryCatch;
  38094. var errorObj = util.errorObj;
  38095. function spreadAdapter(val, nodeback) {
  38096. var promise = this;
  38097. if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
  38098. var ret =
  38099. tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
  38100. if (ret === errorObj) {
  38101. async.throwLater(ret.e);
  38102. }
  38103. }
  38104. function successAdapter(val, nodeback) {
  38105. var promise = this;
  38106. var receiver = promise._boundValue();
  38107. var ret = val === undefined
  38108. ? tryCatch(nodeback).call(receiver, null)
  38109. : tryCatch(nodeback).call(receiver, null, val);
  38110. if (ret === errorObj) {
  38111. async.throwLater(ret.e);
  38112. }
  38113. }
  38114. function errorAdapter(reason, nodeback) {
  38115. var promise = this;
  38116. if (!reason) {
  38117. var newReason = new Error(reason + "");
  38118. newReason.cause = reason;
  38119. reason = newReason;
  38120. }
  38121. var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
  38122. if (ret === errorObj) {
  38123. async.throwLater(ret.e);
  38124. }
  38125. }
  38126. Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
  38127. options) {
  38128. if (typeof nodeback == "function") {
  38129. var adapter = successAdapter;
  38130. if (options !== undefined && Object(options).spread) {
  38131. adapter = spreadAdapter;
  38132. }
  38133. this._then(
  38134. adapter,
  38135. errorAdapter,
  38136. undefined,
  38137. this,
  38138. nodeback
  38139. );
  38140. }
  38141. return this;
  38142. };
  38143. };
  38144. },{"./util":36}],22:[function(_dereq_,module,exports){
  38145. "use strict";
  38146. module.exports = function() {
  38147. var makeSelfResolutionError = function () {
  38148. return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  38149. };
  38150. var reflectHandler = function() {
  38151. return new Promise.PromiseInspection(this._target());
  38152. };
  38153. var apiRejection = function(msg) {
  38154. return Promise.reject(new TypeError(msg));
  38155. };
  38156. function Proxyable() {}
  38157. var UNDEFINED_BINDING = {};
  38158. var util = _dereq_("./util");
  38159. var getDomain;
  38160. if (util.isNode) {
  38161. getDomain = function() {
  38162. var ret = process.domain;
  38163. if (ret === undefined) ret = null;
  38164. return ret;
  38165. };
  38166. } else {
  38167. getDomain = function() {
  38168. return null;
  38169. };
  38170. }
  38171. util.notEnumerableProp(Promise, "_getDomain", getDomain);
  38172. var es5 = _dereq_("./es5");
  38173. var Async = _dereq_("./async");
  38174. var async = new Async();
  38175. es5.defineProperty(Promise, "_async", {value: async});
  38176. var errors = _dereq_("./errors");
  38177. var TypeError = Promise.TypeError = errors.TypeError;
  38178. Promise.RangeError = errors.RangeError;
  38179. var CancellationError = Promise.CancellationError = errors.CancellationError;
  38180. Promise.TimeoutError = errors.TimeoutError;
  38181. Promise.OperationalError = errors.OperationalError;
  38182. Promise.RejectionError = errors.OperationalError;
  38183. Promise.AggregateError = errors.AggregateError;
  38184. var INTERNAL = function(){};
  38185. var APPLY = {};
  38186. var NEXT_FILTER = {};
  38187. var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
  38188. var PromiseArray =
  38189. _dereq_("./promise_array")(Promise, INTERNAL,
  38190. tryConvertToPromise, apiRejection, Proxyable);
  38191. var Context = _dereq_("./context")(Promise);
  38192. /*jshint unused:false*/
  38193. var createContext = Context.create;
  38194. var debug = _dereq_("./debuggability")(Promise, Context);
  38195. var CapturedTrace = debug.CapturedTrace;
  38196. var finallyHandler = _dereq_("./finally")(Promise, tryConvertToPromise);
  38197. var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
  38198. var nodebackForPromise = _dereq_("./nodeback");
  38199. var errorObj = util.errorObj;
  38200. var tryCatch = util.tryCatch;
  38201. function check(self, executor) {
  38202. if (typeof executor !== "function") {
  38203. throw new TypeError("expecting a function but got " + util.classString(executor));
  38204. }
  38205. if (self.constructor !== Promise) {
  38206. throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  38207. }
  38208. }
  38209. function Promise(executor) {
  38210. this._bitField = 0;
  38211. this._fulfillmentHandler0 = undefined;
  38212. this._rejectionHandler0 = undefined;
  38213. this._promise0 = undefined;
  38214. this._receiver0 = undefined;
  38215. if (executor !== INTERNAL) {
  38216. check(this, executor);
  38217. this._resolveFromExecutor(executor);
  38218. }
  38219. this._promiseCreated();
  38220. }
  38221. Promise.prototype.toString = function () {
  38222. return "[object Promise]";
  38223. };
  38224. Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
  38225. var len = arguments.length;
  38226. if (len > 1) {
  38227. var catchInstances = new Array(len - 1),
  38228. j = 0, i;
  38229. for (i = 0; i < len - 1; ++i) {
  38230. var item = arguments[i];
  38231. if (util.isObject(item)) {
  38232. catchInstances[j++] = item;
  38233. } else {
  38234. return apiRejection("expecting an object but got " + util.classString(item));
  38235. }
  38236. }
  38237. catchInstances.length = j;
  38238. fn = arguments[i];
  38239. return this.then(undefined, catchFilter(catchInstances, fn, this));
  38240. }
  38241. return this.then(undefined, fn);
  38242. };
  38243. Promise.prototype.reflect = function () {
  38244. return this._then(reflectHandler,
  38245. reflectHandler, undefined, this, undefined);
  38246. };
  38247. Promise.prototype.then = function (didFulfill, didReject) {
  38248. if (debug.warnings() && arguments.length > 0 &&
  38249. typeof didFulfill !== "function" &&
  38250. typeof didReject !== "function") {
  38251. var msg = ".then() only accepts functions but was passed: " +
  38252. util.classString(didFulfill);
  38253. if (arguments.length > 1) {
  38254. msg += ", " + util.classString(didReject);
  38255. }
  38256. this._warn(msg);
  38257. }
  38258. return this._then(didFulfill, didReject, undefined, undefined, undefined);
  38259. };
  38260. Promise.prototype.done = function (didFulfill, didReject) {
  38261. var promise =
  38262. this._then(didFulfill, didReject, undefined, undefined, undefined);
  38263. promise._setIsFinal();
  38264. };
  38265. Promise.prototype.spread = function (fn) {
  38266. if (typeof fn !== "function") {
  38267. return apiRejection("expecting a function but got " + util.classString(fn));
  38268. }
  38269. return this.all()._then(fn, undefined, undefined, APPLY, undefined);
  38270. };
  38271. Promise.prototype.toJSON = function () {
  38272. var ret = {
  38273. isFulfilled: false,
  38274. isRejected: false,
  38275. fulfillmentValue: undefined,
  38276. rejectionReason: undefined
  38277. };
  38278. if (this.isFulfilled()) {
  38279. ret.fulfillmentValue = this.value();
  38280. ret.isFulfilled = true;
  38281. } else if (this.isRejected()) {
  38282. ret.rejectionReason = this.reason();
  38283. ret.isRejected = true;
  38284. }
  38285. return ret;
  38286. };
  38287. Promise.prototype.all = function () {
  38288. if (arguments.length > 0) {
  38289. this._warn(".all() was passed arguments but it does not take any");
  38290. }
  38291. return new PromiseArray(this).promise();
  38292. };
  38293. Promise.prototype.error = function (fn) {
  38294. return this.caught(util.originatesFromRejection, fn);
  38295. };
  38296. Promise.is = function (val) {
  38297. return val instanceof Promise;
  38298. };
  38299. Promise.fromNode = Promise.fromCallback = function(fn) {
  38300. var ret = new Promise(INTERNAL);
  38301. var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
  38302. : false;
  38303. var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
  38304. if (result === errorObj) {
  38305. ret._rejectCallback(result.e, true);
  38306. }
  38307. if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
  38308. return ret;
  38309. };
  38310. Promise.all = function (promises) {
  38311. return new PromiseArray(promises).promise();
  38312. };
  38313. Promise.cast = function (obj) {
  38314. var ret = tryConvertToPromise(obj);
  38315. if (!(ret instanceof Promise)) {
  38316. ret = new Promise(INTERNAL);
  38317. ret._setFulfilled();
  38318. ret._rejectionHandler0 = obj;
  38319. }
  38320. return ret;
  38321. };
  38322. Promise.resolve = Promise.fulfilled = Promise.cast;
  38323. Promise.reject = Promise.rejected = function (reason) {
  38324. var ret = new Promise(INTERNAL);
  38325. ret._captureStackTrace();
  38326. ret._rejectCallback(reason, true);
  38327. return ret;
  38328. };
  38329. Promise.setScheduler = function(fn) {
  38330. if (typeof fn !== "function") {
  38331. throw new TypeError("expecting a function but got " + util.classString(fn));
  38332. }
  38333. var prev = async._schedule;
  38334. async._schedule = fn;
  38335. return prev;
  38336. };
  38337. Promise.prototype._then = function (
  38338. didFulfill,
  38339. didReject,
  38340. _, receiver,
  38341. internalData
  38342. ) {
  38343. var haveInternalData = internalData !== undefined;
  38344. var promise = haveInternalData ? internalData : new Promise(INTERNAL);
  38345. var target = this._target();
  38346. var bitField = target._bitField;
  38347. if (!haveInternalData) {
  38348. promise._propagateFrom(this, 3);
  38349. promise._captureStackTrace();
  38350. if (receiver === undefined &&
  38351. ((this._bitField & 2097152) !== 0)) {
  38352. if (!((bitField & 50397184) === 0)) {
  38353. receiver = this._boundValue();
  38354. } else {
  38355. receiver = target === this ? undefined : this._boundTo;
  38356. }
  38357. }
  38358. }
  38359. var domain = getDomain();
  38360. if (!((bitField & 50397184) === 0)) {
  38361. var handler, value, settler = target._settlePromiseCtx;
  38362. if (((bitField & 33554432) !== 0)) {
  38363. value = target._rejectionHandler0;
  38364. handler = didFulfill;
  38365. } else if (((bitField & 16777216) !== 0)) {
  38366. value = target._fulfillmentHandler0;
  38367. handler = didReject;
  38368. target._unsetRejectionIsUnhandled();
  38369. } else {
  38370. settler = target._settlePromiseLateCancellationObserver;
  38371. value = new CancellationError("late cancellation observer");
  38372. target._attachExtraTrace(value);
  38373. handler = didReject;
  38374. }
  38375. async.invoke(settler, target, {
  38376. handler: domain === null ? handler
  38377. : (typeof handler === "function" && domain.bind(handler)),
  38378. promise: promise,
  38379. receiver: receiver,
  38380. value: value
  38381. });
  38382. } else {
  38383. target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
  38384. }
  38385. return promise;
  38386. };
  38387. Promise.prototype._length = function () {
  38388. return this._bitField & 65535;
  38389. };
  38390. Promise.prototype._isFateSealed = function () {
  38391. return (this._bitField & 117506048) !== 0;
  38392. };
  38393. Promise.prototype._isFollowing = function () {
  38394. return (this._bitField & 67108864) === 67108864;
  38395. };
  38396. Promise.prototype._setLength = function (len) {
  38397. this._bitField = (this._bitField & -65536) |
  38398. (len & 65535);
  38399. };
  38400. Promise.prototype._setFulfilled = function () {
  38401. this._bitField = this._bitField | 33554432;
  38402. };
  38403. Promise.prototype._setRejected = function () {
  38404. this._bitField = this._bitField | 16777216;
  38405. };
  38406. Promise.prototype._setFollowing = function () {
  38407. this._bitField = this._bitField | 67108864;
  38408. };
  38409. Promise.prototype._setIsFinal = function () {
  38410. this._bitField = this._bitField | 4194304;
  38411. };
  38412. Promise.prototype._isFinal = function () {
  38413. return (this._bitField & 4194304) > 0;
  38414. };
  38415. Promise.prototype._unsetCancelled = function() {
  38416. this._bitField = this._bitField & (~65536);
  38417. };
  38418. Promise.prototype._setCancelled = function() {
  38419. this._bitField = this._bitField | 65536;
  38420. };
  38421. Promise.prototype._setAsyncGuaranteed = function() {
  38422. this._bitField = this._bitField | 134217728;
  38423. };
  38424. Promise.prototype._receiverAt = function (index) {
  38425. var ret = index === 0 ? this._receiver0 : this[
  38426. index * 4 - 4 + 3];
  38427. if (ret === UNDEFINED_BINDING) {
  38428. return undefined;
  38429. } else if (ret === undefined && this._isBound()) {
  38430. return this._boundValue();
  38431. }
  38432. return ret;
  38433. };
  38434. Promise.prototype._promiseAt = function (index) {
  38435. return this[
  38436. index * 4 - 4 + 2];
  38437. };
  38438. Promise.prototype._fulfillmentHandlerAt = function (index) {
  38439. return this[
  38440. index * 4 - 4 + 0];
  38441. };
  38442. Promise.prototype._rejectionHandlerAt = function (index) {
  38443. return this[
  38444. index * 4 - 4 + 1];
  38445. };
  38446. Promise.prototype._boundValue = function() {};
  38447. Promise.prototype._migrateCallback0 = function (follower) {
  38448. var bitField = follower._bitField;
  38449. var fulfill = follower._fulfillmentHandler0;
  38450. var reject = follower._rejectionHandler0;
  38451. var promise = follower._promise0;
  38452. var receiver = follower._receiverAt(0);
  38453. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  38454. this._addCallbacks(fulfill, reject, promise, receiver, null);
  38455. };
  38456. Promise.prototype._migrateCallbackAt = function (follower, index) {
  38457. var fulfill = follower._fulfillmentHandlerAt(index);
  38458. var reject = follower._rejectionHandlerAt(index);
  38459. var promise = follower._promiseAt(index);
  38460. var receiver = follower._receiverAt(index);
  38461. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  38462. this._addCallbacks(fulfill, reject, promise, receiver, null);
  38463. };
  38464. Promise.prototype._addCallbacks = function (
  38465. fulfill,
  38466. reject,
  38467. promise,
  38468. receiver,
  38469. domain
  38470. ) {
  38471. var index = this._length();
  38472. if (index >= 65535 - 4) {
  38473. index = 0;
  38474. this._setLength(0);
  38475. }
  38476. if (index === 0) {
  38477. this._promise0 = promise;
  38478. this._receiver0 = receiver;
  38479. if (typeof fulfill === "function") {
  38480. this._fulfillmentHandler0 =
  38481. domain === null ? fulfill : domain.bind(fulfill);
  38482. }
  38483. if (typeof reject === "function") {
  38484. this._rejectionHandler0 =
  38485. domain === null ? reject : domain.bind(reject);
  38486. }
  38487. } else {
  38488. var base = index * 4 - 4;
  38489. this[base + 2] = promise;
  38490. this[base + 3] = receiver;
  38491. if (typeof fulfill === "function") {
  38492. this[base + 0] =
  38493. domain === null ? fulfill : domain.bind(fulfill);
  38494. }
  38495. if (typeof reject === "function") {
  38496. this[base + 1] =
  38497. domain === null ? reject : domain.bind(reject);
  38498. }
  38499. }
  38500. this._setLength(index + 1);
  38501. return index;
  38502. };
  38503. Promise.prototype._proxy = function (proxyable, arg) {
  38504. this._addCallbacks(undefined, undefined, arg, proxyable, null);
  38505. };
  38506. Promise.prototype._resolveCallback = function(value, shouldBind) {
  38507. if (((this._bitField & 117506048) !== 0)) return;
  38508. if (value === this)
  38509. return this._rejectCallback(makeSelfResolutionError(), false);
  38510. var maybePromise = tryConvertToPromise(value, this);
  38511. if (!(maybePromise instanceof Promise)) return this._fulfill(value);
  38512. if (shouldBind) this._propagateFrom(maybePromise, 2);
  38513. var promise = maybePromise._target();
  38514. var bitField = promise._bitField;
  38515. if (((bitField & 50397184) === 0)) {
  38516. var len = this._length();
  38517. if (len > 0) promise._migrateCallback0(this);
  38518. for (var i = 1; i < len; ++i) {
  38519. promise._migrateCallbackAt(this, i);
  38520. }
  38521. this._setFollowing();
  38522. this._setLength(0);
  38523. this._setFollowee(promise);
  38524. } else if (((bitField & 33554432) !== 0)) {
  38525. this._fulfill(promise._value());
  38526. } else if (((bitField & 16777216) !== 0)) {
  38527. this._reject(promise._reason());
  38528. } else {
  38529. var reason = new CancellationError("late cancellation observer");
  38530. promise._attachExtraTrace(reason);
  38531. this._reject(reason);
  38532. }
  38533. };
  38534. Promise.prototype._rejectCallback = function(reason, synchronous) {
  38535. var trace = util.ensureErrorObject(reason);
  38536. var hasStack = trace === reason;
  38537. if (!hasStack && debug.warnings()) {
  38538. var message = "a promise was rejected with a non-error: " +
  38539. util.classString(reason);
  38540. this._warn(message, true);
  38541. }
  38542. this._attachExtraTrace(trace, synchronous ? hasStack : false);
  38543. this._reject(reason);
  38544. };
  38545. Promise.prototype._resolveFromExecutor = function (executor) {
  38546. var promise = this;
  38547. this._captureStackTrace();
  38548. this._pushContext();
  38549. var synchronous = true;
  38550. var r = this._execute(executor, function(value) {
  38551. promise._resolveCallback(value);
  38552. }, function (reason) {
  38553. promise._rejectCallback(reason, synchronous);
  38554. });
  38555. synchronous = false;
  38556. this._popContext();
  38557. if (r !== undefined) {
  38558. promise._rejectCallback(r, true);
  38559. }
  38560. };
  38561. Promise.prototype._settlePromiseFromHandler = function (
  38562. handler, receiver, value, promise
  38563. ) {
  38564. var bitField = promise._bitField;
  38565. if (((bitField & 65536) !== 0)) return;
  38566. promise._pushContext();
  38567. var x;
  38568. if (receiver === APPLY) {
  38569. if (!value || typeof value.length !== "number") {
  38570. x = errorObj;
  38571. x.e = new TypeError("cannot .spread() a non-array: " +
  38572. util.classString(value));
  38573. } else {
  38574. x = tryCatch(handler).apply(this._boundValue(), value);
  38575. }
  38576. } else {
  38577. x = tryCatch(handler).call(receiver, value);
  38578. }
  38579. var promisesCreatedDuringHandlerInvocation = promise._popContext();
  38580. bitField = promise._bitField;
  38581. if (((bitField & 65536) !== 0)) return;
  38582. if (x === NEXT_FILTER) {
  38583. promise._reject(value);
  38584. } else if (x === errorObj || x === promise) {
  38585. var err = x === promise ? makeSelfResolutionError() : x.e;
  38586. promise._rejectCallback(err, false);
  38587. } else {
  38588. if (x === undefined &&
  38589. promisesCreatedDuringHandlerInvocation > 0 &&
  38590. debug.longStackTraces() &&
  38591. debug.warnings()) {
  38592. promise._warn("a promise was created in a handler but " +
  38593. "none were returned from it", true);
  38594. }
  38595. promise._resolveCallback(x);
  38596. }
  38597. };
  38598. Promise.prototype._target = function() {
  38599. var ret = this;
  38600. while (ret._isFollowing()) ret = ret._followee();
  38601. return ret;
  38602. };
  38603. Promise.prototype._followee = function() {
  38604. return this._rejectionHandler0;
  38605. };
  38606. Promise.prototype._setFollowee = function(promise) {
  38607. this._rejectionHandler0 = promise;
  38608. };
  38609. Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
  38610. var isPromise = promise instanceof Promise;
  38611. var bitField = this._bitField;
  38612. var asyncGuaranteed = ((bitField & 134217728) !== 0);
  38613. if (((bitField & 65536) !== 0)) {
  38614. if (isPromise) promise._invokeInternalOnCancel();
  38615. if (handler === finallyHandler) {
  38616. receiver.cancelPromise = promise;
  38617. if (tryCatch(handler).call(receiver, value) === errorObj) {
  38618. promise._reject(errorObj.e);
  38619. }
  38620. } else if (handler === reflectHandler) {
  38621. promise._fulfill(reflectHandler.call(receiver));
  38622. } else if (receiver instanceof Proxyable) {
  38623. receiver._promiseCancelled(promise);
  38624. } else if (isPromise || promise instanceof PromiseArray) {
  38625. promise._cancel();
  38626. } else {
  38627. receiver.cancel();
  38628. }
  38629. } else if (typeof handler === "function") {
  38630. if (!isPromise) {
  38631. handler.call(receiver, value, promise);
  38632. } else {
  38633. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  38634. this._settlePromiseFromHandler(handler, receiver, value, promise);
  38635. }
  38636. } else if (receiver instanceof Proxyable) {
  38637. if (!receiver._isResolved()) {
  38638. if (((bitField & 33554432) !== 0)) {
  38639. receiver._promiseFulfilled(value, promise);
  38640. } else {
  38641. receiver._promiseRejected(value, promise);
  38642. }
  38643. }
  38644. } else if (isPromise) {
  38645. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  38646. if (((bitField & 33554432) !== 0)) {
  38647. promise._fulfill(value);
  38648. } else {
  38649. promise._reject(value);
  38650. }
  38651. }
  38652. };
  38653. Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
  38654. var handler = ctx.handler;
  38655. var promise = ctx.promise;
  38656. var receiver = ctx.receiver;
  38657. var value = ctx.value;
  38658. if (typeof handler === "function") {
  38659. if (!(promise instanceof Promise)) {
  38660. handler.call(receiver, value, promise);
  38661. } else {
  38662. this._settlePromiseFromHandler(handler, receiver, value, promise);
  38663. }
  38664. } else if (promise instanceof Promise) {
  38665. promise._reject(value);
  38666. }
  38667. };
  38668. Promise.prototype._settlePromiseCtx = function(ctx) {
  38669. this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
  38670. };
  38671. Promise.prototype._settlePromise0 = function(handler, value, bitField) {
  38672. var promise = this._promise0;
  38673. var receiver = this._receiverAt(0);
  38674. this._promise0 = undefined;
  38675. this._receiver0 = undefined;
  38676. this._settlePromise(promise, handler, receiver, value);
  38677. };
  38678. Promise.prototype._clearCallbackDataAtIndex = function(index) {
  38679. var base = index * 4 - 4;
  38680. this[base + 2] =
  38681. this[base + 3] =
  38682. this[base + 0] =
  38683. this[base + 1] = undefined;
  38684. };
  38685. Promise.prototype._fulfill = function (value) {
  38686. var bitField = this._bitField;
  38687. if (((bitField & 117506048) >>> 16)) return;
  38688. if (value === this) {
  38689. var err = makeSelfResolutionError();
  38690. this._attachExtraTrace(err);
  38691. return this._reject(err);
  38692. }
  38693. this._setFulfilled();
  38694. this._rejectionHandler0 = value;
  38695. if ((bitField & 65535) > 0) {
  38696. if (((bitField & 134217728) !== 0)) {
  38697. this._settlePromises();
  38698. } else {
  38699. async.settlePromises(this);
  38700. }
  38701. }
  38702. };
  38703. Promise.prototype._reject = function (reason) {
  38704. var bitField = this._bitField;
  38705. if (((bitField & 117506048) >>> 16)) return;
  38706. this._setRejected();
  38707. this._fulfillmentHandler0 = reason;
  38708. if (this._isFinal()) {
  38709. return async.fatalError(reason, util.isNode);
  38710. }
  38711. if ((bitField & 65535) > 0) {
  38712. if (((bitField & 134217728) !== 0)) {
  38713. this._settlePromises();
  38714. } else {
  38715. async.settlePromises(this);
  38716. }
  38717. } else {
  38718. this._ensurePossibleRejectionHandled();
  38719. }
  38720. };
  38721. Promise.prototype._fulfillPromises = function (len, value) {
  38722. for (var i = 1; i < len; i++) {
  38723. var handler = this._fulfillmentHandlerAt(i);
  38724. var promise = this._promiseAt(i);
  38725. var receiver = this._receiverAt(i);
  38726. this._clearCallbackDataAtIndex(i);
  38727. this._settlePromise(promise, handler, receiver, value);
  38728. }
  38729. };
  38730. Promise.prototype._rejectPromises = function (len, reason) {
  38731. for (var i = 1; i < len; i++) {
  38732. var handler = this._rejectionHandlerAt(i);
  38733. var promise = this._promiseAt(i);
  38734. var receiver = this._receiverAt(i);
  38735. this._clearCallbackDataAtIndex(i);
  38736. this._settlePromise(promise, handler, receiver, reason);
  38737. }
  38738. };
  38739. Promise.prototype._settlePromises = function () {
  38740. var bitField = this._bitField;
  38741. var len = (bitField & 65535);
  38742. if (len > 0) {
  38743. if (((bitField & 16842752) !== 0)) {
  38744. var reason = this._fulfillmentHandler0;
  38745. this._settlePromise0(this._rejectionHandler0, reason, bitField);
  38746. this._rejectPromises(len, reason);
  38747. } else {
  38748. var value = this._rejectionHandler0;
  38749. this._settlePromise0(this._fulfillmentHandler0, value, bitField);
  38750. this._fulfillPromises(len, value);
  38751. }
  38752. this._setLength(0);
  38753. }
  38754. this._clearCancellationData();
  38755. };
  38756. Promise.prototype._settledValue = function() {
  38757. var bitField = this._bitField;
  38758. if (((bitField & 33554432) !== 0)) {
  38759. return this._rejectionHandler0;
  38760. } else if (((bitField & 16777216) !== 0)) {
  38761. return this._fulfillmentHandler0;
  38762. }
  38763. };
  38764. function deferResolve(v) {this.promise._resolveCallback(v);}
  38765. function deferReject(v) {this.promise._rejectCallback(v, false);}
  38766. Promise.defer = Promise.pending = function() {
  38767. debug.deprecated("Promise.defer", "new Promise");
  38768. var promise = new Promise(INTERNAL);
  38769. return {
  38770. promise: promise,
  38771. resolve: deferResolve,
  38772. reject: deferReject
  38773. };
  38774. };
  38775. util.notEnumerableProp(Promise,
  38776. "_makeSelfResolutionError",
  38777. makeSelfResolutionError);
  38778. _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
  38779. debug);
  38780. _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
  38781. _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
  38782. _dereq_("./direct_resolve")(Promise);
  38783. _dereq_("./synchronous_inspection")(Promise);
  38784. _dereq_("./join")(
  38785. Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug);
  38786. Promise.Promise = Promise;
  38787. _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  38788. _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
  38789. _dereq_('./timers.js')(Promise, INTERNAL);
  38790. _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
  38791. _dereq_('./nodeify.js')(Promise);
  38792. _dereq_('./call_get.js')(Promise);
  38793. _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
  38794. _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  38795. _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  38796. _dereq_('./settle.js')(Promise, PromiseArray, debug);
  38797. _dereq_('./some.js')(Promise, PromiseArray, apiRejection);
  38798. _dereq_('./promisify.js')(Promise, INTERNAL);
  38799. _dereq_('./any.js')(Promise);
  38800. _dereq_('./each.js')(Promise, INTERNAL);
  38801. _dereq_('./filter.js')(Promise, INTERNAL);
  38802. util.toFastProperties(Promise);
  38803. util.toFastProperties(Promise.prototype);
  38804. function fillTypes(value) {
  38805. var p = new Promise(INTERNAL);
  38806. p._fulfillmentHandler0 = value;
  38807. p._rejectionHandler0 = value;
  38808. p._promise0 = value;
  38809. p._receiver0 = value;
  38810. }
  38811. // Complete slack tracking, opt out of field-type tracking and
  38812. // stabilize map
  38813. fillTypes({a: 1});
  38814. fillTypes({b: 2});
  38815. fillTypes({c: 3});
  38816. fillTypes(1);
  38817. fillTypes(function(){});
  38818. fillTypes(undefined);
  38819. fillTypes(false);
  38820. fillTypes(new Promise(INTERNAL));
  38821. debug.setBounds(Async.firstLineError, util.lastLineError);
  38822. return Promise;
  38823. };
  38824. },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){
  38825. "use strict";
  38826. module.exports = function(Promise, INTERNAL, tryConvertToPromise,
  38827. apiRejection, Proxyable) {
  38828. var util = _dereq_("./util");
  38829. var isArray = util.isArray;
  38830. function toResolutionValue(val) {
  38831. switch(val) {
  38832. case -2: return [];
  38833. case -3: return {};
  38834. }
  38835. }
  38836. function PromiseArray(values) {
  38837. var promise = this._promise = new Promise(INTERNAL);
  38838. if (values instanceof Promise) {
  38839. promise._propagateFrom(values, 3);
  38840. }
  38841. promise._setOnCancel(this);
  38842. this._values = values;
  38843. this._length = 0;
  38844. this._totalResolved = 0;
  38845. this._init(undefined, -2);
  38846. }
  38847. util.inherits(PromiseArray, Proxyable);
  38848. PromiseArray.prototype.length = function () {
  38849. return this._length;
  38850. };
  38851. PromiseArray.prototype.promise = function () {
  38852. return this._promise;
  38853. };
  38854. PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
  38855. var values = tryConvertToPromise(this._values, this._promise);
  38856. if (values instanceof Promise) {
  38857. values = values._target();
  38858. var bitField = values._bitField;
  38859. ;
  38860. this._values = values;
  38861. if (((bitField & 50397184) === 0)) {
  38862. this._promise._setAsyncGuaranteed();
  38863. return values._then(
  38864. init,
  38865. this._reject,
  38866. undefined,
  38867. this,
  38868. resolveValueIfEmpty
  38869. );
  38870. } else if (((bitField & 33554432) !== 0)) {
  38871. values = values._value();
  38872. } else if (((bitField & 16777216) !== 0)) {
  38873. return this._reject(values._reason());
  38874. } else {
  38875. return this._cancel();
  38876. }
  38877. }
  38878. values = util.asArray(values);
  38879. if (values === null) {
  38880. var err = apiRejection(
  38881. "expecting an array or an iterable object but got " + util.classString(values)).reason();
  38882. this._promise._rejectCallback(err, false);
  38883. return;
  38884. }
  38885. if (values.length === 0) {
  38886. if (resolveValueIfEmpty === -5) {
  38887. this._resolveEmptyArray();
  38888. }
  38889. else {
  38890. this._resolve(toResolutionValue(resolveValueIfEmpty));
  38891. }
  38892. return;
  38893. }
  38894. this._iterate(values);
  38895. };
  38896. PromiseArray.prototype._iterate = function(values) {
  38897. var len = this.getActualLength(values.length);
  38898. this._length = len;
  38899. this._values = this.shouldCopyValues() ? new Array(len) : this._values;
  38900. var result = this._promise;
  38901. var isResolved = false;
  38902. var bitField = null;
  38903. for (var i = 0; i < len; ++i) {
  38904. var maybePromise = tryConvertToPromise(values[i], result);
  38905. if (maybePromise instanceof Promise) {
  38906. maybePromise = maybePromise._target();
  38907. bitField = maybePromise._bitField;
  38908. } else {
  38909. bitField = null;
  38910. }
  38911. if (isResolved) {
  38912. if (bitField !== null) {
  38913. maybePromise.suppressUnhandledRejections();
  38914. }
  38915. } else if (bitField !== null) {
  38916. if (((bitField & 50397184) === 0)) {
  38917. maybePromise._proxy(this, i);
  38918. this._values[i] = maybePromise;
  38919. } else if (((bitField & 33554432) !== 0)) {
  38920. isResolved = this._promiseFulfilled(maybePromise._value(), i);
  38921. } else if (((bitField & 16777216) !== 0)) {
  38922. isResolved = this._promiseRejected(maybePromise._reason(), i);
  38923. } else {
  38924. isResolved = this._promiseCancelled(i);
  38925. }
  38926. } else {
  38927. isResolved = this._promiseFulfilled(maybePromise, i);
  38928. }
  38929. }
  38930. if (!isResolved) result._setAsyncGuaranteed();
  38931. };
  38932. PromiseArray.prototype._isResolved = function () {
  38933. return this._values === null;
  38934. };
  38935. PromiseArray.prototype._resolve = function (value) {
  38936. this._values = null;
  38937. this._promise._fulfill(value);
  38938. };
  38939. PromiseArray.prototype._cancel = function() {
  38940. if (this._isResolved() || !this._promise.isCancellable()) return;
  38941. this._values = null;
  38942. this._promise._cancel();
  38943. };
  38944. PromiseArray.prototype._reject = function (reason) {
  38945. this._values = null;
  38946. this._promise._rejectCallback(reason, false);
  38947. };
  38948. PromiseArray.prototype._promiseFulfilled = function (value, index) {
  38949. this._values[index] = value;
  38950. var totalResolved = ++this._totalResolved;
  38951. if (totalResolved >= this._length) {
  38952. this._resolve(this._values);
  38953. return true;
  38954. }
  38955. return false;
  38956. };
  38957. PromiseArray.prototype._promiseCancelled = function() {
  38958. this._cancel();
  38959. return true;
  38960. };
  38961. PromiseArray.prototype._promiseRejected = function (reason) {
  38962. this._totalResolved++;
  38963. this._reject(reason);
  38964. return true;
  38965. };
  38966. PromiseArray.prototype._resultCancelled = function() {
  38967. if (this._isResolved()) return;
  38968. var values = this._values;
  38969. this._cancel();
  38970. if (values instanceof Promise) {
  38971. values.cancel();
  38972. } else {
  38973. for (var i = 0; i < values.length; ++i) {
  38974. if (values[i] instanceof Promise) {
  38975. values[i].cancel();
  38976. }
  38977. }
  38978. }
  38979. };
  38980. PromiseArray.prototype.shouldCopyValues = function () {
  38981. return true;
  38982. };
  38983. PromiseArray.prototype.getActualLength = function (len) {
  38984. return len;
  38985. };
  38986. return PromiseArray;
  38987. };
  38988. },{"./util":36}],24:[function(_dereq_,module,exports){
  38989. "use strict";
  38990. module.exports = function(Promise, INTERNAL) {
  38991. var THIS = {};
  38992. var util = _dereq_("./util");
  38993. var nodebackForPromise = _dereq_("./nodeback");
  38994. var withAppended = util.withAppended;
  38995. var maybeWrapAsError = util.maybeWrapAsError;
  38996. var canEvaluate = util.canEvaluate;
  38997. var TypeError = _dereq_("./errors").TypeError;
  38998. var defaultSuffix = "Async";
  38999. var defaultPromisified = {__isPromisified__: true};
  39000. var noCopyProps = [
  39001. "arity", "length",
  39002. "name",
  39003. "arguments",
  39004. "caller",
  39005. "callee",
  39006. "prototype",
  39007. "__isPromisified__"
  39008. ];
  39009. var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
  39010. var defaultFilter = function(name) {
  39011. return util.isIdentifier(name) &&
  39012. name.charAt(0) !== "_" &&
  39013. name !== "constructor";
  39014. };
  39015. function propsFilter(key) {
  39016. return !noCopyPropsPattern.test(key);
  39017. }
  39018. function isPromisified(fn) {
  39019. try {
  39020. return fn.__isPromisified__ === true;
  39021. }
  39022. catch (e) {
  39023. return false;
  39024. }
  39025. }
  39026. function hasPromisified(obj, key, suffix) {
  39027. var val = util.getDataPropertyOrDefault(obj, key + suffix,
  39028. defaultPromisified);
  39029. return val ? isPromisified(val) : false;
  39030. }
  39031. function checkValid(ret, suffix, suffixRegexp) {
  39032. for (var i = 0; i < ret.length; i += 2) {
  39033. var key = ret[i];
  39034. if (suffixRegexp.test(key)) {
  39035. var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
  39036. for (var j = 0; j < ret.length; j += 2) {
  39037. if (ret[j] === keyWithoutAsyncSuffix) {
  39038. throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
  39039. .replace("%s", suffix));
  39040. }
  39041. }
  39042. }
  39043. }
  39044. }
  39045. function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
  39046. var keys = util.inheritedDataKeys(obj);
  39047. var ret = [];
  39048. for (var i = 0; i < keys.length; ++i) {
  39049. var key = keys[i];
  39050. var value = obj[key];
  39051. var passesDefaultFilter = filter === defaultFilter
  39052. ? true : defaultFilter(key, value, obj);
  39053. if (typeof value === "function" &&
  39054. !isPromisified(value) &&
  39055. !hasPromisified(obj, key, suffix) &&
  39056. filter(key, value, obj, passesDefaultFilter)) {
  39057. ret.push(key, value);
  39058. }
  39059. }
  39060. checkValid(ret, suffix, suffixRegexp);
  39061. return ret;
  39062. }
  39063. var escapeIdentRegex = function(str) {
  39064. return str.replace(/([$])/, "\\$");
  39065. };
  39066. var makeNodePromisifiedEval;
  39067. if (!true) {
  39068. var switchCaseArgumentOrder = function(likelyArgumentCount) {
  39069. var ret = [likelyArgumentCount];
  39070. var min = Math.max(0, likelyArgumentCount - 1 - 3);
  39071. for(var i = likelyArgumentCount - 1; i >= min; --i) {
  39072. ret.push(i);
  39073. }
  39074. for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
  39075. ret.push(i);
  39076. }
  39077. return ret;
  39078. };
  39079. var argumentSequence = function(argumentCount) {
  39080. return util.filledRange(argumentCount, "_arg", "");
  39081. };
  39082. var parameterDeclaration = function(parameterCount) {
  39083. return util.filledRange(
  39084. Math.max(parameterCount, 3), "_arg", "");
  39085. };
  39086. var parameterCount = function(fn) {
  39087. if (typeof fn.length === "number") {
  39088. return Math.max(Math.min(fn.length, 1023 + 1), 0);
  39089. }
  39090. return 0;
  39091. };
  39092. makeNodePromisifiedEval =
  39093. function(callback, receiver, originalName, fn, _, multiArgs) {
  39094. var newParameterCount = Math.max(0, parameterCount(fn) - 1);
  39095. var argumentOrder = switchCaseArgumentOrder(newParameterCount);
  39096. var shouldProxyThis = typeof callback === "string" || receiver === THIS;
  39097. function generateCallForArgumentCount(count) {
  39098. var args = argumentSequence(count).join(", ");
  39099. var comma = count > 0 ? ", " : "";
  39100. var ret;
  39101. if (shouldProxyThis) {
  39102. ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
  39103. } else {
  39104. ret = receiver === undefined
  39105. ? "ret = callback({{args}}, nodeback); break;\n"
  39106. : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
  39107. }
  39108. return ret.replace("{{args}}", args).replace(", ", comma);
  39109. }
  39110. function generateArgumentSwitchCase() {
  39111. var ret = "";
  39112. for (var i = 0; i < argumentOrder.length; ++i) {
  39113. ret += "case " + argumentOrder[i] +":" +
  39114. generateCallForArgumentCount(argumentOrder[i]);
  39115. }
  39116. ret += " \n\
  39117. default: \n\
  39118. var args = new Array(len + 1); \n\
  39119. var i = 0; \n\
  39120. for (var i = 0; i < len; ++i) { \n\
  39121. args[i] = arguments[i]; \n\
  39122. } \n\
  39123. args[i] = nodeback; \n\
  39124. [CodeForCall] \n\
  39125. break; \n\
  39126. ".replace("[CodeForCall]", (shouldProxyThis
  39127. ? "ret = callback.apply(this, args);\n"
  39128. : "ret = callback.apply(receiver, args);\n"));
  39129. return ret;
  39130. }
  39131. var getFunctionCode = typeof callback === "string"
  39132. ? ("this != null ? this['"+callback+"'] : fn")
  39133. : "fn";
  39134. var body = "'use strict'; \n\
  39135. var ret = function (Parameters) { \n\
  39136. 'use strict'; \n\
  39137. var len = arguments.length; \n\
  39138. var promise = new Promise(INTERNAL); \n\
  39139. promise._captureStackTrace(); \n\
  39140. var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
  39141. var ret; \n\
  39142. var callback = tryCatch([GetFunctionCode]); \n\
  39143. switch(len) { \n\
  39144. [CodeForSwitchCase] \n\
  39145. } \n\
  39146. if (ret === errorObj) { \n\
  39147. promise._rejectCallback(maybeWrapAsError(ret.e), true); \n\
  39148. } \n\
  39149. if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
  39150. return promise; \n\
  39151. }; \n\
  39152. notEnumerableProp(ret, '__isPromisified__', true); \n\
  39153. return ret; \n\
  39154. ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
  39155. .replace("[GetFunctionCode]", getFunctionCode);
  39156. body = body.replace("Parameters", parameterDeclaration(newParameterCount));
  39157. return new Function("Promise",
  39158. "fn",
  39159. "receiver",
  39160. "withAppended",
  39161. "maybeWrapAsError",
  39162. "nodebackForPromise",
  39163. "tryCatch",
  39164. "errorObj",
  39165. "notEnumerableProp",
  39166. "INTERNAL",
  39167. body)(
  39168. Promise,
  39169. fn,
  39170. receiver,
  39171. withAppended,
  39172. maybeWrapAsError,
  39173. nodebackForPromise,
  39174. util.tryCatch,
  39175. util.errorObj,
  39176. util.notEnumerableProp,
  39177. INTERNAL);
  39178. };
  39179. }
  39180. function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
  39181. var defaultThis = (function() {return this;})();
  39182. var method = callback;
  39183. if (typeof method === "string") {
  39184. callback = fn;
  39185. }
  39186. function promisified() {
  39187. var _receiver = receiver;
  39188. if (receiver === THIS) _receiver = this;
  39189. var promise = new Promise(INTERNAL);
  39190. promise._captureStackTrace();
  39191. var cb = typeof method === "string" && this !== defaultThis
  39192. ? this[method] : callback;
  39193. var fn = nodebackForPromise(promise, multiArgs);
  39194. try {
  39195. cb.apply(_receiver, withAppended(arguments, fn));
  39196. } catch(e) {
  39197. promise._rejectCallback(maybeWrapAsError(e), true);
  39198. }
  39199. if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
  39200. return promise;
  39201. }
  39202. util.notEnumerableProp(promisified, "__isPromisified__", true);
  39203. return promisified;
  39204. }
  39205. var makeNodePromisified = canEvaluate
  39206. ? makeNodePromisifiedEval
  39207. : makeNodePromisifiedClosure;
  39208. function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
  39209. var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
  39210. var methods =
  39211. promisifiableMethods(obj, suffix, suffixRegexp, filter);
  39212. for (var i = 0, len = methods.length; i < len; i+= 2) {
  39213. var key = methods[i];
  39214. var fn = methods[i+1];
  39215. var promisifiedKey = key + suffix;
  39216. if (promisifier === makeNodePromisified) {
  39217. obj[promisifiedKey] =
  39218. makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
  39219. } else {
  39220. var promisified = promisifier(fn, function() {
  39221. return makeNodePromisified(key, THIS, key,
  39222. fn, suffix, multiArgs);
  39223. });
  39224. util.notEnumerableProp(promisified, "__isPromisified__", true);
  39225. obj[promisifiedKey] = promisified;
  39226. }
  39227. }
  39228. util.toFastProperties(obj);
  39229. return obj;
  39230. }
  39231. function promisify(callback, receiver, multiArgs) {
  39232. return makeNodePromisified(callback, receiver, undefined,
  39233. callback, null, multiArgs);
  39234. }
  39235. Promise.promisify = function (fn, options) {
  39236. if (typeof fn !== "function") {
  39237. throw new TypeError("expecting a function but got " + util.classString(fn));
  39238. }
  39239. if (isPromisified(fn)) {
  39240. return fn;
  39241. }
  39242. options = Object(options);
  39243. var receiver = options.context === undefined ? THIS : options.context;
  39244. var multiArgs = !!options.multiArgs;
  39245. var ret = promisify(fn, receiver, multiArgs);
  39246. util.copyDescriptors(fn, ret, propsFilter);
  39247. return ret;
  39248. };
  39249. Promise.promisifyAll = function (target, options) {
  39250. if (typeof target !== "function" && typeof target !== "object") {
  39251. throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  39252. }
  39253. options = Object(options);
  39254. var multiArgs = !!options.multiArgs;
  39255. var suffix = options.suffix;
  39256. if (typeof suffix !== "string") suffix = defaultSuffix;
  39257. var filter = options.filter;
  39258. if (typeof filter !== "function") filter = defaultFilter;
  39259. var promisifier = options.promisifier;
  39260. if (typeof promisifier !== "function") promisifier = makeNodePromisified;
  39261. if (!util.isIdentifier(suffix)) {
  39262. throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  39263. }
  39264. var keys = util.inheritedDataKeys(target);
  39265. for (var i = 0; i < keys.length; ++i) {
  39266. var value = target[keys[i]];
  39267. if (keys[i] !== "constructor" &&
  39268. util.isClass(value)) {
  39269. promisifyAll(value.prototype, suffix, filter, promisifier,
  39270. multiArgs);
  39271. promisifyAll(value, suffix, filter, promisifier, multiArgs);
  39272. }
  39273. }
  39274. return promisifyAll(target, suffix, filter, promisifier, multiArgs);
  39275. };
  39276. };
  39277. },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
  39278. "use strict";
  39279. module.exports = function(
  39280. Promise, PromiseArray, tryConvertToPromise, apiRejection) {
  39281. var util = _dereq_("./util");
  39282. var isObject = util.isObject;
  39283. var es5 = _dereq_("./es5");
  39284. var Es6Map;
  39285. if (typeof Map === "function") Es6Map = Map;
  39286. var mapToEntries = (function() {
  39287. var index = 0;
  39288. var size = 0;
  39289. function extractEntry(value, key) {
  39290. this[index] = value;
  39291. this[index + size] = key;
  39292. index++;
  39293. }
  39294. return function mapToEntries(map) {
  39295. size = map.size;
  39296. index = 0;
  39297. var ret = new Array(map.size * 2);
  39298. map.forEach(extractEntry, ret);
  39299. return ret;
  39300. };
  39301. })();
  39302. var entriesToMap = function(entries) {
  39303. var ret = new Es6Map();
  39304. var length = entries.length / 2 | 0;
  39305. for (var i = 0; i < length; ++i) {
  39306. var key = entries[length + i];
  39307. var value = entries[i];
  39308. ret.set(key, value);
  39309. }
  39310. return ret;
  39311. };
  39312. function PropertiesPromiseArray(obj) {
  39313. var isMap = false;
  39314. var entries;
  39315. if (Es6Map !== undefined && obj instanceof Es6Map) {
  39316. entries = mapToEntries(obj);
  39317. isMap = true;
  39318. } else {
  39319. var keys = es5.keys(obj);
  39320. var len = keys.length;
  39321. entries = new Array(len * 2);
  39322. for (var i = 0; i < len; ++i) {
  39323. var key = keys[i];
  39324. entries[i] = obj[key];
  39325. entries[i + len] = key;
  39326. }
  39327. }
  39328. this.constructor$(entries);
  39329. this._isMap = isMap;
  39330. this._init$(undefined, -3);
  39331. }
  39332. util.inherits(PropertiesPromiseArray, PromiseArray);
  39333. PropertiesPromiseArray.prototype._init = function () {};
  39334. PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
  39335. this._values[index] = value;
  39336. var totalResolved = ++this._totalResolved;
  39337. if (totalResolved >= this._length) {
  39338. var val;
  39339. if (this._isMap) {
  39340. val = entriesToMap(this._values);
  39341. } else {
  39342. val = {};
  39343. var keyOffset = this.length();
  39344. for (var i = 0, len = this.length(); i < len; ++i) {
  39345. val[this._values[i + keyOffset]] = this._values[i];
  39346. }
  39347. }
  39348. this._resolve(val);
  39349. return true;
  39350. }
  39351. return false;
  39352. };
  39353. PropertiesPromiseArray.prototype.shouldCopyValues = function () {
  39354. return false;
  39355. };
  39356. PropertiesPromiseArray.prototype.getActualLength = function (len) {
  39357. return len >> 1;
  39358. };
  39359. function props(promises) {
  39360. var ret;
  39361. var castValue = tryConvertToPromise(promises);
  39362. if (!isObject(castValue)) {
  39363. return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  39364. } else if (castValue instanceof Promise) {
  39365. ret = castValue._then(
  39366. Promise.props, undefined, undefined, undefined, undefined);
  39367. } else {
  39368. ret = new PropertiesPromiseArray(castValue).promise();
  39369. }
  39370. if (castValue instanceof Promise) {
  39371. ret._propagateFrom(castValue, 2);
  39372. }
  39373. return ret;
  39374. }
  39375. Promise.prototype.props = function () {
  39376. return props(this);
  39377. };
  39378. Promise.props = function (promises) {
  39379. return props(promises);
  39380. };
  39381. };
  39382. },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
  39383. "use strict";
  39384. function arrayMove(src, srcIndex, dst, dstIndex, len) {
  39385. for (var j = 0; j < len; ++j) {
  39386. dst[j + dstIndex] = src[j + srcIndex];
  39387. src[j + srcIndex] = void 0;
  39388. }
  39389. }
  39390. function Queue(capacity) {
  39391. this._capacity = capacity;
  39392. this._length = 0;
  39393. this._front = 0;
  39394. }
  39395. Queue.prototype._willBeOverCapacity = function (size) {
  39396. return this._capacity < size;
  39397. };
  39398. Queue.prototype._pushOne = function (arg) {
  39399. var length = this.length();
  39400. this._checkCapacity(length + 1);
  39401. var i = (this._front + length) & (this._capacity - 1);
  39402. this[i] = arg;
  39403. this._length = length + 1;
  39404. };
  39405. Queue.prototype._unshiftOne = function(value) {
  39406. var capacity = this._capacity;
  39407. this._checkCapacity(this.length() + 1);
  39408. var front = this._front;
  39409. var i = (((( front - 1 ) &
  39410. ( capacity - 1) ) ^ capacity ) - capacity );
  39411. this[i] = value;
  39412. this._front = i;
  39413. this._length = this.length() + 1;
  39414. };
  39415. Queue.prototype.unshift = function(fn, receiver, arg) {
  39416. this._unshiftOne(arg);
  39417. this._unshiftOne(receiver);
  39418. this._unshiftOne(fn);
  39419. };
  39420. Queue.prototype.push = function (fn, receiver, arg) {
  39421. var length = this.length() + 3;
  39422. if (this._willBeOverCapacity(length)) {
  39423. this._pushOne(fn);
  39424. this._pushOne(receiver);
  39425. this._pushOne(arg);
  39426. return;
  39427. }
  39428. var j = this._front + length - 3;
  39429. this._checkCapacity(length);
  39430. var wrapMask = this._capacity - 1;
  39431. this[(j + 0) & wrapMask] = fn;
  39432. this[(j + 1) & wrapMask] = receiver;
  39433. this[(j + 2) & wrapMask] = arg;
  39434. this._length = length;
  39435. };
  39436. Queue.prototype.shift = function () {
  39437. var front = this._front,
  39438. ret = this[front];
  39439. this[front] = undefined;
  39440. this._front = (front + 1) & (this._capacity - 1);
  39441. this._length--;
  39442. return ret;
  39443. };
  39444. Queue.prototype.length = function () {
  39445. return this._length;
  39446. };
  39447. Queue.prototype._checkCapacity = function (size) {
  39448. if (this._capacity < size) {
  39449. this._resizeTo(this._capacity << 1);
  39450. }
  39451. };
  39452. Queue.prototype._resizeTo = function (capacity) {
  39453. var oldCapacity = this._capacity;
  39454. this._capacity = capacity;
  39455. var front = this._front;
  39456. var length = this._length;
  39457. var moveItemsCount = (front + length) & (oldCapacity - 1);
  39458. arrayMove(this, 0, this, oldCapacity, moveItemsCount);
  39459. };
  39460. module.exports = Queue;
  39461. },{}],27:[function(_dereq_,module,exports){
  39462. "use strict";
  39463. module.exports = function(
  39464. Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  39465. var util = _dereq_("./util");
  39466. var raceLater = function (promise) {
  39467. return promise.then(function(array) {
  39468. return race(array, promise);
  39469. });
  39470. };
  39471. function race(promises, parent) {
  39472. var maybePromise = tryConvertToPromise(promises);
  39473. if (maybePromise instanceof Promise) {
  39474. return raceLater(maybePromise);
  39475. } else {
  39476. promises = util.asArray(promises);
  39477. if (promises === null)
  39478. return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
  39479. }
  39480. var ret = new Promise(INTERNAL);
  39481. if (parent !== undefined) {
  39482. ret._propagateFrom(parent, 3);
  39483. }
  39484. var fulfill = ret._fulfill;
  39485. var reject = ret._reject;
  39486. for (var i = 0, len = promises.length; i < len; ++i) {
  39487. var val = promises[i];
  39488. if (val === undefined && !(i in promises)) {
  39489. continue;
  39490. }
  39491. Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
  39492. }
  39493. return ret;
  39494. }
  39495. Promise.race = function (promises) {
  39496. return race(promises, undefined);
  39497. };
  39498. Promise.prototype.race = function () {
  39499. return race(this, undefined);
  39500. };
  39501. };
  39502. },{"./util":36}],28:[function(_dereq_,module,exports){
  39503. "use strict";
  39504. module.exports = function(Promise,
  39505. PromiseArray,
  39506. apiRejection,
  39507. tryConvertToPromise,
  39508. INTERNAL,
  39509. debug) {
  39510. var getDomain = Promise._getDomain;
  39511. var util = _dereq_("./util");
  39512. var tryCatch = util.tryCatch;
  39513. function ReductionPromiseArray(promises, fn, initialValue, _each) {
  39514. this.constructor$(promises);
  39515. var domain = getDomain();
  39516. this._fn = domain === null ? fn : domain.bind(fn);
  39517. if (initialValue !== undefined) {
  39518. initialValue = Promise.resolve(initialValue);
  39519. initialValue._attachCancellationCallback(this);
  39520. }
  39521. this._initialValue = initialValue;
  39522. this._currentCancellable = null;
  39523. this._eachValues = _each === INTERNAL ? [] : undefined;
  39524. this._promise._captureStackTrace();
  39525. this._init$(undefined, -5);
  39526. }
  39527. util.inherits(ReductionPromiseArray, PromiseArray);
  39528. ReductionPromiseArray.prototype._gotAccum = function(accum) {
  39529. if (this._eachValues !== undefined && accum !== INTERNAL) {
  39530. this._eachValues.push(accum);
  39531. }
  39532. };
  39533. ReductionPromiseArray.prototype._eachComplete = function(value) {
  39534. this._eachValues.push(value);
  39535. return this._eachValues;
  39536. };
  39537. ReductionPromiseArray.prototype._init = function() {};
  39538. ReductionPromiseArray.prototype._resolveEmptyArray = function() {
  39539. this._resolve(this._eachValues !== undefined ? this._eachValues
  39540. : this._initialValue);
  39541. };
  39542. ReductionPromiseArray.prototype.shouldCopyValues = function () {
  39543. return false;
  39544. };
  39545. ReductionPromiseArray.prototype._resolve = function(value) {
  39546. this._promise._resolveCallback(value);
  39547. this._values = null;
  39548. };
  39549. ReductionPromiseArray.prototype._resultCancelled = function(sender) {
  39550. if (sender === this._initialValue) return this._cancel();
  39551. if (this._isResolved()) return;
  39552. this._resultCancelled$();
  39553. if (this._currentCancellable instanceof Promise) {
  39554. this._currentCancellable.cancel();
  39555. }
  39556. if (this._initialValue instanceof Promise) {
  39557. this._initialValue.cancel();
  39558. }
  39559. };
  39560. ReductionPromiseArray.prototype._iterate = function (values) {
  39561. this._values = values;
  39562. var value;
  39563. var i;
  39564. var length = values.length;
  39565. if (this._initialValue !== undefined) {
  39566. value = this._initialValue;
  39567. i = 0;
  39568. } else {
  39569. value = Promise.resolve(values[0]);
  39570. i = 1;
  39571. }
  39572. this._currentCancellable = value;
  39573. if (!value.isRejected()) {
  39574. for (; i < length; ++i) {
  39575. var ctx = {
  39576. accum: null,
  39577. value: values[i],
  39578. index: i,
  39579. length: length,
  39580. array: this
  39581. };
  39582. value = value._then(gotAccum, undefined, undefined, ctx, undefined);
  39583. }
  39584. }
  39585. if (this._eachValues !== undefined) {
  39586. value = value
  39587. ._then(this._eachComplete, undefined, undefined, this, undefined);
  39588. }
  39589. value._then(completed, completed, undefined, value, this);
  39590. };
  39591. Promise.prototype.reduce = function (fn, initialValue) {
  39592. return reduce(this, fn, initialValue, null);
  39593. };
  39594. Promise.reduce = function (promises, fn, initialValue, _each) {
  39595. return reduce(promises, fn, initialValue, _each);
  39596. };
  39597. function completed(valueOrReason, array) {
  39598. if (this.isFulfilled()) {
  39599. array._resolve(valueOrReason);
  39600. } else {
  39601. array._reject(valueOrReason);
  39602. }
  39603. }
  39604. function reduce(promises, fn, initialValue, _each) {
  39605. if (typeof fn !== "function") {
  39606. return apiRejection("expecting a function but got " + util.classString(fn));
  39607. }
  39608. var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
  39609. return array.promise();
  39610. }
  39611. function gotAccum(accum) {
  39612. this.accum = accum;
  39613. this.array._gotAccum(accum);
  39614. var value = tryConvertToPromise(this.value, this.array._promise);
  39615. if (value instanceof Promise) {
  39616. this.array._currentCancellable = value;
  39617. return value._then(gotValue, undefined, undefined, this, undefined);
  39618. } else {
  39619. return gotValue.call(this, value);
  39620. }
  39621. }
  39622. function gotValue(value) {
  39623. var array = this.array;
  39624. var promise = array._promise;
  39625. var fn = tryCatch(array._fn);
  39626. promise._pushContext();
  39627. var ret;
  39628. if (array._eachValues !== undefined) {
  39629. ret = fn.call(promise._boundValue(), value, this.index, this.length);
  39630. } else {
  39631. ret = fn.call(promise._boundValue(),
  39632. this.accum, value, this.index, this.length);
  39633. }
  39634. if (ret instanceof Promise) {
  39635. array._currentCancellable = ret;
  39636. }
  39637. var promisesCreated = promise._popContext();
  39638. debug.checkForgottenReturns(
  39639. ret,
  39640. promisesCreated,
  39641. array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
  39642. promise
  39643. );
  39644. return ret;
  39645. }
  39646. };
  39647. },{"./util":36}],29:[function(_dereq_,module,exports){
  39648. "use strict";
  39649. var util = _dereq_("./util");
  39650. var schedule;
  39651. var noAsyncScheduler = function() {
  39652. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  39653. };
  39654. if (util.isNode && typeof MutationObserver === "undefined") {
  39655. var GlobalSetImmediate = global.setImmediate;
  39656. var ProcessNextTick = process.nextTick;
  39657. schedule = util.isRecentNode
  39658. ? function(fn) { GlobalSetImmediate.call(global, fn); }
  39659. : function(fn) { ProcessNextTick.call(process, fn); };
  39660. } else if ((typeof MutationObserver !== "undefined") &&
  39661. !(typeof window !== "undefined" &&
  39662. window.navigator &&
  39663. window.navigator.standalone)) {
  39664. schedule = function(fn) {
  39665. var div = document.createElement("div");
  39666. var observer = new MutationObserver(fn);
  39667. observer.observe(div, {attributes: true});
  39668. return function() { div.classList.toggle("foo"); };
  39669. };
  39670. schedule.isStatic = true;
  39671. } else if (typeof setImmediate !== "undefined") {
  39672. schedule = function (fn) {
  39673. setImmediate(fn);
  39674. };
  39675. } else if (typeof setTimeout !== "undefined") {
  39676. schedule = function (fn) {
  39677. setTimeout(fn, 0);
  39678. };
  39679. } else {
  39680. schedule = noAsyncScheduler;
  39681. }
  39682. module.exports = schedule;
  39683. },{"./util":36}],30:[function(_dereq_,module,exports){
  39684. "use strict";
  39685. module.exports =
  39686. function(Promise, PromiseArray, debug) {
  39687. var PromiseInspection = Promise.PromiseInspection;
  39688. var util = _dereq_("./util");
  39689. function SettledPromiseArray(values) {
  39690. this.constructor$(values);
  39691. }
  39692. util.inherits(SettledPromiseArray, PromiseArray);
  39693. SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
  39694. this._values[index] = inspection;
  39695. var totalResolved = ++this._totalResolved;
  39696. if (totalResolved >= this._length) {
  39697. this._resolve(this._values);
  39698. return true;
  39699. }
  39700. return false;
  39701. };
  39702. SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
  39703. var ret = new PromiseInspection();
  39704. ret._bitField = 33554432;
  39705. ret._settledValueField = value;
  39706. return this._promiseResolved(index, ret);
  39707. };
  39708. SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
  39709. var ret = new PromiseInspection();
  39710. ret._bitField = 16777216;
  39711. ret._settledValueField = reason;
  39712. return this._promiseResolved(index, ret);
  39713. };
  39714. Promise.settle = function (promises) {
  39715. debug.deprecated(".settle()", ".reflect()");
  39716. return new SettledPromiseArray(promises).promise();
  39717. };
  39718. Promise.prototype.settle = function () {
  39719. return Promise.settle(this);
  39720. };
  39721. };
  39722. },{"./util":36}],31:[function(_dereq_,module,exports){
  39723. "use strict";
  39724. module.exports =
  39725. function(Promise, PromiseArray, apiRejection) {
  39726. var util = _dereq_("./util");
  39727. var RangeError = _dereq_("./errors").RangeError;
  39728. var AggregateError = _dereq_("./errors").AggregateError;
  39729. var isArray = util.isArray;
  39730. var CANCELLATION = {};
  39731. function SomePromiseArray(values) {
  39732. this.constructor$(values);
  39733. this._howMany = 0;
  39734. this._unwrap = false;
  39735. this._initialized = false;
  39736. }
  39737. util.inherits(SomePromiseArray, PromiseArray);
  39738. SomePromiseArray.prototype._init = function () {
  39739. if (!this._initialized) {
  39740. return;
  39741. }
  39742. if (this._howMany === 0) {
  39743. this._resolve([]);
  39744. return;
  39745. }
  39746. this._init$(undefined, -5);
  39747. var isArrayResolved = isArray(this._values);
  39748. if (!this._isResolved() &&
  39749. isArrayResolved &&
  39750. this._howMany > this._canPossiblyFulfill()) {
  39751. this._reject(this._getRangeError(this.length()));
  39752. }
  39753. };
  39754. SomePromiseArray.prototype.init = function () {
  39755. this._initialized = true;
  39756. this._init();
  39757. };
  39758. SomePromiseArray.prototype.setUnwrap = function () {
  39759. this._unwrap = true;
  39760. };
  39761. SomePromiseArray.prototype.howMany = function () {
  39762. return this._howMany;
  39763. };
  39764. SomePromiseArray.prototype.setHowMany = function (count) {
  39765. this._howMany = count;
  39766. };
  39767. SomePromiseArray.prototype._promiseFulfilled = function (value) {
  39768. this._addFulfilled(value);
  39769. if (this._fulfilled() === this.howMany()) {
  39770. this._values.length = this.howMany();
  39771. if (this.howMany() === 1 && this._unwrap) {
  39772. this._resolve(this._values[0]);
  39773. } else {
  39774. this._resolve(this._values);
  39775. }
  39776. return true;
  39777. }
  39778. return false;
  39779. };
  39780. SomePromiseArray.prototype._promiseRejected = function (reason) {
  39781. this._addRejected(reason);
  39782. return this._checkOutcome();
  39783. };
  39784. SomePromiseArray.prototype._promiseCancelled = function () {
  39785. if (this._values instanceof Promise || this._values == null) {
  39786. return this._cancel();
  39787. }
  39788. this._addRejected(CANCELLATION);
  39789. return this._checkOutcome();
  39790. };
  39791. SomePromiseArray.prototype._checkOutcome = function() {
  39792. if (this.howMany() > this._canPossiblyFulfill()) {
  39793. var e = new AggregateError();
  39794. for (var i = this.length(); i < this._values.length; ++i) {
  39795. if (this._values[i] !== CANCELLATION) {
  39796. e.push(this._values[i]);
  39797. }
  39798. }
  39799. if (e.length > 0) {
  39800. this._reject(e);
  39801. } else {
  39802. this._cancel();
  39803. }
  39804. return true;
  39805. }
  39806. return false;
  39807. };
  39808. SomePromiseArray.prototype._fulfilled = function () {
  39809. return this._totalResolved;
  39810. };
  39811. SomePromiseArray.prototype._rejected = function () {
  39812. return this._values.length - this.length();
  39813. };
  39814. SomePromiseArray.prototype._addRejected = function (reason) {
  39815. this._values.push(reason);
  39816. };
  39817. SomePromiseArray.prototype._addFulfilled = function (value) {
  39818. this._values[this._totalResolved++] = value;
  39819. };
  39820. SomePromiseArray.prototype._canPossiblyFulfill = function () {
  39821. return this.length() - this._rejected();
  39822. };
  39823. SomePromiseArray.prototype._getRangeError = function (count) {
  39824. var message = "Input array must contain at least " +
  39825. this._howMany + " items but contains only " + count + " items";
  39826. return new RangeError(message);
  39827. };
  39828. SomePromiseArray.prototype._resolveEmptyArray = function () {
  39829. this._reject(this._getRangeError(0));
  39830. };
  39831. function some(promises, howMany) {
  39832. if ((howMany | 0) !== howMany || howMany < 0) {
  39833. return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  39834. }
  39835. var ret = new SomePromiseArray(promises);
  39836. var promise = ret.promise();
  39837. ret.setHowMany(howMany);
  39838. ret.init();
  39839. return promise;
  39840. }
  39841. Promise.some = function (promises, howMany) {
  39842. return some(promises, howMany);
  39843. };
  39844. Promise.prototype.some = function (howMany) {
  39845. return some(this, howMany);
  39846. };
  39847. Promise._SomePromiseArray = SomePromiseArray;
  39848. };
  39849. },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
  39850. "use strict";
  39851. module.exports = function(Promise) {
  39852. function PromiseInspection(promise) {
  39853. if (promise !== undefined) {
  39854. promise = promise._target();
  39855. this._bitField = promise._bitField;
  39856. this._settledValueField = promise._isFateSealed()
  39857. ? promise._settledValue() : undefined;
  39858. }
  39859. else {
  39860. this._bitField = 0;
  39861. this._settledValueField = undefined;
  39862. }
  39863. }
  39864. PromiseInspection.prototype._settledValue = function() {
  39865. return this._settledValueField;
  39866. };
  39867. var value = PromiseInspection.prototype.value = function () {
  39868. if (!this.isFulfilled()) {
  39869. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  39870. }
  39871. return this._settledValue();
  39872. };
  39873. var reason = PromiseInspection.prototype.error =
  39874. PromiseInspection.prototype.reason = function () {
  39875. if (!this.isRejected()) {
  39876. throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  39877. }
  39878. return this._settledValue();
  39879. };
  39880. var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
  39881. return (this._bitField & 33554432) !== 0;
  39882. };
  39883. var isRejected = PromiseInspection.prototype.isRejected = function () {
  39884. return (this._bitField & 16777216) !== 0;
  39885. };
  39886. var isPending = PromiseInspection.prototype.isPending = function () {
  39887. return (this._bitField & 50397184) === 0;
  39888. };
  39889. var isResolved = PromiseInspection.prototype.isResolved = function () {
  39890. return (this._bitField & 50331648) !== 0;
  39891. };
  39892. PromiseInspection.prototype.isCancelled =
  39893. Promise.prototype._isCancelled = function() {
  39894. return (this._bitField & 65536) === 65536;
  39895. };
  39896. Promise.prototype.isCancelled = function() {
  39897. return this._target()._isCancelled();
  39898. };
  39899. Promise.prototype.isPending = function() {
  39900. return isPending.call(this._target());
  39901. };
  39902. Promise.prototype.isRejected = function() {
  39903. return isRejected.call(this._target());
  39904. };
  39905. Promise.prototype.isFulfilled = function() {
  39906. return isFulfilled.call(this._target());
  39907. };
  39908. Promise.prototype.isResolved = function() {
  39909. return isResolved.call(this._target());
  39910. };
  39911. Promise.prototype.value = function() {
  39912. return value.call(this._target());
  39913. };
  39914. Promise.prototype.reason = function() {
  39915. var target = this._target();
  39916. target._unsetRejectionIsUnhandled();
  39917. return reason.call(target);
  39918. };
  39919. Promise.prototype._value = function() {
  39920. return this._settledValue();
  39921. };
  39922. Promise.prototype._reason = function() {
  39923. this._unsetRejectionIsUnhandled();
  39924. return this._settledValue();
  39925. };
  39926. Promise.PromiseInspection = PromiseInspection;
  39927. };
  39928. },{}],33:[function(_dereq_,module,exports){
  39929. "use strict";
  39930. module.exports = function(Promise, INTERNAL) {
  39931. var util = _dereq_("./util");
  39932. var errorObj = util.errorObj;
  39933. var isObject = util.isObject;
  39934. function tryConvertToPromise(obj, context) {
  39935. if (isObject(obj)) {
  39936. if (obj instanceof Promise) return obj;
  39937. var then = getThen(obj);
  39938. if (then === errorObj) {
  39939. if (context) context._pushContext();
  39940. var ret = Promise.reject(then.e);
  39941. if (context) context._popContext();
  39942. return ret;
  39943. } else if (typeof then === "function") {
  39944. if (isAnyBluebirdPromise(obj)) {
  39945. var ret = new Promise(INTERNAL);
  39946. obj._then(
  39947. ret._fulfill,
  39948. ret._reject,
  39949. undefined,
  39950. ret,
  39951. null
  39952. );
  39953. return ret;
  39954. }
  39955. return doThenable(obj, then, context);
  39956. }
  39957. }
  39958. return obj;
  39959. }
  39960. function doGetThen(obj) {
  39961. return obj.then;
  39962. }
  39963. function getThen(obj) {
  39964. try {
  39965. return doGetThen(obj);
  39966. } catch (e) {
  39967. errorObj.e = e;
  39968. return errorObj;
  39969. }
  39970. }
  39971. var hasProp = {}.hasOwnProperty;
  39972. function isAnyBluebirdPromise(obj) {
  39973. return hasProp.call(obj, "_promise0");
  39974. }
  39975. function doThenable(x, then, context) {
  39976. var promise = new Promise(INTERNAL);
  39977. var ret = promise;
  39978. if (context) context._pushContext();
  39979. promise._captureStackTrace();
  39980. if (context) context._popContext();
  39981. var synchronous = true;
  39982. var result = util.tryCatch(then).call(x, resolve, reject);
  39983. synchronous = false;
  39984. if (promise && result === errorObj) {
  39985. promise._rejectCallback(result.e, true);
  39986. promise = null;
  39987. }
  39988. function resolve(value) {
  39989. if (!promise) return;
  39990. promise._resolveCallback(value);
  39991. promise = null;
  39992. }
  39993. function reject(reason) {
  39994. if (!promise) return;
  39995. promise._rejectCallback(reason, synchronous);
  39996. promise = null;
  39997. }
  39998. return ret;
  39999. }
  40000. return tryConvertToPromise;
  40001. };
  40002. },{"./util":36}],34:[function(_dereq_,module,exports){
  40003. "use strict";
  40004. module.exports = function(Promise, INTERNAL) {
  40005. var util = _dereq_("./util");
  40006. var TimeoutError = Promise.TimeoutError;
  40007. var afterTimeout = function (promise, message) {
  40008. if (!promise.isPending()) return;
  40009. var err;
  40010. if (typeof message !== "string") {
  40011. if (message instanceof Error) {
  40012. err = message;
  40013. } else {
  40014. err = new TimeoutError("operation timed out");
  40015. }
  40016. } else {
  40017. err = new TimeoutError(message);
  40018. }
  40019. util.markAsOriginatingFromRejection(err);
  40020. promise._attachExtraTrace(err);
  40021. promise._reject(err);
  40022. };
  40023. var afterValue = function(value) { return delay(+this).thenReturn(value); };
  40024. var delay = Promise.delay = function (ms, value) {
  40025. var ret;
  40026. if (value !== undefined) {
  40027. ret = Promise.resolve(value)
  40028. ._then(afterValue, null, null, ms, undefined);
  40029. } else {
  40030. ret = new Promise(INTERNAL);
  40031. setTimeout(function() { ret._fulfill(); }, +ms);
  40032. }
  40033. ret._setAsyncGuaranteed();
  40034. return ret;
  40035. };
  40036. Promise.prototype.delay = function (ms) {
  40037. return delay(ms, this);
  40038. };
  40039. function successClear(value) {
  40040. var handle = this;
  40041. if (handle instanceof Number) handle = +handle;
  40042. clearTimeout(handle);
  40043. return value;
  40044. }
  40045. function failureClear(reason) {
  40046. var handle = this;
  40047. if (handle instanceof Number) handle = +handle;
  40048. clearTimeout(handle);
  40049. throw reason;
  40050. }
  40051. Promise.prototype.timeout = function (ms, message) {
  40052. ms = +ms;
  40053. var ret = this.then();
  40054. var handle = setTimeout(function timeoutTimeout() {
  40055. afterTimeout(ret, message);
  40056. }, ms);
  40057. return ret._then(successClear, failureClear, undefined, handle, undefined);
  40058. };
  40059. };
  40060. },{"./util":36}],35:[function(_dereq_,module,exports){
  40061. "use strict";
  40062. module.exports = function (Promise, apiRejection, tryConvertToPromise,
  40063. createContext, INTERNAL, debug) {
  40064. var util = _dereq_("./util");
  40065. var TypeError = _dereq_("./errors").TypeError;
  40066. var inherits = _dereq_("./util").inherits;
  40067. var errorObj = util.errorObj;
  40068. var tryCatch = util.tryCatch;
  40069. function thrower(e) {
  40070. setTimeout(function(){throw e;}, 0);
  40071. }
  40072. function castPreservingDisposable(thenable) {
  40073. var maybePromise = tryConvertToPromise(thenable);
  40074. if (maybePromise !== thenable &&
  40075. typeof thenable._isDisposable === "function" &&
  40076. typeof thenable._getDisposer === "function" &&
  40077. thenable._isDisposable()) {
  40078. maybePromise._setDisposable(thenable._getDisposer());
  40079. }
  40080. return maybePromise;
  40081. }
  40082. function dispose(resources, inspection) {
  40083. var i = 0;
  40084. var len = resources.length;
  40085. var ret = new Promise(INTERNAL);
  40086. function iterator() {
  40087. if (i >= len) return ret._fulfill();
  40088. var maybePromise = castPreservingDisposable(resources[i++]);
  40089. if (maybePromise instanceof Promise &&
  40090. maybePromise._isDisposable()) {
  40091. try {
  40092. maybePromise = tryConvertToPromise(
  40093. maybePromise._getDisposer().tryDispose(inspection),
  40094. resources.promise);
  40095. } catch (e) {
  40096. return thrower(e);
  40097. }
  40098. if (maybePromise instanceof Promise) {
  40099. return maybePromise._then(iterator, thrower,
  40100. null, null, null);
  40101. }
  40102. }
  40103. iterator();
  40104. }
  40105. iterator();
  40106. return ret;
  40107. }
  40108. function Disposer(data, promise, context) {
  40109. this._data = data;
  40110. this._promise = promise;
  40111. this._context = context;
  40112. }
  40113. Disposer.prototype.data = function () {
  40114. return this._data;
  40115. };
  40116. Disposer.prototype.promise = function () {
  40117. return this._promise;
  40118. };
  40119. Disposer.prototype.resource = function () {
  40120. if (this.promise().isFulfilled()) {
  40121. return this.promise().value();
  40122. }
  40123. return null;
  40124. };
  40125. Disposer.prototype.tryDispose = function(inspection) {
  40126. var resource = this.resource();
  40127. var context = this._context;
  40128. if (context !== undefined) context._pushContext();
  40129. var ret = resource !== null
  40130. ? this.doDispose(resource, inspection) : null;
  40131. if (context !== undefined) context._popContext();
  40132. this._promise._unsetDisposable();
  40133. this._data = null;
  40134. return ret;
  40135. };
  40136. Disposer.isDisposer = function (d) {
  40137. return (d != null &&
  40138. typeof d.resource === "function" &&
  40139. typeof d.tryDispose === "function");
  40140. };
  40141. function FunctionDisposer(fn, promise, context) {
  40142. this.constructor$(fn, promise, context);
  40143. }
  40144. inherits(FunctionDisposer, Disposer);
  40145. FunctionDisposer.prototype.doDispose = function (resource, inspection) {
  40146. var fn = this.data();
  40147. return fn.call(resource, resource, inspection);
  40148. };
  40149. function maybeUnwrapDisposer(value) {
  40150. if (Disposer.isDisposer(value)) {
  40151. this.resources[this.index]._setDisposable(value);
  40152. return value.promise();
  40153. }
  40154. return value;
  40155. }
  40156. function ResourceList(length) {
  40157. this.length = length;
  40158. this.promise = null;
  40159. this[length-1] = null;
  40160. }
  40161. ResourceList.prototype._resultCancelled = function() {
  40162. var len = this.length;
  40163. for (var i = 0; i < len; ++i) {
  40164. var item = this[i];
  40165. if (item instanceof Promise) {
  40166. item.cancel();
  40167. }
  40168. }
  40169. };
  40170. Promise.using = function () {
  40171. var len = arguments.length;
  40172. if (len < 2) return apiRejection(
  40173. "you must pass at least 2 arguments to Promise.using");
  40174. var fn = arguments[len - 1];
  40175. if (typeof fn !== "function") {
  40176. return apiRejection("expecting a function but got " + util.classString(fn));
  40177. }
  40178. var input;
  40179. var spreadArgs = true;
  40180. if (len === 2 && Array.isArray(arguments[0])) {
  40181. input = arguments[0];
  40182. len = input.length;
  40183. spreadArgs = false;
  40184. } else {
  40185. input = arguments;
  40186. len--;
  40187. }
  40188. var resources = new ResourceList(len);
  40189. for (var i = 0; i < len; ++i) {
  40190. var resource = input[i];
  40191. if (Disposer.isDisposer(resource)) {
  40192. var disposer = resource;
  40193. resource = resource.promise();
  40194. resource._setDisposable(disposer);
  40195. } else {
  40196. var maybePromise = tryConvertToPromise(resource);
  40197. if (maybePromise instanceof Promise) {
  40198. resource =
  40199. maybePromise._then(maybeUnwrapDisposer, null, null, {
  40200. resources: resources,
  40201. index: i
  40202. }, undefined);
  40203. }
  40204. }
  40205. resources[i] = resource;
  40206. }
  40207. var reflectedResources = new Array(resources.length);
  40208. for (var i = 0; i < reflectedResources.length; ++i) {
  40209. reflectedResources[i] = Promise.resolve(resources[i]).reflect();
  40210. }
  40211. var resultPromise = Promise.all(reflectedResources)
  40212. .then(function(inspections) {
  40213. for (var i = 0; i < inspections.length; ++i) {
  40214. var inspection = inspections[i];
  40215. if (inspection.isRejected()) {
  40216. errorObj.e = inspection.error();
  40217. return errorObj;
  40218. } else if (!inspection.isFulfilled()) {
  40219. resultPromise.cancel();
  40220. return;
  40221. }
  40222. inspections[i] = inspection.value();
  40223. }
  40224. promise._pushContext();
  40225. fn = tryCatch(fn);
  40226. var ret = spreadArgs
  40227. ? fn.apply(undefined, inspections) : fn(inspections);
  40228. var promisesCreated = promise._popContext();
  40229. debug.checkForgottenReturns(
  40230. ret, promisesCreated, "Promise.using", promise);
  40231. return ret;
  40232. });
  40233. var promise = resultPromise.lastly(function() {
  40234. var inspection = new Promise.PromiseInspection(resultPromise);
  40235. return dispose(resources, inspection);
  40236. });
  40237. resources.promise = promise;
  40238. promise._setOnCancel(resources);
  40239. return promise;
  40240. };
  40241. Promise.prototype._setDisposable = function (disposer) {
  40242. this._bitField = this._bitField | 131072;
  40243. this._disposer = disposer;
  40244. };
  40245. Promise.prototype._isDisposable = function () {
  40246. return (this._bitField & 131072) > 0;
  40247. };
  40248. Promise.prototype._getDisposer = function () {
  40249. return this._disposer;
  40250. };
  40251. Promise.prototype._unsetDisposable = function () {
  40252. this._bitField = this._bitField & (~131072);
  40253. this._disposer = undefined;
  40254. };
  40255. Promise.prototype.disposer = function (fn) {
  40256. if (typeof fn === "function") {
  40257. return new FunctionDisposer(fn, this, createContext());
  40258. }
  40259. throw new TypeError();
  40260. };
  40261. };
  40262. },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
  40263. "use strict";
  40264. var es5 = _dereq_("./es5");
  40265. var canEvaluate = typeof navigator == "undefined";
  40266. var errorObj = {e: {}};
  40267. var tryCatchTarget;
  40268. function tryCatcher() {
  40269. try {
  40270. var target = tryCatchTarget;
  40271. tryCatchTarget = null;
  40272. return target.apply(this, arguments);
  40273. } catch (e) {
  40274. errorObj.e = e;
  40275. return errorObj;
  40276. }
  40277. }
  40278. function tryCatch(fn) {
  40279. tryCatchTarget = fn;
  40280. return tryCatcher;
  40281. }
  40282. var inherits = function(Child, Parent) {
  40283. var hasProp = {}.hasOwnProperty;
  40284. function T() {
  40285. this.constructor = Child;
  40286. this.constructor$ = Parent;
  40287. for (var propertyName in Parent.prototype) {
  40288. if (hasProp.call(Parent.prototype, propertyName) &&
  40289. propertyName.charAt(propertyName.length-1) !== "$"
  40290. ) {
  40291. this[propertyName + "$"] = Parent.prototype[propertyName];
  40292. }
  40293. }
  40294. }
  40295. T.prototype = Parent.prototype;
  40296. Child.prototype = new T();
  40297. return Child.prototype;
  40298. };
  40299. function isPrimitive(val) {
  40300. return val == null || val === true || val === false ||
  40301. typeof val === "string" || typeof val === "number";
  40302. }
  40303. function isObject(value) {
  40304. return typeof value === "function" ||
  40305. typeof value === "object" && value !== null;
  40306. }
  40307. function maybeWrapAsError(maybeError) {
  40308. if (!isPrimitive(maybeError)) return maybeError;
  40309. return new Error(safeToString(maybeError));
  40310. }
  40311. function withAppended(target, appendee) {
  40312. var len = target.length;
  40313. var ret = new Array(len + 1);
  40314. var i;
  40315. for (i = 0; i < len; ++i) {
  40316. ret[i] = target[i];
  40317. }
  40318. ret[i] = appendee;
  40319. return ret;
  40320. }
  40321. function getDataPropertyOrDefault(obj, key, defaultValue) {
  40322. if (es5.isES5) {
  40323. var desc = Object.getOwnPropertyDescriptor(obj, key);
  40324. if (desc != null) {
  40325. return desc.get == null && desc.set == null
  40326. ? desc.value
  40327. : defaultValue;
  40328. }
  40329. } else {
  40330. return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
  40331. }
  40332. }
  40333. function notEnumerableProp(obj, name, value) {
  40334. if (isPrimitive(obj)) return obj;
  40335. var descriptor = {
  40336. value: value,
  40337. configurable: true,
  40338. enumerable: false,
  40339. writable: true
  40340. };
  40341. es5.defineProperty(obj, name, descriptor);
  40342. return obj;
  40343. }
  40344. function thrower(r) {
  40345. throw r;
  40346. }
  40347. var inheritedDataKeys = (function() {
  40348. var excludedPrototypes = [
  40349. Array.prototype,
  40350. Object.prototype,
  40351. Function.prototype
  40352. ];
  40353. var isExcludedProto = function(val) {
  40354. for (var i = 0; i < excludedPrototypes.length; ++i) {
  40355. if (excludedPrototypes[i] === val) {
  40356. return true;
  40357. }
  40358. }
  40359. return false;
  40360. };
  40361. if (es5.isES5) {
  40362. var getKeys = Object.getOwnPropertyNames;
  40363. return function(obj) {
  40364. var ret = [];
  40365. var visitedKeys = Object.create(null);
  40366. while (obj != null && !isExcludedProto(obj)) {
  40367. var keys;
  40368. try {
  40369. keys = getKeys(obj);
  40370. } catch (e) {
  40371. return ret;
  40372. }
  40373. for (var i = 0; i < keys.length; ++i) {
  40374. var key = keys[i];
  40375. if (visitedKeys[key]) continue;
  40376. visitedKeys[key] = true;
  40377. var desc = Object.getOwnPropertyDescriptor(obj, key);
  40378. if (desc != null && desc.get == null && desc.set == null) {
  40379. ret.push(key);
  40380. }
  40381. }
  40382. obj = es5.getPrototypeOf(obj);
  40383. }
  40384. return ret;
  40385. };
  40386. } else {
  40387. var hasProp = {}.hasOwnProperty;
  40388. return function(obj) {
  40389. if (isExcludedProto(obj)) return [];
  40390. var ret = [];
  40391. /*jshint forin:false */
  40392. enumeration: for (var key in obj) {
  40393. if (hasProp.call(obj, key)) {
  40394. ret.push(key);
  40395. } else {
  40396. for (var i = 0; i < excludedPrototypes.length; ++i) {
  40397. if (hasProp.call(excludedPrototypes[i], key)) {
  40398. continue enumeration;
  40399. }
  40400. }
  40401. ret.push(key);
  40402. }
  40403. }
  40404. return ret;
  40405. };
  40406. }
  40407. })();
  40408. var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
  40409. function isClass(fn) {
  40410. try {
  40411. if (typeof fn === "function") {
  40412. var keys = es5.names(fn.prototype);
  40413. var hasMethods = es5.isES5 && keys.length > 1;
  40414. var hasMethodsOtherThanConstructor = keys.length > 0 &&
  40415. !(keys.length === 1 && keys[0] === "constructor");
  40416. var hasThisAssignmentAndStaticMethods =
  40417. thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
  40418. if (hasMethods || hasMethodsOtherThanConstructor ||
  40419. hasThisAssignmentAndStaticMethods) {
  40420. return true;
  40421. }
  40422. }
  40423. return false;
  40424. } catch (e) {
  40425. return false;
  40426. }
  40427. }
  40428. function toFastProperties(obj) {
  40429. /*jshint -W027,-W055,-W031*/
  40430. function FakeConstructor() {}
  40431. FakeConstructor.prototype = obj;
  40432. var l = 8;
  40433. while (l--) new FakeConstructor();
  40434. return obj;
  40435. eval(obj);
  40436. }
  40437. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  40438. function isIdentifier(str) {
  40439. return rident.test(str);
  40440. }
  40441. function filledRange(count, prefix, suffix) {
  40442. var ret = new Array(count);
  40443. for(var i = 0; i < count; ++i) {
  40444. ret[i] = prefix + i + suffix;
  40445. }
  40446. return ret;
  40447. }
  40448. function safeToString(obj) {
  40449. try {
  40450. return obj + "";
  40451. } catch (e) {
  40452. return "[no string representation]";
  40453. }
  40454. }
  40455. function markAsOriginatingFromRejection(e) {
  40456. try {
  40457. notEnumerableProp(e, "isOperational", true);
  40458. }
  40459. catch(ignore) {}
  40460. }
  40461. function originatesFromRejection(e) {
  40462. if (e == null) return false;
  40463. return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
  40464. e["isOperational"] === true);
  40465. }
  40466. function canAttachTrace(obj) {
  40467. return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
  40468. }
  40469. var ensureErrorObject = (function() {
  40470. if (!("stack" in new Error())) {
  40471. return function(value) {
  40472. if (canAttachTrace(value)) return value;
  40473. try {throw new Error(safeToString(value));}
  40474. catch(err) {return err;}
  40475. };
  40476. } else {
  40477. return function(value) {
  40478. if (canAttachTrace(value)) return value;
  40479. return new Error(safeToString(value));
  40480. };
  40481. }
  40482. })();
  40483. function classString(obj) {
  40484. return {}.toString.call(obj);
  40485. }
  40486. function copyDescriptors(from, to, filter) {
  40487. var keys = es5.names(from);
  40488. for (var i = 0; i < keys.length; ++i) {
  40489. var key = keys[i];
  40490. if (filter(key)) {
  40491. try {
  40492. es5.defineProperty(to, key, es5.getDescriptor(from, key));
  40493. } catch (ignore) {}
  40494. }
  40495. }
  40496. }
  40497. var asArray = function(v) {
  40498. if (es5.isArray(v)) {
  40499. return v;
  40500. }
  40501. return null;
  40502. };
  40503. if (typeof Symbol !== "undefined" && Symbol.iterator) {
  40504. var ArrayFrom = typeof Array.from === "function" ? function(v) {
  40505. return Array.from(v);
  40506. } : function(v) {
  40507. var ret = [];
  40508. var it = v[Symbol.iterator]();
  40509. var itResult;
  40510. while (!((itResult = it.next()).done)) {
  40511. ret.push(itResult.value);
  40512. }
  40513. return ret;
  40514. };
  40515. asArray = function(v) {
  40516. if (es5.isArray(v)) {
  40517. return v;
  40518. } else if (v != null && typeof v[Symbol.iterator] === "function") {
  40519. return ArrayFrom(v);
  40520. }
  40521. return null;
  40522. };
  40523. }
  40524. var isNode = typeof process !== "undefined" &&
  40525. classString(process).toLowerCase() === "[object process]";
  40526. function env(key, def) {
  40527. return isNode ? process.env[key] : def;
  40528. }
  40529. var ret = {
  40530. isClass: isClass,
  40531. isIdentifier: isIdentifier,
  40532. inheritedDataKeys: inheritedDataKeys,
  40533. getDataPropertyOrDefault: getDataPropertyOrDefault,
  40534. thrower: thrower,
  40535. isArray: es5.isArray,
  40536. asArray: asArray,
  40537. notEnumerableProp: notEnumerableProp,
  40538. isPrimitive: isPrimitive,
  40539. isObject: isObject,
  40540. canEvaluate: canEvaluate,
  40541. errorObj: errorObj,
  40542. tryCatch: tryCatch,
  40543. inherits: inherits,
  40544. withAppended: withAppended,
  40545. maybeWrapAsError: maybeWrapAsError,
  40546. toFastProperties: toFastProperties,
  40547. filledRange: filledRange,
  40548. toString: safeToString,
  40549. canAttachTrace: canAttachTrace,
  40550. ensureErrorObject: ensureErrorObject,
  40551. originatesFromRejection: originatesFromRejection,
  40552. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  40553. classString: classString,
  40554. copyDescriptors: copyDescriptors,
  40555. hasDevTools: typeof chrome !== "undefined" && chrome &&
  40556. typeof chrome.loadTimes === "function",
  40557. isNode: isNode,
  40558. env: env
  40559. };
  40560. ret.isRecentNode = ret.isNode && (function() {
  40561. var version = process.versions.node.split(".").map(Number);
  40562. return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
  40563. })();
  40564. if (ret.isNode) ret.toFastProperties(process);
  40565. try {throw new Error(); } catch (e) {ret.lastLineError = e;}
  40566. module.exports = ret;
  40567. },{"./es5":13}]},{},[4])(4)
  40568. }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
  40569. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  40570. },{"_process":215}],208:[function(require,module,exports){
  40571. },{}],209:[function(require,module,exports){
  40572. // Generated by CoffeeScript 1.10.0
  40573. var Animator, Decoder, Gif, GifReader, Promise, gifler,
  40574. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  40575. GifReader = require('omggif').GifReader;
  40576. Promise = require('bluebird');
  40577. /*---
  40578. head : 'gifler()'
  40579. text :
  40580. - This is the main entrypoint to the library.
  40581. - Prepares and sends an XHR request to load the GIF file.
  40582. - Returns a <b>Gif</b> instance for interacting with the library.
  40583. args :
  40584. url : 'URL to .gif file'
  40585. return : 'a Gif instance object'
  40586. */
  40587. gifler = function(url) {
  40588. var aync, promise, xhr;
  40589. xhr = new XMLHttpRequest();
  40590. xhr.open('GET', url, aync = true);
  40591. xhr.responseType = 'arraybuffer';
  40592. promise = new Promise(function(resolve, reject) {
  40593. return xhr.onload = function(e) {
  40594. return resolve(this.response);
  40595. };
  40596. });
  40597. xhr.send();
  40598. return new Gif(promise);
  40599. };
  40600. Gif = (function() {
  40601. Gif.getCanvasElement = function(selector) {
  40602. var element, ref;
  40603. if (typeof selector === 'string' && ((ref = (element = document.querySelector(selector))) != null ? ref.tagName : void 0) === 'CANVAS') {
  40604. return element;
  40605. } else if ((selector != null ? selector.tagName : void 0) === 'CANVAS') {
  40606. return selector;
  40607. } else {
  40608. throw new Error('Unexpected selector type. Valid types are query-selector-string/canvas-element');
  40609. }
  40610. };
  40611. function Gif(dataPromise) {
  40612. this._animatorPromise = dataPromise.then(function(data) {
  40613. var reader;
  40614. reader = new GifReader(new Uint8Array(data));
  40615. return Decoder.decodeFramesAsync(reader).then(function(frames) {
  40616. return new Animator(reader, frames);
  40617. });
  40618. });
  40619. }
  40620. /*---
  40621. head : 'gif.animate()'
  40622. text :
  40623. - >
  40624. Animates the loaded GIF, drawing each frame into the canvas.
  40625. This matches the look of an &lt;img&gt; tag.
  40626. args :
  40627. selector : 'A <canvas> element or query selector for a <canvas> element.'
  40628. */
  40629. Gif.prototype.animate = function(selector) {
  40630. var canvas;
  40631. canvas = Gif.getCanvasElement(selector);
  40632. return this._animatorPromise.then(function(animator) {
  40633. return animator.animateInCanvas(canvas);
  40634. });
  40635. };
  40636. /*---
  40637. head : 'gif.frames()'
  40638. text :
  40639. - >
  40640. Runs the animation on the loaded GIF, but passes the
  40641. canvas context and GIF frame to the <b>onDrawFrame</b>
  40642. callback for rendering.
  40643. - >
  40644. This gives you complete control of how the frame is drawn
  40645. into the canvas context.
  40646. args :
  40647. selector : 'A <canvas> element or query selector for a <canvas> element.'
  40648. onDrawFrame : 'A callback that will be invoked when each frame should be drawn into the canvas. see Animator.onDrawFrame.'
  40649. setDimesions : 'OPTIONAL. If true, the canvas''s width/height will be set to the dimension of the loaded GIF. default: false.'
  40650. */
  40651. Gif.prototype.frames = function(selector, onDrawFrame, setCanvasDimesions) {
  40652. var canvas;
  40653. if (setCanvasDimesions == null) {
  40654. setCanvasDimesions = false;
  40655. }
  40656. canvas = Gif.getCanvasElement(selector);
  40657. return this._animatorPromise.then(function(animator) {
  40658. animator.onDrawFrame = onDrawFrame;
  40659. return animator.animateInCanvas(canvas, setCanvasDimesions);
  40660. });
  40661. };
  40662. /*---
  40663. head : 'gif.get()'
  40664. text :
  40665. - >
  40666. To get even more control, and for your convenience,
  40667. this method returns a promise that will be fulfilled with
  40668. an <b>Animator</b> instance. The animator will be in an unstarted state,
  40669. but can be started with a call to <b>animator.animateInCanvas()</b>
  40670. */
  40671. Gif.prototype.get = function(callback) {
  40672. return this._animatorPromise;
  40673. };
  40674. return Gif;
  40675. })();
  40676. /*
  40677. These methods decode the pixels for each frame (decompressing and de-interlacing)
  40678. into a Uint8ClampedArray, which is suitable for canvas ImageData.
  40679. */
  40680. Decoder = (function() {
  40681. function Decoder() {}
  40682. Decoder.decodeFramesSync = function(reader) {
  40683. var j, ref, results;
  40684. return (function() {
  40685. results = [];
  40686. for (var j = 0, ref = reader.numFrames(); 0 <= ref ? j < ref : j > ref; 0 <= ref ? j++ : j--){ results.push(j); }
  40687. return results;
  40688. }).apply(this).map(function(frameIndex) {
  40689. return Decoder.decodeFrame(reader, frameIndex);
  40690. });
  40691. };
  40692. Decoder.decodeFramesAsync = function(reader) {
  40693. var concurrency, j, ref, results;
  40694. return Promise.map((function() {
  40695. results = [];
  40696. for (var j = 0, ref = reader.numFrames(); 0 <= ref ? j < ref : j > ref; 0 <= ref ? j++ : j--){ results.push(j); }
  40697. return results;
  40698. }).apply(this), (function(i) {
  40699. return Decoder.decodeFrame(reader, i);
  40700. }), concurrency = 1);
  40701. };
  40702. Decoder.decodeFrame = function(reader, frameIndex) {
  40703. var frameInfo;
  40704. frameInfo = reader.frameInfo(frameIndex);
  40705. frameInfo.pixels = new Uint8ClampedArray(reader.width * reader.height * 4);
  40706. reader.decodeAndBlitFrameRGBA(frameIndex, frameInfo.pixels);
  40707. return frameInfo;
  40708. };
  40709. return Decoder;
  40710. })();
  40711. Animator = (function() {
  40712. /*---
  40713. head : 'animator::createBufferCanvas()'
  40714. text :
  40715. - >
  40716. Creates a buffer canvas element since it is much faster
  40717. to call <b>.putImage()</b> than <b>.putImageData()</b>.
  40718. - >
  40719. The omggif library decodes the pixels into the full gif
  40720. dimensions. We only need to store the frame dimensions,
  40721. so we offset the putImageData call.
  40722. args :
  40723. frame : A frame of the GIF (from the omggif library)
  40724. width : width of the GIF (not the frame)
  40725. height : height of the GIF
  40726. return : A <canvas> element containing the frame's image.
  40727. */
  40728. Animator.createBufferCanvas = function(frame, width, height) {
  40729. var bufferCanvas, bufferContext, imageData;
  40730. bufferCanvas = document.createElement('canvas');
  40731. bufferContext = bufferCanvas.getContext('2d');
  40732. bufferCanvas.width = frame.width;
  40733. bufferCanvas.height = frame.height;
  40734. imageData = bufferContext.createImageData(width, height);
  40735. imageData.data.set(frame.pixels);
  40736. bufferContext.putImageData(imageData, -frame.x, -frame.y);
  40737. return bufferCanvas;
  40738. };
  40739. function Animator(_reader, _frames) {
  40740. var ref;
  40741. this._reader = _reader;
  40742. this._frames = _frames;
  40743. this._advanceFrame = bind(this._advanceFrame, this);
  40744. this._nextFrameRender = bind(this._nextFrameRender, this);
  40745. this._nextFrame = bind(this._nextFrame, this);
  40746. ref = this._reader, this.width = ref.width, this.height = ref.height;
  40747. this._loopCount = this._reader.loopCount();
  40748. this._loops = 0;
  40749. this._frameIndex = 0;
  40750. this._running = false;
  40751. }
  40752. /*---
  40753. head : 'animator.start()'
  40754. text :
  40755. - Starts running the GIF animation loop.
  40756. */
  40757. Animator.prototype.start = function() {
  40758. this._lastTime = new Date().valueOf();
  40759. this._delayCompensation = 0;
  40760. this._running = true;
  40761. setTimeout(this._nextFrame, 0);
  40762. return this;
  40763. };
  40764. /*---
  40765. head : 'animator.stop()'
  40766. text :
  40767. - Stops running the GIF animation loop.
  40768. */
  40769. Animator.prototype.stop = function() {
  40770. this._running = false;
  40771. return this;
  40772. };
  40773. /*---
  40774. head : 'animator.reset()'
  40775. text :
  40776. - Resets the animation loop to the first frame.
  40777. - Does not stop the animation from running.
  40778. */
  40779. Animator.prototype.reset = function() {
  40780. this._frameIndex = 0;
  40781. this._loops = 0;
  40782. return this;
  40783. };
  40784. /*---
  40785. head : 'animator.running()'
  40786. return : A boolean indicating whether or not the animation is running.
  40787. */
  40788. Animator.prototype.running = function() {
  40789. return this._running;
  40790. };
  40791. Animator.prototype._nextFrame = function() {
  40792. requestAnimationFrame(this._nextFrameRender);
  40793. };
  40794. Animator.prototype._nextFrameRender = function() {
  40795. var frame, ref;
  40796. if (!this._running) {
  40797. return;
  40798. }
  40799. frame = this._frames[this._frameIndex];
  40800. if ((ref = this.onFrame) != null) {
  40801. ref.apply(this, [frame, this._frameIndex]);
  40802. }
  40803. return this._enqueueNextFrame();
  40804. };
  40805. Animator.prototype._advanceFrame = function() {
  40806. this._frameIndex += 1;
  40807. if (this._frameIndex >= this._frames.length) {
  40808. if (this._loopCount !== 0 && this._loopCount === this._loops) {
  40809. this.stop();
  40810. } else {
  40811. this._frameIndex = 0;
  40812. this._loops += 1;
  40813. }
  40814. }
  40815. };
  40816. Animator.prototype._enqueueNextFrame = function() {
  40817. var actualDelay, delta, frame, frameDelay;
  40818. this._advanceFrame();
  40819. while (this._running) {
  40820. frame = this._frames[this._frameIndex];
  40821. delta = new Date().valueOf() - this._lastTime;
  40822. this._lastTime += delta;
  40823. this._delayCompensation += delta;
  40824. frameDelay = frame.delay * 10;
  40825. actualDelay = frameDelay - this._delayCompensation;
  40826. this._delayCompensation -= frameDelay;
  40827. if (actualDelay < 0) {
  40828. this._advanceFrame();
  40829. continue;
  40830. } else {
  40831. setTimeout(this._nextFrame, actualDelay);
  40832. break;
  40833. }
  40834. }
  40835. };
  40836. /*---
  40837. head : 'animator.animateInCanvas()'
  40838. text :
  40839. - >
  40840. This method prepares the canvas to be drawn into and sets up
  40841. the callbacks for each frame while the animation is running.
  40842. - >
  40843. To change how each frame is drawn into the canvas, override
  40844. <b>animator.onDrawFrame()</b> before calling this method.
  40845. If <b>animator.onDrawFrame()</b> is not set, we simply draw
  40846. the frame directly into the canvas as is.
  40847. - >
  40848. You may also override <b>animator.onFrame()</b> before calling
  40849. this method. onFrame handles the lazy construction of canvas
  40850. buffers for each frame as well as the disposal method for each frame.
  40851. args :
  40852. canvas : A canvas element.
  40853. setDimensions : 'OPTIONAL. If true, the canvas width/height will be set to match the GIF. default: true.'
  40854. */
  40855. Animator.prototype.animateInCanvas = function(canvas, setDimensions) {
  40856. var ctx;
  40857. if (setDimensions == null) {
  40858. setDimensions = true;
  40859. }
  40860. if (setDimensions) {
  40861. canvas.width = this.width;
  40862. canvas.height = this.height;
  40863. }
  40864. ctx = canvas.getContext('2d');
  40865. if (this.onDrawFrame == null) {
  40866. this.onDrawFrame = function(ctx, frame, i) {
  40867. return ctx.drawImage(frame.buffer, frame.x, frame.y);
  40868. };
  40869. }
  40870. if (this.onFrame == null) {
  40871. this.onFrame = (function(_this) {
  40872. return function(frame, i) {
  40873. var ref, saved;
  40874. if (frame.buffer == null) {
  40875. frame.buffer = Animator.createBufferCanvas(frame, _this.width, _this.height);
  40876. }
  40877. if (typeof _this.disposeFrame === "function") {
  40878. _this.disposeFrame();
  40879. }
  40880. switch (frame.disposal) {
  40881. case 2:
  40882. _this.disposeFrame = function() {
  40883. return ctx.clearRect(0, 0, canvas.width, canvas.height);
  40884. };
  40885. break;
  40886. case 3:
  40887. saved = ctx.getImageData(0, 0, canvas.width, canvas.height);
  40888. _this.disposeFrame = function() {
  40889. return ctx.putImageData(saved, 0, 0);
  40890. };
  40891. break;
  40892. default:
  40893. _this.disposeFrame = null;
  40894. }
  40895. return (ref = _this.onDrawFrame) != null ? ref.apply(_this, [ctx, frame, i]) : void 0;
  40896. };
  40897. })(this);
  40898. }
  40899. this.start();
  40900. return this;
  40901. };
  40902. return Animator;
  40903. })();
  40904. gifler.Gif = Gif;
  40905. gifler.Decoder = Decoder;
  40906. gifler.Animator = Animator;
  40907. if (typeof window !== "undefined" && window !== null) {
  40908. window.gifler = gifler;
  40909. }
  40910. if (typeof module !== "undefined" && module !== null) {
  40911. module.exports = gifler;
  40912. }
  40913. },{"bluebird":207,"omggif":214}],210:[function(require,module,exports){
  40914. (function (global){
  40915. /*!
  40916. * VERSION: 1.9.0
  40917. * DATE: 2017-06-19
  40918. * UPDATES AND DOCS AT: http://greensock.com
  40919. *
  40920. * @license Copyright (c) 2008-2017, GreenSock. All rights reserved.
  40921. * This work is subject to the terms at http://greensock.com/standard-license or for
  40922. * Club GreenSock members, the software agreement that was issued with your membership.
  40923. *
  40924. * @author: Jack Doyle, jack@greensock.com
  40925. **/
  40926. var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node
  40927. (_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() {
  40928. "use strict";
  40929. var _doc = (_gsScope.document || {}).documentElement,
  40930. _window = _gsScope,
  40931. _max = function(element, axis) {
  40932. var dim = (axis === "x") ? "Width" : "Height",
  40933. scroll = "scroll" + dim,
  40934. client = "client" + dim,
  40935. body = document.body;
  40936. return (element === _window || element === _doc || element === body) ? Math.max(_doc[scroll], body[scroll]) - (_window["inner" + dim] || _doc[client] || body[client]) : element[scroll] - element["offset" + dim];
  40937. },
  40938. _unwrapElement = function(value) {
  40939. if (typeof(value) === "string") {
  40940. value = TweenLite.selector(value);
  40941. }
  40942. if (value.length && value !== _window && value[0] && value[0].style && !value.nodeType) {
  40943. value = value[0];
  40944. }
  40945. return (value === _window || (value.nodeType && value.style)) ? value : null;
  40946. },
  40947. _buildGetter = function(e, axis) { //pass in an element and an axis ("x" or "y") and it'll return a getter function for the scroll position of that element (like scrollTop or scrollLeft, although if the element is the window, it'll use the pageXOffset/pageYOffset or the documentElement's scrollTop/scrollLeft or document.body's. Basically this streamlines things and makes a very fast getter across browsers.
  40948. var p = "scroll" + ((axis === "x") ? "Left" : "Top");
  40949. if (e === _window) {
  40950. if (e.pageXOffset != null) {
  40951. p = "page" + axis.toUpperCase() + "Offset";
  40952. } else if (_doc[p] != null) {
  40953. e = _doc;
  40954. } else {
  40955. e = document.body;
  40956. }
  40957. }
  40958. return function() {
  40959. return e[p];
  40960. };
  40961. },
  40962. _getOffset = function(element, container) {
  40963. var rect = _unwrapElement(element).getBoundingClientRect(),
  40964. isRoot = (!container || container === _window || container === document.body),
  40965. cRect = (isRoot ? _doc : container).getBoundingClientRect(),
  40966. offsets = {x: rect.left - cRect.left, y: rect.top - cRect.top};
  40967. if (!isRoot && container) { //only add the current scroll position if it's not the window/body.
  40968. offsets.x += _buildGetter(container, "x")();
  40969. offsets.y += _buildGetter(container, "y")();
  40970. }
  40971. return offsets;
  40972. },
  40973. _parseVal = function(value, target, axis) {
  40974. var type = typeof(value);
  40975. return !isNaN(value) ? parseFloat(value) : (type === "number" || (type === "string" && value.charAt(1) === "=")) ? value : (value === "max") ? _max(target, axis) : Math.min(_max(target, axis), _getOffset(value, target)[axis]);
  40976. },
  40977. ScrollToPlugin = _gsScope._gsDefine.plugin({
  40978. propName: "scrollTo",
  40979. API: 2,
  40980. global: true,
  40981. version:"1.9.0",
  40982. //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
  40983. init: function(target, value, tween) {
  40984. this._wdw = (target === _window);
  40985. this._target = target;
  40986. this._tween = tween;
  40987. if (typeof(value) !== "object") {
  40988. value = {y:value}; //if we don't receive an object as the parameter, assume the user intends "y".
  40989. if (typeof(value.y) === "string" && value.y !== "max" && value.y.charAt(1) !== "=") {
  40990. value.x = value.y;
  40991. }
  40992. } else if (value.nodeType) {
  40993. value = {y:value, x:value};
  40994. }
  40995. this.vars = value;
  40996. this._autoKill = (value.autoKill !== false);
  40997. this.getX = _buildGetter(target, "x");
  40998. this.getY = _buildGetter(target, "y");
  40999. this.x = this.xPrev = this.getX();
  41000. this.y = this.yPrev = this.getY();
  41001. if (value.x != null) {
  41002. this._addTween(this, "x", this.x, _parseVal(value.x, target, "x") - (value.offsetX || 0), "scrollTo_x", true);
  41003. this._overwriteProps.push("scrollTo_x");
  41004. } else {
  41005. this.skipX = true;
  41006. }
  41007. if (value.y != null) {
  41008. this._addTween(this, "y", this.y, _parseVal(value.y, target, "y") - (value.offsetY || 0), "scrollTo_y", true);
  41009. this._overwriteProps.push("scrollTo_y");
  41010. } else {
  41011. this.skipY = true;
  41012. }
  41013. return true;
  41014. },
  41015. //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.)
  41016. set: function(v) {
  41017. this._super.setRatio.call(this, v);
  41018. var x = (this._wdw || !this.skipX) ? this.getX() : this.xPrev,
  41019. y = (this._wdw || !this.skipY) ? this.getY() : this.yPrev,
  41020. yDif = y - this.yPrev,
  41021. xDif = x - this.xPrev,
  41022. threshold = ScrollToPlugin.autoKillThreshold;
  41023. if (this.x < 0) { //can't scroll to a position less than 0! Might happen if someone uses a Back.easeOut or Elastic.easeOut when scrolling back to the top of the page (for example)
  41024. this.x = 0;
  41025. }
  41026. if (this.y < 0) {
  41027. this.y = 0;
  41028. }
  41029. if (this._autoKill) {
  41030. //note: iOS has a bug that throws off the scroll by several pixels, so we need to check if it's within 7 pixels of the previous one that we set instead of just looking for an exact match.
  41031. if (!this.skipX && (xDif > threshold || xDif < -threshold) && x < _max(this._target, "x")) {
  41032. this.skipX = true; //if the user scrolls separately, we should stop tweening!
  41033. }
  41034. if (!this.skipY && (yDif > threshold || yDif < -threshold) && y < _max(this._target, "y")) {
  41035. this.skipY = true; //if the user scrolls separately, we should stop tweening!
  41036. }
  41037. if (this.skipX && this.skipY) {
  41038. this._tween.kill();
  41039. if (this.vars.onAutoKill) {
  41040. this.vars.onAutoKill.apply(this.vars.onAutoKillScope || this._tween, this.vars.onAutoKillParams || []);
  41041. }
  41042. }
  41043. }
  41044. if (this._wdw) {
  41045. _window.scrollTo((!this.skipX) ? this.x : x, (!this.skipY) ? this.y : y);
  41046. } else {
  41047. if (!this.skipY) {
  41048. this._target.scrollTop = this.y;
  41049. }
  41050. if (!this.skipX) {
  41051. this._target.scrollLeft = this.x;
  41052. }
  41053. }
  41054. this.xPrev = this.x;
  41055. this.yPrev = this.y;
  41056. }
  41057. }),
  41058. p = ScrollToPlugin.prototype;
  41059. ScrollToPlugin.max = _max;
  41060. ScrollToPlugin.getOffset = _getOffset;
  41061. ScrollToPlugin.buildGetter = _buildGetter;
  41062. ScrollToPlugin.autoKillThreshold = 7;
  41063. p._kill = function(lookup) {
  41064. if (lookup.scrollTo_x) {
  41065. this.skipX = true;
  41066. }
  41067. if (lookup.scrollTo_y) {
  41068. this.skipY = true;
  41069. }
  41070. return this._super._kill.call(this, lookup);
  41071. };
  41072. }); if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); }
  41073. //export to AMD/RequireJS and CommonJS/Node (precursor to full modular build system coming at a later date)
  41074. (function(name) {
  41075. "use strict";
  41076. var getGlobal = function() {
  41077. return (_gsScope.GreenSockGlobals || _gsScope)[name];
  41078. };
  41079. if (typeof(module) !== "undefined" && module.exports) { //node
  41080. require("gsap/TweenLite");
  41081. module.exports = getGlobal();
  41082. } else if (typeof(define) === "function" && define.amd) { //AMD
  41083. define(["gsap/TweenLite"], getGlobal);
  41084. }
  41085. }("ScrollToPlugin"));
  41086. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  41087. },{"gsap/TweenLite":211}],211:[function(require,module,exports){
  41088. (function (global){
  41089. /*!
  41090. * VERSION: 1.20.2
  41091. * DATE: 2017-06-30
  41092. * UPDATES AND DOCS AT: http://greensock.com
  41093. *
  41094. * @license Copyright (c) 2008-2017, GreenSock. All rights reserved.
  41095. * This work is subject to the terms at http://greensock.com/standard-license or for
  41096. * Club GreenSock members, the software agreement that was issued with your membership.
  41097. *
  41098. * @author: Jack Doyle, jack@greensock.com
  41099. */
  41100. (function(window, moduleName) {
  41101. "use strict";
  41102. var _exports = {},
  41103. _doc = window.document,
  41104. _globals = window.GreenSockGlobals = window.GreenSockGlobals || window;
  41105. if (_globals.TweenLite) {
  41106. return; //in case the core set of classes is already loaded, don't instantiate twice.
  41107. }
  41108. var _namespace = function(ns) {
  41109. var a = ns.split("."),
  41110. p = _globals, i;
  41111. for (i = 0; i < a.length; i++) {
  41112. p[a[i]] = p = p[a[i]] || {};
  41113. }
  41114. return p;
  41115. },
  41116. gs = _namespace("com.greensock"),
  41117. _tinyNum = 0.0000000001,
  41118. _slice = function(a) { //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
  41119. var b = [],
  41120. l = a.length,
  41121. i;
  41122. for (i = 0; i !== l; b.push(a[i++])) {}
  41123. return b;
  41124. },
  41125. _emptyFunc = function() {},
  41126. _isArray = (function() { //works around issues in iframe environments where the Array global isn't shared, thus if the object originates in a different window/iframe, "(obj instanceof Array)" will evaluate false. We added some speed optimizations to avoid Object.prototype.toString.call() unless it's absolutely necessary because it's VERY slow (like 20x slower)
  41127. var toString = Object.prototype.toString,
  41128. array = toString.call([]);
  41129. return function(obj) {
  41130. return obj != null && (obj instanceof Array || (typeof(obj) === "object" && !!obj.push && toString.call(obj) === array));
  41131. };
  41132. }()),
  41133. a, i, p, _ticker, _tickerActive,
  41134. _defLookup = {},
  41135. /**
  41136. * @constructor
  41137. * Defines a GreenSock class, optionally with an array of dependencies that must be instantiated first and passed into the definition.
  41138. * This allows users to load GreenSock JS files in any order even if they have interdependencies (like CSSPlugin extends TweenPlugin which is
  41139. * inside TweenLite.js, but if CSSPlugin is loaded first, it should wait to run its code until TweenLite.js loads and instantiates TweenPlugin
  41140. * and then pass TweenPlugin to CSSPlugin's definition). This is all done automatically and internally.
  41141. *
  41142. * Every definition will be added to a "com.greensock" global object (typically window, but if a window.GreenSockGlobals object is found,
  41143. * it will go there as of v1.7). For example, TweenLite will be found at window.com.greensock.TweenLite and since it's a global class that should be available anywhere,
  41144. * it is ALSO referenced at window.TweenLite. However some classes aren't considered global, like the base com.greensock.core.Animation class, so
  41145. * those will only be at the package like window.com.greensock.core.Animation. Again, if you define a GreenSockGlobals object on the window, everything
  41146. * gets tucked neatly inside there instead of on the window directly. This allows you to do advanced things like load multiple versions of GreenSock
  41147. * files and put them into distinct objects (imagine a banner ad uses a newer version but the main site uses an older one). In that case, you could
  41148. * sandbox the banner one like:
  41149. *
  41150. * <script>
  41151. * var gs = window.GreenSockGlobals = {}; //the newer version we're about to load could now be referenced in a "gs" object, like gs.TweenLite.to(...). Use whatever alias you want as long as it's unique, "gs" or "banner" or whatever.
  41152. * </script>
  41153. * <script src="js/greensock/v1.7/TweenMax.js"></script>
  41154. * <script>
  41155. * window.GreenSockGlobals = window._gsQueue = window._gsDefine = null; //reset it back to null (along with the special _gsQueue variable) so that the next load of TweenMax affects the window and we can reference things directly like TweenLite.to(...)
  41156. * </script>
  41157. * <script src="js/greensock/v1.6/TweenMax.js"></script>
  41158. * <script>
  41159. * gs.TweenLite.to(...); //would use v1.7
  41160. * TweenLite.to(...); //would use v1.6
  41161. * </script>
  41162. *
  41163. * @param {!string} ns The namespace of the class definition, leaving off "com.greensock." as that's assumed. For example, "TweenLite" or "plugins.CSSPlugin" or "easing.Back".
  41164. * @param {!Array.<string>} dependencies An array of dependencies (described as their namespaces minus "com.greensock." prefix). For example ["TweenLite","plugins.TweenPlugin","core.Animation"]
  41165. * @param {!function():Object} func The function that should be called and passed the resolved dependencies which will return the actual class for this definition.
  41166. * @param {boolean=} global If true, the class will be added to the global scope (typically window unless you define a window.GreenSockGlobals object)
  41167. */
  41168. Definition = function(ns, dependencies, func, global) {
  41169. this.sc = (_defLookup[ns]) ? _defLookup[ns].sc : []; //subclasses
  41170. _defLookup[ns] = this;
  41171. this.gsClass = null;
  41172. this.func = func;
  41173. var _classes = [];
  41174. this.check = function(init) {
  41175. var i = dependencies.length,
  41176. missing = i,
  41177. cur, a, n, cl;
  41178. while (--i > -1) {
  41179. if ((cur = _defLookup[dependencies[i]] || new Definition(dependencies[i], [])).gsClass) {
  41180. _classes[i] = cur.gsClass;
  41181. missing--;
  41182. } else if (init) {
  41183. cur.sc.push(this);
  41184. }
  41185. }
  41186. if (missing === 0 && func) {
  41187. a = ("com.greensock." + ns).split(".");
  41188. n = a.pop();
  41189. cl = _namespace(a.join("."))[n] = this.gsClass = func.apply(func, _classes);
  41190. //exports to multiple environments
  41191. if (global) {
  41192. _globals[n] = _exports[n] = cl; //provides a way to avoid global namespace pollution. By default, the main classes like TweenLite, Power1, Strong, etc. are added to window unless a GreenSockGlobals is defined. So if you want to have things added to a custom object instead, just do something like window.GreenSockGlobals = {} before loading any GreenSock files. You can even set up an alias like window.GreenSockGlobals = windows.gs = {} so that you can access everything like gs.TweenLite. Also remember that ALL classes are added to the window.com.greensock object (in their respective packages, like com.greensock.easing.Power1, com.greensock.TweenLite, etc.)
  41193. if (typeof(module) !== "undefined" && module.exports) { //node
  41194. if (ns === moduleName) {
  41195. module.exports = _exports[moduleName] = cl;
  41196. for (i in _exports) {
  41197. cl[i] = _exports[i];
  41198. }
  41199. } else if (_exports[moduleName]) {
  41200. _exports[moduleName][n] = cl;
  41201. }
  41202. } else if (typeof(define) === "function" && define.amd){ //AMD
  41203. define((window.GreenSockAMDPath ? window.GreenSockAMDPath + "/" : "") + ns.split(".").pop(), [], function() { return cl; });
  41204. }
  41205. }
  41206. for (i = 0; i < this.sc.length; i++) {
  41207. this.sc[i].check();
  41208. }
  41209. }
  41210. };
  41211. this.check(true);
  41212. },
  41213. //used to create Definition instances (which basically registers a class that has dependencies).
  41214. _gsDefine = window._gsDefine = function(ns, dependencies, func, global) {
  41215. return new Definition(ns, dependencies, func, global);
  41216. },
  41217. //a quick way to create a class that doesn't have any dependencies. Returns the class, but first registers it in the GreenSock namespace so that other classes can grab it (other classes might be dependent on the class).
  41218. _class = gs._class = function(ns, func, global) {
  41219. func = func || function() {};
  41220. _gsDefine(ns, [], function(){ return func; }, global);
  41221. return func;
  41222. };
  41223. _gsDefine.globals = _globals;
  41224. /*
  41225. * ----------------------------------------------------------------
  41226. * Ease
  41227. * ----------------------------------------------------------------
  41228. */
  41229. var _baseParams = [0, 0, 1, 1],
  41230. Ease = _class("easing.Ease", function(func, extraParams, type, power) {
  41231. this._func = func;
  41232. this._type = type || 0;
  41233. this._power = power || 0;
  41234. this._params = extraParams ? _baseParams.concat(extraParams) : _baseParams;
  41235. }, true),
  41236. _easeMap = Ease.map = {},
  41237. _easeReg = Ease.register = function(ease, names, types, create) {
  41238. var na = names.split(","),
  41239. i = na.length,
  41240. ta = (types || "easeIn,easeOut,easeInOut").split(","),
  41241. e, name, j, type;
  41242. while (--i > -1) {
  41243. name = na[i];
  41244. e = create ? _class("easing."+name, null, true) : gs.easing[name] || {};
  41245. j = ta.length;
  41246. while (--j > -1) {
  41247. type = ta[j];
  41248. _easeMap[name + "." + type] = _easeMap[type + name] = e[type] = ease.getRatio ? ease : ease[type] || new ease();
  41249. }
  41250. }
  41251. };
  41252. p = Ease.prototype;
  41253. p._calcEnd = false;
  41254. p.getRatio = function(p) {
  41255. if (this._func) {
  41256. this._params[0] = p;
  41257. return this._func.apply(null, this._params);
  41258. }
  41259. var t = this._type,
  41260. pw = this._power,
  41261. r = (t === 1) ? 1 - p : (t === 2) ? p : (p < 0.5) ? p * 2 : (1 - p) * 2;
  41262. if (pw === 1) {
  41263. r *= r;
  41264. } else if (pw === 2) {
  41265. r *= r * r;
  41266. } else if (pw === 3) {
  41267. r *= r * r * r;
  41268. } else if (pw === 4) {
  41269. r *= r * r * r * r;
  41270. }
  41271. return (t === 1) ? 1 - r : (t === 2) ? r : (p < 0.5) ? r / 2 : 1 - (r / 2);
  41272. };
  41273. //create all the standard eases like Linear, Quad, Cubic, Quart, Quint, Strong, Power0, Power1, Power2, Power3, and Power4 (each with easeIn, easeOut, and easeInOut)
  41274. a = ["Linear","Quad","Cubic","Quart","Quint,Strong"];
  41275. i = a.length;
  41276. while (--i > -1) {
  41277. p = a[i]+",Power"+i;
  41278. _easeReg(new Ease(null,null,1,i), p, "easeOut", true);
  41279. _easeReg(new Ease(null,null,2,i), p, "easeIn" + ((i === 0) ? ",easeNone" : ""));
  41280. _easeReg(new Ease(null,null,3,i), p, "easeInOut");
  41281. }
  41282. _easeMap.linear = gs.easing.Linear.easeIn;
  41283. _easeMap.swing = gs.easing.Quad.easeInOut; //for jQuery folks
  41284. /*
  41285. * ----------------------------------------------------------------
  41286. * EventDispatcher
  41287. * ----------------------------------------------------------------
  41288. */
  41289. var EventDispatcher = _class("events.EventDispatcher", function(target) {
  41290. this._listeners = {};
  41291. this._eventTarget = target || this;
  41292. });
  41293. p = EventDispatcher.prototype;
  41294. p.addEventListener = function(type, callback, scope, useParam, priority) {
  41295. priority = priority || 0;
  41296. var list = this._listeners[type],
  41297. index = 0,
  41298. listener, i;
  41299. if (this === _ticker && !_tickerActive) {
  41300. _ticker.wake();
  41301. }
  41302. if (list == null) {
  41303. this._listeners[type] = list = [];
  41304. }
  41305. i = list.length;
  41306. while (--i > -1) {
  41307. listener = list[i];
  41308. if (listener.c === callback && listener.s === scope) {
  41309. list.splice(i, 1);
  41310. } else if (index === 0 && listener.pr < priority) {
  41311. index = i + 1;
  41312. }
  41313. }
  41314. list.splice(index, 0, {c:callback, s:scope, up:useParam, pr:priority});
  41315. };
  41316. p.removeEventListener = function(type, callback) {
  41317. var list = this._listeners[type], i;
  41318. if (list) {
  41319. i = list.length;
  41320. while (--i > -1) {
  41321. if (list[i].c === callback) {
  41322. list.splice(i, 1);
  41323. return;
  41324. }
  41325. }
  41326. }
  41327. };
  41328. p.dispatchEvent = function(type) {
  41329. var list = this._listeners[type],
  41330. i, t, listener;
  41331. if (list) {
  41332. i = list.length;
  41333. if (i > 1) {
  41334. list = list.slice(0); //in case addEventListener() is called from within a listener/callback (otherwise the index could change, resulting in a skip)
  41335. }
  41336. t = this._eventTarget;
  41337. while (--i > -1) {
  41338. listener = list[i];
  41339. if (listener) {
  41340. if (listener.up) {
  41341. listener.c.call(listener.s || t, {type:type, target:t});
  41342. } else {
  41343. listener.c.call(listener.s || t);
  41344. }
  41345. }
  41346. }
  41347. }
  41348. };
  41349. /*
  41350. * ----------------------------------------------------------------
  41351. * Ticker
  41352. * ----------------------------------------------------------------
  41353. */
  41354. var _reqAnimFrame = window.requestAnimationFrame,
  41355. _cancelAnimFrame = window.cancelAnimationFrame,
  41356. _getTime = Date.now || function() {return new Date().getTime();},
  41357. _lastUpdate = _getTime();
  41358. //now try to determine the requestAnimationFrame and cancelAnimationFrame functions and if none are found, we'll use a setTimeout()/clearTimeout() polyfill.
  41359. a = ["ms","moz","webkit","o"];
  41360. i = a.length;
  41361. while (--i > -1 && !_reqAnimFrame) {
  41362. _reqAnimFrame = window[a[i] + "RequestAnimationFrame"];
  41363. _cancelAnimFrame = window[a[i] + "CancelAnimationFrame"] || window[a[i] + "CancelRequestAnimationFrame"];
  41364. }
  41365. _class("Ticker", function(fps, useRAF) {
  41366. var _self = this,
  41367. _startTime = _getTime(),
  41368. _useRAF = (useRAF !== false && _reqAnimFrame) ? "auto" : false,
  41369. _lagThreshold = 500,
  41370. _adjustedLag = 33,
  41371. _tickWord = "tick", //helps reduce gc burden
  41372. _fps, _req, _id, _gap, _nextTime,
  41373. _tick = function(manual) {
  41374. var elapsed = _getTime() - _lastUpdate,
  41375. overlap, dispatch;
  41376. if (elapsed > _lagThreshold) {
  41377. _startTime += elapsed - _adjustedLag;
  41378. }
  41379. _lastUpdate += elapsed;
  41380. _self.time = (_lastUpdate - _startTime) / 1000;
  41381. overlap = _self.time - _nextTime;
  41382. if (!_fps || overlap > 0 || manual === true) {
  41383. _self.frame++;
  41384. _nextTime += overlap + (overlap >= _gap ? 0.004 : _gap - overlap);
  41385. dispatch = true;
  41386. }
  41387. if (manual !== true) { //make sure the request is made before we dispatch the "tick" event so that timing is maintained. Otherwise, if processing the "tick" requires a bunch of time (like 15ms) and we're using a setTimeout() that's based on 16.7ms, it'd technically take 31.7ms between frames otherwise.
  41388. _id = _req(_tick);
  41389. }
  41390. if (dispatch) {
  41391. _self.dispatchEvent(_tickWord);
  41392. }
  41393. };
  41394. EventDispatcher.call(_self);
  41395. _self.time = _self.frame = 0;
  41396. _self.tick = function() {
  41397. _tick(true);
  41398. };
  41399. _self.lagSmoothing = function(threshold, adjustedLag) {
  41400. _lagThreshold = threshold || (1 / _tinyNum); //zero should be interpreted as basically unlimited
  41401. _adjustedLag = Math.min(adjustedLag, _lagThreshold, 0);
  41402. };
  41403. _self.sleep = function() {
  41404. if (_id == null) {
  41405. return;
  41406. }
  41407. if (!_useRAF || !_cancelAnimFrame) {
  41408. clearTimeout(_id);
  41409. } else {
  41410. _cancelAnimFrame(_id);
  41411. }
  41412. _req = _emptyFunc;
  41413. _id = null;
  41414. if (_self === _ticker) {
  41415. _tickerActive = false;
  41416. }
  41417. };
  41418. _self.wake = function(seamless) {
  41419. if (_id !== null) {
  41420. _self.sleep();
  41421. } else if (seamless) {
  41422. _startTime += -_lastUpdate + (_lastUpdate = _getTime());
  41423. } else if (_self.frame > 10) { //don't trigger lagSmoothing if we're just waking up, and make sure that at least 10 frames have elapsed because of the iOS bug that we work around below with the 1.5-second setTimout().
  41424. _lastUpdate = _getTime() - _lagThreshold + 5;
  41425. }
  41426. _req = (_fps === 0) ? _emptyFunc : (!_useRAF || !_reqAnimFrame) ? function(f) { return setTimeout(f, ((_nextTime - _self.time) * 1000 + 1) | 0); } : _reqAnimFrame;
  41427. if (_self === _ticker) {
  41428. _tickerActive = true;
  41429. }
  41430. _tick(2);
  41431. };
  41432. _self.fps = function(value) {
  41433. if (!arguments.length) {
  41434. return _fps;
  41435. }
  41436. _fps = value;
  41437. _gap = 1 / (_fps || 60);
  41438. _nextTime = this.time + _gap;
  41439. _self.wake();
  41440. };
  41441. _self.useRAF = function(value) {
  41442. if (!arguments.length) {
  41443. return _useRAF;
  41444. }
  41445. _self.sleep();
  41446. _useRAF = value;
  41447. _self.fps(_fps);
  41448. };
  41449. _self.fps(fps);
  41450. //a bug in iOS 6 Safari occasionally prevents the requestAnimationFrame from working initially, so we use a 1.5-second timeout that automatically falls back to setTimeout() if it senses this condition.
  41451. setTimeout(function() {
  41452. if (_useRAF === "auto" && _self.frame < 5 && _doc.visibilityState !== "hidden") {
  41453. _self.useRAF(false);
  41454. }
  41455. }, 1500);
  41456. });
  41457. p = gs.Ticker.prototype = new gs.events.EventDispatcher();
  41458. p.constructor = gs.Ticker;
  41459. /*
  41460. * ----------------------------------------------------------------
  41461. * Animation
  41462. * ----------------------------------------------------------------
  41463. */
  41464. var Animation = _class("core.Animation", function(duration, vars) {
  41465. this.vars = vars = vars || {};
  41466. this._duration = this._totalDuration = duration || 0;
  41467. this._delay = Number(vars.delay) || 0;
  41468. this._timeScale = 1;
  41469. this._active = (vars.immediateRender === true);
  41470. this.data = vars.data;
  41471. this._reversed = (vars.reversed === true);
  41472. if (!_rootTimeline) {
  41473. return;
  41474. }
  41475. if (!_tickerActive) { //some browsers (like iOS 6 Safari) shut down JavaScript execution when the tab is disabled and they [occasionally] neglect to start up requestAnimationFrame again when returning - this code ensures that the engine starts up again properly.
  41476. _ticker.wake();
  41477. }
  41478. var tl = this.vars.useFrames ? _rootFramesTimeline : _rootTimeline;
  41479. tl.add(this, tl._time);
  41480. if (this.vars.paused) {
  41481. this.paused(true);
  41482. }
  41483. });
  41484. _ticker = Animation.ticker = new gs.Ticker();
  41485. p = Animation.prototype;
  41486. p._dirty = p._gc = p._initted = p._paused = false;
  41487. p._totalTime = p._time = 0;
  41488. p._rawPrevTime = -1;
  41489. p._next = p._last = p._onUpdate = p._timeline = p.timeline = null;
  41490. p._paused = false;
  41491. //some browsers (like iOS) occasionally drop the requestAnimationFrame event when the user switches to a different tab and then comes back again, so we use a 2-second setTimeout() to sense if/when that condition occurs and then wake() the ticker.
  41492. var _checkTimeout = function() {
  41493. if (_tickerActive && _getTime() - _lastUpdate > 2000 && _doc.visibilityState !== "hidden") {
  41494. _ticker.wake();
  41495. }
  41496. var t = setTimeout(_checkTimeout, 2000);
  41497. if (t.unref) {
  41498. // allows a node process to exit even if the timeout’s callback hasn't been invoked. Without it, the node process could hang as this function is called every two seconds.
  41499. t.unref();
  41500. }
  41501. };
  41502. _checkTimeout();
  41503. p.play = function(from, suppressEvents) {
  41504. if (from != null) {
  41505. this.seek(from, suppressEvents);
  41506. }
  41507. return this.reversed(false).paused(false);
  41508. };
  41509. p.pause = function(atTime, suppressEvents) {
  41510. if (atTime != null) {
  41511. this.seek(atTime, suppressEvents);
  41512. }
  41513. return this.paused(true);
  41514. };
  41515. p.resume = function(from, suppressEvents) {
  41516. if (from != null) {
  41517. this.seek(from, suppressEvents);
  41518. }
  41519. return this.paused(false);
  41520. };
  41521. p.seek = function(time, suppressEvents) {
  41522. return this.totalTime(Number(time), suppressEvents !== false);
  41523. };
  41524. p.restart = function(includeDelay, suppressEvents) {
  41525. return this.reversed(false).paused(false).totalTime(includeDelay ? -this._delay : 0, (suppressEvents !== false), true);
  41526. };
  41527. p.reverse = function(from, suppressEvents) {
  41528. if (from != null) {
  41529. this.seek((from || this.totalDuration()), suppressEvents);
  41530. }
  41531. return this.reversed(true).paused(false);
  41532. };
  41533. p.render = function(time, suppressEvents, force) {
  41534. //stub - we override this method in subclasses.
  41535. };
  41536. p.invalidate = function() {
  41537. this._time = this._totalTime = 0;
  41538. this._initted = this._gc = false;
  41539. this._rawPrevTime = -1;
  41540. if (this._gc || !this.timeline) {
  41541. this._enabled(true);
  41542. }
  41543. return this;
  41544. };
  41545. p.isActive = function() {
  41546. var tl = this._timeline, //the 2 root timelines won't have a _timeline; they're always active.
  41547. startTime = this._startTime,
  41548. rawTime;
  41549. return (!tl || (!this._gc && !this._paused && tl.isActive() && (rawTime = tl.rawTime(true)) >= startTime && rawTime < startTime + this.totalDuration() / this._timeScale - 0.0000001));
  41550. };
  41551. p._enabled = function (enabled, ignoreTimeline) {
  41552. if (!_tickerActive) {
  41553. _ticker.wake();
  41554. }
  41555. this._gc = !enabled;
  41556. this._active = this.isActive();
  41557. if (ignoreTimeline !== true) {
  41558. if (enabled && !this.timeline) {
  41559. this._timeline.add(this, this._startTime - this._delay);
  41560. } else if (!enabled && this.timeline) {
  41561. this._timeline._remove(this, true);
  41562. }
  41563. }
  41564. return false;
  41565. };
  41566. p._kill = function(vars, target) {
  41567. return this._enabled(false, false);
  41568. };
  41569. p.kill = function(vars, target) {
  41570. this._kill(vars, target);
  41571. return this;
  41572. };
  41573. p._uncache = function(includeSelf) {
  41574. var tween = includeSelf ? this : this.timeline;
  41575. while (tween) {
  41576. tween._dirty = true;
  41577. tween = tween.timeline;
  41578. }
  41579. return this;
  41580. };
  41581. p._swapSelfInParams = function(params) {
  41582. var i = params.length,
  41583. copy = params.concat();
  41584. while (--i > -1) {
  41585. if (params[i] === "{self}") {
  41586. copy[i] = this;
  41587. }
  41588. }
  41589. return copy;
  41590. };
  41591. p._callback = function(type) {
  41592. var v = this.vars,
  41593. callback = v[type],
  41594. params = v[type + "Params"],
  41595. scope = v[type + "Scope"] || v.callbackScope || this,
  41596. l = params ? params.length : 0;
  41597. switch (l) { //speed optimization; call() is faster than apply() so use it when there are only a few parameters (which is by far most common). Previously we simply did var v = this.vars; v[type].apply(v[type + "Scope"] || v.callbackScope || this, v[type + "Params"] || _blankArray);
  41598. case 0: callback.call(scope); break;
  41599. case 1: callback.call(scope, params[0]); break;
  41600. case 2: callback.call(scope, params[0], params[1]); break;
  41601. default: callback.apply(scope, params);
  41602. }
  41603. };
  41604. //----Animation getters/setters --------------------------------------------------------
  41605. p.eventCallback = function(type, callback, params, scope) {
  41606. if ((type || "").substr(0,2) === "on") {
  41607. var v = this.vars;
  41608. if (arguments.length === 1) {
  41609. return v[type];
  41610. }
  41611. if (callback == null) {
  41612. delete v[type];
  41613. } else {
  41614. v[type] = callback;
  41615. v[type + "Params"] = (_isArray(params) && params.join("").indexOf("{self}") !== -1) ? this._swapSelfInParams(params) : params;
  41616. v[type + "Scope"] = scope;
  41617. }
  41618. if (type === "onUpdate") {
  41619. this._onUpdate = callback;
  41620. }
  41621. }
  41622. return this;
  41623. };
  41624. p.delay = function(value) {
  41625. if (!arguments.length) {
  41626. return this._delay;
  41627. }
  41628. if (this._timeline.smoothChildTiming) {
  41629. this.startTime( this._startTime + value - this._delay );
  41630. }
  41631. this._delay = value;
  41632. return this;
  41633. };
  41634. p.duration = function(value) {
  41635. if (!arguments.length) {
  41636. this._dirty = false;
  41637. return this._duration;
  41638. }
  41639. this._duration = this._totalDuration = value;
  41640. this._uncache(true); //true in case it's a TweenMax or TimelineMax that has a repeat - we'll need to refresh the totalDuration.
  41641. if (this._timeline.smoothChildTiming) if (this._time > 0) if (this._time < this._duration) if (value !== 0) {
  41642. this.totalTime(this._totalTime * (value / this._duration), true);
  41643. }
  41644. return this;
  41645. };
  41646. p.totalDuration = function(value) {
  41647. this._dirty = false;
  41648. return (!arguments.length) ? this._totalDuration : this.duration(value);
  41649. };
  41650. p.time = function(value, suppressEvents) {
  41651. if (!arguments.length) {
  41652. return this._time;
  41653. }
  41654. if (this._dirty) {
  41655. this.totalDuration();
  41656. }
  41657. return this.totalTime((value > this._duration) ? this._duration : value, suppressEvents);
  41658. };
  41659. p.totalTime = function(time, suppressEvents, uncapped) {
  41660. if (!_tickerActive) {
  41661. _ticker.wake();
  41662. }
  41663. if (!arguments.length) {
  41664. return this._totalTime;
  41665. }
  41666. if (this._timeline) {
  41667. if (time < 0 && !uncapped) {
  41668. time += this.totalDuration();
  41669. }
  41670. if (this._timeline.smoothChildTiming) {
  41671. if (this._dirty) {
  41672. this.totalDuration();
  41673. }
  41674. var totalDuration = this._totalDuration,
  41675. tl = this._timeline;
  41676. if (time > totalDuration && !uncapped) {
  41677. time = totalDuration;
  41678. }
  41679. this._startTime = (this._paused ? this._pauseTime : tl._time) - ((!this._reversed ? time : totalDuration - time) / this._timeScale);
  41680. if (!tl._dirty) { //for performance improvement. If the parent's cache is already dirty, it already took care of marking the ancestors as dirty too, so skip the function call here.
  41681. this._uncache(false);
  41682. }
  41683. //in case any of the ancestor timelines had completed but should now be enabled, we should reset their totalTime() which will also ensure that they're lined up properly and enabled. Skip for animations that are on the root (wasteful). Example: a TimelineLite.exportRoot() is performed when there's a paused tween on the root, the export will not complete until that tween is unpaused, but imagine a child gets restarted later, after all [unpaused] tweens have completed. The startTime of that child would get pushed out, but one of the ancestors may have completed.
  41684. if (tl._timeline) {
  41685. while (tl._timeline) {
  41686. if (tl._timeline._time !== (tl._startTime + tl._totalTime) / tl._timeScale) {
  41687. tl.totalTime(tl._totalTime, true);
  41688. }
  41689. tl = tl._timeline;
  41690. }
  41691. }
  41692. }
  41693. if (this._gc) {
  41694. this._enabled(true, false);
  41695. }
  41696. if (this._totalTime !== time || this._duration === 0) {
  41697. if (_lazyTweens.length) {
  41698. _lazyRender();
  41699. }
  41700. this.render(time, suppressEvents, false);
  41701. if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when someone calls seek() or time() or progress(), they expect an immediate render.
  41702. _lazyRender();
  41703. }
  41704. }
  41705. }
  41706. return this;
  41707. };
  41708. p.progress = p.totalProgress = function(value, suppressEvents) {
  41709. var duration = this.duration();
  41710. return (!arguments.length) ? (duration ? this._time / duration : this.ratio) : this.totalTime(duration * value, suppressEvents);
  41711. };
  41712. p.startTime = function(value) {
  41713. if (!arguments.length) {
  41714. return this._startTime;
  41715. }
  41716. if (value !== this._startTime) {
  41717. this._startTime = value;
  41718. if (this.timeline) if (this.timeline._sortChildren) {
  41719. this.timeline.add(this, value - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct.
  41720. }
  41721. }
  41722. return this;
  41723. };
  41724. p.endTime = function(includeRepeats) {
  41725. return this._startTime + ((includeRepeats != false) ? this.totalDuration() : this.duration()) / this._timeScale;
  41726. };
  41727. p.timeScale = function(value) {
  41728. if (!arguments.length) {
  41729. return this._timeScale;
  41730. }
  41731. value = value || _tinyNum; //can't allow zero because it'll throw the math off
  41732. if (this._timeline && this._timeline.smoothChildTiming) {
  41733. var pauseTime = this._pauseTime,
  41734. t = (pauseTime || pauseTime === 0) ? pauseTime : this._timeline.totalTime();
  41735. this._startTime = t - ((t - this._startTime) * this._timeScale / value);
  41736. }
  41737. this._timeScale = value;
  41738. return this._uncache(false);
  41739. };
  41740. p.reversed = function(value) {
  41741. if (!arguments.length) {
  41742. return this._reversed;
  41743. }
  41744. if (value != this._reversed) {
  41745. this._reversed = value;
  41746. this.totalTime(((this._timeline && !this._timeline.smoothChildTiming) ? this.totalDuration() - this._totalTime : this._totalTime), true);
  41747. }
  41748. return this;
  41749. };
  41750. p.paused = function(value) {
  41751. if (!arguments.length) {
  41752. return this._paused;
  41753. }
  41754. var tl = this._timeline,
  41755. raw, elapsed;
  41756. if (value != this._paused) if (tl) {
  41757. if (!_tickerActive && !value) {
  41758. _ticker.wake();
  41759. }
  41760. raw = tl.rawTime();
  41761. elapsed = raw - this._pauseTime;
  41762. if (!value && tl.smoothChildTiming) {
  41763. this._startTime += elapsed;
  41764. this._uncache(false);
  41765. }
  41766. this._pauseTime = value ? raw : null;
  41767. this._paused = value;
  41768. this._active = this.isActive();
  41769. if (!value && elapsed !== 0 && this._initted && this.duration()) {
  41770. raw = tl.smoothChildTiming ? this._totalTime : (raw - this._startTime) / this._timeScale;
  41771. this.render(raw, (raw === this._totalTime), true); //in case the target's properties changed via some other tween or manual update by the user, we should force a render.
  41772. }
  41773. }
  41774. if (this._gc && !value) {
  41775. this._enabled(true, false);
  41776. }
  41777. return this;
  41778. };
  41779. /*
  41780. * ----------------------------------------------------------------
  41781. * SimpleTimeline
  41782. * ----------------------------------------------------------------
  41783. */
  41784. var SimpleTimeline = _class("core.SimpleTimeline", function(vars) {
  41785. Animation.call(this, 0, vars);
  41786. this.autoRemoveChildren = this.smoothChildTiming = true;
  41787. });
  41788. p = SimpleTimeline.prototype = new Animation();
  41789. p.constructor = SimpleTimeline;
  41790. p.kill()._gc = false;
  41791. p._first = p._last = p._recent = null;
  41792. p._sortChildren = false;
  41793. p.add = p.insert = function(child, position, align, stagger) {
  41794. var prevTween, st;
  41795. child._startTime = Number(position || 0) + child._delay;
  41796. if (child._paused) if (this !== child._timeline) { //we only adjust the _pauseTime if it wasn't in this timeline already. Remember, sometimes a tween will be inserted again into the same timeline when its startTime is changed so that the tweens in the TimelineLite/Max are re-ordered properly in the linked list (so everything renders in the proper order).
  41797. child._pauseTime = child._startTime + ((this.rawTime() - child._startTime) / child._timeScale);
  41798. }
  41799. if (child.timeline) {
  41800. child.timeline._remove(child, true); //removes from existing timeline so that it can be properly added to this one.
  41801. }
  41802. child.timeline = child._timeline = this;
  41803. if (child._gc) {
  41804. child._enabled(true, true);
  41805. }
  41806. prevTween = this._last;
  41807. if (this._sortChildren) {
  41808. st = child._startTime;
  41809. while (prevTween && prevTween._startTime > st) {
  41810. prevTween = prevTween._prev;
  41811. }
  41812. }
  41813. if (prevTween) {
  41814. child._next = prevTween._next;
  41815. prevTween._next = child;
  41816. } else {
  41817. child._next = this._first;
  41818. this._first = child;
  41819. }
  41820. if (child._next) {
  41821. child._next._prev = child;
  41822. } else {
  41823. this._last = child;
  41824. }
  41825. child._prev = prevTween;
  41826. this._recent = child;
  41827. if (this._timeline) {
  41828. this._uncache(true);
  41829. }
  41830. return this;
  41831. };
  41832. p._remove = function(tween, skipDisable) {
  41833. if (tween.timeline === this) {
  41834. if (!skipDisable) {
  41835. tween._enabled(false, true);
  41836. }
  41837. if (tween._prev) {
  41838. tween._prev._next = tween._next;
  41839. } else if (this._first === tween) {
  41840. this._first = tween._next;
  41841. }
  41842. if (tween._next) {
  41843. tween._next._prev = tween._prev;
  41844. } else if (this._last === tween) {
  41845. this._last = tween._prev;
  41846. }
  41847. tween._next = tween._prev = tween.timeline = null;
  41848. if (tween === this._recent) {
  41849. this._recent = this._last;
  41850. }
  41851. if (this._timeline) {
  41852. this._uncache(true);
  41853. }
  41854. }
  41855. return this;
  41856. };
  41857. p.render = function(time, suppressEvents, force) {
  41858. var tween = this._first,
  41859. next;
  41860. this._totalTime = this._time = this._rawPrevTime = time;
  41861. while (tween) {
  41862. next = tween._next; //record it here because the value could change after rendering...
  41863. if (tween._active || (time >= tween._startTime && !tween._paused && !tween._gc)) {
  41864. if (!tween._reversed) {
  41865. tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
  41866. } else {
  41867. tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
  41868. }
  41869. }
  41870. tween = next;
  41871. }
  41872. };
  41873. p.rawTime = function() {
  41874. if (!_tickerActive) {
  41875. _ticker.wake();
  41876. }
  41877. return this._totalTime;
  41878. };
  41879. /*
  41880. * ----------------------------------------------------------------
  41881. * TweenLite
  41882. * ----------------------------------------------------------------
  41883. */
  41884. var TweenLite = _class("TweenLite", function(target, duration, vars) {
  41885. Animation.call(this, duration, vars);
  41886. this.render = TweenLite.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method)
  41887. if (target == null) {
  41888. throw "Cannot tween a null target.";
  41889. }
  41890. this.target = target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target;
  41891. var isSelector = (target.jquery || (target.length && target !== window && target[0] && (target[0] === window || (target[0].nodeType && target[0].style && !target.nodeType)))),
  41892. overwrite = this.vars.overwrite,
  41893. i, targ, targets;
  41894. this._overwrite = overwrite = (overwrite == null) ? _overwriteLookup[TweenLite.defaultOverwrite] : (typeof(overwrite) === "number") ? overwrite >> 0 : _overwriteLookup[overwrite];
  41895. if ((isSelector || target instanceof Array || (target.push && _isArray(target))) && typeof(target[0]) !== "number") {
  41896. this._targets = targets = _slice(target); //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
  41897. this._propLookup = [];
  41898. this._siblings = [];
  41899. for (i = 0; i < targets.length; i++) {
  41900. targ = targets[i];
  41901. if (!targ) {
  41902. targets.splice(i--, 1);
  41903. continue;
  41904. } else if (typeof(targ) === "string") {
  41905. targ = targets[i--] = TweenLite.selector(targ); //in case it's an array of strings
  41906. if (typeof(targ) === "string") {
  41907. targets.splice(i+1, 1); //to avoid an endless loop (can't imagine why the selector would return a string, but just in case)
  41908. }
  41909. continue;
  41910. } else if (targ.length && targ !== window && targ[0] && (targ[0] === window || (targ[0].nodeType && targ[0].style && !targ.nodeType))) { //in case the user is passing in an array of selector objects (like jQuery objects), we need to check one more level and pull things out if necessary. Also note that <select> elements pass all the criteria regarding length and the first child having style, so we must also check to ensure the target isn't an HTML node itself.
  41911. targets.splice(i--, 1);
  41912. this._targets = targets = targets.concat(_slice(targ));
  41913. continue;
  41914. }
  41915. this._siblings[i] = _register(targ, this, false);
  41916. if (overwrite === 1) if (this._siblings[i].length > 1) {
  41917. _applyOverwrite(targ, this, null, 1, this._siblings[i]);
  41918. }
  41919. }
  41920. } else {
  41921. this._propLookup = {};
  41922. this._siblings = _register(target, this, false);
  41923. if (overwrite === 1) if (this._siblings.length > 1) {
  41924. _applyOverwrite(target, this, null, 1, this._siblings);
  41925. }
  41926. }
  41927. if (this.vars.immediateRender || (duration === 0 && this._delay === 0 && this.vars.immediateRender !== false)) {
  41928. this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
  41929. this.render(Math.min(0, -this._delay)); //in case delay is negative
  41930. }
  41931. }, true),
  41932. _isSelector = function(v) {
  41933. return (v && v.length && v !== window && v[0] && (v[0] === window || (v[0].nodeType && v[0].style && !v.nodeType))); //we cannot check "nodeType" if the target is window from within an iframe, otherwise it will trigger a security error in some browsers like Firefox.
  41934. },
  41935. _autoCSS = function(vars, target) {
  41936. var css = {},
  41937. p;
  41938. for (p in vars) {
  41939. if (!_reservedProps[p] && (!(p in target) || p === "transform" || p === "x" || p === "y" || p === "width" || p === "height" || p === "className" || p === "border") && (!_plugins[p] || (_plugins[p] && _plugins[p]._autoCSS))) { //note: <img> elements contain read-only "x" and "y" properties. We should also prioritize editing css width/height rather than the element's properties.
  41940. css[p] = vars[p];
  41941. delete vars[p];
  41942. }
  41943. }
  41944. vars.css = css;
  41945. };
  41946. p = TweenLite.prototype = new Animation();
  41947. p.constructor = TweenLite;
  41948. p.kill()._gc = false;
  41949. //----TweenLite defaults, overwrite management, and root updates ----------------------------------------------------
  41950. p.ratio = 0;
  41951. p._firstPT = p._targets = p._overwrittenProps = p._startAt = null;
  41952. p._notifyPluginsOfEnabled = p._lazy = false;
  41953. TweenLite.version = "1.20.2";
  41954. TweenLite.defaultEase = p._ease = new Ease(null, null, 1, 1);
  41955. TweenLite.defaultOverwrite = "auto";
  41956. TweenLite.ticker = _ticker;
  41957. TweenLite.autoSleep = 120;
  41958. TweenLite.lagSmoothing = function(threshold, adjustedLag) {
  41959. _ticker.lagSmoothing(threshold, adjustedLag);
  41960. };
  41961. TweenLite.selector = window.$ || window.jQuery || function(e) {
  41962. var selector = window.$ || window.jQuery;
  41963. if (selector) {
  41964. TweenLite.selector = selector;
  41965. return selector(e);
  41966. }
  41967. return (typeof(_doc) === "undefined") ? e : (_doc.querySelectorAll ? _doc.querySelectorAll(e) : _doc.getElementById((e.charAt(0) === "#") ? e.substr(1) : e));
  41968. };
  41969. var _lazyTweens = [],
  41970. _lazyLookup = {},
  41971. _numbersExp = /(?:(-|-=|\+=)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig,
  41972. _relExp = /[\+-]=-?[\.\d]/,
  41973. //_nonNumbersExp = /(?:([\-+](?!(\d|=)))|[^\d\-+=e]|(e(?![\-+][\d])))+/ig,
  41974. _setRatio = function(v) {
  41975. var pt = this._firstPT,
  41976. min = 0.000001,
  41977. val;
  41978. while (pt) {
  41979. val = !pt.blob ? pt.c * v + pt.s : (v === 1 && this.end) ? this.end : v ? this.join("") : this.start;
  41980. if (pt.m) {
  41981. val = pt.m(val, this._target || pt.t);
  41982. } else if (val < min) if (val > -min && !pt.blob) { //prevents issues with converting very small numbers to strings in the browser
  41983. val = 0;
  41984. }
  41985. if (!pt.f) {
  41986. pt.t[pt.p] = val;
  41987. } else if (pt.fp) {
  41988. pt.t[pt.p](pt.fp, val);
  41989. } else {
  41990. pt.t[pt.p](val);
  41991. }
  41992. pt = pt._next;
  41993. }
  41994. },
  41995. //compares two strings (start/end), finds the numbers that are different and spits back an array representing the whole value but with the changing values isolated as elements. For example, "rgb(0,0,0)" and "rgb(100,50,0)" would become ["rgb(", 0, ",", 50, ",0)"]. Notice it merges the parts that are identical (performance optimization). The array also has a linked list of PropTweens attached starting with _firstPT that contain the tweening data (t, p, s, c, f, etc.). It also stores the starting value as a "start" property so that we can revert to it if/when necessary, like when a tween rewinds fully. If the quantity of numbers differs between the start and end, it will always prioritize the end value(s). The pt parameter is optional - it's for a PropTween that will be appended to the end of the linked list and is typically for actually setting the value after all of the elements have been updated (with array.join("")).
  41996. _blobDif = function(start, end, filter, pt) {
  41997. var a = [],
  41998. charIndex = 0,
  41999. s = "",
  42000. color = 0,
  42001. startNums, endNums, num, i, l, nonNumbers, currentNum;
  42002. a.start = start;
  42003. a.end = end;
  42004. start = a[0] = start + ""; //ensure values are strings
  42005. end = a[1] = end + "";
  42006. if (filter) {
  42007. filter(a); //pass an array with the starting and ending values and let the filter do whatever it needs to the values.
  42008. start = a[0];
  42009. end = a[1];
  42010. }
  42011. a.length = 0;
  42012. startNums = start.match(_numbersExp) || [];
  42013. endNums = end.match(_numbersExp) || [];
  42014. if (pt) {
  42015. pt._next = null;
  42016. pt.blob = 1;
  42017. a._firstPT = a._applyPT = pt; //apply last in the linked list (which means inserting it first)
  42018. }
  42019. l = endNums.length;
  42020. for (i = 0; i < l; i++) {
  42021. currentNum = endNums[i];
  42022. nonNumbers = end.substr(charIndex, end.indexOf(currentNum, charIndex)-charIndex);
  42023. s += (nonNumbers || !i) ? nonNumbers : ","; //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case.
  42024. charIndex += nonNumbers.length;
  42025. if (color) { //sense rgba() values and round them.
  42026. color = (color + 1) % 5;
  42027. } else if (nonNumbers.substr(-5) === "rgba(") {
  42028. color = 1;
  42029. }
  42030. if (currentNum === startNums[i] || startNums.length <= i) {
  42031. s += currentNum;
  42032. } else {
  42033. if (s) {
  42034. a.push(s);
  42035. s = "";
  42036. }
  42037. num = parseFloat(startNums[i]);
  42038. a.push(num);
  42039. a._firstPT = {_next: a._firstPT, t:a, p: a.length-1, s:num, c:((currentNum.charAt(1) === "=") ? parseInt(currentNum.charAt(0) + "1", 10) * parseFloat(currentNum.substr(2)) : (parseFloat(currentNum) - num)) || 0, f:0, m:(color && color < 4) ? Math.round : 0};
  42040. //note: we don't set _prev because we'll never need to remove individual PropTweens from this list.
  42041. }
  42042. charIndex += currentNum.length;
  42043. }
  42044. s += end.substr(charIndex);
  42045. if (s) {
  42046. a.push(s);
  42047. }
  42048. a.setRatio = _setRatio;
  42049. if (_relExp.test(end)) { //if the end string contains relative values, delete it so that on the final render (in _setRatio()), we don't actually set it to the string with += or -= characters (forces it to use the calculated value).
  42050. a.end = 0;
  42051. }
  42052. return a;
  42053. },
  42054. //note: "funcParam" is only necessary for function-based getters/setters that require an extra parameter like getAttribute("width") and setAttribute("width", value). In this example, funcParam would be "width". Used by AttrPlugin for example.
  42055. _addPropTween = function(target, prop, start, end, overwriteProp, mod, funcParam, stringFilter, index) {
  42056. if (typeof(end) === "function") {
  42057. end = end(index || 0, target);
  42058. }
  42059. var type = typeof(target[prop]),
  42060. getterName = (type !== "function") ? "" : ((prop.indexOf("set") || typeof(target["get" + prop.substr(3)]) !== "function") ? prop : "get" + prop.substr(3)),
  42061. s = (start !== "get") ? start : !getterName ? target[prop] : funcParam ? target[getterName](funcParam) : target[getterName](),
  42062. isRelative = (typeof(end) === "string" && end.charAt(1) === "="),
  42063. pt = {t:target, p:prop, s:s, f:(type === "function"), pg:0, n:overwriteProp || prop, m:(!mod ? 0 : (typeof(mod) === "function") ? mod : Math.round), pr:0, c:isRelative ? parseInt(end.charAt(0) + "1", 10) * parseFloat(end.substr(2)) : (parseFloat(end) - s) || 0},
  42064. blob;
  42065. if (typeof(s) !== "number" || (typeof(end) !== "number" && !isRelative)) {
  42066. if (funcParam || isNaN(s) || (!isRelative && isNaN(end)) || typeof(s) === "boolean" || typeof(end) === "boolean") {
  42067. //a blob (string that has multiple numbers in it)
  42068. pt.fp = funcParam;
  42069. blob = _blobDif(s, (isRelative ? parseFloat(pt.s) + pt.c : end), stringFilter || TweenLite.defaultStringFilter, pt);
  42070. pt = {t: blob, p: "setRatio", s: 0, c: 1, f: 2, pg: 0, n: overwriteProp || prop, pr: 0, m: 0}; //"2" indicates it's a Blob property tween. Needed for RoundPropsPlugin for example.
  42071. } else {
  42072. pt.s = parseFloat(s);
  42073. if (!isRelative) {
  42074. pt.c = (parseFloat(end) - pt.s) || 0;
  42075. }
  42076. }
  42077. }
  42078. if (pt.c) { //only add it to the linked list if there's a change.
  42079. if ((pt._next = this._firstPT)) {
  42080. pt._next._prev = pt;
  42081. }
  42082. this._firstPT = pt;
  42083. return pt;
  42084. }
  42085. },
  42086. _internals = TweenLite._internals = {isArray:_isArray, isSelector:_isSelector, lazyTweens:_lazyTweens, blobDif:_blobDif}, //gives us a way to expose certain private values to other GreenSock classes without contaminating tha main TweenLite object.
  42087. _plugins = TweenLite._plugins = {},
  42088. _tweenLookup = _internals.tweenLookup = {},
  42089. _tweenLookupNum = 0,
  42090. _reservedProps = _internals.reservedProps = {ease:1, delay:1, overwrite:1, onComplete:1, onCompleteParams:1, onCompleteScope:1, useFrames:1, runBackwards:1, startAt:1, onUpdate:1, onUpdateParams:1, onUpdateScope:1, onStart:1, onStartParams:1, onStartScope:1, onReverseComplete:1, onReverseCompleteParams:1, onReverseCompleteScope:1, onRepeat:1, onRepeatParams:1, onRepeatScope:1, easeParams:1, yoyo:1, immediateRender:1, repeat:1, repeatDelay:1, data:1, paused:1, reversed:1, autoCSS:1, lazy:1, onOverwrite:1, callbackScope:1, stringFilter:1, id:1, yoyoEase:1},
  42091. _overwriteLookup = {none:0, all:1, auto:2, concurrent:3, allOnStart:4, preexisting:5, "true":1, "false":0},
  42092. _rootFramesTimeline = Animation._rootFramesTimeline = new SimpleTimeline(),
  42093. _rootTimeline = Animation._rootTimeline = new SimpleTimeline(),
  42094. _nextGCFrame = 30,
  42095. _lazyRender = _internals.lazyRender = function() {
  42096. var i = _lazyTweens.length,
  42097. tween;
  42098. _lazyLookup = {};
  42099. while (--i > -1) {
  42100. tween = _lazyTweens[i];
  42101. if (tween && tween._lazy !== false) {
  42102. tween.render(tween._lazy[0], tween._lazy[1], true);
  42103. tween._lazy = false;
  42104. }
  42105. }
  42106. _lazyTweens.length = 0;
  42107. };
  42108. _rootTimeline._startTime = _ticker.time;
  42109. _rootFramesTimeline._startTime = _ticker.frame;
  42110. _rootTimeline._active = _rootFramesTimeline._active = true;
  42111. setTimeout(_lazyRender, 1); //on some mobile devices, there isn't a "tick" before code runs which means any lazy renders wouldn't run before the next official "tick".
  42112. Animation._updateRoot = TweenLite.render = function() {
  42113. var i, a, p;
  42114. if (_lazyTweens.length) { //if code is run outside of the requestAnimationFrame loop, there may be tweens queued AFTER the engine refreshed, so we need to ensure any pending renders occur before we refresh again.
  42115. _lazyRender();
  42116. }
  42117. _rootTimeline.render((_ticker.time - _rootTimeline._startTime) * _rootTimeline._timeScale, false, false);
  42118. _rootFramesTimeline.render((_ticker.frame - _rootFramesTimeline._startTime) * _rootFramesTimeline._timeScale, false, false);
  42119. if (_lazyTweens.length) {
  42120. _lazyRender();
  42121. }
  42122. if (_ticker.frame >= _nextGCFrame) { //dump garbage every 120 frames or whatever the user sets TweenLite.autoSleep to
  42123. _nextGCFrame = _ticker.frame + (parseInt(TweenLite.autoSleep, 10) || 120);
  42124. for (p in _tweenLookup) {
  42125. a = _tweenLookup[p].tweens;
  42126. i = a.length;
  42127. while (--i > -1) {
  42128. if (a[i]._gc) {
  42129. a.splice(i, 1);
  42130. }
  42131. }
  42132. if (a.length === 0) {
  42133. delete _tweenLookup[p];
  42134. }
  42135. }
  42136. //if there are no more tweens in the root timelines, or if they're all paused, make the _timer sleep to reduce load on the CPU slightly
  42137. p = _rootTimeline._first;
  42138. if (!p || p._paused) if (TweenLite.autoSleep && !_rootFramesTimeline._first && _ticker._listeners.tick.length === 1) {
  42139. while (p && p._paused) {
  42140. p = p._next;
  42141. }
  42142. if (!p) {
  42143. _ticker.sleep();
  42144. }
  42145. }
  42146. }
  42147. };
  42148. _ticker.addEventListener("tick", Animation._updateRoot);
  42149. var _register = function(target, tween, scrub) {
  42150. var id = target._gsTweenID, a, i;
  42151. if (!_tweenLookup[id || (target._gsTweenID = id = "t" + (_tweenLookupNum++))]) {
  42152. _tweenLookup[id] = {target:target, tweens:[]};
  42153. }
  42154. if (tween) {
  42155. a = _tweenLookup[id].tweens;
  42156. a[(i = a.length)] = tween;
  42157. if (scrub) {
  42158. while (--i > -1) {
  42159. if (a[i] === tween) {
  42160. a.splice(i, 1);
  42161. }
  42162. }
  42163. }
  42164. }
  42165. return _tweenLookup[id].tweens;
  42166. },
  42167. _onOverwrite = function(overwrittenTween, overwritingTween, target, killedProps) {
  42168. var func = overwrittenTween.vars.onOverwrite, r1, r2;
  42169. if (func) {
  42170. r1 = func(overwrittenTween, overwritingTween, target, killedProps);
  42171. }
  42172. func = TweenLite.onOverwrite;
  42173. if (func) {
  42174. r2 = func(overwrittenTween, overwritingTween, target, killedProps);
  42175. }
  42176. return (r1 !== false && r2 !== false);
  42177. },
  42178. _applyOverwrite = function(target, tween, props, mode, siblings) {
  42179. var i, changed, curTween, l;
  42180. if (mode === 1 || mode >= 4) {
  42181. l = siblings.length;
  42182. for (i = 0; i < l; i++) {
  42183. if ((curTween = siblings[i]) !== tween) {
  42184. if (!curTween._gc) {
  42185. if (curTween._kill(null, target, tween)) {
  42186. changed = true;
  42187. }
  42188. }
  42189. } else if (mode === 5) {
  42190. break;
  42191. }
  42192. }
  42193. return changed;
  42194. }
  42195. //NOTE: Add 0.0000000001 to overcome floating point errors that can cause the startTime to be VERY slightly off (when a tween's time() is set for example)
  42196. var startTime = tween._startTime + _tinyNum,
  42197. overlaps = [],
  42198. oCount = 0,
  42199. zeroDur = (tween._duration === 0),
  42200. globalStart;
  42201. i = siblings.length;
  42202. while (--i > -1) {
  42203. if ((curTween = siblings[i]) === tween || curTween._gc || curTween._paused) {
  42204. //ignore
  42205. } else if (curTween._timeline !== tween._timeline) {
  42206. globalStart = globalStart || _checkOverlap(tween, 0, zeroDur);
  42207. if (_checkOverlap(curTween, globalStart, zeroDur) === 0) {
  42208. overlaps[oCount++] = curTween;
  42209. }
  42210. } else if (curTween._startTime <= startTime) if (curTween._startTime + curTween.totalDuration() / curTween._timeScale > startTime) if (!((zeroDur || !curTween._initted) && startTime - curTween._startTime <= 0.0000000002)) {
  42211. overlaps[oCount++] = curTween;
  42212. }
  42213. }
  42214. i = oCount;
  42215. while (--i > -1) {
  42216. curTween = overlaps[i];
  42217. if (mode === 2) if (curTween._kill(props, target, tween)) {
  42218. changed = true;
  42219. }
  42220. if (mode !== 2 || (!curTween._firstPT && curTween._initted)) {
  42221. if (mode !== 2 && !_onOverwrite(curTween, tween)) {
  42222. continue;
  42223. }
  42224. if (curTween._enabled(false, false)) { //if all property tweens have been overwritten, kill the tween.
  42225. changed = true;
  42226. }
  42227. }
  42228. }
  42229. return changed;
  42230. },
  42231. _checkOverlap = function(tween, reference, zeroDur) {
  42232. var tl = tween._timeline,
  42233. ts = tl._timeScale,
  42234. t = tween._startTime;
  42235. while (tl._timeline) {
  42236. t += tl._startTime;
  42237. ts *= tl._timeScale;
  42238. if (tl._paused) {
  42239. return -100;
  42240. }
  42241. tl = tl._timeline;
  42242. }
  42243. t /= ts;
  42244. return (t > reference) ? t - reference : ((zeroDur && t === reference) || (!tween._initted && t - reference < 2 * _tinyNum)) ? _tinyNum : ((t += tween.totalDuration() / tween._timeScale / ts) > reference + _tinyNum) ? 0 : t - reference - _tinyNum;
  42245. };
  42246. //---- TweenLite instance methods -----------------------------------------------------------------------------
  42247. p._init = function() {
  42248. var v = this.vars,
  42249. op = this._overwrittenProps,
  42250. dur = this._duration,
  42251. immediate = !!v.immediateRender,
  42252. ease = v.ease,
  42253. i, initPlugins, pt, p, startVars, l;
  42254. if (v.startAt) {
  42255. if (this._startAt) {
  42256. this._startAt.render(-1, true); //if we've run a startAt previously (when the tween instantiated), we should revert it so that the values re-instantiate correctly particularly for relative tweens. Without this, a TweenLite.fromTo(obj, 1, {x:"+=100"}, {x:"-=100"}), for example, would actually jump to +=200 because the startAt would run twice, doubling the relative change.
  42257. this._startAt.kill();
  42258. }
  42259. startVars = {};
  42260. for (p in v.startAt) { //copy the properties/values into a new object to avoid collisions, like var to = {x:0}, from = {x:500}; timeline.fromTo(e, 1, from, to).fromTo(e, 1, to, from);
  42261. startVars[p] = v.startAt[p];
  42262. }
  42263. startVars.overwrite = false;
  42264. startVars.immediateRender = true;
  42265. startVars.lazy = (immediate && v.lazy !== false);
  42266. startVars.startAt = startVars.delay = null; //no nesting of startAt objects allowed (otherwise it could cause an infinite loop).
  42267. startVars.onUpdate = v.onUpdate;
  42268. startVars.onUpdateScope = v.onUpdateScope || v.callbackScope || this;
  42269. this._startAt = TweenLite.to(this.target, 0, startVars);
  42270. if (immediate) {
  42271. if (this._time > 0) {
  42272. this._startAt = null; //tweens that render immediately (like most from() and fromTo() tweens) shouldn't revert when their parent timeline's playhead goes backward past the startTime because the initial render could have happened anytime and it shouldn't be directly correlated to this tween's startTime. Imagine setting up a complex animation where the beginning states of various objects are rendered immediately but the tween doesn't happen for quite some time - if we revert to the starting values as soon as the playhead goes backward past the tween's startTime, it will throw things off visually. Reversion should only happen in TimelineLite/Max instances where immediateRender was false (which is the default in the convenience methods like from()).
  42273. } else if (dur !== 0) {
  42274. return; //we skip initialization here so that overwriting doesn't occur until the tween actually begins. Otherwise, if you create several immediateRender:true tweens of the same target/properties to drop into a TimelineLite or TimelineMax, the last one created would overwrite the first ones because they didn't get placed into the timeline yet before the first render occurs and kicks in overwriting.
  42275. }
  42276. }
  42277. } else if (v.runBackwards && dur !== 0) {
  42278. //from() tweens must be handled uniquely: their beginning values must be rendered but we don't want overwriting to occur yet (when time is still 0). Wait until the tween actually begins before doing all the routines like overwriting. At that time, we should render at the END of the tween to ensure that things initialize correctly (remember, from() tweens go backwards)
  42279. if (this._startAt) {
  42280. this._startAt.render(-1, true);
  42281. this._startAt.kill();
  42282. this._startAt = null;
  42283. } else {
  42284. if (this._time !== 0) { //in rare cases (like if a from() tween runs and then is invalidate()-ed), immediateRender could be true but the initial forced-render gets skipped, so there's no need to force the render in this context when the _time is greater than 0
  42285. immediate = false;
  42286. }
  42287. pt = {};
  42288. for (p in v) { //copy props into a new object and skip any reserved props, otherwise onComplete or onUpdate or onStart could fire. We should, however, permit autoCSS to go through.
  42289. if (!_reservedProps[p] || p === "autoCSS") {
  42290. pt[p] = v[p];
  42291. }
  42292. }
  42293. pt.overwrite = 0;
  42294. pt.data = "isFromStart"; //we tag the tween with as "isFromStart" so that if [inside a plugin] we need to only do something at the very END of a tween, we have a way of identifying this tween as merely the one that's setting the beginning values for a "from()" tween. For example, clearProps in CSSPlugin should only get applied at the very END of a tween and without this tag, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in.
  42295. pt.lazy = (immediate && v.lazy !== false);
  42296. pt.immediateRender = immediate; //zero-duration tweens render immediately by default, but if we're not specifically instructed to render this tween immediately, we should skip this and merely _init() to record the starting values (rendering them immediately would push them to completion which is wasteful in that case - we'd have to render(-1) immediately after)
  42297. this._startAt = TweenLite.to(this.target, 0, pt);
  42298. if (!immediate) {
  42299. this._startAt._init(); //ensures that the initial values are recorded
  42300. this._startAt._enabled(false); //no need to have the tween render on the next cycle. Disable it because we'll always manually control the renders of the _startAt tween.
  42301. if (this.vars.immediateRender) {
  42302. this._startAt = null;
  42303. }
  42304. } else if (this._time === 0) {
  42305. return;
  42306. }
  42307. }
  42308. }
  42309. this._ease = ease = (!ease) ? TweenLite.defaultEase : (ease instanceof Ease) ? ease : (typeof(ease) === "function") ? new Ease(ease, v.easeParams) : _easeMap[ease] || TweenLite.defaultEase;
  42310. if (v.easeParams instanceof Array && ease.config) {
  42311. this._ease = ease.config.apply(ease, v.easeParams);
  42312. }
  42313. this._easeType = this._ease._type;
  42314. this._easePower = this._ease._power;
  42315. this._firstPT = null;
  42316. if (this._targets) {
  42317. l = this._targets.length;
  42318. for (i = 0; i < l; i++) {
  42319. if ( this._initProps( this._targets[i], (this._propLookup[i] = {}), this._siblings[i], (op ? op[i] : null), i) ) {
  42320. initPlugins = true;
  42321. }
  42322. }
  42323. } else {
  42324. initPlugins = this._initProps(this.target, this._propLookup, this._siblings, op, 0);
  42325. }
  42326. if (initPlugins) {
  42327. TweenLite._onPluginEvent("_onInitAllProps", this); //reorders the array in order of priority. Uses a static TweenPlugin method in order to minimize file size in TweenLite
  42328. }
  42329. if (op) if (!this._firstPT) if (typeof(this.target) !== "function") { //if all tweening properties have been overwritten, kill the tween. If the target is a function, it's probably a delayedCall so let it live.
  42330. this._enabled(false, false);
  42331. }
  42332. if (v.runBackwards) {
  42333. pt = this._firstPT;
  42334. while (pt) {
  42335. pt.s += pt.c;
  42336. pt.c = -pt.c;
  42337. pt = pt._next;
  42338. }
  42339. }
  42340. this._onUpdate = v.onUpdate;
  42341. this._initted = true;
  42342. };
  42343. p._initProps = function(target, propLookup, siblings, overwrittenProps, index) {
  42344. var p, i, initPlugins, plugin, pt, v;
  42345. if (target == null) {
  42346. return false;
  42347. }
  42348. if (_lazyLookup[target._gsTweenID]) {
  42349. _lazyRender(); //if other tweens of the same target have recently initted but haven't rendered yet, we've got to force the render so that the starting values are correct (imagine populating a timeline with a bunch of sequential tweens and then jumping to the end)
  42350. }
  42351. if (!this.vars.css) if (target.style) if (target !== window && target.nodeType) if (_plugins.css) if (this.vars.autoCSS !== false) { //it's so common to use TweenLite/Max to animate the css of DOM elements, we assume that if the target is a DOM element, that's what is intended (a convenience so that users don't have to wrap things in css:{}, although we still recommend it for a slight performance boost and better specificity). Note: we cannot check "nodeType" on the window inside an iframe.
  42352. _autoCSS(this.vars, target);
  42353. }
  42354. for (p in this.vars) {
  42355. v = this.vars[p];
  42356. if (_reservedProps[p]) {
  42357. if (v) if ((v instanceof Array) || (v.push && _isArray(v))) if (v.join("").indexOf("{self}") !== -1) {
  42358. this.vars[p] = v = this._swapSelfInParams(v, this);
  42359. }
  42360. } else if (_plugins[p] && (plugin = new _plugins[p]())._onInitTween(target, this.vars[p], this, index)) {
  42361. //t - target [object]
  42362. //p - property [string]
  42363. //s - start [number]
  42364. //c - change [number]
  42365. //f - isFunction [boolean]
  42366. //n - name [string]
  42367. //pg - isPlugin [boolean]
  42368. //pr - priority [number]
  42369. //m - mod [function | 0]
  42370. this._firstPT = pt = {_next:this._firstPT, t:plugin, p:"setRatio", s:0, c:1, f:1, n:p, pg:1, pr:plugin._priority, m:0};
  42371. i = plugin._overwriteProps.length;
  42372. while (--i > -1) {
  42373. propLookup[plugin._overwriteProps[i]] = this._firstPT;
  42374. }
  42375. if (plugin._priority || plugin._onInitAllProps) {
  42376. initPlugins = true;
  42377. }
  42378. if (plugin._onDisable || plugin._onEnable) {
  42379. this._notifyPluginsOfEnabled = true;
  42380. }
  42381. if (pt._next) {
  42382. pt._next._prev = pt;
  42383. }
  42384. } else {
  42385. propLookup[p] = _addPropTween.call(this, target, p, "get", v, p, 0, null, this.vars.stringFilter, index);
  42386. }
  42387. }
  42388. if (overwrittenProps) if (this._kill(overwrittenProps, target)) { //another tween may have tried to overwrite properties of this tween before init() was called (like if two tweens start at the same time, the one created second will run first)
  42389. return this._initProps(target, propLookup, siblings, overwrittenProps, index);
  42390. }
  42391. if (this._overwrite > 1) if (this._firstPT) if (siblings.length > 1) if (_applyOverwrite(target, this, propLookup, this._overwrite, siblings)) {
  42392. this._kill(propLookup, target);
  42393. return this._initProps(target, propLookup, siblings, overwrittenProps, index);
  42394. }
  42395. if (this._firstPT) if ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration)) { //zero duration tweens don't lazy render by default; everything else does.
  42396. _lazyLookup[target._gsTweenID] = true;
  42397. }
  42398. return initPlugins;
  42399. };
  42400. p.render = function(time, suppressEvents, force) {
  42401. var prevTime = this._time,
  42402. duration = this._duration,
  42403. prevRawPrevTime = this._rawPrevTime,
  42404. isComplete, callback, pt, rawPrevTime;
  42405. if (time >= duration - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts.
  42406. this._totalTime = this._time = duration;
  42407. this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1;
  42408. if (!this._reversed ) {
  42409. isComplete = true;
  42410. callback = "onComplete";
  42411. force = (force || this._timeline.autoRemoveChildren); //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
  42412. }
  42413. if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
  42414. if (this._startTime === this._timeline._duration) { //if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate.
  42415. time = 0;
  42416. }
  42417. if (prevRawPrevTime < 0 || (time <= 0 && time >= -0.0000001) || (prevRawPrevTime === _tinyNum && this.data !== "isPause")) if (prevRawPrevTime !== time) { //note: when this.data is "isPause", it's a callback added by addPause() on a timeline that we should not be triggered when LEAVING its exact start time. In other words, tl.addPause(1).play(1) shouldn't pause.
  42418. force = true;
  42419. if (prevRawPrevTime > _tinyNum) {
  42420. callback = "onReverseComplete";
  42421. }
  42422. }
  42423. this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  42424. }
  42425. } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
  42426. this._totalTime = this._time = 0;
  42427. this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
  42428. if (prevTime !== 0 || (duration === 0 && prevRawPrevTime > 0)) {
  42429. callback = "onReverseComplete";
  42430. isComplete = this._reversed;
  42431. }
  42432. if (time < 0) {
  42433. this._active = false;
  42434. if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
  42435. if (prevRawPrevTime >= 0 && !(prevRawPrevTime === _tinyNum && this.data === "isPause")) {
  42436. force = true;
  42437. }
  42438. this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  42439. }
  42440. }
  42441. if (!this._initted || (this._startAt && this._startAt.progress())) { //if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately. Also, we check progress() because if startAt has already rendered at its end, we should force a render at its beginning. Otherwise, if you put the playhead directly on top of where a fromTo({immediateRender:false}) starts, and then move it backwards, the from() won't revert its values.
  42442. force = true;
  42443. }
  42444. } else {
  42445. this._totalTime = this._time = time;
  42446. if (this._easeType) {
  42447. var r = time / duration, type = this._easeType, pow = this._easePower;
  42448. if (type === 1 || (type === 3 && r >= 0.5)) {
  42449. r = 1 - r;
  42450. }
  42451. if (type === 3) {
  42452. r *= 2;
  42453. }
  42454. if (pow === 1) {
  42455. r *= r;
  42456. } else if (pow === 2) {
  42457. r *= r * r;
  42458. } else if (pow === 3) {
  42459. r *= r * r * r;
  42460. } else if (pow === 4) {
  42461. r *= r * r * r * r;
  42462. }
  42463. if (type === 1) {
  42464. this.ratio = 1 - r;
  42465. } else if (type === 2) {
  42466. this.ratio = r;
  42467. } else if (time / duration < 0.5) {
  42468. this.ratio = r / 2;
  42469. } else {
  42470. this.ratio = 1 - (r / 2);
  42471. }
  42472. } else {
  42473. this.ratio = this._ease.getRatio(time / duration);
  42474. }
  42475. }
  42476. if (this._time === prevTime && !force) {
  42477. return;
  42478. } else if (!this._initted) {
  42479. this._init();
  42480. if (!this._initted || this._gc) { //immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example.
  42481. return;
  42482. } else if (!force && this._firstPT && ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration))) {
  42483. this._time = this._totalTime = prevTime;
  42484. this._rawPrevTime = prevRawPrevTime;
  42485. _lazyTweens.push(this);
  42486. this._lazy = [time, suppressEvents];
  42487. return;
  42488. }
  42489. //_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently.
  42490. if (this._time && !isComplete) {
  42491. this.ratio = this._ease.getRatio(this._time / duration);
  42492. } else if (isComplete && this._ease._calcEnd) {
  42493. this.ratio = this._ease.getRatio((this._time === 0) ? 0 : 1);
  42494. }
  42495. }
  42496. if (this._lazy !== false) { //in case a lazy render is pending, we should flush it because the new render is occurring now (imagine a lazy tween instantiating and then immediately the user calls tween.seek(tween.duration()), skipping to the end - the end render would be forced, and then if we didn't flush the lazy render, it'd fire AFTER the seek(), rendering it at the wrong time.
  42497. this._lazy = false;
  42498. }
  42499. if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) {
  42500. this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
  42501. }
  42502. if (prevTime === 0) {
  42503. if (this._startAt) {
  42504. if (time >= 0) {
  42505. this._startAt.render(time, suppressEvents, force);
  42506. } else if (!callback) {
  42507. callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area.
  42508. }
  42509. }
  42510. if (this.vars.onStart) if (this._time !== 0 || duration === 0) if (!suppressEvents) {
  42511. this._callback("onStart");
  42512. }
  42513. }
  42514. pt = this._firstPT;
  42515. while (pt) {
  42516. if (pt.f) {
  42517. pt.t[pt.p](pt.c * this.ratio + pt.s);
  42518. } else {
  42519. pt.t[pt.p] = pt.c * this.ratio + pt.s;
  42520. }
  42521. pt = pt._next;
  42522. }
  42523. if (this._onUpdate) {
  42524. if (time < 0) if (this._startAt && time !== -0.0001) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
  42525. this._startAt.render(time, suppressEvents, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.
  42526. }
  42527. if (!suppressEvents) if (this._time !== prevTime || isComplete || force) {
  42528. this._callback("onUpdate");
  42529. }
  42530. }
  42531. if (callback) if (!this._gc || force) { //check _gc because there's a chance that kill() could be called in an onUpdate
  42532. if (time < 0 && this._startAt && !this._onUpdate && time !== -0.0001) { //-0.0001 is a special value that we use when looping back to the beginning of a repeated TimelineMax, in which case we shouldn't render the _startAt values.
  42533. this._startAt.render(time, suppressEvents, force);
  42534. }
  42535. if (isComplete) {
  42536. if (this._timeline.autoRemoveChildren) {
  42537. this._enabled(false, false);
  42538. }
  42539. this._active = false;
  42540. }
  42541. if (!suppressEvents && this.vars[callback]) {
  42542. this._callback(callback);
  42543. }
  42544. if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) { //the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless.
  42545. this._rawPrevTime = 0;
  42546. }
  42547. }
  42548. };
  42549. p._kill = function(vars, target, overwritingTween) {
  42550. if (vars === "all") {
  42551. vars = null;
  42552. }
  42553. if (vars == null) if (target == null || target === this.target) {
  42554. this._lazy = false;
  42555. return this._enabled(false, false);
  42556. }
  42557. target = (typeof(target) !== "string") ? (target || this._targets || this.target) : TweenLite.selector(target) || target;
  42558. var simultaneousOverwrite = (overwritingTween && this._time && overwritingTween._startTime === this._startTime && this._timeline === overwritingTween._timeline),
  42559. i, overwrittenProps, p, pt, propLookup, changed, killProps, record, killed;
  42560. if ((_isArray(target) || _isSelector(target)) && typeof(target[0]) !== "number") {
  42561. i = target.length;
  42562. while (--i > -1) {
  42563. if (this._kill(vars, target[i], overwritingTween)) {
  42564. changed = true;
  42565. }
  42566. }
  42567. } else {
  42568. if (this._targets) {
  42569. i = this._targets.length;
  42570. while (--i > -1) {
  42571. if (target === this._targets[i]) {
  42572. propLookup = this._propLookup[i] || {};
  42573. this._overwrittenProps = this._overwrittenProps || [];
  42574. overwrittenProps = this._overwrittenProps[i] = vars ? this._overwrittenProps[i] || {} : "all";
  42575. break;
  42576. }
  42577. }
  42578. } else if (target !== this.target) {
  42579. return false;
  42580. } else {
  42581. propLookup = this._propLookup;
  42582. overwrittenProps = this._overwrittenProps = vars ? this._overwrittenProps || {} : "all";
  42583. }
  42584. if (propLookup) {
  42585. killProps = vars || propLookup;
  42586. record = (vars !== overwrittenProps && overwrittenProps !== "all" && vars !== propLookup && (typeof(vars) !== "object" || !vars._tempKill)); //_tempKill is a super-secret way to delete a particular tweening property but NOT have it remembered as an official overwritten property (like in BezierPlugin)
  42587. if (overwritingTween && (TweenLite.onOverwrite || this.vars.onOverwrite)) {
  42588. for (p in killProps) {
  42589. if (propLookup[p]) {
  42590. if (!killed) {
  42591. killed = [];
  42592. }
  42593. killed.push(p);
  42594. }
  42595. }
  42596. if ((killed || !vars) && !_onOverwrite(this, overwritingTween, target, killed)) { //if the onOverwrite returned false, that means the user wants to override the overwriting (cancel it).
  42597. return false;
  42598. }
  42599. }
  42600. for (p in killProps) {
  42601. if ((pt = propLookup[p])) {
  42602. if (simultaneousOverwrite) { //if another tween overwrites this one and they both start at exactly the same time, yet this tween has already rendered once (for example, at 0.001) because it's first in the queue, we should revert the values to where they were at 0 so that the starting values aren't contaminated on the overwriting tween.
  42603. if (pt.f) {
  42604. pt.t[pt.p](pt.s);
  42605. } else {
  42606. pt.t[pt.p] = pt.s;
  42607. }
  42608. changed = true;
  42609. }
  42610. if (pt.pg && pt.t._kill(killProps)) {
  42611. changed = true; //some plugins need to be notified so they can perform cleanup tasks first
  42612. }
  42613. if (!pt.pg || pt.t._overwriteProps.length === 0) {
  42614. if (pt._prev) {
  42615. pt._prev._next = pt._next;
  42616. } else if (pt === this._firstPT) {
  42617. this._firstPT = pt._next;
  42618. }
  42619. if (pt._next) {
  42620. pt._next._prev = pt._prev;
  42621. }
  42622. pt._next = pt._prev = null;
  42623. }
  42624. delete propLookup[p];
  42625. }
  42626. if (record) {
  42627. overwrittenProps[p] = 1;
  42628. }
  42629. }
  42630. if (!this._firstPT && this._initted) { //if all tweening properties are killed, kill the tween. Without this line, if there's a tween with multiple targets and then you killTweensOf() each target individually, the tween would technically still remain active and fire its onComplete even though there aren't any more properties tweening.
  42631. this._enabled(false, false);
  42632. }
  42633. }
  42634. }
  42635. return changed;
  42636. };
  42637. p.invalidate = function() {
  42638. if (this._notifyPluginsOfEnabled) {
  42639. TweenLite._onPluginEvent("_onDisable", this);
  42640. }
  42641. this._firstPT = this._overwrittenProps = this._startAt = this._onUpdate = null;
  42642. this._notifyPluginsOfEnabled = this._active = this._lazy = false;
  42643. this._propLookup = (this._targets) ? {} : [];
  42644. Animation.prototype.invalidate.call(this);
  42645. if (this.vars.immediateRender) {
  42646. this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
  42647. this.render(Math.min(0, -this._delay)); //in case delay is negative.
  42648. }
  42649. return this;
  42650. };
  42651. p._enabled = function(enabled, ignoreTimeline) {
  42652. if (!_tickerActive) {
  42653. _ticker.wake();
  42654. }
  42655. if (enabled && this._gc) {
  42656. var targets = this._targets,
  42657. i;
  42658. if (targets) {
  42659. i = targets.length;
  42660. while (--i > -1) {
  42661. this._siblings[i] = _register(targets[i], this, true);
  42662. }
  42663. } else {
  42664. this._siblings = _register(this.target, this, true);
  42665. }
  42666. }
  42667. Animation.prototype._enabled.call(this, enabled, ignoreTimeline);
  42668. if (this._notifyPluginsOfEnabled) if (this._firstPT) {
  42669. return TweenLite._onPluginEvent((enabled ? "_onEnable" : "_onDisable"), this);
  42670. }
  42671. return false;
  42672. };
  42673. //----TweenLite static methods -----------------------------------------------------
  42674. TweenLite.to = function(target, duration, vars) {
  42675. return new TweenLite(target, duration, vars);
  42676. };
  42677. TweenLite.from = function(target, duration, vars) {
  42678. vars.runBackwards = true;
  42679. vars.immediateRender = (vars.immediateRender != false);
  42680. return new TweenLite(target, duration, vars);
  42681. };
  42682. TweenLite.fromTo = function(target, duration, fromVars, toVars) {
  42683. toVars.startAt = fromVars;
  42684. toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
  42685. return new TweenLite(target, duration, toVars);
  42686. };
  42687. TweenLite.delayedCall = function(delay, callback, params, scope, useFrames) {
  42688. return new TweenLite(callback, 0, {delay:delay, onComplete:callback, onCompleteParams:params, callbackScope:scope, onReverseComplete:callback, onReverseCompleteParams:params, immediateRender:false, lazy:false, useFrames:useFrames, overwrite:0});
  42689. };
  42690. TweenLite.set = function(target, vars) {
  42691. return new TweenLite(target, 0, vars);
  42692. };
  42693. TweenLite.getTweensOf = function(target, onlyActive) {
  42694. if (target == null) { return []; }
  42695. target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target;
  42696. var i, a, j, t;
  42697. if ((_isArray(target) || _isSelector(target)) && typeof(target[0]) !== "number") {
  42698. i = target.length;
  42699. a = [];
  42700. while (--i > -1) {
  42701. a = a.concat(TweenLite.getTweensOf(target[i], onlyActive));
  42702. }
  42703. i = a.length;
  42704. //now get rid of any duplicates (tweens of arrays of objects could cause duplicates)
  42705. while (--i > -1) {
  42706. t = a[i];
  42707. j = i;
  42708. while (--j > -1) {
  42709. if (t === a[j]) {
  42710. a.splice(i, 1);
  42711. }
  42712. }
  42713. }
  42714. } else if (target._gsTweenID) {
  42715. a = _register(target).concat();
  42716. i = a.length;
  42717. while (--i > -1) {
  42718. if (a[i]._gc || (onlyActive && !a[i].isActive())) {
  42719. a.splice(i, 1);
  42720. }
  42721. }
  42722. }
  42723. return a || [];
  42724. };
  42725. TweenLite.killTweensOf = TweenLite.killDelayedCallsTo = function(target, onlyActive, vars) {
  42726. if (typeof(onlyActive) === "object") {
  42727. vars = onlyActive; //for backwards compatibility (before "onlyActive" parameter was inserted)
  42728. onlyActive = false;
  42729. }
  42730. var a = TweenLite.getTweensOf(target, onlyActive),
  42731. i = a.length;
  42732. while (--i > -1) {
  42733. a[i]._kill(vars, target);
  42734. }
  42735. };
  42736. /*
  42737. * ----------------------------------------------------------------
  42738. * TweenPlugin (could easily be split out as a separate file/class, but included for ease of use (so that people don't need to include another script call before loading plugins which is easy to forget)
  42739. * ----------------------------------------------------------------
  42740. */
  42741. var TweenPlugin = _class("plugins.TweenPlugin", function(props, priority) {
  42742. this._overwriteProps = (props || "").split(",");
  42743. this._propName = this._overwriteProps[0];
  42744. this._priority = priority || 0;
  42745. this._super = TweenPlugin.prototype;
  42746. }, true);
  42747. p = TweenPlugin.prototype;
  42748. TweenPlugin.version = "1.19.0";
  42749. TweenPlugin.API = 2;
  42750. p._firstPT = null;
  42751. p._addTween = _addPropTween;
  42752. p.setRatio = _setRatio;
  42753. p._kill = function(lookup) {
  42754. var a = this._overwriteProps,
  42755. pt = this._firstPT,
  42756. i;
  42757. if (lookup[this._propName] != null) {
  42758. this._overwriteProps = [];
  42759. } else {
  42760. i = a.length;
  42761. while (--i > -1) {
  42762. if (lookup[a[i]] != null) {
  42763. a.splice(i, 1);
  42764. }
  42765. }
  42766. }
  42767. while (pt) {
  42768. if (lookup[pt.n] != null) {
  42769. if (pt._next) {
  42770. pt._next._prev = pt._prev;
  42771. }
  42772. if (pt._prev) {
  42773. pt._prev._next = pt._next;
  42774. pt._prev = null;
  42775. } else if (this._firstPT === pt) {
  42776. this._firstPT = pt._next;
  42777. }
  42778. }
  42779. pt = pt._next;
  42780. }
  42781. return false;
  42782. };
  42783. p._mod = p._roundProps = function(lookup) {
  42784. var pt = this._firstPT,
  42785. val;
  42786. while (pt) {
  42787. val = lookup[this._propName] || (pt.n != null && lookup[ pt.n.split(this._propName + "_").join("") ]);
  42788. if (val && typeof(val) === "function") { //some properties that are very plugin-specific add a prefix named after the _propName plus an underscore, so we need to ignore that extra stuff here.
  42789. if (pt.f === 2) {
  42790. pt.t._applyPT.m = val;
  42791. } else {
  42792. pt.m = val;
  42793. }
  42794. }
  42795. pt = pt._next;
  42796. }
  42797. };
  42798. TweenLite._onPluginEvent = function(type, tween) {
  42799. var pt = tween._firstPT,
  42800. changed, pt2, first, last, next;
  42801. if (type === "_onInitAllProps") {
  42802. //sorts the PropTween linked list in order of priority because some plugins need to render earlier/later than others, like MotionBlurPlugin applies its effects after all x/y/alpha tweens have rendered on each frame.
  42803. while (pt) {
  42804. next = pt._next;
  42805. pt2 = first;
  42806. while (pt2 && pt2.pr > pt.pr) {
  42807. pt2 = pt2._next;
  42808. }
  42809. if ((pt._prev = pt2 ? pt2._prev : last)) {
  42810. pt._prev._next = pt;
  42811. } else {
  42812. first = pt;
  42813. }
  42814. if ((pt._next = pt2)) {
  42815. pt2._prev = pt;
  42816. } else {
  42817. last = pt;
  42818. }
  42819. pt = next;
  42820. }
  42821. pt = tween._firstPT = first;
  42822. }
  42823. while (pt) {
  42824. if (pt.pg) if (typeof(pt.t[type]) === "function") if (pt.t[type]()) {
  42825. changed = true;
  42826. }
  42827. pt = pt._next;
  42828. }
  42829. return changed;
  42830. };
  42831. TweenPlugin.activate = function(plugins) {
  42832. var i = plugins.length;
  42833. while (--i > -1) {
  42834. if (plugins[i].API === TweenPlugin.API) {
  42835. _plugins[(new plugins[i]())._propName] = plugins[i];
  42836. }
  42837. }
  42838. return true;
  42839. };
  42840. //provides a more concise way to define plugins that have no dependencies besides TweenPlugin and TweenLite, wrapping common boilerplate stuff into one function (added in 1.9.0). You don't NEED to use this to define a plugin - the old way still works and can be useful in certain (rare) situations.
  42841. _gsDefine.plugin = function(config) {
  42842. if (!config || !config.propName || !config.init || !config.API) { throw "illegal plugin definition."; }
  42843. var propName = config.propName,
  42844. priority = config.priority || 0,
  42845. overwriteProps = config.overwriteProps,
  42846. map = {init:"_onInitTween", set:"setRatio", kill:"_kill", round:"_mod", mod:"_mod", initAll:"_onInitAllProps"},
  42847. Plugin = _class("plugins." + propName.charAt(0).toUpperCase() + propName.substr(1) + "Plugin",
  42848. function() {
  42849. TweenPlugin.call(this, propName, priority);
  42850. this._overwriteProps = overwriteProps || [];
  42851. }, (config.global === true)),
  42852. p = Plugin.prototype = new TweenPlugin(propName),
  42853. prop;
  42854. p.constructor = Plugin;
  42855. Plugin.API = config.API;
  42856. for (prop in map) {
  42857. if (typeof(config[prop]) === "function") {
  42858. p[map[prop]] = config[prop];
  42859. }
  42860. }
  42861. Plugin.version = config.version;
  42862. TweenPlugin.activate([Plugin]);
  42863. return Plugin;
  42864. };
  42865. //now run through all the dependencies discovered and if any are missing, log that to the console as a warning. This is why it's best to have TweenLite load last - it can check all the dependencies for you.
  42866. a = window._gsQueue;
  42867. if (a) {
  42868. for (i = 0; i < a.length; i++) {
  42869. a[i]();
  42870. }
  42871. for (p in _defLookup) {
  42872. if (!_defLookup[p].func) {
  42873. window.console.log("GSAP encountered missing dependency: " + p);
  42874. }
  42875. }
  42876. }
  42877. _tickerActive = false; //ensures that the first official animation forces a ticker.tick() to update the time when it is instantiated
  42878. })((typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window, "TweenLite");
  42879. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  42880. },{}],212:[function(require,module,exports){
  42881. (function (global){
  42882. /*!
  42883. * VERSION: 1.20.2
  42884. * DATE: 2017-06-30
  42885. * UPDATES AND DOCS AT: http://greensock.com
  42886. *
  42887. * Includes all of the following: TweenLite, TweenMax, TimelineLite, TimelineMax, EasePack, CSSPlugin, RoundPropsPlugin, BezierPlugin, AttrPlugin, DirectionalRotationPlugin
  42888. *
  42889. * @license Copyright (c) 2008-2017, GreenSock. All rights reserved.
  42890. * This work is subject to the terms at http://greensock.com/standard-license or for
  42891. * Club GreenSock members, the software agreement that was issued with your membership.
  42892. *
  42893. * @author: Jack Doyle, jack@greensock.com
  42894. **/
  42895. var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node
  42896. (_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() {
  42897. "use strict";
  42898. _gsScope._gsDefine("TweenMax", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) {
  42899. var _slice = function(a) { //don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
  42900. var b = [],
  42901. l = a.length,
  42902. i;
  42903. for (i = 0; i !== l; b.push(a[i++]));
  42904. return b;
  42905. },
  42906. _applyCycle = function(vars, targets, i) {
  42907. var alt = vars.cycle,
  42908. p, val;
  42909. for (p in alt) {
  42910. val = alt[p];
  42911. vars[p] = (typeof(val) === "function") ? val(i, targets[i]) : val[i % val.length];
  42912. }
  42913. delete vars.cycle;
  42914. },
  42915. TweenMax = function(target, duration, vars) {
  42916. TweenLite.call(this, target, duration, vars);
  42917. this._cycle = 0;
  42918. this._yoyo = (this.vars.yoyo === true || !!this.vars.yoyoEase);
  42919. this._repeat = this.vars.repeat || 0;
  42920. this._repeatDelay = this.vars.repeatDelay || 0;
  42921. this._dirty = true; //ensures that if there is any repeat, the totalDuration will get recalculated to accurately report it.
  42922. this.render = TweenMax.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method)
  42923. },
  42924. _tinyNum = 0.0000000001,
  42925. TweenLiteInternals = TweenLite._internals,
  42926. _isSelector = TweenLiteInternals.isSelector,
  42927. _isArray = TweenLiteInternals.isArray,
  42928. p = TweenMax.prototype = TweenLite.to({}, 0.1, {}),
  42929. _blankArray = [];
  42930. TweenMax.version = "1.20.2";
  42931. p.constructor = TweenMax;
  42932. p.kill()._gc = false;
  42933. TweenMax.killTweensOf = TweenMax.killDelayedCallsTo = TweenLite.killTweensOf;
  42934. TweenMax.getTweensOf = TweenLite.getTweensOf;
  42935. TweenMax.lagSmoothing = TweenLite.lagSmoothing;
  42936. TweenMax.ticker = TweenLite.ticker;
  42937. TweenMax.render = TweenLite.render;
  42938. p.invalidate = function() {
  42939. this._yoyo = (this.vars.yoyo === true || !!this.vars.yoyoEase);
  42940. this._repeat = this.vars.repeat || 0;
  42941. this._repeatDelay = this.vars.repeatDelay || 0;
  42942. this._yoyoEase = null;
  42943. this._uncache(true);
  42944. return TweenLite.prototype.invalidate.call(this);
  42945. };
  42946. p.updateTo = function(vars, resetDuration) {
  42947. var curRatio = this.ratio,
  42948. immediate = this.vars.immediateRender || vars.immediateRender,
  42949. p;
  42950. if (resetDuration && this._startTime < this._timeline._time) {
  42951. this._startTime = this._timeline._time;
  42952. this._uncache(false);
  42953. if (this._gc) {
  42954. this._enabled(true, false);
  42955. } else {
  42956. this._timeline.insert(this, this._startTime - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct.
  42957. }
  42958. }
  42959. for (p in vars) {
  42960. this.vars[p] = vars[p];
  42961. }
  42962. if (this._initted || immediate) {
  42963. if (resetDuration) {
  42964. this._initted = false;
  42965. if (immediate) {
  42966. this.render(0, true, true);
  42967. }
  42968. } else {
  42969. if (this._gc) {
  42970. this._enabled(true, false);
  42971. }
  42972. if (this._notifyPluginsOfEnabled && this._firstPT) {
  42973. TweenLite._onPluginEvent("_onDisable", this); //in case a plugin like MotionBlur must perform some cleanup tasks
  42974. }
  42975. if (this._time / this._duration > 0.998) { //if the tween has finished (or come extremely close to finishing), we just need to rewind it to 0 and then render it again at the end which forces it to re-initialize (parsing the new vars). We allow tweens that are close to finishing (but haven't quite finished) to work this way too because otherwise, the values are so small when determining where to project the starting values that binary math issues creep in and can make the tween appear to render incorrectly when run backwards.
  42976. var prevTime = this._totalTime;
  42977. this.render(0, true, false);
  42978. this._initted = false;
  42979. this.render(prevTime, true, false);
  42980. } else {
  42981. this._initted = false;
  42982. this._init();
  42983. if (this._time > 0 || immediate) {
  42984. var inv = 1 / (1 - curRatio),
  42985. pt = this._firstPT, endValue;
  42986. while (pt) {
  42987. endValue = pt.s + pt.c;
  42988. pt.c *= inv;
  42989. pt.s = endValue - pt.c;
  42990. pt = pt._next;
  42991. }
  42992. }
  42993. }
  42994. }
  42995. }
  42996. return this;
  42997. };
  42998. p.render = function(time, suppressEvents, force) {
  42999. if (!this._initted) if (this._duration === 0 && this.vars.repeat) { //zero duration tweens that render immediately have render() called from TweenLite's constructor, before TweenMax's constructor has finished setting _repeat, _repeatDelay, and _yoyo which are critical in determining totalDuration() so we need to call invalidate() which is a low-kb way to get those set properly.
  43000. this.invalidate();
  43001. }
  43002. var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(),
  43003. prevTime = this._time,
  43004. prevTotalTime = this._totalTime,
  43005. prevCycle = this._cycle,
  43006. duration = this._duration,
  43007. prevRawPrevTime = this._rawPrevTime,
  43008. isComplete, callback, pt, cycleDuration, r, type, pow, rawPrevTime, yoyoEase;
  43009. if (time >= totalDur - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts.
  43010. this._totalTime = totalDur;
  43011. this._cycle = this._repeat;
  43012. if (this._yoyo && (this._cycle & 1) !== 0) {
  43013. this._time = 0;
  43014. this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
  43015. } else {
  43016. this._time = duration;
  43017. this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1;
  43018. }
  43019. if (!this._reversed) {
  43020. isComplete = true;
  43021. callback = "onComplete";
  43022. force = (force || this._timeline.autoRemoveChildren); //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
  43023. }
  43024. if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
  43025. if (this._startTime === this._timeline._duration) { //if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate.
  43026. time = 0;
  43027. }
  43028. if (prevRawPrevTime < 0 || (time <= 0 && time >= -0.0000001) || (prevRawPrevTime === _tinyNum && this.data !== "isPause")) if (prevRawPrevTime !== time) { //note: when this.data is "isPause", it's a callback added by addPause() on a timeline that we should not be triggered when LEAVING its exact start time. In other words, tl.addPause(1).play(1) shouldn't pause.
  43029. force = true;
  43030. if (prevRawPrevTime > _tinyNum) {
  43031. callback = "onReverseComplete";
  43032. }
  43033. }
  43034. this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  43035. }
  43036. } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
  43037. this._totalTime = this._time = this._cycle = 0;
  43038. this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
  43039. if (prevTotalTime !== 0 || (duration === 0 && prevRawPrevTime > 0)) {
  43040. callback = "onReverseComplete";
  43041. isComplete = this._reversed;
  43042. }
  43043. if (time < 0) {
  43044. this._active = false;
  43045. if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
  43046. if (prevRawPrevTime >= 0) {
  43047. force = true;
  43048. }
  43049. this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  43050. }
  43051. }
  43052. if (!this._initted) { //if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately.
  43053. force = true;
  43054. }
  43055. } else {
  43056. this._totalTime = this._time = time;
  43057. if (this._repeat !== 0) {
  43058. cycleDuration = duration + this._repeatDelay;
  43059. this._cycle = (this._totalTime / cycleDuration) >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but some browsers report it as 0.79999999!)
  43060. if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration && prevTotalTime <= time) {
  43061. this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning)
  43062. }
  43063. this._time = this._totalTime - (this._cycle * cycleDuration);
  43064. if (this._yoyo) if ((this._cycle & 1) !== 0) {
  43065. this._time = duration - this._time;
  43066. yoyoEase = this._yoyoEase || this.vars.yoyoEase; //note: we don't set this._yoyoEase in _init() like we do other properties because it's TweenMax-specific and doing it here allows us to optimize performance (most tweens don't have a yoyoEase). Note that we also must skip the this.ratio calculation further down right after we _init() in this function, because we're doing it here.
  43067. if (yoyoEase) {
  43068. if (!this._yoyoEase) {
  43069. if (yoyoEase === true && !this._initted) { //if it's not initted and yoyoEase is true, this._ease won't have been populated yet so we must discern it here.
  43070. yoyoEase = this.vars.ease;
  43071. this._yoyoEase = yoyoEase = !yoyoEase ? TweenLite.defaultEase : (yoyoEase instanceof Ease) ? yoyoEase : (typeof(yoyoEase) === "function") ? new Ease(yoyoEase, this.vars.easeParams) : Ease.map[yoyoEase] || TweenLite.defaultEase;
  43072. } else {
  43073. this._yoyoEase = yoyoEase = (yoyoEase === true) ? this._ease : (yoyoEase instanceof Ease) ? yoyoEase : Ease.map[yoyoEase];
  43074. }
  43075. }
  43076. this.ratio = yoyoEase ? 1 - yoyoEase.getRatio((duration - this._time) / duration) : 0;
  43077. }
  43078. }
  43079. if (this._time > duration) {
  43080. this._time = duration;
  43081. } else if (this._time < 0) {
  43082. this._time = 0;
  43083. }
  43084. }
  43085. if (this._easeType && !yoyoEase) {
  43086. r = this._time / duration;
  43087. type = this._easeType;
  43088. pow = this._easePower;
  43089. if (type === 1 || (type === 3 && r >= 0.5)) {
  43090. r = 1 - r;
  43091. }
  43092. if (type === 3) {
  43093. r *= 2;
  43094. }
  43095. if (pow === 1) {
  43096. r *= r;
  43097. } else if (pow === 2) {
  43098. r *= r * r;
  43099. } else if (pow === 3) {
  43100. r *= r * r * r;
  43101. } else if (pow === 4) {
  43102. r *= r * r * r * r;
  43103. }
  43104. if (type === 1) {
  43105. this.ratio = 1 - r;
  43106. } else if (type === 2) {
  43107. this.ratio = r;
  43108. } else if (this._time / duration < 0.5) {
  43109. this.ratio = r / 2;
  43110. } else {
  43111. this.ratio = 1 - (r / 2);
  43112. }
  43113. } else if (!yoyoEase) {
  43114. this.ratio = this._ease.getRatio(this._time / duration);
  43115. }
  43116. }
  43117. if (prevTime === this._time && !force && prevCycle === this._cycle) {
  43118. if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) { //so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate.
  43119. this._callback("onUpdate");
  43120. }
  43121. return;
  43122. } else if (!this._initted) {
  43123. this._init();
  43124. if (!this._initted || this._gc) { //immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example.
  43125. return;
  43126. } else if (!force && this._firstPT && ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration))) { //we stick it in the queue for rendering at the very end of the tick - this is a performance optimization because browsers invalidate styles and force a recalculation if you read, write, and then read style data (so it's better to read/read/read/write/write/write than read/write/read/write/read/write). The down side, of course, is that usually you WANT things to render immediately because you may have code running right after that which depends on the change. Like imagine running TweenLite.set(...) and then immediately after that, creating a nother tween that animates the same property to another value; the starting values of that 2nd tween wouldn't be accurate if lazy is true.
  43127. this._time = prevTime;
  43128. this._totalTime = prevTotalTime;
  43129. this._rawPrevTime = prevRawPrevTime;
  43130. this._cycle = prevCycle;
  43131. TweenLiteInternals.lazyTweens.push(this);
  43132. this._lazy = [time, suppressEvents];
  43133. return;
  43134. }
  43135. //_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently.
  43136. if (this._time && !isComplete && !yoyoEase) {
  43137. this.ratio = this._ease.getRatio(this._time / duration);
  43138. } else if (isComplete && this._ease._calcEnd && !yoyoEase) {
  43139. this.ratio = this._ease.getRatio((this._time === 0) ? 0 : 1);
  43140. }
  43141. }
  43142. if (this._lazy !== false) {
  43143. this._lazy = false;
  43144. }
  43145. if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) {
  43146. this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
  43147. }
  43148. if (prevTotalTime === 0) {
  43149. if (this._initted === 2 && time > 0) {
  43150. //this.invalidate();
  43151. this._init(); //will just apply overwriting since _initted of (2) means it was a from() tween that had immediateRender:true
  43152. }
  43153. if (this._startAt) {
  43154. if (time >= 0) {
  43155. this._startAt.render(time, suppressEvents, force);
  43156. } else if (!callback) {
  43157. callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area.
  43158. }
  43159. }
  43160. if (this.vars.onStart) if (this._totalTime !== 0 || duration === 0) if (!suppressEvents) {
  43161. this._callback("onStart");
  43162. }
  43163. }
  43164. pt = this._firstPT;
  43165. while (pt) {
  43166. if (pt.f) {
  43167. pt.t[pt.p](pt.c * this.ratio + pt.s);
  43168. } else {
  43169. pt.t[pt.p] = pt.c * this.ratio + pt.s;
  43170. }
  43171. pt = pt._next;
  43172. }
  43173. if (this._onUpdate) {
  43174. if (time < 0) if (this._startAt && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
  43175. this._startAt.render(time, suppressEvents, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.
  43176. }
  43177. if (!suppressEvents) if (this._totalTime !== prevTotalTime || callback) {
  43178. this._callback("onUpdate");
  43179. }
  43180. }
  43181. if (this._cycle !== prevCycle) if (!suppressEvents) if (!this._gc) if (this.vars.onRepeat) {
  43182. this._callback("onRepeat");
  43183. }
  43184. if (callback) if (!this._gc || force) { //check gc because there's a chance that kill() could be called in an onUpdate
  43185. if (time < 0 && this._startAt && !this._onUpdate && this._startTime) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
  43186. this._startAt.render(time, suppressEvents, force);
  43187. }
  43188. if (isComplete) {
  43189. if (this._timeline.autoRemoveChildren) {
  43190. this._enabled(false, false);
  43191. }
  43192. this._active = false;
  43193. }
  43194. if (!suppressEvents && this.vars[callback]) {
  43195. this._callback(callback);
  43196. }
  43197. if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) { //the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless.
  43198. this._rawPrevTime = 0;
  43199. }
  43200. }
  43201. };
  43202. //---- STATIC FUNCTIONS -----------------------------------------------------------------------------------------------------------
  43203. TweenMax.to = function(target, duration, vars) {
  43204. return new TweenMax(target, duration, vars);
  43205. };
  43206. TweenMax.from = function(target, duration, vars) {
  43207. vars.runBackwards = true;
  43208. vars.immediateRender = (vars.immediateRender != false);
  43209. return new TweenMax(target, duration, vars);
  43210. };
  43211. TweenMax.fromTo = function(target, duration, fromVars, toVars) {
  43212. toVars.startAt = fromVars;
  43213. toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
  43214. return new TweenMax(target, duration, toVars);
  43215. };
  43216. TweenMax.staggerTo = TweenMax.allTo = function(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
  43217. stagger = stagger || 0;
  43218. var delay = 0,
  43219. a = [],
  43220. finalComplete = function() {
  43221. if (vars.onComplete) {
  43222. vars.onComplete.apply(vars.onCompleteScope || this, arguments);
  43223. }
  43224. onCompleteAll.apply(onCompleteAllScope || vars.callbackScope || this, onCompleteAllParams || _blankArray);
  43225. },
  43226. cycle = vars.cycle,
  43227. fromCycle = (vars.startAt && vars.startAt.cycle),
  43228. l, copy, i, p;
  43229. if (!_isArray(targets)) {
  43230. if (typeof(targets) === "string") {
  43231. targets = TweenLite.selector(targets) || targets;
  43232. }
  43233. if (_isSelector(targets)) {
  43234. targets = _slice(targets);
  43235. }
  43236. }
  43237. targets = targets || [];
  43238. if (stagger < 0) {
  43239. targets = _slice(targets);
  43240. targets.reverse();
  43241. stagger *= -1;
  43242. }
  43243. l = targets.length - 1;
  43244. for (i = 0; i <= l; i++) {
  43245. copy = {};
  43246. for (p in vars) {
  43247. copy[p] = vars[p];
  43248. }
  43249. if (cycle) {
  43250. _applyCycle(copy, targets, i);
  43251. if (copy.duration != null) {
  43252. duration = copy.duration;
  43253. delete copy.duration;
  43254. }
  43255. }
  43256. if (fromCycle) {
  43257. fromCycle = copy.startAt = {};
  43258. for (p in vars.startAt) {
  43259. fromCycle[p] = vars.startAt[p];
  43260. }
  43261. _applyCycle(copy.startAt, targets, i);
  43262. }
  43263. copy.delay = delay + (copy.delay || 0);
  43264. if (i === l && onCompleteAll) {
  43265. copy.onComplete = finalComplete;
  43266. }
  43267. a[i] = new TweenMax(targets[i], duration, copy);
  43268. delay += stagger;
  43269. }
  43270. return a;
  43271. };
  43272. TweenMax.staggerFrom = TweenMax.allFrom = function(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
  43273. vars.runBackwards = true;
  43274. vars.immediateRender = (vars.immediateRender != false);
  43275. return TweenMax.staggerTo(targets, duration, vars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
  43276. };
  43277. TweenMax.staggerFromTo = TweenMax.allFromTo = function(targets, duration, fromVars, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
  43278. toVars.startAt = fromVars;
  43279. toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
  43280. return TweenMax.staggerTo(targets, duration, toVars, stagger, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
  43281. };
  43282. TweenMax.delayedCall = function(delay, callback, params, scope, useFrames) {
  43283. return new TweenMax(callback, 0, {delay:delay, onComplete:callback, onCompleteParams:params, callbackScope:scope, onReverseComplete:callback, onReverseCompleteParams:params, immediateRender:false, useFrames:useFrames, overwrite:0});
  43284. };
  43285. TweenMax.set = function(target, vars) {
  43286. return new TweenMax(target, 0, vars);
  43287. };
  43288. TweenMax.isTweening = function(target) {
  43289. return (TweenLite.getTweensOf(target, true).length > 0);
  43290. };
  43291. var _getChildrenOf = function(timeline, includeTimelines) {
  43292. var a = [],
  43293. cnt = 0,
  43294. tween = timeline._first;
  43295. while (tween) {
  43296. if (tween instanceof TweenLite) {
  43297. a[cnt++] = tween;
  43298. } else {
  43299. if (includeTimelines) {
  43300. a[cnt++] = tween;
  43301. }
  43302. a = a.concat(_getChildrenOf(tween, includeTimelines));
  43303. cnt = a.length;
  43304. }
  43305. tween = tween._next;
  43306. }
  43307. return a;
  43308. },
  43309. getAllTweens = TweenMax.getAllTweens = function(includeTimelines) {
  43310. return _getChildrenOf(Animation._rootTimeline, includeTimelines).concat( _getChildrenOf(Animation._rootFramesTimeline, includeTimelines) );
  43311. };
  43312. TweenMax.killAll = function(complete, tweens, delayedCalls, timelines) {
  43313. if (tweens == null) {
  43314. tweens = true;
  43315. }
  43316. if (delayedCalls == null) {
  43317. delayedCalls = true;
  43318. }
  43319. var a = getAllTweens((timelines != false)),
  43320. l = a.length,
  43321. allTrue = (tweens && delayedCalls && timelines),
  43322. isDC, tween, i;
  43323. for (i = 0; i < l; i++) {
  43324. tween = a[i];
  43325. if (allTrue || (tween instanceof SimpleTimeline) || ((isDC = (tween.target === tween.vars.onComplete)) && delayedCalls) || (tweens && !isDC)) {
  43326. if (complete) {
  43327. tween.totalTime(tween._reversed ? 0 : tween.totalDuration());
  43328. } else {
  43329. tween._enabled(false, false);
  43330. }
  43331. }
  43332. }
  43333. };
  43334. TweenMax.killChildTweensOf = function(parent, complete) {
  43335. if (parent == null) {
  43336. return;
  43337. }
  43338. var tl = TweenLiteInternals.tweenLookup,
  43339. a, curParent, p, i, l;
  43340. if (typeof(parent) === "string") {
  43341. parent = TweenLite.selector(parent) || parent;
  43342. }
  43343. if (_isSelector(parent)) {
  43344. parent = _slice(parent);
  43345. }
  43346. if (_isArray(parent)) {
  43347. i = parent.length;
  43348. while (--i > -1) {
  43349. TweenMax.killChildTweensOf(parent[i], complete);
  43350. }
  43351. return;
  43352. }
  43353. a = [];
  43354. for (p in tl) {
  43355. curParent = tl[p].target.parentNode;
  43356. while (curParent) {
  43357. if (curParent === parent) {
  43358. a = a.concat(tl[p].tweens);
  43359. }
  43360. curParent = curParent.parentNode;
  43361. }
  43362. }
  43363. l = a.length;
  43364. for (i = 0; i < l; i++) {
  43365. if (complete) {
  43366. a[i].totalTime(a[i].totalDuration());
  43367. }
  43368. a[i]._enabled(false, false);
  43369. }
  43370. };
  43371. var _changePause = function(pause, tweens, delayedCalls, timelines) {
  43372. tweens = (tweens !== false);
  43373. delayedCalls = (delayedCalls !== false);
  43374. timelines = (timelines !== false);
  43375. var a = getAllTweens(timelines),
  43376. allTrue = (tweens && delayedCalls && timelines),
  43377. i = a.length,
  43378. isDC, tween;
  43379. while (--i > -1) {
  43380. tween = a[i];
  43381. if (allTrue || (tween instanceof SimpleTimeline) || ((isDC = (tween.target === tween.vars.onComplete)) && delayedCalls) || (tweens && !isDC)) {
  43382. tween.paused(pause);
  43383. }
  43384. }
  43385. };
  43386. TweenMax.pauseAll = function(tweens, delayedCalls, timelines) {
  43387. _changePause(true, tweens, delayedCalls, timelines);
  43388. };
  43389. TweenMax.resumeAll = function(tweens, delayedCalls, timelines) {
  43390. _changePause(false, tweens, delayedCalls, timelines);
  43391. };
  43392. TweenMax.globalTimeScale = function(value) {
  43393. var tl = Animation._rootTimeline,
  43394. t = TweenLite.ticker.time;
  43395. if (!arguments.length) {
  43396. return tl._timeScale;
  43397. }
  43398. value = value || _tinyNum; //can't allow zero because it'll throw the math off
  43399. tl._startTime = t - ((t - tl._startTime) * tl._timeScale / value);
  43400. tl = Animation._rootFramesTimeline;
  43401. t = TweenLite.ticker.frame;
  43402. tl._startTime = t - ((t - tl._startTime) * tl._timeScale / value);
  43403. tl._timeScale = Animation._rootTimeline._timeScale = value;
  43404. return value;
  43405. };
  43406. //---- GETTERS / SETTERS ----------------------------------------------------------------------------------------------------------
  43407. p.progress = function(value, suppressEvents) {
  43408. return (!arguments.length) ? this._time / this.duration() : this.totalTime( this.duration() * ((this._yoyo && (this._cycle & 1) !== 0) ? 1 - value : value) + (this._cycle * (this._duration + this._repeatDelay)), suppressEvents);
  43409. };
  43410. p.totalProgress = function(value, suppressEvents) {
  43411. return (!arguments.length) ? this._totalTime / this.totalDuration() : this.totalTime( this.totalDuration() * value, suppressEvents);
  43412. };
  43413. p.time = function(value, suppressEvents) {
  43414. if (!arguments.length) {
  43415. return this._time;
  43416. }
  43417. if (this._dirty) {
  43418. this.totalDuration();
  43419. }
  43420. if (value > this._duration) {
  43421. value = this._duration;
  43422. }
  43423. if (this._yoyo && (this._cycle & 1) !== 0) {
  43424. value = (this._duration - value) + (this._cycle * (this._duration + this._repeatDelay));
  43425. } else if (this._repeat !== 0) {
  43426. value += this._cycle * (this._duration + this._repeatDelay);
  43427. }
  43428. return this.totalTime(value, suppressEvents);
  43429. };
  43430. p.duration = function(value) {
  43431. if (!arguments.length) {
  43432. return this._duration; //don't set _dirty = false because there could be repeats that haven't been factored into the _totalDuration yet. Otherwise, if you create a repeated TweenMax and then immediately check its duration(), it would cache the value and the totalDuration would not be correct, thus repeats wouldn't take effect.
  43433. }
  43434. return Animation.prototype.duration.call(this, value);
  43435. };
  43436. p.totalDuration = function(value) {
  43437. if (!arguments.length) {
  43438. if (this._dirty) {
  43439. //instead of Infinity, we use 999999999999 so that we can accommodate reverses
  43440. this._totalDuration = (this._repeat === -1) ? 999999999999 : this._duration * (this._repeat + 1) + (this._repeatDelay * this._repeat);
  43441. this._dirty = false;
  43442. }
  43443. return this._totalDuration;
  43444. }
  43445. return (this._repeat === -1) ? this : this.duration( (value - (this._repeat * this._repeatDelay)) / (this._repeat + 1) );
  43446. };
  43447. p.repeat = function(value) {
  43448. if (!arguments.length) {
  43449. return this._repeat;
  43450. }
  43451. this._repeat = value;
  43452. return this._uncache(true);
  43453. };
  43454. p.repeatDelay = function(value) {
  43455. if (!arguments.length) {
  43456. return this._repeatDelay;
  43457. }
  43458. this._repeatDelay = value;
  43459. return this._uncache(true);
  43460. };
  43461. p.yoyo = function(value) {
  43462. if (!arguments.length) {
  43463. return this._yoyo;
  43464. }
  43465. this._yoyo = value;
  43466. return this;
  43467. };
  43468. return TweenMax;
  43469. }, true);
  43470. /*
  43471. * ----------------------------------------------------------------
  43472. * TimelineLite
  43473. * ----------------------------------------------------------------
  43474. */
  43475. _gsScope._gsDefine("TimelineLite", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) {
  43476. var TimelineLite = function(vars) {
  43477. SimpleTimeline.call(this, vars);
  43478. this._labels = {};
  43479. this.autoRemoveChildren = (this.vars.autoRemoveChildren === true);
  43480. this.smoothChildTiming = (this.vars.smoothChildTiming === true);
  43481. this._sortChildren = true;
  43482. this._onUpdate = this.vars.onUpdate;
  43483. var v = this.vars,
  43484. val, p;
  43485. for (p in v) {
  43486. val = v[p];
  43487. if (_isArray(val)) if (val.join("").indexOf("{self}") !== -1) {
  43488. v[p] = this._swapSelfInParams(val);
  43489. }
  43490. }
  43491. if (_isArray(v.tweens)) {
  43492. this.add(v.tweens, 0, v.align, v.stagger);
  43493. }
  43494. },
  43495. _tinyNum = 0.0000000001,
  43496. TweenLiteInternals = TweenLite._internals,
  43497. _internals = TimelineLite._internals = {},
  43498. _isSelector = TweenLiteInternals.isSelector,
  43499. _isArray = TweenLiteInternals.isArray,
  43500. _lazyTweens = TweenLiteInternals.lazyTweens,
  43501. _lazyRender = TweenLiteInternals.lazyRender,
  43502. _globals = _gsScope._gsDefine.globals,
  43503. _copy = function(vars) {
  43504. var copy = {}, p;
  43505. for (p in vars) {
  43506. copy[p] = vars[p];
  43507. }
  43508. return copy;
  43509. },
  43510. _applyCycle = function(vars, targets, i) {
  43511. var alt = vars.cycle,
  43512. p, val;
  43513. for (p in alt) {
  43514. val = alt[p];
  43515. vars[p] = (typeof(val) === "function") ? val(i, targets[i]) : val[i % val.length];
  43516. }
  43517. delete vars.cycle;
  43518. },
  43519. _pauseCallback = _internals.pauseCallback = function() {},
  43520. _slice = function(a) { //don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
  43521. var b = [],
  43522. l = a.length,
  43523. i;
  43524. for (i = 0; i !== l; b.push(a[i++]));
  43525. return b;
  43526. },
  43527. p = TimelineLite.prototype = new SimpleTimeline();
  43528. TimelineLite.version = "1.20.2";
  43529. p.constructor = TimelineLite;
  43530. p.kill()._gc = p._forcingPlayhead = p._hasPause = false;
  43531. /* might use later...
  43532. //translates a local time inside an animation to the corresponding time on the root/global timeline, factoring in all nesting and timeScales.
  43533. function localToGlobal(time, animation) {
  43534. while (animation) {
  43535. time = (time / animation._timeScale) + animation._startTime;
  43536. animation = animation.timeline;
  43537. }
  43538. return time;
  43539. }
  43540. //translates the supplied time on the root/global timeline into the corresponding local time inside a particular animation, factoring in all nesting and timeScales
  43541. function globalToLocal(time, animation) {
  43542. var scale = 1;
  43543. time -= localToGlobal(0, animation);
  43544. while (animation) {
  43545. scale *= animation._timeScale;
  43546. animation = animation.timeline;
  43547. }
  43548. return time * scale;
  43549. }
  43550. */
  43551. p.to = function(target, duration, vars, position) {
  43552. var Engine = (vars.repeat && _globals.TweenMax) || TweenLite;
  43553. return duration ? this.add( new Engine(target, duration, vars), position) : this.set(target, vars, position);
  43554. };
  43555. p.from = function(target, duration, vars, position) {
  43556. return this.add( ((vars.repeat && _globals.TweenMax) || TweenLite).from(target, duration, vars), position);
  43557. };
  43558. p.fromTo = function(target, duration, fromVars, toVars, position) {
  43559. var Engine = (toVars.repeat && _globals.TweenMax) || TweenLite;
  43560. return duration ? this.add( Engine.fromTo(target, duration, fromVars, toVars), position) : this.set(target, toVars, position);
  43561. };
  43562. p.staggerTo = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
  43563. var tl = new TimelineLite({onComplete:onCompleteAll, onCompleteParams:onCompleteAllParams, callbackScope:onCompleteAllScope, smoothChildTiming:this.smoothChildTiming}),
  43564. cycle = vars.cycle,
  43565. copy, i;
  43566. if (typeof(targets) === "string") {
  43567. targets = TweenLite.selector(targets) || targets;
  43568. }
  43569. targets = targets || [];
  43570. if (_isSelector(targets)) { //senses if the targets object is a selector. If it is, we should translate it into an array.
  43571. targets = _slice(targets);
  43572. }
  43573. stagger = stagger || 0;
  43574. if (stagger < 0) {
  43575. targets = _slice(targets);
  43576. targets.reverse();
  43577. stagger *= -1;
  43578. }
  43579. for (i = 0; i < targets.length; i++) {
  43580. copy = _copy(vars);
  43581. if (copy.startAt) {
  43582. copy.startAt = _copy(copy.startAt);
  43583. if (copy.startAt.cycle) {
  43584. _applyCycle(copy.startAt, targets, i);
  43585. }
  43586. }
  43587. if (cycle) {
  43588. _applyCycle(copy, targets, i);
  43589. if (copy.duration != null) {
  43590. duration = copy.duration;
  43591. delete copy.duration;
  43592. }
  43593. }
  43594. tl.to(targets[i], duration, copy, i * stagger);
  43595. }
  43596. return this.add(tl, position);
  43597. };
  43598. p.staggerFrom = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
  43599. vars.immediateRender = (vars.immediateRender != false);
  43600. vars.runBackwards = true;
  43601. return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
  43602. };
  43603. p.staggerFromTo = function(targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
  43604. toVars.startAt = fromVars;
  43605. toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
  43606. return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
  43607. };
  43608. p.call = function(callback, params, scope, position) {
  43609. return this.add( TweenLite.delayedCall(0, callback, params, scope), position);
  43610. };
  43611. p.set = function(target, vars, position) {
  43612. position = this._parseTimeOrLabel(position, 0, true);
  43613. if (vars.immediateRender == null) {
  43614. vars.immediateRender = (position === this._time && !this._paused);
  43615. }
  43616. return this.add( new TweenLite(target, 0, vars), position);
  43617. };
  43618. TimelineLite.exportRoot = function(vars, ignoreDelayedCalls) {
  43619. vars = vars || {};
  43620. if (vars.smoothChildTiming == null) {
  43621. vars.smoothChildTiming = true;
  43622. }
  43623. var tl = new TimelineLite(vars),
  43624. root = tl._timeline,
  43625. tween, next;
  43626. if (ignoreDelayedCalls == null) {
  43627. ignoreDelayedCalls = true;
  43628. }
  43629. root._remove(tl, true);
  43630. tl._startTime = 0;
  43631. tl._rawPrevTime = tl._time = tl._totalTime = root._time;
  43632. tween = root._first;
  43633. while (tween) {
  43634. next = tween._next;
  43635. if (!ignoreDelayedCalls || !(tween instanceof TweenLite && tween.target === tween.vars.onComplete)) {
  43636. tl.add(tween, tween._startTime - tween._delay);
  43637. }
  43638. tween = next;
  43639. }
  43640. root.add(tl, 0);
  43641. return tl;
  43642. };
  43643. p.add = function(value, position, align, stagger) {
  43644. var curTime, l, i, child, tl, beforeRawTime;
  43645. if (typeof(position) !== "number") {
  43646. position = this._parseTimeOrLabel(position, 0, true, value);
  43647. }
  43648. if (!(value instanceof Animation)) {
  43649. if ((value instanceof Array) || (value && value.push && _isArray(value))) {
  43650. align = align || "normal";
  43651. stagger = stagger || 0;
  43652. curTime = position;
  43653. l = value.length;
  43654. for (i = 0; i < l; i++) {
  43655. if (_isArray(child = value[i])) {
  43656. child = new TimelineLite({tweens:child});
  43657. }
  43658. this.add(child, curTime);
  43659. if (typeof(child) !== "string" && typeof(child) !== "function") {
  43660. if (align === "sequence") {
  43661. curTime = child._startTime + (child.totalDuration() / child._timeScale);
  43662. } else if (align === "start") {
  43663. child._startTime -= child.delay();
  43664. }
  43665. }
  43666. curTime += stagger;
  43667. }
  43668. return this._uncache(true);
  43669. } else if (typeof(value) === "string") {
  43670. return this.addLabel(value, position);
  43671. } else if (typeof(value) === "function") {
  43672. value = TweenLite.delayedCall(0, value);
  43673. } else {
  43674. throw("Cannot add " + value + " into the timeline; it is not a tween, timeline, function, or string.");
  43675. }
  43676. }
  43677. SimpleTimeline.prototype.add.call(this, value, position);
  43678. if (value._time) { //in case, for example, the _startTime is moved on a tween that has already rendered. Imagine it's at its end state, then the startTime is moved WAY later (after the end of this timeline), it should render at its beginning.
  43679. value.render((this.rawTime() - value._startTime) * value._timeScale, false, false);
  43680. }
  43681. //if the timeline has already ended but the inserted tween/timeline extends the duration, we should enable this timeline again so that it renders properly. We should also align the playhead with the parent timeline's when appropriate.
  43682. if (this._gc || this._time === this._duration) if (!this._paused) if (this._duration < this.duration()) {
  43683. //in case any of the ancestors had completed but should now be enabled...
  43684. tl = this;
  43685. beforeRawTime = (tl.rawTime() > value._startTime); //if the tween is placed on the timeline so that it starts BEFORE the current rawTime, we should align the playhead (move the timeline). This is because sometimes users will create a timeline, let it finish, and much later append a tween and expect it to run instead of jumping to its end state. While technically one could argue that it should jump to its end state, that's not what users intuitively expect.
  43686. while (tl._timeline) {
  43687. if (beforeRawTime && tl._timeline.smoothChildTiming) {
  43688. tl.totalTime(tl._totalTime, true); //moves the timeline (shifts its startTime) if necessary, and also enables it.
  43689. } else if (tl._gc) {
  43690. tl._enabled(true, false);
  43691. }
  43692. tl = tl._timeline;
  43693. }
  43694. }
  43695. return this;
  43696. };
  43697. p.remove = function(value) {
  43698. if (value instanceof Animation) {
  43699. this._remove(value, false);
  43700. var tl = value._timeline = value.vars.useFrames ? Animation._rootFramesTimeline : Animation._rootTimeline; //now that it's removed, default it to the root timeline so that if it gets played again, it doesn't jump back into this timeline.
  43701. value._startTime = (value._paused ? value._pauseTime : tl._time) - ((!value._reversed ? value._totalTime : value.totalDuration() - value._totalTime) / value._timeScale); //ensure that if it gets played again, the timing is correct.
  43702. return this;
  43703. } else if (value instanceof Array || (value && value.push && _isArray(value))) {
  43704. var i = value.length;
  43705. while (--i > -1) {
  43706. this.remove(value[i]);
  43707. }
  43708. return this;
  43709. } else if (typeof(value) === "string") {
  43710. return this.removeLabel(value);
  43711. }
  43712. return this.kill(null, value);
  43713. };
  43714. p._remove = function(tween, skipDisable) {
  43715. SimpleTimeline.prototype._remove.call(this, tween, skipDisable);
  43716. var last = this._last;
  43717. if (!last) {
  43718. this._time = this._totalTime = this._duration = this._totalDuration = 0;
  43719. } else if (this._time > this.duration()) {
  43720. this._time = this._duration;
  43721. this._totalTime = this._totalDuration;
  43722. }
  43723. return this;
  43724. };
  43725. p.append = function(value, offsetOrLabel) {
  43726. return this.add(value, this._parseTimeOrLabel(null, offsetOrLabel, true, value));
  43727. };
  43728. p.insert = p.insertMultiple = function(value, position, align, stagger) {
  43729. return this.add(value, position || 0, align, stagger);
  43730. };
  43731. p.appendMultiple = function(tweens, offsetOrLabel, align, stagger) {
  43732. return this.add(tweens, this._parseTimeOrLabel(null, offsetOrLabel, true, tweens), align, stagger);
  43733. };
  43734. p.addLabel = function(label, position) {
  43735. this._labels[label] = this._parseTimeOrLabel(position);
  43736. return this;
  43737. };
  43738. p.addPause = function(position, callback, params, scope) {
  43739. var t = TweenLite.delayedCall(0, _pauseCallback, params, scope || this);
  43740. t.vars.onComplete = t.vars.onReverseComplete = callback;
  43741. t.data = "isPause";
  43742. this._hasPause = true;
  43743. return this.add(t, position);
  43744. };
  43745. p.removeLabel = function(label) {
  43746. delete this._labels[label];
  43747. return this;
  43748. };
  43749. p.getLabelTime = function(label) {
  43750. return (this._labels[label] != null) ? this._labels[label] : -1;
  43751. };
  43752. p._parseTimeOrLabel = function(timeOrLabel, offsetOrLabel, appendIfAbsent, ignore) {
  43753. var clippedDuration, i;
  43754. //if we're about to add a tween/timeline (or an array of them) that's already a child of this timeline, we should remove it first so that it doesn't contaminate the duration().
  43755. if (ignore instanceof Animation && ignore.timeline === this) {
  43756. this.remove(ignore);
  43757. } else if (ignore && ((ignore instanceof Array) || (ignore.push && _isArray(ignore)))) {
  43758. i = ignore.length;
  43759. while (--i > -1) {
  43760. if (ignore[i] instanceof Animation && ignore[i].timeline === this) {
  43761. this.remove(ignore[i]);
  43762. }
  43763. }
  43764. }
  43765. clippedDuration = (this.duration() > 99999999999) ? this.recent().endTime(false) : this._duration; //in case there's a child that infinitely repeats, users almost never intend for the insertion point of a new child to be based on a SUPER long value like that so we clip it and assume the most recently-added child's endTime should be used instead.
  43766. if (typeof(offsetOrLabel) === "string") {
  43767. return this._parseTimeOrLabel(offsetOrLabel, (appendIfAbsent && typeof(timeOrLabel) === "number" && this._labels[offsetOrLabel] == null) ? timeOrLabel - clippedDuration : 0, appendIfAbsent);
  43768. }
  43769. offsetOrLabel = offsetOrLabel || 0;
  43770. if (typeof(timeOrLabel) === "string" && (isNaN(timeOrLabel) || this._labels[timeOrLabel] != null)) { //if the string is a number like "1", check to see if there's a label with that name, otherwise interpret it as a number (absolute value).
  43771. i = timeOrLabel.indexOf("=");
  43772. if (i === -1) {
  43773. if (this._labels[timeOrLabel] == null) {
  43774. return appendIfAbsent ? (this._labels[timeOrLabel] = clippedDuration + offsetOrLabel) : offsetOrLabel;
  43775. }
  43776. return this._labels[timeOrLabel] + offsetOrLabel;
  43777. }
  43778. offsetOrLabel = parseInt(timeOrLabel.charAt(i-1) + "1", 10) * Number(timeOrLabel.substr(i+1));
  43779. timeOrLabel = (i > 1) ? this._parseTimeOrLabel(timeOrLabel.substr(0, i-1), 0, appendIfAbsent) : clippedDuration;
  43780. } else if (timeOrLabel == null) {
  43781. timeOrLabel = clippedDuration;
  43782. }
  43783. return Number(timeOrLabel) + offsetOrLabel;
  43784. };
  43785. p.seek = function(position, suppressEvents) {
  43786. return this.totalTime((typeof(position) === "number") ? position : this._parseTimeOrLabel(position), (suppressEvents !== false));
  43787. };
  43788. p.stop = function() {
  43789. return this.paused(true);
  43790. };
  43791. p.gotoAndPlay = function(position, suppressEvents) {
  43792. return this.play(position, suppressEvents);
  43793. };
  43794. p.gotoAndStop = function(position, suppressEvents) {
  43795. return this.pause(position, suppressEvents);
  43796. };
  43797. p.render = function(time, suppressEvents, force) {
  43798. if (this._gc) {
  43799. this._enabled(true, false);
  43800. }
  43801. var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(),
  43802. prevTime = this._time,
  43803. prevStart = this._startTime,
  43804. prevTimeScale = this._timeScale,
  43805. prevPaused = this._paused,
  43806. tween, isComplete, next, callback, internalForce, pauseTween, curTime;
  43807. if (time >= totalDur - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts.
  43808. this._totalTime = this._time = totalDur;
  43809. if (!this._reversed) if (!this._hasPausedChild()) {
  43810. isComplete = true;
  43811. callback = "onComplete";
  43812. internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
  43813. if (this._duration === 0) if ((time <= 0 && time >= -0.0000001) || this._rawPrevTime < 0 || this._rawPrevTime === _tinyNum) if (this._rawPrevTime !== time && this._first) {
  43814. internalForce = true;
  43815. if (this._rawPrevTime > _tinyNum) {
  43816. callback = "onReverseComplete";
  43817. }
  43818. }
  43819. }
  43820. this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  43821. time = totalDur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7.
  43822. } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
  43823. this._totalTime = this._time = 0;
  43824. if (prevTime !== 0 || (this._duration === 0 && this._rawPrevTime !== _tinyNum && (this._rawPrevTime > 0 || (time < 0 && this._rawPrevTime >= 0)))) {
  43825. callback = "onReverseComplete";
  43826. isComplete = this._reversed;
  43827. }
  43828. if (time < 0) {
  43829. this._active = false;
  43830. if (this._timeline.autoRemoveChildren && this._reversed) { //ensures proper GC if a timeline is resumed after it's finished reversing.
  43831. internalForce = isComplete = true;
  43832. callback = "onReverseComplete";
  43833. } else if (this._rawPrevTime >= 0 && this._first) { //when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state.
  43834. internalForce = true;
  43835. }
  43836. this._rawPrevTime = time;
  43837. } else {
  43838. this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  43839. if (time === 0 && isComplete) { //if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good).
  43840. tween = this._first;
  43841. while (tween && tween._startTime === 0) {
  43842. if (!tween._duration) {
  43843. isComplete = false;
  43844. }
  43845. tween = tween._next;
  43846. }
  43847. }
  43848. time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
  43849. if (!this._initted) {
  43850. internalForce = true;
  43851. }
  43852. }
  43853. } else {
  43854. if (this._hasPause && !this._forcingPlayhead && !suppressEvents) {
  43855. if (time >= prevTime) {
  43856. tween = this._first;
  43857. while (tween && tween._startTime <= time && !pauseTween) {
  43858. if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) {
  43859. pauseTween = tween;
  43860. }
  43861. tween = tween._next;
  43862. }
  43863. } else {
  43864. tween = this._last;
  43865. while (tween && tween._startTime >= time && !pauseTween) {
  43866. if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) {
  43867. pauseTween = tween;
  43868. }
  43869. tween = tween._prev;
  43870. }
  43871. }
  43872. if (pauseTween) {
  43873. this._time = time = pauseTween._startTime;
  43874. this._totalTime = time + (this._cycle * (this._totalDuration + this._repeatDelay));
  43875. }
  43876. }
  43877. this._totalTime = this._time = this._rawPrevTime = time;
  43878. }
  43879. if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) {
  43880. return;
  43881. } else if (!this._initted) {
  43882. this._initted = true;
  43883. }
  43884. if (!this._active) if (!this._paused && this._time !== prevTime && time > 0) {
  43885. this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
  43886. }
  43887. if (prevTime === 0) if (this.vars.onStart) if (this._time !== 0 || !this._duration) if (!suppressEvents) {
  43888. this._callback("onStart");
  43889. }
  43890. curTime = this._time;
  43891. if (curTime >= prevTime) {
  43892. tween = this._first;
  43893. while (tween) {
  43894. next = tween._next; //record it here because the value could change after rendering...
  43895. if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
  43896. break;
  43897. } else if (tween._active || (tween._startTime <= curTime && !tween._paused && !tween._gc)) {
  43898. if (pauseTween === tween) {
  43899. this.pause();
  43900. }
  43901. if (!tween._reversed) {
  43902. tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
  43903. } else {
  43904. tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
  43905. }
  43906. }
  43907. tween = next;
  43908. }
  43909. } else {
  43910. tween = this._last;
  43911. while (tween) {
  43912. next = tween._prev; //record it here because the value could change after rendering...
  43913. if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
  43914. break;
  43915. } else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) {
  43916. if (pauseTween === tween) {
  43917. pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse.
  43918. while (pauseTween && pauseTween.endTime() > this._time) {
  43919. pauseTween.render( (pauseTween._reversed ? pauseTween.totalDuration() - ((time - pauseTween._startTime) * pauseTween._timeScale) : (time - pauseTween._startTime) * pauseTween._timeScale), suppressEvents, force);
  43920. pauseTween = pauseTween._prev;
  43921. }
  43922. pauseTween = null;
  43923. this.pause();
  43924. }
  43925. if (!tween._reversed) {
  43926. tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
  43927. } else {
  43928. tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
  43929. }
  43930. }
  43931. tween = next;
  43932. }
  43933. }
  43934. if (this._onUpdate) if (!suppressEvents) {
  43935. if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
  43936. _lazyRender();
  43937. }
  43938. this._callback("onUpdate");
  43939. }
  43940. if (callback) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
  43941. if (isComplete) {
  43942. if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values.
  43943. _lazyRender();
  43944. }
  43945. if (this._timeline.autoRemoveChildren) {
  43946. this._enabled(false, false);
  43947. }
  43948. this._active = false;
  43949. }
  43950. if (!suppressEvents && this.vars[callback]) {
  43951. this._callback(callback);
  43952. }
  43953. }
  43954. };
  43955. p._hasPausedChild = function() {
  43956. var tween = this._first;
  43957. while (tween) {
  43958. if (tween._paused || ((tween instanceof TimelineLite) && tween._hasPausedChild())) {
  43959. return true;
  43960. }
  43961. tween = tween._next;
  43962. }
  43963. return false;
  43964. };
  43965. p.getChildren = function(nested, tweens, timelines, ignoreBeforeTime) {
  43966. ignoreBeforeTime = ignoreBeforeTime || -9999999999;
  43967. var a = [],
  43968. tween = this._first,
  43969. cnt = 0;
  43970. while (tween) {
  43971. if (tween._startTime < ignoreBeforeTime) {
  43972. //do nothing
  43973. } else if (tween instanceof TweenLite) {
  43974. if (tweens !== false) {
  43975. a[cnt++] = tween;
  43976. }
  43977. } else {
  43978. if (timelines !== false) {
  43979. a[cnt++] = tween;
  43980. }
  43981. if (nested !== false) {
  43982. a = a.concat(tween.getChildren(true, tweens, timelines));
  43983. cnt = a.length;
  43984. }
  43985. }
  43986. tween = tween._next;
  43987. }
  43988. return a;
  43989. };
  43990. p.getTweensOf = function(target, nested) {
  43991. var disabled = this._gc,
  43992. a = [],
  43993. cnt = 0,
  43994. tweens, i;
  43995. if (disabled) {
  43996. this._enabled(true, true); //getTweensOf() filters out disabled tweens, and we have to mark them as _gc = true when the timeline completes in order to allow clean garbage collection, so temporarily re-enable the timeline here.
  43997. }
  43998. tweens = TweenLite.getTweensOf(target);
  43999. i = tweens.length;
  44000. while (--i > -1) {
  44001. if (tweens[i].timeline === this || (nested && this._contains(tweens[i]))) {
  44002. a[cnt++] = tweens[i];
  44003. }
  44004. }
  44005. if (disabled) {
  44006. this._enabled(false, true);
  44007. }
  44008. return a;
  44009. };
  44010. p.recent = function() {
  44011. return this._recent;
  44012. };
  44013. p._contains = function(tween) {
  44014. var tl = tween.timeline;
  44015. while (tl) {
  44016. if (tl === this) {
  44017. return true;
  44018. }
  44019. tl = tl.timeline;
  44020. }
  44021. return false;
  44022. };
  44023. p.shiftChildren = function(amount, adjustLabels, ignoreBeforeTime) {
  44024. ignoreBeforeTime = ignoreBeforeTime || 0;
  44025. var tween = this._first,
  44026. labels = this._labels,
  44027. p;
  44028. while (tween) {
  44029. if (tween._startTime >= ignoreBeforeTime) {
  44030. tween._startTime += amount;
  44031. }
  44032. tween = tween._next;
  44033. }
  44034. if (adjustLabels) {
  44035. for (p in labels) {
  44036. if (labels[p] >= ignoreBeforeTime) {
  44037. labels[p] += amount;
  44038. }
  44039. }
  44040. }
  44041. return this._uncache(true);
  44042. };
  44043. p._kill = function(vars, target) {
  44044. if (!vars && !target) {
  44045. return this._enabled(false, false);
  44046. }
  44047. var tweens = (!target) ? this.getChildren(true, true, false) : this.getTweensOf(target),
  44048. i = tweens.length,
  44049. changed = false;
  44050. while (--i > -1) {
  44051. if (tweens[i]._kill(vars, target)) {
  44052. changed = true;
  44053. }
  44054. }
  44055. return changed;
  44056. };
  44057. p.clear = function(labels) {
  44058. var tweens = this.getChildren(false, true, true),
  44059. i = tweens.length;
  44060. this._time = this._totalTime = 0;
  44061. while (--i > -1) {
  44062. tweens[i]._enabled(false, false);
  44063. }
  44064. if (labels !== false) {
  44065. this._labels = {};
  44066. }
  44067. return this._uncache(true);
  44068. };
  44069. p.invalidate = function() {
  44070. var tween = this._first;
  44071. while (tween) {
  44072. tween.invalidate();
  44073. tween = tween._next;
  44074. }
  44075. return Animation.prototype.invalidate.call(this);;
  44076. };
  44077. p._enabled = function(enabled, ignoreTimeline) {
  44078. if (enabled === this._gc) {
  44079. var tween = this._first;
  44080. while (tween) {
  44081. tween._enabled(enabled, true);
  44082. tween = tween._next;
  44083. }
  44084. }
  44085. return SimpleTimeline.prototype._enabled.call(this, enabled, ignoreTimeline);
  44086. };
  44087. p.totalTime = function(time, suppressEvents, uncapped) {
  44088. this._forcingPlayhead = true;
  44089. var val = Animation.prototype.totalTime.apply(this, arguments);
  44090. this._forcingPlayhead = false;
  44091. return val;
  44092. };
  44093. p.duration = function(value) {
  44094. if (!arguments.length) {
  44095. if (this._dirty) {
  44096. this.totalDuration(); //just triggers recalculation
  44097. }
  44098. return this._duration;
  44099. }
  44100. if (this.duration() !== 0 && value !== 0) {
  44101. this.timeScale(this._duration / value);
  44102. }
  44103. return this;
  44104. };
  44105. p.totalDuration = function(value) {
  44106. if (!arguments.length) {
  44107. if (this._dirty) {
  44108. var max = 0,
  44109. tween = this._last,
  44110. prevStart = 999999999999,
  44111. prev, end;
  44112. while (tween) {
  44113. prev = tween._prev; //record it here in case the tween changes position in the sequence...
  44114. if (tween._dirty) {
  44115. tween.totalDuration(); //could change the tween._startTime, so make sure the tween's cache is clean before analyzing it.
  44116. }
  44117. if (tween._startTime > prevStart && this._sortChildren && !tween._paused) { //in case one of the tweens shifted out of order, it needs to be re-inserted into the correct position in the sequence
  44118. this.add(tween, tween._startTime - tween._delay);
  44119. } else {
  44120. prevStart = tween._startTime;
  44121. }
  44122. if (tween._startTime < 0 && !tween._paused) { //children aren't allowed to have negative startTimes unless smoothChildTiming is true, so adjust here if one is found.
  44123. max -= tween._startTime;
  44124. if (this._timeline.smoothChildTiming) {
  44125. this._startTime += tween._startTime / this._timeScale;
  44126. }
  44127. this.shiftChildren(-tween._startTime, false, -9999999999);
  44128. prevStart = 0;
  44129. }
  44130. end = tween._startTime + (tween._totalDuration / tween._timeScale);
  44131. if (end > max) {
  44132. max = end;
  44133. }
  44134. tween = prev;
  44135. }
  44136. this._duration = this._totalDuration = max;
  44137. this._dirty = false;
  44138. }
  44139. return this._totalDuration;
  44140. }
  44141. return (value && this.totalDuration()) ? this.timeScale(this._totalDuration / value) : this;
  44142. };
  44143. p.paused = function(value) {
  44144. if (!value) { //if there's a pause directly at the spot from where we're unpausing, skip it.
  44145. var tween = this._first,
  44146. time = this._time;
  44147. while (tween) {
  44148. if (tween._startTime === time && tween.data === "isPause") {
  44149. tween._rawPrevTime = 0; //remember, _rawPrevTime is how zero-duration tweens/callbacks sense directionality and determine whether or not to fire. If _rawPrevTime is the same as _startTime on the next render, it won't fire.
  44150. }
  44151. tween = tween._next;
  44152. }
  44153. }
  44154. return Animation.prototype.paused.apply(this, arguments);
  44155. };
  44156. p.usesFrames = function() {
  44157. var tl = this._timeline;
  44158. while (tl._timeline) {
  44159. tl = tl._timeline;
  44160. }
  44161. return (tl === Animation._rootFramesTimeline);
  44162. };
  44163. p.rawTime = function(wrapRepeats) {
  44164. return (wrapRepeats && (this._paused || (this._repeat && this.time() > 0 && this.totalProgress() < 1))) ? this._totalTime % (this._duration + this._repeatDelay) : this._paused ? this._totalTime : (this._timeline.rawTime(wrapRepeats) - this._startTime) * this._timeScale;
  44165. };
  44166. return TimelineLite;
  44167. }, true);
  44168. /*
  44169. * ----------------------------------------------------------------
  44170. * TimelineMax
  44171. * ----------------------------------------------------------------
  44172. */
  44173. _gsScope._gsDefine("TimelineMax", ["TimelineLite","TweenLite","easing.Ease"], function(TimelineLite, TweenLite, Ease) {
  44174. var TimelineMax = function(vars) {
  44175. TimelineLite.call(this, vars);
  44176. this._repeat = this.vars.repeat || 0;
  44177. this._repeatDelay = this.vars.repeatDelay || 0;
  44178. this._cycle = 0;
  44179. this._yoyo = (this.vars.yoyo === true);
  44180. this._dirty = true;
  44181. },
  44182. _tinyNum = 0.0000000001,
  44183. TweenLiteInternals = TweenLite._internals,
  44184. _lazyTweens = TweenLiteInternals.lazyTweens,
  44185. _lazyRender = TweenLiteInternals.lazyRender,
  44186. _globals = _gsScope._gsDefine.globals,
  44187. _easeNone = new Ease(null, null, 1, 0),
  44188. p = TimelineMax.prototype = new TimelineLite();
  44189. p.constructor = TimelineMax;
  44190. p.kill()._gc = false;
  44191. TimelineMax.version = "1.20.2";
  44192. p.invalidate = function() {
  44193. this._yoyo = (this.vars.yoyo === true);
  44194. this._repeat = this.vars.repeat || 0;
  44195. this._repeatDelay = this.vars.repeatDelay || 0;
  44196. this._uncache(true);
  44197. return TimelineLite.prototype.invalidate.call(this);
  44198. };
  44199. p.addCallback = function(callback, position, params, scope) {
  44200. return this.add( TweenLite.delayedCall(0, callback, params, scope), position);
  44201. };
  44202. p.removeCallback = function(callback, position) {
  44203. if (callback) {
  44204. if (position == null) {
  44205. this._kill(null, callback);
  44206. } else {
  44207. var a = this.getTweensOf(callback, false),
  44208. i = a.length,
  44209. time = this._parseTimeOrLabel(position);
  44210. while (--i > -1) {
  44211. if (a[i]._startTime === time) {
  44212. a[i]._enabled(false, false);
  44213. }
  44214. }
  44215. }
  44216. }
  44217. return this;
  44218. };
  44219. p.removePause = function(position) {
  44220. return this.removeCallback(TimelineLite._internals.pauseCallback, position);
  44221. };
  44222. p.tweenTo = function(position, vars) {
  44223. vars = vars || {};
  44224. var copy = {ease:_easeNone, useFrames:this.usesFrames(), immediateRender:false},
  44225. Engine = (vars.repeat && _globals.TweenMax) || TweenLite,
  44226. duration, p, t;
  44227. for (p in vars) {
  44228. copy[p] = vars[p];
  44229. }
  44230. copy.time = this._parseTimeOrLabel(position);
  44231. duration = (Math.abs(Number(copy.time) - this._time) / this._timeScale) || 0.001;
  44232. t = new Engine(this, duration, copy);
  44233. copy.onStart = function() {
  44234. t.target.paused(true);
  44235. if (t.vars.time !== t.target.time() && duration === t.duration()) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all.
  44236. t.duration( Math.abs( t.vars.time - t.target.time()) / t.target._timeScale );
  44237. }
  44238. if (vars.onStart) { //in case the user had an onStart in the vars - we don't want to overwrite it.
  44239. vars.onStart.apply(vars.onStartScope || vars.callbackScope || t, vars.onStartParams || []); //don't use t._callback("onStart") or it'll point to the copy.onStart and we'll get a recursion error.
  44240. }
  44241. };
  44242. return t;
  44243. };
  44244. p.tweenFromTo = function(fromPosition, toPosition, vars) {
  44245. vars = vars || {};
  44246. fromPosition = this._parseTimeOrLabel(fromPosition);
  44247. vars.startAt = {onComplete:this.seek, onCompleteParams:[fromPosition], callbackScope:this};
  44248. vars.immediateRender = (vars.immediateRender !== false);
  44249. var t = this.tweenTo(toPosition, vars);
  44250. return t.duration((Math.abs( t.vars.time - fromPosition) / this._timeScale) || 0.001);
  44251. };
  44252. p.render = function(time, suppressEvents, force) {
  44253. if (this._gc) {
  44254. this._enabled(true, false);
  44255. }
  44256. var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(),
  44257. dur = this._duration,
  44258. prevTime = this._time,
  44259. prevTotalTime = this._totalTime,
  44260. prevStart = this._startTime,
  44261. prevTimeScale = this._timeScale,
  44262. prevRawPrevTime = this._rawPrevTime,
  44263. prevPaused = this._paused,
  44264. prevCycle = this._cycle,
  44265. tween, isComplete, next, callback, internalForce, cycleDuration, pauseTween, curTime;
  44266. if (time >= totalDur - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts.
  44267. if (!this._locked) {
  44268. this._totalTime = totalDur;
  44269. this._cycle = this._repeat;
  44270. }
  44271. if (!this._reversed) if (!this._hasPausedChild()) {
  44272. isComplete = true;
  44273. callback = "onComplete";
  44274. internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
  44275. if (this._duration === 0) if ((time <= 0 && time >= -0.0000001) || prevRawPrevTime < 0 || prevRawPrevTime === _tinyNum) if (prevRawPrevTime !== time && this._first) {
  44276. internalForce = true;
  44277. if (prevRawPrevTime > _tinyNum) {
  44278. callback = "onReverseComplete";
  44279. }
  44280. }
  44281. }
  44282. this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  44283. if (this._yoyo && (this._cycle & 1) !== 0) {
  44284. this._time = time = 0;
  44285. } else {
  44286. this._time = dur;
  44287. time = dur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7. We cannot do less then 0.0001 because the same issue can occur when the duration is extremely large like 999999999999 in which case adding 0.00000001, for example, causes it to act like nothing was added.
  44288. }
  44289. } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
  44290. if (!this._locked) {
  44291. this._totalTime = this._cycle = 0;
  44292. }
  44293. this._time = 0;
  44294. if (prevTime !== 0 || (dur === 0 && prevRawPrevTime !== _tinyNum && (prevRawPrevTime > 0 || (time < 0 && prevRawPrevTime >= 0)) && !this._locked)) { //edge case for checking time < 0 && prevRawPrevTime >= 0: a zero-duration fromTo() tween inside a zero-duration timeline (yeah, very rare)
  44295. callback = "onReverseComplete";
  44296. isComplete = this._reversed;
  44297. }
  44298. if (time < 0) {
  44299. this._active = false;
  44300. if (this._timeline.autoRemoveChildren && this._reversed) {
  44301. internalForce = isComplete = true;
  44302. callback = "onReverseComplete";
  44303. } else if (prevRawPrevTime >= 0 && this._first) { //when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state.
  44304. internalForce = true;
  44305. }
  44306. this._rawPrevTime = time;
  44307. } else {
  44308. this._rawPrevTime = (dur || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  44309. if (time === 0 && isComplete) { //if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good).
  44310. tween = this._first;
  44311. while (tween && tween._startTime === 0) {
  44312. if (!tween._duration) {
  44313. isComplete = false;
  44314. }
  44315. tween = tween._next;
  44316. }
  44317. }
  44318. time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
  44319. if (!this._initted) {
  44320. internalForce = true;
  44321. }
  44322. }
  44323. } else {
  44324. if (dur === 0 && prevRawPrevTime < 0) { //without this, zero-duration repeating timelines (like with a simple callback nested at the very beginning and a repeatDelay) wouldn't render the first time through.
  44325. internalForce = true;
  44326. }
  44327. this._time = this._rawPrevTime = time;
  44328. if (!this._locked) {
  44329. this._totalTime = time;
  44330. if (this._repeat !== 0) {
  44331. cycleDuration = dur + this._repeatDelay;
  44332. this._cycle = (this._totalTime / cycleDuration) >> 0; //originally _totalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but it gets reported as 0.79999999!)
  44333. if (this._cycle !== 0) if (this._cycle === this._totalTime / cycleDuration && prevTotalTime <= time) {
  44334. this._cycle--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning)
  44335. }
  44336. this._time = this._totalTime - (this._cycle * cycleDuration);
  44337. if (this._yoyo) if ((this._cycle & 1) !== 0) {
  44338. this._time = dur - this._time;
  44339. }
  44340. if (this._time > dur) {
  44341. this._time = dur;
  44342. time = dur + 0.0001; //to avoid occasional floating point rounding error
  44343. } else if (this._time < 0) {
  44344. this._time = time = 0;
  44345. } else {
  44346. time = this._time;
  44347. }
  44348. }
  44349. }
  44350. if (this._hasPause && !this._forcingPlayhead && !suppressEvents) {
  44351. time = this._time;
  44352. if (time >= prevTime || (this._repeat && prevCycle !== this._cycle)) {
  44353. tween = this._first;
  44354. while (tween && tween._startTime <= time && !pauseTween) {
  44355. if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) {
  44356. pauseTween = tween;
  44357. }
  44358. tween = tween._next;
  44359. }
  44360. } else {
  44361. tween = this._last;
  44362. while (tween && tween._startTime >= time && !pauseTween) {
  44363. if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) {
  44364. pauseTween = tween;
  44365. }
  44366. tween = tween._prev;
  44367. }
  44368. }
  44369. if (pauseTween && pauseTween._startTime < dur) {
  44370. this._time = time = pauseTween._startTime;
  44371. this._totalTime = time + (this._cycle * (this._totalDuration + this._repeatDelay));
  44372. }
  44373. }
  44374. }
  44375. if (this._cycle !== prevCycle) if (!this._locked) {
  44376. /*
  44377. make sure children at the end/beginning of the timeline are rendered properly. If, for example,
  44378. a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which
  44379. would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there
  44380. could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So
  44381. we need to push the timeline to the end (and/or beginning depending on its yoyo value). Also we must
  44382. ensure that zero-duration tweens at the very beginning or end of the TimelineMax work.
  44383. */
  44384. var backwards = (this._yoyo && (prevCycle & 1) !== 0),
  44385. wrap = (backwards === (this._yoyo && (this._cycle & 1) !== 0)),
  44386. recTotalTime = this._totalTime,
  44387. recCycle = this._cycle,
  44388. recRawPrevTime = this._rawPrevTime,
  44389. recTime = this._time;
  44390. this._totalTime = prevCycle * dur;
  44391. if (this._cycle < prevCycle) {
  44392. backwards = !backwards;
  44393. } else {
  44394. this._totalTime += dur;
  44395. }
  44396. this._time = prevTime; //temporarily revert _time so that render() renders the children in the correct order. Without this, tweens won't rewind correctly. We could arhictect things in a "cleaner" way by splitting out the rendering queue into a separate method but for performance reasons, we kept it all inside this method.
  44397. this._rawPrevTime = (dur === 0) ? prevRawPrevTime - 0.0001 : prevRawPrevTime;
  44398. this._cycle = prevCycle;
  44399. this._locked = true; //prevents changes to totalTime and skips repeat/yoyo behavior when we recursively call render()
  44400. prevTime = (backwards) ? 0 : dur;
  44401. this.render(prevTime, suppressEvents, (dur === 0));
  44402. if (!suppressEvents) if (!this._gc) {
  44403. if (this.vars.onRepeat) {
  44404. this._cycle = recCycle; //in case the onRepeat alters the playhead or invalidates(), we shouldn't stay locked or use the previous cycle.
  44405. this._locked = false;
  44406. this._callback("onRepeat");
  44407. }
  44408. }
  44409. if (prevTime !== this._time) { //in case there's a callback like onComplete in a nested tween/timeline that changes the playhead position, like via seek(), we should just abort.
  44410. return;
  44411. }
  44412. if (wrap) {
  44413. this._cycle = prevCycle; //if there's an onRepeat, we reverted this above, so make sure it's set properly again. We also unlocked in that scenario, so reset that too.
  44414. this._locked = true;
  44415. prevTime = (backwards) ? dur + 0.0001 : -0.0001;
  44416. this.render(prevTime, true, false);
  44417. }
  44418. this._locked = false;
  44419. if (this._paused && !prevPaused) { //if the render() triggered callback that paused this timeline, we should abort (very rare, but possible)
  44420. return;
  44421. }
  44422. this._time = recTime;
  44423. this._totalTime = recTotalTime;
  44424. this._cycle = recCycle;
  44425. this._rawPrevTime = recRawPrevTime;
  44426. }
  44427. if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) {
  44428. if (prevTotalTime !== this._totalTime) if (this._onUpdate) if (!suppressEvents) { //so that onUpdate fires even during the repeatDelay - as long as the totalTime changed, we should trigger onUpdate.
  44429. this._callback("onUpdate");
  44430. }
  44431. return;
  44432. } else if (!this._initted) {
  44433. this._initted = true;
  44434. }
  44435. if (!this._active) if (!this._paused && this._totalTime !== prevTotalTime && time > 0) {
  44436. this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
  44437. }
  44438. if (prevTotalTime === 0) if (this.vars.onStart) if (this._totalTime !== 0 || !this._totalDuration) if (!suppressEvents) {
  44439. this._callback("onStart");
  44440. }
  44441. curTime = this._time;
  44442. if (curTime >= prevTime) {
  44443. tween = this._first;
  44444. while (tween) {
  44445. next = tween._next; //record it here because the value could change after rendering...
  44446. if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
  44447. break;
  44448. } else if (tween._active || (tween._startTime <= this._time && !tween._paused && !tween._gc)) {
  44449. if (pauseTween === tween) {
  44450. this.pause();
  44451. }
  44452. if (!tween._reversed) {
  44453. tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
  44454. } else {
  44455. tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
  44456. }
  44457. }
  44458. tween = next;
  44459. }
  44460. } else {
  44461. tween = this._last;
  44462. while (tween) {
  44463. next = tween._prev; //record it here because the value could change after rendering...
  44464. if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
  44465. break;
  44466. } else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) {
  44467. if (pauseTween === tween) {
  44468. pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse.
  44469. while (pauseTween && pauseTween.endTime() > this._time) {
  44470. pauseTween.render( (pauseTween._reversed ? pauseTween.totalDuration() - ((time - pauseTween._startTime) * pauseTween._timeScale) : (time - pauseTween._startTime) * pauseTween._timeScale), suppressEvents, force);
  44471. pauseTween = pauseTween._prev;
  44472. }
  44473. pauseTween = null;
  44474. this.pause();
  44475. }
  44476. if (!tween._reversed) {
  44477. tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
  44478. } else {
  44479. tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
  44480. }
  44481. }
  44482. tween = next;
  44483. }
  44484. }
  44485. if (this._onUpdate) if (!suppressEvents) {
  44486. if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
  44487. _lazyRender();
  44488. }
  44489. this._callback("onUpdate");
  44490. }
  44491. if (callback) if (!this._locked) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
  44492. if (isComplete) {
  44493. if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values.
  44494. _lazyRender();
  44495. }
  44496. if (this._timeline.autoRemoveChildren) {
  44497. this._enabled(false, false);
  44498. }
  44499. this._active = false;
  44500. }
  44501. if (!suppressEvents && this.vars[callback]) {
  44502. this._callback(callback);
  44503. }
  44504. }
  44505. };
  44506. p.getActive = function(nested, tweens, timelines) {
  44507. if (nested == null) {
  44508. nested = true;
  44509. }
  44510. if (tweens == null) {
  44511. tweens = true;
  44512. }
  44513. if (timelines == null) {
  44514. timelines = false;
  44515. }
  44516. var a = [],
  44517. all = this.getChildren(nested, tweens, timelines),
  44518. cnt = 0,
  44519. l = all.length,
  44520. i, tween;
  44521. for (i = 0; i < l; i++) {
  44522. tween = all[i];
  44523. if (tween.isActive()) {
  44524. a[cnt++] = tween;
  44525. }
  44526. }
  44527. return a;
  44528. };
  44529. p.getLabelAfter = function(time) {
  44530. if (!time) if (time !== 0) { //faster than isNan()
  44531. time = this._time;
  44532. }
  44533. var labels = this.getLabelsArray(),
  44534. l = labels.length,
  44535. i;
  44536. for (i = 0; i < l; i++) {
  44537. if (labels[i].time > time) {
  44538. return labels[i].name;
  44539. }
  44540. }
  44541. return null;
  44542. };
  44543. p.getLabelBefore = function(time) {
  44544. if (time == null) {
  44545. time = this._time;
  44546. }
  44547. var labels = this.getLabelsArray(),
  44548. i = labels.length;
  44549. while (--i > -1) {
  44550. if (labels[i].time < time) {
  44551. return labels[i].name;
  44552. }
  44553. }
  44554. return null;
  44555. };
  44556. p.getLabelsArray = function() {
  44557. var a = [],
  44558. cnt = 0,
  44559. p;
  44560. for (p in this._labels) {
  44561. a[cnt++] = {time:this._labels[p], name:p};
  44562. }
  44563. a.sort(function(a,b) {
  44564. return a.time - b.time;
  44565. });
  44566. return a;
  44567. };
  44568. p.invalidate = function() {
  44569. this._locked = false; //unlock and set cycle in case invalidate() is called from inside an onRepeat
  44570. return TimelineLite.prototype.invalidate.call(this);
  44571. };
  44572. //---- GETTERS / SETTERS -------------------------------------------------------------------------------------------------------
  44573. p.progress = function(value, suppressEvents) {
  44574. return (!arguments.length) ? (this._time / this.duration()) || 0 : this.totalTime( this.duration() * ((this._yoyo && (this._cycle & 1) !== 0) ? 1 - value : value) + (this._cycle * (this._duration + this._repeatDelay)), suppressEvents);
  44575. };
  44576. p.totalProgress = function(value, suppressEvents) {
  44577. return (!arguments.length) ? (this._totalTime / this.totalDuration()) || 0 : this.totalTime( this.totalDuration() * value, suppressEvents);
  44578. };
  44579. p.totalDuration = function(value) {
  44580. if (!arguments.length) {
  44581. if (this._dirty) {
  44582. TimelineLite.prototype.totalDuration.call(this); //just forces refresh
  44583. //Instead of Infinity, we use 999999999999 so that we can accommodate reverses.
  44584. this._totalDuration = (this._repeat === -1) ? 999999999999 : this._duration * (this._repeat + 1) + (this._repeatDelay * this._repeat);
  44585. }
  44586. return this._totalDuration;
  44587. }
  44588. return (this._repeat === -1 || !value) ? this : this.timeScale( this.totalDuration() / value );
  44589. };
  44590. p.time = function(value, suppressEvents) {
  44591. if (!arguments.length) {
  44592. return this._time;
  44593. }
  44594. if (this._dirty) {
  44595. this.totalDuration();
  44596. }
  44597. if (value > this._duration) {
  44598. value = this._duration;
  44599. }
  44600. if (this._yoyo && (this._cycle & 1) !== 0) {
  44601. value = (this._duration - value) + (this._cycle * (this._duration + this._repeatDelay));
  44602. } else if (this._repeat !== 0) {
  44603. value += this._cycle * (this._duration + this._repeatDelay);
  44604. }
  44605. return this.totalTime(value, suppressEvents);
  44606. };
  44607. p.repeat = function(value) {
  44608. if (!arguments.length) {
  44609. return this._repeat;
  44610. }
  44611. this._repeat = value;
  44612. return this._uncache(true);
  44613. };
  44614. p.repeatDelay = function(value) {
  44615. if (!arguments.length) {
  44616. return this._repeatDelay;
  44617. }
  44618. this._repeatDelay = value;
  44619. return this._uncache(true);
  44620. };
  44621. p.yoyo = function(value) {
  44622. if (!arguments.length) {
  44623. return this._yoyo;
  44624. }
  44625. this._yoyo = value;
  44626. return this;
  44627. };
  44628. p.currentLabel = function(value) {
  44629. if (!arguments.length) {
  44630. return this.getLabelBefore(this._time + 0.00000001);
  44631. }
  44632. return this.seek(value, true);
  44633. };
  44634. return TimelineMax;
  44635. }, true);
  44636. /*
  44637. * ----------------------------------------------------------------
  44638. * BezierPlugin
  44639. * ----------------------------------------------------------------
  44640. */
  44641. (function() {
  44642. var _RAD2DEG = 180 / Math.PI,
  44643. _r1 = [],
  44644. _r2 = [],
  44645. _r3 = [],
  44646. _corProps = {},
  44647. _globals = _gsScope._gsDefine.globals,
  44648. Segment = function(a, b, c, d) {
  44649. if (c === d) { //if c and d match, the final autoRotate value could lock at -90 degrees, so differentiate them slightly.
  44650. c = d - (d - b) / 1000000;
  44651. }
  44652. if (a === b) { //if a and b match, the starting autoRotate value could lock at -90 degrees, so differentiate them slightly.
  44653. b = a + (c - a) / 1000000;
  44654. }
  44655. this.a = a;
  44656. this.b = b;
  44657. this.c = c;
  44658. this.d = d;
  44659. this.da = d - a;
  44660. this.ca = c - a;
  44661. this.ba = b - a;
  44662. },
  44663. _correlate = ",x,y,z,left,top,right,bottom,marginTop,marginLeft,marginRight,marginBottom,paddingLeft,paddingTop,paddingRight,paddingBottom,backgroundPosition,backgroundPosition_y,",
  44664. cubicToQuadratic = function(a, b, c, d) {
  44665. var q1 = {a:a},
  44666. q2 = {},
  44667. q3 = {},
  44668. q4 = {c:d},
  44669. mab = (a + b) / 2,
  44670. mbc = (b + c) / 2,
  44671. mcd = (c + d) / 2,
  44672. mabc = (mab + mbc) / 2,
  44673. mbcd = (mbc + mcd) / 2,
  44674. m8 = (mbcd - mabc) / 8;
  44675. q1.b = mab + (a - mab) / 4;
  44676. q2.b = mabc + m8;
  44677. q1.c = q2.a = (q1.b + q2.b) / 2;
  44678. q2.c = q3.a = (mabc + mbcd) / 2;
  44679. q3.b = mbcd - m8;
  44680. q4.b = mcd + (d - mcd) / 4;
  44681. q3.c = q4.a = (q3.b + q4.b) / 2;
  44682. return [q1, q2, q3, q4];
  44683. },
  44684. _calculateControlPoints = function(a, curviness, quad, basic, correlate) {
  44685. var l = a.length - 1,
  44686. ii = 0,
  44687. cp1 = a[0].a,
  44688. i, p1, p2, p3, seg, m1, m2, mm, cp2, qb, r1, r2, tl;
  44689. for (i = 0; i < l; i++) {
  44690. seg = a[ii];
  44691. p1 = seg.a;
  44692. p2 = seg.d;
  44693. p3 = a[ii+1].d;
  44694. if (correlate) {
  44695. r1 = _r1[i];
  44696. r2 = _r2[i];
  44697. tl = ((r2 + r1) * curviness * 0.25) / (basic ? 0.5 : _r3[i] || 0.5);
  44698. m1 = p2 - (p2 - p1) * (basic ? curviness * 0.5 : (r1 !== 0 ? tl / r1 : 0));
  44699. m2 = p2 + (p3 - p2) * (basic ? curviness * 0.5 : (r2 !== 0 ? tl / r2 : 0));
  44700. mm = p2 - (m1 + (((m2 - m1) * ((r1 * 3 / (r1 + r2)) + 0.5) / 4) || 0));
  44701. } else {
  44702. m1 = p2 - (p2 - p1) * curviness * 0.5;
  44703. m2 = p2 + (p3 - p2) * curviness * 0.5;
  44704. mm = p2 - (m1 + m2) / 2;
  44705. }
  44706. m1 += mm;
  44707. m2 += mm;
  44708. seg.c = cp2 = m1;
  44709. if (i !== 0) {
  44710. seg.b = cp1;
  44711. } else {
  44712. seg.b = cp1 = seg.a + (seg.c - seg.a) * 0.6; //instead of placing b on a exactly, we move it inline with c so that if the user specifies an ease like Back.easeIn or Elastic.easeIn which goes BEYOND the beginning, it will do so smoothly.
  44713. }
  44714. seg.da = p2 - p1;
  44715. seg.ca = cp2 - p1;
  44716. seg.ba = cp1 - p1;
  44717. if (quad) {
  44718. qb = cubicToQuadratic(p1, cp1, cp2, p2);
  44719. a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]);
  44720. ii += 4;
  44721. } else {
  44722. ii++;
  44723. }
  44724. cp1 = m2;
  44725. }
  44726. seg = a[ii];
  44727. seg.b = cp1;
  44728. seg.c = cp1 + (seg.d - cp1) * 0.4; //instead of placing c on d exactly, we move it inline with b so that if the user specifies an ease like Back.easeOut or Elastic.easeOut which goes BEYOND the end, it will do so smoothly.
  44729. seg.da = seg.d - seg.a;
  44730. seg.ca = seg.c - seg.a;
  44731. seg.ba = cp1 - seg.a;
  44732. if (quad) {
  44733. qb = cubicToQuadratic(seg.a, cp1, seg.c, seg.d);
  44734. a.splice(ii, 1, qb[0], qb[1], qb[2], qb[3]);
  44735. }
  44736. },
  44737. _parseAnchors = function(values, p, correlate, prepend) {
  44738. var a = [],
  44739. l, i, p1, p2, p3, tmp;
  44740. if (prepend) {
  44741. values = [prepend].concat(values);
  44742. i = values.length;
  44743. while (--i > -1) {
  44744. if (typeof( (tmp = values[i][p]) ) === "string") if (tmp.charAt(1) === "=") {
  44745. values[i][p] = prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)); //accommodate relative values. Do it inline instead of breaking it out into a function for speed reasons
  44746. }
  44747. }
  44748. }
  44749. l = values.length - 2;
  44750. if (l < 0) {
  44751. a[0] = new Segment(values[0][p], 0, 0, values[0][p]);
  44752. return a;
  44753. }
  44754. for (i = 0; i < l; i++) {
  44755. p1 = values[i][p];
  44756. p2 = values[i+1][p];
  44757. a[i] = new Segment(p1, 0, 0, p2);
  44758. if (correlate) {
  44759. p3 = values[i+2][p];
  44760. _r1[i] = (_r1[i] || 0) + (p2 - p1) * (p2 - p1);
  44761. _r2[i] = (_r2[i] || 0) + (p3 - p2) * (p3 - p2);
  44762. }
  44763. }
  44764. a[i] = new Segment(values[i][p], 0, 0, values[i+1][p]);
  44765. return a;
  44766. },
  44767. bezierThrough = function(values, curviness, quadratic, basic, correlate, prepend) {
  44768. var obj = {},
  44769. props = [],
  44770. first = prepend || values[0],
  44771. i, p, a, j, r, l, seamless, last;
  44772. correlate = (typeof(correlate) === "string") ? ","+correlate+"," : _correlate;
  44773. if (curviness == null) {
  44774. curviness = 1;
  44775. }
  44776. for (p in values[0]) {
  44777. props.push(p);
  44778. }
  44779. //check to see if the last and first values are identical (well, within 0.05). If so, make seamless by appending the second element to the very end of the values array and the 2nd-to-last element to the very beginning (we'll remove those segments later)
  44780. if (values.length > 1) {
  44781. last = values[values.length - 1];
  44782. seamless = true;
  44783. i = props.length;
  44784. while (--i > -1) {
  44785. p = props[i];
  44786. if (Math.abs(first[p] - last[p]) > 0.05) { //build in a tolerance of +/-0.05 to accommodate rounding errors.
  44787. seamless = false;
  44788. break;
  44789. }
  44790. }
  44791. if (seamless) {
  44792. values = values.concat(); //duplicate the array to avoid contaminating the original which the user may be reusing for other tweens
  44793. if (prepend) {
  44794. values.unshift(prepend);
  44795. }
  44796. values.push(values[1]);
  44797. prepend = values[values.length - 3];
  44798. }
  44799. }
  44800. _r1.length = _r2.length = _r3.length = 0;
  44801. i = props.length;
  44802. while (--i > -1) {
  44803. p = props[i];
  44804. _corProps[p] = (correlate.indexOf(","+p+",") !== -1);
  44805. obj[p] = _parseAnchors(values, p, _corProps[p], prepend);
  44806. }
  44807. i = _r1.length;
  44808. while (--i > -1) {
  44809. _r1[i] = Math.sqrt(_r1[i]);
  44810. _r2[i] = Math.sqrt(_r2[i]);
  44811. }
  44812. if (!basic) {
  44813. i = props.length;
  44814. while (--i > -1) {
  44815. if (_corProps[p]) {
  44816. a = obj[props[i]];
  44817. l = a.length - 1;
  44818. for (j = 0; j < l; j++) {
  44819. r = (a[j+1].da / _r2[j] + a[j].da / _r1[j]) || 0;
  44820. _r3[j] = (_r3[j] || 0) + r * r;
  44821. }
  44822. }
  44823. }
  44824. i = _r3.length;
  44825. while (--i > -1) {
  44826. _r3[i] = Math.sqrt(_r3[i]);
  44827. }
  44828. }
  44829. i = props.length;
  44830. j = quadratic ? 4 : 1;
  44831. while (--i > -1) {
  44832. p = props[i];
  44833. a = obj[p];
  44834. _calculateControlPoints(a, curviness, quadratic, basic, _corProps[p]); //this method requires that _parseAnchors() and _setSegmentRatios() ran first so that _r1, _r2, and _r3 values are populated for all properties
  44835. if (seamless) {
  44836. a.splice(0, j);
  44837. a.splice(a.length - j, j);
  44838. }
  44839. }
  44840. return obj;
  44841. },
  44842. _parseBezierData = function(values, type, prepend) {
  44843. type = type || "soft";
  44844. var obj = {},
  44845. inc = (type === "cubic") ? 3 : 2,
  44846. soft = (type === "soft"),
  44847. props = [],
  44848. a, b, c, d, cur, i, j, l, p, cnt, tmp;
  44849. if (soft && prepend) {
  44850. values = [prepend].concat(values);
  44851. }
  44852. if (values == null || values.length < inc + 1) { throw "invalid Bezier data"; }
  44853. for (p in values[0]) {
  44854. props.push(p);
  44855. }
  44856. i = props.length;
  44857. while (--i > -1) {
  44858. p = props[i];
  44859. obj[p] = cur = [];
  44860. cnt = 0;
  44861. l = values.length;
  44862. for (j = 0; j < l; j++) {
  44863. a = (prepend == null) ? values[j][p] : (typeof( (tmp = values[j][p]) ) === "string" && tmp.charAt(1) === "=") ? prepend[p] + Number(tmp.charAt(0) + tmp.substr(2)) : Number(tmp);
  44864. if (soft) if (j > 1) if (j < l - 1) {
  44865. cur[cnt++] = (a + cur[cnt-2]) / 2;
  44866. }
  44867. cur[cnt++] = a;
  44868. }
  44869. l = cnt - inc + 1;
  44870. cnt = 0;
  44871. for (j = 0; j < l; j += inc) {
  44872. a = cur[j];
  44873. b = cur[j+1];
  44874. c = cur[j+2];
  44875. d = (inc === 2) ? 0 : cur[j+3];
  44876. cur[cnt++] = tmp = (inc === 3) ? new Segment(a, b, c, d) : new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c);
  44877. }
  44878. cur.length = cnt;
  44879. }
  44880. return obj;
  44881. },
  44882. _addCubicLengths = function(a, steps, resolution) {
  44883. var inc = 1 / resolution,
  44884. j = a.length,
  44885. d, d1, s, da, ca, ba, p, i, inv, bez, index;
  44886. while (--j > -1) {
  44887. bez = a[j];
  44888. s = bez.a;
  44889. da = bez.d - s;
  44890. ca = bez.c - s;
  44891. ba = bez.b - s;
  44892. d = d1 = 0;
  44893. for (i = 1; i <= resolution; i++) {
  44894. p = inc * i;
  44895. inv = 1 - p;
  44896. d = d1 - (d1 = (p * p * da + 3 * inv * (p * ca + inv * ba)) * p);
  44897. index = j * resolution + i - 1;
  44898. steps[index] = (steps[index] || 0) + d * d;
  44899. }
  44900. }
  44901. },
  44902. _parseLengthData = function(obj, resolution) {
  44903. resolution = resolution >> 0 || 6;
  44904. var a = [],
  44905. lengths = [],
  44906. d = 0,
  44907. total = 0,
  44908. threshold = resolution - 1,
  44909. segments = [],
  44910. curLS = [], //current length segments array
  44911. p, i, l, index;
  44912. for (p in obj) {
  44913. _addCubicLengths(obj[p], a, resolution);
  44914. }
  44915. l = a.length;
  44916. for (i = 0; i < l; i++) {
  44917. d += Math.sqrt(a[i]);
  44918. index = i % resolution;
  44919. curLS[index] = d;
  44920. if (index === threshold) {
  44921. total += d;
  44922. index = (i / resolution) >> 0;
  44923. segments[index] = curLS;
  44924. lengths[index] = total;
  44925. d = 0;
  44926. curLS = [];
  44927. }
  44928. }
  44929. return {length:total, lengths:lengths, segments:segments};
  44930. },
  44931. BezierPlugin = _gsScope._gsDefine.plugin({
  44932. propName: "bezier",
  44933. priority: -1,
  44934. version: "1.3.8",
  44935. API: 2,
  44936. global:true,
  44937. //gets called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
  44938. init: function(target, vars, tween) {
  44939. this._target = target;
  44940. if (vars instanceof Array) {
  44941. vars = {values:vars};
  44942. }
  44943. this._func = {};
  44944. this._mod = {};
  44945. this._props = [];
  44946. this._timeRes = (vars.timeResolution == null) ? 6 : parseInt(vars.timeResolution, 10);
  44947. var values = vars.values || [],
  44948. first = {},
  44949. second = values[0],
  44950. autoRotate = vars.autoRotate || tween.vars.orientToBezier,
  44951. p, isFunc, i, j, prepend;
  44952. this._autoRotate = autoRotate ? (autoRotate instanceof Array) ? autoRotate : [["x","y","rotation",((autoRotate === true) ? 0 : Number(autoRotate) || 0)]] : null;
  44953. for (p in second) {
  44954. this._props.push(p);
  44955. }
  44956. i = this._props.length;
  44957. while (--i > -1) {
  44958. p = this._props[i];
  44959. this._overwriteProps.push(p);
  44960. isFunc = this._func[p] = (typeof(target[p]) === "function");
  44961. first[p] = (!isFunc) ? parseFloat(target[p]) : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ]();
  44962. if (!prepend) if (first[p] !== values[0][p]) {
  44963. prepend = first;
  44964. }
  44965. }
  44966. this._beziers = (vars.type !== "cubic" && vars.type !== "quadratic" && vars.type !== "soft") ? bezierThrough(values, isNaN(vars.curviness) ? 1 : vars.curviness, false, (vars.type === "thruBasic"), vars.correlate, prepend) : _parseBezierData(values, vars.type, first);
  44967. this._segCount = this._beziers[p].length;
  44968. if (this._timeRes) {
  44969. var ld = _parseLengthData(this._beziers, this._timeRes);
  44970. this._length = ld.length;
  44971. this._lengths = ld.lengths;
  44972. this._segments = ld.segments;
  44973. this._l1 = this._li = this._s1 = this._si = 0;
  44974. this._l2 = this._lengths[0];
  44975. this._curSeg = this._segments[0];
  44976. this._s2 = this._curSeg[0];
  44977. this._prec = 1 / this._curSeg.length;
  44978. }
  44979. if ((autoRotate = this._autoRotate)) {
  44980. this._initialRotations = [];
  44981. if (!(autoRotate[0] instanceof Array)) {
  44982. this._autoRotate = autoRotate = [autoRotate];
  44983. }
  44984. i = autoRotate.length;
  44985. while (--i > -1) {
  44986. for (j = 0; j < 3; j++) {
  44987. p = autoRotate[i][j];
  44988. this._func[p] = (typeof(target[p]) === "function") ? target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ] : false;
  44989. }
  44990. p = autoRotate[i][2];
  44991. this._initialRotations[i] = (this._func[p] ? this._func[p].call(this._target) : this._target[p]) || 0;
  44992. this._overwriteProps.push(p);
  44993. }
  44994. }
  44995. this._startRatio = tween.vars.runBackwards ? 1 : 0; //we determine the starting ratio when the tween inits which is always 0 unless the tween has runBackwards:true (indicating it's a from() tween) in which case it's 1.
  44996. return true;
  44997. },
  44998. //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.)
  44999. set: function(v) {
  45000. var segments = this._segCount,
  45001. func = this._func,
  45002. target = this._target,
  45003. notStart = (v !== this._startRatio),
  45004. curIndex, inv, i, p, b, t, val, l, lengths, curSeg;
  45005. if (!this._timeRes) {
  45006. curIndex = (v < 0) ? 0 : (v >= 1) ? segments - 1 : (segments * v) >> 0;
  45007. t = (v - (curIndex * (1 / segments))) * segments;
  45008. } else {
  45009. lengths = this._lengths;
  45010. curSeg = this._curSeg;
  45011. v *= this._length;
  45012. i = this._li;
  45013. //find the appropriate segment (if the currently cached one isn't correct)
  45014. if (v > this._l2 && i < segments - 1) {
  45015. l = segments - 1;
  45016. while (i < l && (this._l2 = lengths[++i]) <= v) { }
  45017. this._l1 = lengths[i-1];
  45018. this._li = i;
  45019. this._curSeg = curSeg = this._segments[i];
  45020. this._s2 = curSeg[(this._s1 = this._si = 0)];
  45021. } else if (v < this._l1 && i > 0) {
  45022. while (i > 0 && (this._l1 = lengths[--i]) >= v) { }
  45023. if (i === 0 && v < this._l1) {
  45024. this._l1 = 0;
  45025. } else {
  45026. i++;
  45027. }
  45028. this._l2 = lengths[i];
  45029. this._li = i;
  45030. this._curSeg = curSeg = this._segments[i];
  45031. this._s1 = curSeg[(this._si = curSeg.length - 1) - 1] || 0;
  45032. this._s2 = curSeg[this._si];
  45033. }
  45034. curIndex = i;
  45035. //now find the appropriate sub-segment (we split it into the number of pieces that was defined by "precision" and measured each one)
  45036. v -= this._l1;
  45037. i = this._si;
  45038. if (v > this._s2 && i < curSeg.length - 1) {
  45039. l = curSeg.length - 1;
  45040. while (i < l && (this._s2 = curSeg[++i]) <= v) { }
  45041. this._s1 = curSeg[i-1];
  45042. this._si = i;
  45043. } else if (v < this._s1 && i > 0) {
  45044. while (i > 0 && (this._s1 = curSeg[--i]) >= v) { }
  45045. if (i === 0 && v < this._s1) {
  45046. this._s1 = 0;
  45047. } else {
  45048. i++;
  45049. }
  45050. this._s2 = curSeg[i];
  45051. this._si = i;
  45052. }
  45053. t = ((i + (v - this._s1) / (this._s2 - this._s1)) * this._prec) || 0;
  45054. }
  45055. inv = 1 - t;
  45056. i = this._props.length;
  45057. while (--i > -1) {
  45058. p = this._props[i];
  45059. b = this._beziers[p][curIndex];
  45060. val = (t * t * b.da + 3 * inv * (t * b.ca + inv * b.ba)) * t + b.a;
  45061. if (this._mod[p]) {
  45062. val = this._mod[p](val, target);
  45063. }
  45064. if (func[p]) {
  45065. target[p](val);
  45066. } else {
  45067. target[p] = val;
  45068. }
  45069. }
  45070. if (this._autoRotate) {
  45071. var ar = this._autoRotate,
  45072. b2, x1, y1, x2, y2, add, conv;
  45073. i = ar.length;
  45074. while (--i > -1) {
  45075. p = ar[i][2];
  45076. add = ar[i][3] || 0;
  45077. conv = (ar[i][4] === true) ? 1 : _RAD2DEG;
  45078. b = this._beziers[ar[i][0]];
  45079. b2 = this._beziers[ar[i][1]];
  45080. if (b && b2) { //in case one of the properties got overwritten.
  45081. b = b[curIndex];
  45082. b2 = b2[curIndex];
  45083. x1 = b.a + (b.b - b.a) * t;
  45084. x2 = b.b + (b.c - b.b) * t;
  45085. x1 += (x2 - x1) * t;
  45086. x2 += ((b.c + (b.d - b.c) * t) - x2) * t;
  45087. y1 = b2.a + (b2.b - b2.a) * t;
  45088. y2 = b2.b + (b2.c - b2.b) * t;
  45089. y1 += (y2 - y1) * t;
  45090. y2 += ((b2.c + (b2.d - b2.c) * t) - y2) * t;
  45091. val = notStart ? Math.atan2(y2 - y1, x2 - x1) * conv + add : this._initialRotations[i];
  45092. if (this._mod[p]) {
  45093. val = this._mod[p](val, target); //for modProps
  45094. }
  45095. if (func[p]) {
  45096. target[p](val);
  45097. } else {
  45098. target[p] = val;
  45099. }
  45100. }
  45101. }
  45102. }
  45103. }
  45104. }),
  45105. p = BezierPlugin.prototype;
  45106. BezierPlugin.bezierThrough = bezierThrough;
  45107. BezierPlugin.cubicToQuadratic = cubicToQuadratic;
  45108. BezierPlugin._autoCSS = true; //indicates that this plugin can be inserted into the "css" object using the autoCSS feature of TweenLite
  45109. BezierPlugin.quadraticToCubic = function(a, b, c) {
  45110. return new Segment(a, (2 * b + a) / 3, (2 * b + c) / 3, c);
  45111. };
  45112. BezierPlugin._cssRegister = function() {
  45113. var CSSPlugin = _globals.CSSPlugin;
  45114. if (!CSSPlugin) {
  45115. return;
  45116. }
  45117. var _internals = CSSPlugin._internals,
  45118. _parseToProxy = _internals._parseToProxy,
  45119. _setPluginRatio = _internals._setPluginRatio,
  45120. CSSPropTween = _internals.CSSPropTween;
  45121. _internals._registerComplexSpecialProp("bezier", {parser:function(t, e, prop, cssp, pt, plugin) {
  45122. if (e instanceof Array) {
  45123. e = {values:e};
  45124. }
  45125. plugin = new BezierPlugin();
  45126. var values = e.values,
  45127. l = values.length - 1,
  45128. pluginValues = [],
  45129. v = {},
  45130. i, p, data;
  45131. if (l < 0) {
  45132. return pt;
  45133. }
  45134. for (i = 0; i <= l; i++) {
  45135. data = _parseToProxy(t, values[i], cssp, pt, plugin, (l !== i));
  45136. pluginValues[i] = data.end;
  45137. }
  45138. for (p in e) {
  45139. v[p] = e[p]; //duplicate the vars object because we need to alter some things which would cause problems if the user plans to reuse the same vars object for another tween.
  45140. }
  45141. v.values = pluginValues;
  45142. pt = new CSSPropTween(t, "bezier", 0, 0, data.pt, 2);
  45143. pt.data = data;
  45144. pt.plugin = plugin;
  45145. pt.setRatio = _setPluginRatio;
  45146. if (v.autoRotate === 0) {
  45147. v.autoRotate = true;
  45148. }
  45149. if (v.autoRotate && !(v.autoRotate instanceof Array)) {
  45150. i = (v.autoRotate === true) ? 0 : Number(v.autoRotate);
  45151. v.autoRotate = (data.end.left != null) ? [["left","top","rotation",i,false]] : (data.end.x != null) ? [["x","y","rotation",i,false]] : false;
  45152. }
  45153. if (v.autoRotate) {
  45154. if (!cssp._transform) {
  45155. cssp._enableTransforms(false);
  45156. }
  45157. data.autoRotate = cssp._target._gsTransform;
  45158. data.proxy.rotation = data.autoRotate.rotation || 0;
  45159. cssp._overwriteProps.push("rotation");
  45160. }
  45161. plugin._onInitTween(data.proxy, v, cssp._tween);
  45162. return pt;
  45163. }});
  45164. };
  45165. p._mod = function(lookup) {
  45166. var op = this._overwriteProps,
  45167. i = op.length,
  45168. val;
  45169. while (--i > -1) {
  45170. val = lookup[op[i]];
  45171. if (val && typeof(val) === "function") {
  45172. this._mod[op[i]] = val;
  45173. }
  45174. }
  45175. };
  45176. p._kill = function(lookup) {
  45177. var a = this._props,
  45178. p, i;
  45179. for (p in this._beziers) {
  45180. if (p in lookup) {
  45181. delete this._beziers[p];
  45182. delete this._func[p];
  45183. i = a.length;
  45184. while (--i > -1) {
  45185. if (a[i] === p) {
  45186. a.splice(i, 1);
  45187. }
  45188. }
  45189. }
  45190. }
  45191. a = this._autoRotate;
  45192. if (a) {
  45193. i = a.length;
  45194. while (--i > -1) {
  45195. if (lookup[a[i][2]]) {
  45196. a.splice(i, 1);
  45197. }
  45198. }
  45199. }
  45200. return this._super._kill.call(this, lookup);
  45201. };
  45202. }());
  45203. /*
  45204. * ----------------------------------------------------------------
  45205. * CSSPlugin
  45206. * ----------------------------------------------------------------
  45207. */
  45208. _gsScope._gsDefine("plugins.CSSPlugin", ["plugins.TweenPlugin","TweenLite"], function(TweenPlugin, TweenLite) {
  45209. /** @constructor **/
  45210. var CSSPlugin = function() {
  45211. TweenPlugin.call(this, "css");
  45212. this._overwriteProps.length = 0;
  45213. this.setRatio = CSSPlugin.prototype.setRatio; //speed optimization (avoid prototype lookup on this "hot" method)
  45214. },
  45215. _globals = _gsScope._gsDefine.globals,
  45216. _hasPriority, //turns true whenever a CSSPropTween instance is created that has a priority other than 0. This helps us discern whether or not we should spend the time organizing the linked list or not after a CSSPlugin's _onInitTween() method is called.
  45217. _suffixMap, //we set this in _onInitTween() each time as a way to have a persistent variable we can use in other methods like _parse() without having to pass it around as a parameter and we keep _parse() decoupled from a particular CSSPlugin instance
  45218. _cs, //computed style (we store this in a shared variable to conserve memory and make minification tighter
  45219. _overwriteProps, //alias to the currently instantiating CSSPlugin's _overwriteProps array. We use this closure in order to avoid having to pass a reference around from method to method and aid in minification.
  45220. _specialProps = {},
  45221. p = CSSPlugin.prototype = new TweenPlugin("css");
  45222. p.constructor = CSSPlugin;
  45223. CSSPlugin.version = "1.20.0";
  45224. CSSPlugin.API = 2;
  45225. CSSPlugin.defaultTransformPerspective = 0;
  45226. CSSPlugin.defaultSkewType = "compensated";
  45227. CSSPlugin.defaultSmoothOrigin = true;
  45228. p = "px"; //we'll reuse the "p" variable to keep file size down
  45229. CSSPlugin.suffixMap = {top:p, right:p, bottom:p, left:p, width:p, height:p, fontSize:p, padding:p, margin:p, perspective:p, lineHeight:""};
  45230. var _numExp = /(?:\-|\.|\b)(\d|\.|e\-)+/g,
  45231. _relNumExp = /(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g,
  45232. _valuesExp = /(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi, //finds all the values that begin with numbers or += or -= and then a number. Includes suffixes. We use this to split complex values apart like "1px 5px 20px rgb(255,102,51)"
  45233. _NaNExp = /(?![+-]?\d*\.?\d+|[+-]|e[+-]\d+)[^0-9]/g, //also allows scientific notation and doesn't kill the leading -/+ in -= and +=
  45234. _suffixExp = /(?:\d|\-|\+|=|#|\.)*/g,
  45235. _opacityExp = /opacity *= *([^)]*)/i,
  45236. _opacityValExp = /opacity:([^;]*)/i,
  45237. _alphaFilterExp = /alpha\(opacity *=.+?\)/i,
  45238. _rgbhslExp = /^(rgb|hsl)/,
  45239. _capsExp = /([A-Z])/g,
  45240. _camelExp = /-([a-z])/gi,
  45241. _urlExp = /(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi, //for pulling out urls from url(...) or url("...") strings (some browsers wrap urls in quotes, some don't when reporting things like backgroundImage)
  45242. _camelFunc = function(s, g) { return g.toUpperCase(); },
  45243. _horizExp = /(?:Left|Right|Width)/i,
  45244. _ieGetMatrixExp = /(M11|M12|M21|M22)=[\d\-\.e]+/gi,
  45245. _ieSetMatrixExp = /progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i,
  45246. _commasOutsideParenExp = /,(?=[^\)]*(?:\(|$))/gi, //finds any commas that are not within parenthesis
  45247. _complexExp = /[\s,\(]/i, //for testing a string to find if it has a space, comma, or open parenthesis (clues that it's a complex value)
  45248. _DEG2RAD = Math.PI / 180,
  45249. _RAD2DEG = 180 / Math.PI,
  45250. _forcePT = {},
  45251. _dummyElement = {style:{}},
  45252. _doc = _gsScope.document || {createElement: function() {return _dummyElement;}},
  45253. _createElement = function(type, ns) {
  45254. return _doc.createElementNS ? _doc.createElementNS(ns || "http://www.w3.org/1999/xhtml", type) : _doc.createElement(type);
  45255. },
  45256. _tempDiv = _createElement("div"),
  45257. _tempImg = _createElement("img"),
  45258. _internals = CSSPlugin._internals = {_specialProps:_specialProps}, //provides a hook to a few internal methods that we need to access from inside other plugins
  45259. _agent = (_gsScope.navigator || {}).userAgent || "",
  45260. _autoRound,
  45261. _reqSafariFix, //we won't apply the Safari transform fix until we actually come across a tween that affects a transform property (to maintain best performance).
  45262. _isSafari,
  45263. _isFirefox, //Firefox has a bug that causes 3D transformed elements to randomly disappear unless a repaint is forced after each update on each element.
  45264. _isSafariLT6, //Safari (and Android 4 which uses a flavor of Safari) has a bug that prevents changes to "top" and "left" properties from rendering properly if changed on the same frame as a transform UNLESS we set the element's WebkitBackfaceVisibility to hidden (weird, I know). Doing this for Android 3 and earlier seems to actually cause other problems, though (fun!)
  45265. _ieVers,
  45266. _supportsOpacity = (function() { //we set _isSafari, _ieVers, _isFirefox, and _supportsOpacity all in one function here to reduce file size slightly, especially in the minified version.
  45267. var i = _agent.indexOf("Android"),
  45268. a = _createElement("a");
  45269. _isSafari = (_agent.indexOf("Safari") !== -1 && _agent.indexOf("Chrome") === -1 && (i === -1 || parseFloat(_agent.substr(i+8, 2)) > 3));
  45270. _isSafariLT6 = (_isSafari && (parseFloat(_agent.substr(_agent.indexOf("Version/")+8, 2)) < 6));
  45271. _isFirefox = (_agent.indexOf("Firefox") !== -1);
  45272. if ((/MSIE ([0-9]{1,}[\.0-9]{0,})/).exec(_agent) || (/Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/).exec(_agent)) {
  45273. _ieVers = parseFloat( RegExp.$1 );
  45274. }
  45275. if (!a) {
  45276. return false;
  45277. }
  45278. a.style.cssText = "top:1px;opacity:.55;";
  45279. return /^0.55/.test(a.style.opacity);
  45280. }()),
  45281. _getIEOpacity = function(v) {
  45282. return (_opacityExp.test( ((typeof(v) === "string") ? v : (v.currentStyle ? v.currentStyle.filter : v.style.filter) || "") ) ? ( parseFloat( RegExp.$1 ) / 100 ) : 1);
  45283. },
  45284. _log = function(s) {//for logging messages, but in a way that won't throw errors in old versions of IE.
  45285. if (_gsScope.console) {
  45286. console.log(s);
  45287. }
  45288. },
  45289. _target, //when initting a CSSPlugin, we set this variable so that we can access it from within many other functions without having to pass it around as params
  45290. _index, //when initting a CSSPlugin, we set this variable so that we can access it from within many other functions without having to pass it around as params
  45291. _prefixCSS = "", //the non-camelCase vendor prefix like "-o-", "-moz-", "-ms-", or "-webkit-"
  45292. _prefix = "", //camelCase vendor prefix like "O", "ms", "Webkit", or "Moz".
  45293. // @private feed in a camelCase property name like "transform" and it will check to see if it is valid as-is or if it needs a vendor prefix. It returns the corrected camelCase property name (i.e. "WebkitTransform" or "MozTransform" or "transform" or null if no such property is found, like if the browser is IE8 or before, "transform" won't be found at all)
  45294. _checkPropPrefix = function(p, e) {
  45295. e = e || _tempDiv;
  45296. var s = e.style,
  45297. a, i;
  45298. if (s[p] !== undefined) {
  45299. return p;
  45300. }
  45301. p = p.charAt(0).toUpperCase() + p.substr(1);
  45302. a = ["O","Moz","ms","Ms","Webkit"];
  45303. i = 5;
  45304. while (--i > -1 && s[a[i]+p] === undefined) { }
  45305. if (i >= 0) {
  45306. _prefix = (i === 3) ? "ms" : a[i];
  45307. _prefixCSS = "-" + _prefix.toLowerCase() + "-";
  45308. return _prefix + p;
  45309. }
  45310. return null;
  45311. },
  45312. _getComputedStyle = _doc.defaultView ? _doc.defaultView.getComputedStyle : function() {},
  45313. /**
  45314. * @private Returns the css style for a particular property of an element. For example, to get whatever the current "left" css value for an element with an ID of "myElement", you could do:
  45315. * var currentLeft = CSSPlugin.getStyle( document.getElementById("myElement"), "left");
  45316. *
  45317. * @param {!Object} t Target element whose style property you want to query
  45318. * @param {!string} p Property name (like "left" or "top" or "marginTop", etc.)
  45319. * @param {Object=} cs Computed style object. This just provides a way to speed processing if you're going to get several properties on the same element in quick succession - you can reuse the result of the getComputedStyle() call.
  45320. * @param {boolean=} calc If true, the value will not be read directly from the element's "style" property (if it exists there), but instead the getComputedStyle() result will be used. This can be useful when you want to ensure that the browser itself is interpreting the value.
  45321. * @param {string=} dflt Default value that should be returned in the place of null, "none", "auto" or "auto auto".
  45322. * @return {?string} The current property value
  45323. */
  45324. _getStyle = CSSPlugin.getStyle = function(t, p, cs, calc, dflt) {
  45325. var rv;
  45326. if (!_supportsOpacity) if (p === "opacity") { //several versions of IE don't use the standard "opacity" property - they use things like filter:alpha(opacity=50), so we parse that here.
  45327. return _getIEOpacity(t);
  45328. }
  45329. if (!calc && t.style[p]) {
  45330. rv = t.style[p];
  45331. } else if ((cs = cs || _getComputedStyle(t))) {
  45332. rv = cs[p] || cs.getPropertyValue(p) || cs.getPropertyValue(p.replace(_capsExp, "-$1").toLowerCase());
  45333. } else if (t.currentStyle) {
  45334. rv = t.currentStyle[p];
  45335. }
  45336. return (dflt != null && (!rv || rv === "none" || rv === "auto" || rv === "auto auto")) ? dflt : rv;
  45337. },
  45338. /**
  45339. * @private Pass the target element, the property name, the numeric value, and the suffix (like "%", "em", "px", etc.) and it will spit back the equivalent pixel number.
  45340. * @param {!Object} t Target element
  45341. * @param {!string} p Property name (like "left", "top", "marginLeft", etc.)
  45342. * @param {!number} v Value
  45343. * @param {string=} sfx Suffix (like "px" or "%" or "em")
  45344. * @param {boolean=} recurse If true, the call is a recursive one. In some browsers (like IE7/8), occasionally the value isn't accurately reported initially, but if we run the function again it will take effect.
  45345. * @return {number} value in pixels
  45346. */
  45347. _convertToPixels = _internals.convertToPixels = function(t, p, v, sfx, recurse) {
  45348. if (sfx === "px" || (!sfx && p !== "lineHeight")) { return v; }
  45349. if (sfx === "auto" || !v) { return 0; }
  45350. var horiz = _horizExp.test(p),
  45351. node = t,
  45352. style = _tempDiv.style,
  45353. neg = (v < 0),
  45354. precise = (v === 1),
  45355. pix, cache, time;
  45356. if (neg) {
  45357. v = -v;
  45358. }
  45359. if (precise) {
  45360. v *= 100;
  45361. }
  45362. if (p === "lineHeight" && !sfx) { //special case of when a simple lineHeight (without a unit) is used. Set it to the value, read back the computed value, and then revert.
  45363. cache = _getComputedStyle(t).lineHeight;
  45364. t.style.lineHeight = v;
  45365. pix = parseFloat(_getComputedStyle(t).lineHeight);
  45366. t.style.lineHeight = cache;
  45367. } else if (sfx === "%" && p.indexOf("border") !== -1) {
  45368. pix = (v / 100) * (horiz ? t.clientWidth : t.clientHeight);
  45369. } else {
  45370. style.cssText = "border:0 solid red;position:" + _getStyle(t, "position") + ";line-height:0;";
  45371. if (sfx === "%" || !node.appendChild || sfx.charAt(0) === "v" || sfx === "rem") {
  45372. node = t.parentNode || _doc.body;
  45373. if (_getStyle(node, "display").indexOf("flex") !== -1) { //Edge and IE11 have a bug that causes offsetWidth to report as 0 if the container has display:flex and the child is position:relative. Switching to position: absolute solves it.
  45374. style.position = "absolute";
  45375. }
  45376. cache = node._gsCache;
  45377. time = TweenLite.ticker.frame;
  45378. if (cache && horiz && cache.time === time) { //performance optimization: we record the width of elements along with the ticker frame so that we can quickly get it again on the same tick (seems relatively safe to assume it wouldn't change on the same tick)
  45379. return cache.width * v / 100;
  45380. }
  45381. style[(horiz ? "width" : "height")] = v + sfx;
  45382. } else {
  45383. style[(horiz ? "borderLeftWidth" : "borderTopWidth")] = v + sfx;
  45384. }
  45385. node.appendChild(_tempDiv);
  45386. pix = parseFloat(_tempDiv[(horiz ? "offsetWidth" : "offsetHeight")]);
  45387. node.removeChild(_tempDiv);
  45388. if (horiz && sfx === "%" && CSSPlugin.cacheWidths !== false) {
  45389. cache = node._gsCache = node._gsCache || {};
  45390. cache.time = time;
  45391. cache.width = pix / v * 100;
  45392. }
  45393. if (pix === 0 && !recurse) {
  45394. pix = _convertToPixels(t, p, v, sfx, true);
  45395. }
  45396. }
  45397. if (precise) {
  45398. pix /= 100;
  45399. }
  45400. return neg ? -pix : pix;
  45401. },
  45402. _calculateOffset = _internals.calculateOffset = function(t, p, cs) { //for figuring out "top" or "left" in px when it's "auto". We need to factor in margin with the offsetLeft/offsetTop
  45403. if (_getStyle(t, "position", cs) !== "absolute") { return 0; }
  45404. var dim = ((p === "left") ? "Left" : "Top"),
  45405. v = _getStyle(t, "margin" + dim, cs);
  45406. return t["offset" + dim] - (_convertToPixels(t, p, parseFloat(v), v.replace(_suffixExp, "")) || 0);
  45407. },
  45408. // @private returns at object containing ALL of the style properties in camelCase and their associated values.
  45409. _getAllStyles = function(t, cs) {
  45410. var s = {},
  45411. i, tr, p;
  45412. if ((cs = cs || _getComputedStyle(t, null))) {
  45413. if ((i = cs.length)) {
  45414. while (--i > -1) {
  45415. p = cs[i];
  45416. if (p.indexOf("-transform") === -1 || _transformPropCSS === p) { //Some webkit browsers duplicate transform values, one non-prefixed and one prefixed ("transform" and "WebkitTransform"), so we must weed out the extra one here.
  45417. s[p.replace(_camelExp, _camelFunc)] = cs.getPropertyValue(p);
  45418. }
  45419. }
  45420. } else { //some browsers behave differently - cs.length is always 0, so we must do a for...in loop.
  45421. for (i in cs) {
  45422. if (i.indexOf("Transform") === -1 || _transformProp === i) { //Some webkit browsers duplicate transform values, one non-prefixed and one prefixed ("transform" and "WebkitTransform"), so we must weed out the extra one here.
  45423. s[i] = cs[i];
  45424. }
  45425. }
  45426. }
  45427. } else if ((cs = t.currentStyle || t.style)) {
  45428. for (i in cs) {
  45429. if (typeof(i) === "string" && s[i] === undefined) {
  45430. s[i.replace(_camelExp, _camelFunc)] = cs[i];
  45431. }
  45432. }
  45433. }
  45434. if (!_supportsOpacity) {
  45435. s.opacity = _getIEOpacity(t);
  45436. }
  45437. tr = _getTransform(t, cs, false);
  45438. s.rotation = tr.rotation;
  45439. s.skewX = tr.skewX;
  45440. s.scaleX = tr.scaleX;
  45441. s.scaleY = tr.scaleY;
  45442. s.x = tr.x;
  45443. s.y = tr.y;
  45444. if (_supports3D) {
  45445. s.z = tr.z;
  45446. s.rotationX = tr.rotationX;
  45447. s.rotationY = tr.rotationY;
  45448. s.scaleZ = tr.scaleZ;
  45449. }
  45450. if (s.filters) {
  45451. delete s.filters;
  45452. }
  45453. return s;
  45454. },
  45455. // @private analyzes two style objects (as returned by _getAllStyles()) and only looks for differences between them that contain tweenable values (like a number or color). It returns an object with a "difs" property which refers to an object containing only those isolated properties and values for tweening, and a "firstMPT" property which refers to the first MiniPropTween instance in a linked list that recorded all the starting values of the different properties so that we can revert to them at the end or beginning of the tween - we don't want the cascading to get messed up. The forceLookup parameter is an optional generic object with properties that should be forced into the results - this is necessary for className tweens that are overwriting others because imagine a scenario where a rollover/rollout adds/removes a class and the user swipes the mouse over the target SUPER fast, thus nothing actually changed yet and the subsequent comparison of the properties would indicate they match (especially when px rounding is taken into consideration), thus no tweening is necessary even though it SHOULD tween and remove those properties after the tween (otherwise the inline styles will contaminate things). See the className SpecialProp code for details.
  45456. _cssDif = function(t, s1, s2, vars, forceLookup) {
  45457. var difs = {},
  45458. style = t.style,
  45459. val, p, mpt;
  45460. for (p in s2) {
  45461. if (p !== "cssText") if (p !== "length") if (isNaN(p)) if (s1[p] !== (val = s2[p]) || (forceLookup && forceLookup[p])) if (p.indexOf("Origin") === -1) if (typeof(val) === "number" || typeof(val) === "string") {
  45462. difs[p] = (val === "auto" && (p === "left" || p === "top")) ? _calculateOffset(t, p) : ((val === "" || val === "auto" || val === "none") && typeof(s1[p]) === "string" && s1[p].replace(_NaNExp, "") !== "") ? 0 : val; //if the ending value is defaulting ("" or "auto"), we check the starting value and if it can be parsed into a number (a string which could have a suffix too, like 700px), then we swap in 0 for "" or "auto" so that things actually tween.
  45463. if (style[p] !== undefined) { //for className tweens, we must remember which properties already existed inline - the ones that didn't should be removed when the tween isn't in progress because they were only introduced to facilitate the transition between classes.
  45464. mpt = new MiniPropTween(style, p, style[p], mpt);
  45465. }
  45466. }
  45467. }
  45468. if (vars) {
  45469. for (p in vars) { //copy properties (except className)
  45470. if (p !== "className") {
  45471. difs[p] = vars[p];
  45472. }
  45473. }
  45474. }
  45475. return {difs:difs, firstMPT:mpt};
  45476. },
  45477. _dimensions = {width:["Left","Right"], height:["Top","Bottom"]},
  45478. _margins = ["marginLeft","marginRight","marginTop","marginBottom"],
  45479. /**
  45480. * @private Gets the width or height of an element
  45481. * @param {!Object} t Target element
  45482. * @param {!string} p Property name ("width" or "height")
  45483. * @param {Object=} cs Computed style object (if one exists). Just a speed optimization.
  45484. * @return {number} Dimension (in pixels)
  45485. */
  45486. _getDimension = function(t, p, cs) {
  45487. if ((t.nodeName + "").toLowerCase() === "svg") { //Chrome no longer supports offsetWidth/offsetHeight on SVG elements.
  45488. return (cs || _getComputedStyle(t))[p] || 0;
  45489. } else if (t.getCTM && _isSVG(t)) {
  45490. return t.getBBox()[p] || 0;
  45491. }
  45492. var v = parseFloat((p === "width") ? t.offsetWidth : t.offsetHeight),
  45493. a = _dimensions[p],
  45494. i = a.length;
  45495. cs = cs || _getComputedStyle(t, null);
  45496. while (--i > -1) {
  45497. v -= parseFloat( _getStyle(t, "padding" + a[i], cs, true) ) || 0;
  45498. v -= parseFloat( _getStyle(t, "border" + a[i] + "Width", cs, true) ) || 0;
  45499. }
  45500. return v;
  45501. },
  45502. // @private Parses position-related complex strings like "top left" or "50px 10px" or "70% 20%", etc. which are used for things like transformOrigin or backgroundPosition. Optionally decorates a supplied object (recObj) with the following properties: "ox" (offsetX), "oy" (offsetY), "oxp" (if true, "ox" is a percentage not a pixel value), and "oxy" (if true, "oy" is a percentage not a pixel value)
  45503. _parsePosition = function(v, recObj) {
  45504. if (v === "contain" || v === "auto" || v === "auto auto") { //note: Firefox uses "auto auto" as default whereas Chrome uses "auto".
  45505. return v + " ";
  45506. }
  45507. if (v == null || v === "") {
  45508. v = "0 0";
  45509. }
  45510. var a = v.split(" "),
  45511. x = (v.indexOf("left") !== -1) ? "0%" : (v.indexOf("right") !== -1) ? "100%" : a[0],
  45512. y = (v.indexOf("top") !== -1) ? "0%" : (v.indexOf("bottom") !== -1) ? "100%" : a[1],
  45513. i;
  45514. if (a.length > 3 && !recObj) { //multiple positions
  45515. a = v.split(", ").join(",").split(",");
  45516. v = [];
  45517. for (i = 0; i < a.length; i++) {
  45518. v.push(_parsePosition(a[i]));
  45519. }
  45520. return v.join(",");
  45521. }
  45522. if (y == null) {
  45523. y = (x === "center") ? "50%" : "0";
  45524. } else if (y === "center") {
  45525. y = "50%";
  45526. }
  45527. if (x === "center" || (isNaN(parseFloat(x)) && (x + "").indexOf("=") === -1)) { //remember, the user could flip-flop the values and say "bottom center" or "center bottom", etc. "center" is ambiguous because it could be used to describe horizontal or vertical, hence the isNaN(). If there's an "=" sign in the value, it's relative.
  45528. x = "50%";
  45529. }
  45530. v = x + " " + y + ((a.length > 2) ? " " + a[2] : "");
  45531. if (recObj) {
  45532. recObj.oxp = (x.indexOf("%") !== -1);
  45533. recObj.oyp = (y.indexOf("%") !== -1);
  45534. recObj.oxr = (x.charAt(1) === "=");
  45535. recObj.oyr = (y.charAt(1) === "=");
  45536. recObj.ox = parseFloat(x.replace(_NaNExp, ""));
  45537. recObj.oy = parseFloat(y.replace(_NaNExp, ""));
  45538. recObj.v = v;
  45539. }
  45540. return recObj || v;
  45541. },
  45542. /**
  45543. * @private Takes an ending value (typically a string, but can be a number) and a starting value and returns the change between the two, looking for relative value indicators like += and -= and it also ignores suffixes (but make sure the ending value starts with a number or +=/-= and that the starting value is a NUMBER!)
  45544. * @param {(number|string)} e End value which is typically a string, but could be a number
  45545. * @param {(number|string)} b Beginning value which is typically a string but could be a number
  45546. * @return {number} Amount of change between the beginning and ending values (relative values that have a "+=" or "-=" are recognized)
  45547. */
  45548. _parseChange = function(e, b) {
  45549. if (typeof(e) === "function") {
  45550. e = e(_index, _target);
  45551. }
  45552. return (typeof(e) === "string" && e.charAt(1) === "=") ? parseInt(e.charAt(0) + "1", 10) * parseFloat(e.substr(2)) : (parseFloat(e) - parseFloat(b)) || 0;
  45553. },
  45554. /**
  45555. * @private Takes a value and a default number, checks if the value is relative, null, or numeric and spits back a normalized number accordingly. Primarily used in the _parseTransform() function.
  45556. * @param {Object} v Value to be parsed
  45557. * @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter)
  45558. * @return {number} Parsed value
  45559. */
  45560. _parseVal = function(v, d) {
  45561. if (typeof(v) === "function") {
  45562. v = v(_index, _target);
  45563. }
  45564. return (v == null) ? d : (typeof(v) === "string" && v.charAt(1) === "=") ? parseInt(v.charAt(0) + "1", 10) * parseFloat(v.substr(2)) + d : parseFloat(v) || 0;
  45565. },
  45566. /**
  45567. * @private Translates strings like "40deg" or "40" or 40rad" or "+=40deg" or "270_short" or "-90_cw" or "+=45_ccw" to a numeric radian angle. Of course a starting/default value must be fed in too so that relative values can be calculated properly.
  45568. * @param {Object} v Value to be parsed
  45569. * @param {!number} d Default value (which is also used for relative calculations if "+=" or "-=" is found in the first parameter)
  45570. * @param {string=} p property name for directionalEnd (optional - only used when the parsed value is directional ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation). Property name would be "rotation", "rotationX", or "rotationY"
  45571. * @param {Object=} directionalEnd An object that will store the raw end values for directional angles ("_short", "_cw", or "_ccw" suffix). We need a way to store the uncompensated value so that at the end of the tween, we set it to exactly what was requested with no directional compensation.
  45572. * @return {number} parsed angle in radians
  45573. */
  45574. _parseAngle = function(v, d, p, directionalEnd) {
  45575. var min = 0.000001,
  45576. cap, split, dif, result, isRelative;
  45577. if (typeof(v) === "function") {
  45578. v = v(_index, _target);
  45579. }
  45580. if (v == null) {
  45581. result = d;
  45582. } else if (typeof(v) === "number") {
  45583. result = v;
  45584. } else {
  45585. cap = 360;
  45586. split = v.split("_");
  45587. isRelative = (v.charAt(1) === "=");
  45588. dif = (isRelative ? parseInt(v.charAt(0) + "1", 10) * parseFloat(split[0].substr(2)) : parseFloat(split[0])) * ((v.indexOf("rad") === -1) ? 1 : _RAD2DEG) - (isRelative ? 0 : d);
  45589. if (split.length) {
  45590. if (directionalEnd) {
  45591. directionalEnd[p] = d + dif;
  45592. }
  45593. if (v.indexOf("short") !== -1) {
  45594. dif = dif % cap;
  45595. if (dif !== dif % (cap / 2)) {
  45596. dif = (dif < 0) ? dif + cap : dif - cap;
  45597. }
  45598. }
  45599. if (v.indexOf("_cw") !== -1 && dif < 0) {
  45600. dif = ((dif + cap * 9999999999) % cap) - ((dif / cap) | 0) * cap;
  45601. } else if (v.indexOf("ccw") !== -1 && dif > 0) {
  45602. dif = ((dif - cap * 9999999999) % cap) - ((dif / cap) | 0) * cap;
  45603. }
  45604. }
  45605. result = d + dif;
  45606. }
  45607. if (result < min && result > -min) {
  45608. result = 0;
  45609. }
  45610. return result;
  45611. },
  45612. _colorLookup = {aqua:[0,255,255],
  45613. lime:[0,255,0],
  45614. silver:[192,192,192],
  45615. black:[0,0,0],
  45616. maroon:[128,0,0],
  45617. teal:[0,128,128],
  45618. blue:[0,0,255],
  45619. navy:[0,0,128],
  45620. white:[255,255,255],
  45621. fuchsia:[255,0,255],
  45622. olive:[128,128,0],
  45623. yellow:[255,255,0],
  45624. orange:[255,165,0],
  45625. gray:[128,128,128],
  45626. purple:[128,0,128],
  45627. green:[0,128,0],
  45628. red:[255,0,0],
  45629. pink:[255,192,203],
  45630. cyan:[0,255,255],
  45631. transparent:[255,255,255,0]},
  45632. _hue = function(h, m1, m2) {
  45633. h = (h < 0) ? h + 1 : (h > 1) ? h - 1 : h;
  45634. return ((((h * 6 < 1) ? m1 + (m2 - m1) * h * 6 : (h < 0.5) ? m2 : (h * 3 < 2) ? m1 + (m2 - m1) * (2 / 3 - h) * 6 : m1) * 255) + 0.5) | 0;
  45635. },
  45636. /**
  45637. * @private Parses a color (like #9F0, #FF9900, rgb(255,51,153) or hsl(108, 50%, 10%)) into an array with 3 elements for red, green, and blue or if toHSL parameter is true, it will populate the array with hue, saturation, and lightness values. If a relative value is found in an hsl() or hsla() string, it will preserve those relative prefixes and all the values in the array will be strings instead of numbers (in all other cases it will be populated with numbers).
  45638. * @param {(string|number)} v The value the should be parsed which could be a string like #9F0 or rgb(255,102,51) or rgba(255,0,0,0.5) or it could be a number like 0xFF00CC or even a named color like red, blue, purple, etc.
  45639. * @param {(boolean)} toHSL If true, an hsl() or hsla() value will be returned instead of rgb() or rgba()
  45640. * @return {Array.<number>} An array containing red, green, and blue (and optionally alpha) in that order, or if the toHSL parameter was true, the array will contain hue, saturation and lightness (and optionally alpha) in that order. Always numbers unless there's a relative prefix found in an hsl() or hsla() string and toHSL is true.
  45641. */
  45642. _parseColor = CSSPlugin.parseColor = function(v, toHSL) {
  45643. var a, r, g, b, h, s, l, max, min, d, wasHSL;
  45644. if (!v) {
  45645. a = _colorLookup.black;
  45646. } else if (typeof(v) === "number") {
  45647. a = [v >> 16, (v >> 8) & 255, v & 255];
  45648. } else {
  45649. if (v.charAt(v.length - 1) === ",") { //sometimes a trailing comma is included and we should chop it off (typically from a comma-delimited list of values like a textShadow:"2px 2px 2px blue, 5px 5px 5px rgb(255,0,0)" - in this example "blue," has a trailing comma. We could strip it out inside parseComplex() but we'd need to do it to the beginning and ending values plus it wouldn't provide protection from other potential scenarios like if the user passes in a similar value.
  45650. v = v.substr(0, v.length - 1);
  45651. }
  45652. if (_colorLookup[v]) {
  45653. a = _colorLookup[v];
  45654. } else if (v.charAt(0) === "#") {
  45655. if (v.length === 4) { //for shorthand like #9F0
  45656. r = v.charAt(1);
  45657. g = v.charAt(2);
  45658. b = v.charAt(3);
  45659. v = "#" + r + r + g + g + b + b;
  45660. }
  45661. v = parseInt(v.substr(1), 16);
  45662. a = [v >> 16, (v >> 8) & 255, v & 255];
  45663. } else if (v.substr(0, 3) === "hsl") {
  45664. a = wasHSL = v.match(_numExp);
  45665. if (!toHSL) {
  45666. h = (Number(a[0]) % 360) / 360;
  45667. s = Number(a[1]) / 100;
  45668. l = Number(a[2]) / 100;
  45669. g = (l <= 0.5) ? l * (s + 1) : l + s - l * s;
  45670. r = l * 2 - g;
  45671. if (a.length > 3) {
  45672. a[3] = Number(v[3]);
  45673. }
  45674. a[0] = _hue(h + 1 / 3, r, g);
  45675. a[1] = _hue(h, r, g);
  45676. a[2] = _hue(h - 1 / 3, r, g);
  45677. } else if (v.indexOf("=") !== -1) { //if relative values are found, just return the raw strings with the relative prefixes in place.
  45678. return v.match(_relNumExp);
  45679. }
  45680. } else {
  45681. a = v.match(_numExp) || _colorLookup.transparent;
  45682. }
  45683. a[0] = Number(a[0]);
  45684. a[1] = Number(a[1]);
  45685. a[2] = Number(a[2]);
  45686. if (a.length > 3) {
  45687. a[3] = Number(a[3]);
  45688. }
  45689. }
  45690. if (toHSL && !wasHSL) {
  45691. r = a[0] / 255;
  45692. g = a[1] / 255;
  45693. b = a[2] / 255;
  45694. max = Math.max(r, g, b);
  45695. min = Math.min(r, g, b);
  45696. l = (max + min) / 2;
  45697. if (max === min) {
  45698. h = s = 0;
  45699. } else {
  45700. d = max - min;
  45701. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  45702. h = (max === r) ? (g - b) / d + (g < b ? 6 : 0) : (max === g) ? (b - r) / d + 2 : (r - g) / d + 4;
  45703. h *= 60;
  45704. }
  45705. a[0] = (h + 0.5) | 0;
  45706. a[1] = (s * 100 + 0.5) | 0;
  45707. a[2] = (l * 100 + 0.5) | 0;
  45708. }
  45709. return a;
  45710. },
  45711. _formatColors = function(s, toHSL) {
  45712. var colors = s.match(_colorExp) || [],
  45713. charIndex = 0,
  45714. parsed = "",
  45715. i, color, temp;
  45716. if (!colors.length) {
  45717. return s;
  45718. }
  45719. for (i = 0; i < colors.length; i++) {
  45720. color = colors[i];
  45721. temp = s.substr(charIndex, s.indexOf(color, charIndex)-charIndex);
  45722. charIndex += temp.length + color.length;
  45723. color = _parseColor(color, toHSL);
  45724. if (color.length === 3) {
  45725. color.push(1);
  45726. }
  45727. parsed += temp + (toHSL ? "hsla(" + color[0] + "," + color[1] + "%," + color[2] + "%," + color[3] : "rgba(" + color.join(",")) + ")";
  45728. }
  45729. return parsed + s.substr(charIndex);
  45730. },
  45731. _colorExp = "(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3}){1,2}\\b"; //we'll dynamically build this Regular Expression to conserve file size. After building it, it will be able to find rgb(), rgba(), # (hexadecimal), and named color values like red, blue, purple, etc.
  45732. for (p in _colorLookup) {
  45733. _colorExp += "|" + p + "\\b";
  45734. }
  45735. _colorExp = new RegExp(_colorExp+")", "gi");
  45736. CSSPlugin.colorStringFilter = function(a) {
  45737. var combined = a[0] + " " + a[1],
  45738. toHSL;
  45739. if (_colorExp.test(combined)) {
  45740. toHSL = (combined.indexOf("hsl(") !== -1 || combined.indexOf("hsla(") !== -1);
  45741. a[0] = _formatColors(a[0], toHSL);
  45742. a[1] = _formatColors(a[1], toHSL);
  45743. }
  45744. _colorExp.lastIndex = 0;
  45745. };
  45746. if (!TweenLite.defaultStringFilter) {
  45747. TweenLite.defaultStringFilter = CSSPlugin.colorStringFilter;
  45748. }
  45749. /**
  45750. * @private Returns a formatter function that handles taking a string (or number in some cases) and returning a consistently formatted one in terms of delimiters, quantity of values, etc. For example, we may get boxShadow values defined as "0px red" or "0px 0px 10px rgb(255,0,0)" or "0px 0px 20px 20px #F00" and we need to ensure that what we get back is described with 4 numbers and a color. This allows us to feed it into the _parseComplex() method and split the values up appropriately. The neat thing about this _getFormatter() function is that the dflt defines a pattern as well as a default, so for example, _getFormatter("0px 0px 0px 0px #777", true) not only sets the default as 0px for all distances and #777 for the color, but also sets the pattern such that 4 numbers and a color will always get returned.
  45751. * @param {!string} dflt The default value and pattern to follow. So "0px 0px 0px 0px #777" will ensure that 4 numbers and a color will always get returned.
  45752. * @param {boolean=} clr If true, the values should be searched for color-related data. For example, boxShadow values typically contain a color whereas borderRadius don't.
  45753. * @param {boolean=} collapsible If true, the value is a top/left/right/bottom style one that acts like margin or padding, where if only one value is received, it's used for all 4; if 2 are received, the first is duplicated for 3rd (bottom) and the 2nd is duplicated for the 4th spot (left), etc.
  45754. * @return {Function} formatter function
  45755. */
  45756. var _getFormatter = function(dflt, clr, collapsible, multi) {
  45757. if (dflt == null) {
  45758. return function(v) {return v;};
  45759. }
  45760. var dColor = clr ? (dflt.match(_colorExp) || [""])[0] : "",
  45761. dVals = dflt.split(dColor).join("").match(_valuesExp) || [],
  45762. pfx = dflt.substr(0, dflt.indexOf(dVals[0])),
  45763. sfx = (dflt.charAt(dflt.length - 1) === ")") ? ")" : "",
  45764. delim = (dflt.indexOf(" ") !== -1) ? " " : ",",
  45765. numVals = dVals.length,
  45766. dSfx = (numVals > 0) ? dVals[0].replace(_numExp, "") : "",
  45767. formatter;
  45768. if (!numVals) {
  45769. return function(v) {return v;};
  45770. }
  45771. if (clr) {
  45772. formatter = function(v) {
  45773. var color, vals, i, a;
  45774. if (typeof(v) === "number") {
  45775. v += dSfx;
  45776. } else if (multi && _commasOutsideParenExp.test(v)) {
  45777. a = v.replace(_commasOutsideParenExp, "|").split("|");
  45778. for (i = 0; i < a.length; i++) {
  45779. a[i] = formatter(a[i]);
  45780. }
  45781. return a.join(",");
  45782. }
  45783. color = (v.match(_colorExp) || [dColor])[0];
  45784. vals = v.split(color).join("").match(_valuesExp) || [];
  45785. i = vals.length;
  45786. if (numVals > i--) {
  45787. while (++i < numVals) {
  45788. vals[i] = collapsible ? vals[(((i - 1) / 2) | 0)] : dVals[i];
  45789. }
  45790. }
  45791. return pfx + vals.join(delim) + delim + color + sfx + (v.indexOf("inset") !== -1 ? " inset" : "");
  45792. };
  45793. return formatter;
  45794. }
  45795. formatter = function(v) {
  45796. var vals, a, i;
  45797. if (typeof(v) === "number") {
  45798. v += dSfx;
  45799. } else if (multi && _commasOutsideParenExp.test(v)) {
  45800. a = v.replace(_commasOutsideParenExp, "|").split("|");
  45801. for (i = 0; i < a.length; i++) {
  45802. a[i] = formatter(a[i]);
  45803. }
  45804. return a.join(",");
  45805. }
  45806. vals = v.match(_valuesExp) || [];
  45807. i = vals.length;
  45808. if (numVals > i--) {
  45809. while (++i < numVals) {
  45810. vals[i] = collapsible ? vals[(((i - 1) / 2) | 0)] : dVals[i];
  45811. }
  45812. }
  45813. return pfx + vals.join(delim) + sfx;
  45814. };
  45815. return formatter;
  45816. },
  45817. /**
  45818. * @private returns a formatter function that's used for edge-related values like marginTop, marginLeft, paddingBottom, paddingRight, etc. Just pass a comma-delimited list of property names related to the edges.
  45819. * @param {!string} props a comma-delimited list of property names in order from top to left, like "marginTop,marginRight,marginBottom,marginLeft"
  45820. * @return {Function} a formatter function
  45821. */
  45822. _getEdgeParser = function(props) {
  45823. props = props.split(",");
  45824. return function(t, e, p, cssp, pt, plugin, vars) {
  45825. var a = (e + "").split(" "),
  45826. i;
  45827. vars = {};
  45828. for (i = 0; i < 4; i++) {
  45829. vars[props[i]] = a[i] = a[i] || a[(((i - 1) / 2) >> 0)];
  45830. }
  45831. return cssp.parse(t, vars, pt, plugin);
  45832. };
  45833. },
  45834. // @private used when other plugins must tween values first, like BezierPlugin or ThrowPropsPlugin, etc. That plugin's setRatio() gets called first so that the values are updated, and then we loop through the MiniPropTweens which handle copying the values into their appropriate slots so that they can then be applied correctly in the main CSSPlugin setRatio() method. Remember, we typically create a proxy object that has a bunch of uniquely-named properties that we feed to the sub-plugin and it does its magic normally, and then we must interpret those values and apply them to the css because often numbers must get combined/concatenated, suffixes added, etc. to work with css, like boxShadow could have 4 values plus a color.
  45835. _setPluginRatio = _internals._setPluginRatio = function(v) {
  45836. this.plugin.setRatio(v);
  45837. var d = this.data,
  45838. proxy = d.proxy,
  45839. mpt = d.firstMPT,
  45840. min = 0.000001,
  45841. val, pt, i, str, p;
  45842. while (mpt) {
  45843. val = proxy[mpt.v];
  45844. if (mpt.r) {
  45845. val = Math.round(val);
  45846. } else if (val < min && val > -min) {
  45847. val = 0;
  45848. }
  45849. mpt.t[mpt.p] = val;
  45850. mpt = mpt._next;
  45851. }
  45852. if (d.autoRotate) {
  45853. d.autoRotate.rotation = d.mod ? d.mod(proxy.rotation, this.t) : proxy.rotation; //special case for ModifyPlugin to hook into an auto-rotating bezier
  45854. }
  45855. //at the end, we must set the CSSPropTween's "e" (end) value dynamically here because that's what is used in the final setRatio() method. Same for "b" at the beginning.
  45856. if (v === 1 || v === 0) {
  45857. mpt = d.firstMPT;
  45858. p = (v === 1) ? "e" : "b";
  45859. while (mpt) {
  45860. pt = mpt.t;
  45861. if (!pt.type) {
  45862. pt[p] = pt.s + pt.xs0;
  45863. } else if (pt.type === 1) {
  45864. str = pt.xs0 + pt.s + pt.xs1;
  45865. for (i = 1; i < pt.l; i++) {
  45866. str += pt["xn"+i] + pt["xs"+(i+1)];
  45867. }
  45868. pt[p] = str;
  45869. }
  45870. mpt = mpt._next;
  45871. }
  45872. }
  45873. },
  45874. /**
  45875. * @private @constructor Used by a few SpecialProps to hold important values for proxies. For example, _parseToProxy() creates a MiniPropTween instance for each property that must get tweened on the proxy, and we record the original property name as well as the unique one we create for the proxy, plus whether or not the value needs to be rounded plus the original value.
  45876. * @param {!Object} t target object whose property we're tweening (often a CSSPropTween)
  45877. * @param {!string} p property name
  45878. * @param {(number|string|object)} v value
  45879. * @param {MiniPropTween=} next next MiniPropTween in the linked list
  45880. * @param {boolean=} r if true, the tweened value should be rounded to the nearest integer
  45881. */
  45882. MiniPropTween = function(t, p, v, next, r) {
  45883. this.t = t;
  45884. this.p = p;
  45885. this.v = v;
  45886. this.r = r;
  45887. if (next) {
  45888. next._prev = this;
  45889. this._next = next;
  45890. }
  45891. },
  45892. /**
  45893. * @private Most other plugins (like BezierPlugin and ThrowPropsPlugin and others) can only tween numeric values, but CSSPlugin must accommodate special values that have a bunch of extra data (like a suffix or strings between numeric values, etc.). For example, boxShadow has values like "10px 10px 20px 30px rgb(255,0,0)" which would utterly confuse other plugins. This method allows us to split that data apart and grab only the numeric data and attach it to uniquely-named properties of a generic proxy object ({}) so that we can feed that to virtually any plugin to have the numbers tweened. However, we must also keep track of which properties from the proxy go with which CSSPropTween values and instances. So we create a linked list of MiniPropTweens. Each one records a target (the original CSSPropTween), property (like "s" or "xn1" or "xn2") that we're tweening and the unique property name that was used for the proxy (like "boxShadow_xn1" and "boxShadow_xn2") and whether or not they need to be rounded. That way, in the _setPluginRatio() method we can simply copy the values over from the proxy to the CSSPropTween instance(s). Then, when the main CSSPlugin setRatio() method runs and applies the CSSPropTween values accordingly, they're updated nicely. So the external plugin tweens the numbers, _setPluginRatio() copies them over, and setRatio() acts normally, applying css-specific values to the element.
  45894. * This method returns an object that has the following properties:
  45895. * - proxy: a generic object containing the starting values for all the properties that will be tweened by the external plugin. This is what we feed to the external _onInitTween() as the target
  45896. * - end: a generic object containing the ending values for all the properties that will be tweened by the external plugin. This is what we feed to the external plugin's _onInitTween() as the destination values
  45897. * - firstMPT: the first MiniPropTween in the linked list
  45898. * - pt: the first CSSPropTween in the linked list that was created when parsing. If shallow is true, this linked list will NOT attach to the one passed into the _parseToProxy() as the "pt" (4th) parameter.
  45899. * @param {!Object} t target object to be tweened
  45900. * @param {!(Object|string)} vars the object containing the information about the tweening values (typically the end/destination values) that should be parsed
  45901. * @param {!CSSPlugin} cssp The CSSPlugin instance
  45902. * @param {CSSPropTween=} pt the next CSSPropTween in the linked list
  45903. * @param {TweenPlugin=} plugin the external TweenPlugin instance that will be handling tweening the numeric values
  45904. * @param {boolean=} shallow if true, the resulting linked list from the parse will NOT be attached to the CSSPropTween that was passed in as the "pt" (4th) parameter.
  45905. * @return An object containing the following properties: proxy, end, firstMPT, and pt (see above for descriptions)
  45906. */
  45907. _parseToProxy = _internals._parseToProxy = function(t, vars, cssp, pt, plugin, shallow) {
  45908. var bpt = pt,
  45909. start = {},
  45910. end = {},
  45911. transform = cssp._transform,
  45912. oldForce = _forcePT,
  45913. i, p, xp, mpt, firstPT;
  45914. cssp._transform = null;
  45915. _forcePT = vars;
  45916. pt = firstPT = cssp.parse(t, vars, pt, plugin);
  45917. _forcePT = oldForce;
  45918. //break off from the linked list so the new ones are isolated.
  45919. if (shallow) {
  45920. cssp._transform = transform;
  45921. if (bpt) {
  45922. bpt._prev = null;
  45923. if (bpt._prev) {
  45924. bpt._prev._next = null;
  45925. }
  45926. }
  45927. }
  45928. while (pt && pt !== bpt) {
  45929. if (pt.type <= 1) {
  45930. p = pt.p;
  45931. end[p] = pt.s + pt.c;
  45932. start[p] = pt.s;
  45933. if (!shallow) {
  45934. mpt = new MiniPropTween(pt, "s", p, mpt, pt.r);
  45935. pt.c = 0;
  45936. }
  45937. if (pt.type === 1) {
  45938. i = pt.l;
  45939. while (--i > 0) {
  45940. xp = "xn" + i;
  45941. p = pt.p + "_" + xp;
  45942. end[p] = pt.data[xp];
  45943. start[p] = pt[xp];
  45944. if (!shallow) {
  45945. mpt = new MiniPropTween(pt, xp, p, mpt, pt.rxp[xp]);
  45946. }
  45947. }
  45948. }
  45949. }
  45950. pt = pt._next;
  45951. }
  45952. return {proxy:start, end:end, firstMPT:mpt, pt:firstPT};
  45953. },
  45954. /**
  45955. * @constructor Each property that is tweened has at least one CSSPropTween associated with it. These instances store important information like the target, property, starting value, amount of change, etc. They can also optionally have a number of "extra" strings and numeric values named xs1, xn1, xs2, xn2, xs3, xn3, etc. where "s" indicates string and "n" indicates number. These can be pieced together in a complex-value tween (type:1) that has alternating types of data like a string, number, string, number, etc. For example, boxShadow could be "5px 5px 8px rgb(102, 102, 51)". In that value, there are 6 numbers that may need to tween and then pieced back together into a string again with spaces, suffixes, etc. xs0 is special in that it stores the suffix for standard (type:0) tweens, -OR- the first string (prefix) in a complex-value (type:1) CSSPropTween -OR- it can be the non-tweening value in a type:-1 CSSPropTween. We do this to conserve memory.
  45956. * CSSPropTweens have the following optional properties as well (not defined through the constructor):
  45957. * - l: Length in terms of the number of extra properties that the CSSPropTween has (default: 0). For example, for a boxShadow we may need to tween 5 numbers in which case l would be 5; Keep in mind that the start/end values for the first number that's tweened are always stored in the s and c properties to conserve memory. All additional values thereafter are stored in xn1, xn2, etc.
  45958. * - xfirst: The first instance of any sub-CSSPropTweens that are tweening properties of this instance. For example, we may split up a boxShadow tween so that there's a main CSSPropTween of type:1 that has various xs* and xn* values associated with the h-shadow, v-shadow, blur, color, etc. Then we spawn a CSSPropTween for each of those that has a higher priority and runs BEFORE the main CSSPropTween so that the values are all set by the time it needs to re-assemble them. The xfirst gives us an easy way to identify the first one in that chain which typically ends at the main one (because they're all prepende to the linked list)
  45959. * - plugin: The TweenPlugin instance that will handle the tweening of any complex values. For example, sometimes we don't want to use normal subtweens (like xfirst refers to) to tween the values - we might want ThrowPropsPlugin or BezierPlugin some other plugin to do the actual tweening, so we create a plugin instance and store a reference here. We need this reference so that if we get a request to round values or disable a tween, we can pass along that request.
  45960. * - data: Arbitrary data that needs to be stored with the CSSPropTween. Typically if we're going to have a plugin handle the tweening of a complex-value tween, we create a generic object that stores the END values that we're tweening to and the CSSPropTween's xs1, xs2, etc. have the starting values. We store that object as data. That way, we can simply pass that object to the plugin and use the CSSPropTween as the target.
  45961. * - setRatio: Only used for type:2 tweens that require custom functionality. In this case, we call the CSSPropTween's setRatio() method and pass the ratio each time the tween updates. This isn't quite as efficient as doing things directly in the CSSPlugin's setRatio() method, but it's very convenient and flexible.
  45962. * @param {!Object} t Target object whose property will be tweened. Often a DOM element, but not always. It could be anything.
  45963. * @param {string} p Property to tween (name). For example, to tween element.width, p would be "width".
  45964. * @param {number} s Starting numeric value
  45965. * @param {number} c Change in numeric value over the course of the entire tween. For example, if element.width starts at 5 and should end at 100, c would be 95.
  45966. * @param {CSSPropTween=} next The next CSSPropTween in the linked list. If one is defined, we will define its _prev as the new instance, and the new instance's _next will be pointed at it.
  45967. * @param {number=} type The type of CSSPropTween where -1 = a non-tweening value, 0 = a standard simple tween, 1 = a complex value (like one that has multiple numbers in a comma- or space-delimited string like border:"1px solid red"), and 2 = one that uses a custom setRatio function that does all of the work of applying the values on each update.
  45968. * @param {string=} n Name of the property that should be used for overwriting purposes which is typically the same as p but not always. For example, we may need to create a subtween for the 2nd part of a "clip:rect(...)" tween in which case "p" might be xs1 but "n" is still "clip"
  45969. * @param {boolean=} r If true, the value(s) should be rounded
  45970. * @param {number=} pr Priority in the linked list order. Higher priority CSSPropTweens will be updated before lower priority ones. The default priority is 0.
  45971. * @param {string=} b Beginning value. We store this to ensure that it is EXACTLY what it was when the tween began without any risk of interpretation issues.
  45972. * @param {string=} e Ending value. We store this to ensure that it is EXACTLY what the user defined at the end of the tween without any risk of interpretation issues.
  45973. */
  45974. CSSPropTween = _internals.CSSPropTween = function(t, p, s, c, next, type, n, r, pr, b, e) {
  45975. this.t = t; //target
  45976. this.p = p; //property
  45977. this.s = s; //starting value
  45978. this.c = c; //change value
  45979. this.n = n || p; //name that this CSSPropTween should be associated to (usually the same as p, but not always - n is what overwriting looks at)
  45980. if (!(t instanceof CSSPropTween)) {
  45981. _overwriteProps.push(this.n);
  45982. }
  45983. this.r = r; //round (boolean)
  45984. this.type = type || 0; //0 = normal tween, -1 = non-tweening (in which case xs0 will be applied to the target's property, like tp.t[tp.p] = tp.xs0), 1 = complex-value SpecialProp, 2 = custom setRatio() that does all the work
  45985. if (pr) {
  45986. this.pr = pr;
  45987. _hasPriority = true;
  45988. }
  45989. this.b = (b === undefined) ? s : b;
  45990. this.e = (e === undefined) ? s + c : e;
  45991. if (next) {
  45992. this._next = next;
  45993. next._prev = this;
  45994. }
  45995. },
  45996. _addNonTweeningNumericPT = function(target, prop, start, end, next, overwriteProp) { //cleans up some code redundancies and helps minification. Just a fast way to add a NUMERIC non-tweening CSSPropTween
  45997. var pt = new CSSPropTween(target, prop, start, end - start, next, -1, overwriteProp);
  45998. pt.b = start;
  45999. pt.e = pt.xs0 = end;
  46000. return pt;
  46001. },
  46002. /**
  46003. * Takes a target, the beginning value and ending value (as strings) and parses them into a CSSPropTween (possibly with child CSSPropTweens) that accommodates multiple numbers, colors, comma-delimited values, etc. For example:
  46004. * sp.parseComplex(element, "boxShadow", "5px 10px 20px rgb(255,102,51)", "0px 0px 0px red", true, "0px 0px 0px rgb(0,0,0,0)", pt);
  46005. * It will walk through the beginning and ending values (which should be in the same format with the same number and type of values) and figure out which parts are numbers, what strings separate the numeric/tweenable values, and then create the CSSPropTweens accordingly. If a plugin is defined, no child CSSPropTweens will be created. Instead, the ending values will be stored in the "data" property of the returned CSSPropTween like: {s:-5, xn1:-10, xn2:-20, xn3:255, xn4:0, xn5:0} so that it can be fed to any other plugin and it'll be plain numeric tweens but the recomposition of the complex value will be handled inside CSSPlugin's setRatio().
  46006. * If a setRatio is defined, the type of the CSSPropTween will be set to 2 and recomposition of the values will be the responsibility of that method.
  46007. *
  46008. * @param {!Object} t Target whose property will be tweened
  46009. * @param {!string} p Property that will be tweened (its name, like "left" or "backgroundColor" or "boxShadow")
  46010. * @param {string} b Beginning value
  46011. * @param {string} e Ending value
  46012. * @param {boolean} clrs If true, the value could contain a color value like "rgb(255,0,0)" or "#F00" or "red". The default is false, so no colors will be recognized (a performance optimization)
  46013. * @param {(string|number|Object)} dflt The default beginning value that should be used if no valid beginning value is defined or if the number of values inside the complex beginning and ending values don't match
  46014. * @param {?CSSPropTween} pt CSSPropTween instance that is the current head of the linked list (we'll prepend to this).
  46015. * @param {number=} pr Priority in the linked list order. Higher priority properties will be updated before lower priority ones. The default priority is 0.
  46016. * @param {TweenPlugin=} plugin If a plugin should handle the tweening of extra properties, pass the plugin instance here. If one is defined, then NO subtweens will be created for any extra properties (the properties will be created - just not additional CSSPropTween instances to tween them) because the plugin is expected to do so. However, the end values WILL be populated in the "data" property, like {s:100, xn1:50, xn2:300}
  46017. * @param {function(number)=} setRatio If values should be set in a custom function instead of being pieced together in a type:1 (complex-value) CSSPropTween, define that custom function here.
  46018. * @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parseComplex() call.
  46019. */
  46020. _parseComplex = CSSPlugin.parseComplex = function(t, p, b, e, clrs, dflt, pt, pr, plugin, setRatio) {
  46021. //DEBUG: _log("parseComplex: "+p+", b: "+b+", e: "+e);
  46022. b = b || dflt || "";
  46023. if (typeof(e) === "function") {
  46024. e = e(_index, _target);
  46025. }
  46026. pt = new CSSPropTween(t, p, 0, 0, pt, (setRatio ? 2 : 1), null, false, pr, b, e);
  46027. e += ""; //ensures it's a string
  46028. if (clrs && _colorExp.test(e + b)) { //if colors are found, normalize the formatting to rgba() or hsla().
  46029. e = [b, e];
  46030. CSSPlugin.colorStringFilter(e);
  46031. b = e[0];
  46032. e = e[1];
  46033. }
  46034. var ba = b.split(", ").join(",").split(" "), //beginning array
  46035. ea = e.split(", ").join(",").split(" "), //ending array
  46036. l = ba.length,
  46037. autoRound = (_autoRound !== false),
  46038. i, xi, ni, bv, ev, bnums, enums, bn, hasAlpha, temp, cv, str, useHSL;
  46039. if (e.indexOf(",") !== -1 || b.indexOf(",") !== -1) {
  46040. ba = ba.join(" ").replace(_commasOutsideParenExp, ", ").split(" ");
  46041. ea = ea.join(" ").replace(_commasOutsideParenExp, ", ").split(" ");
  46042. l = ba.length;
  46043. }
  46044. if (l !== ea.length) {
  46045. //DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")");
  46046. ba = (dflt || "").split(" ");
  46047. l = ba.length;
  46048. }
  46049. pt.plugin = plugin;
  46050. pt.setRatio = setRatio;
  46051. _colorExp.lastIndex = 0;
  46052. for (i = 0; i < l; i++) {
  46053. bv = ba[i];
  46054. ev = ea[i];
  46055. bn = parseFloat(bv);
  46056. //if the value begins with a number (most common). It's fine if it has a suffix like px
  46057. if (bn || bn === 0) {
  46058. pt.appendXtra("", bn, _parseChange(ev, bn), ev.replace(_relNumExp, ""), (autoRound && ev.indexOf("px") !== -1), true);
  46059. //if the value is a color
  46060. } else if (clrs && _colorExp.test(bv)) {
  46061. str = ev.indexOf(")") + 1;
  46062. str = ")" + (str ? ev.substr(str) : ""); //if there's a comma or ) at the end, retain it.
  46063. useHSL = (ev.indexOf("hsl") !== -1 && _supportsOpacity);
  46064. temp = ev; //original string value so we can look for any prefix later.
  46065. bv = _parseColor(bv, useHSL);
  46066. ev = _parseColor(ev, useHSL);
  46067. hasAlpha = (bv.length + ev.length > 6);
  46068. if (hasAlpha && !_supportsOpacity && ev[3] === 0) { //older versions of IE don't support rgba(), so if the destination alpha is 0, just use "transparent" for the end color
  46069. pt["xs" + pt.l] += pt.l ? " transparent" : "transparent";
  46070. pt.e = pt.e.split(ea[i]).join("transparent");
  46071. } else {
  46072. if (!_supportsOpacity) { //old versions of IE don't support rgba().
  46073. hasAlpha = false;
  46074. }
  46075. if (useHSL) {
  46076. pt.appendXtra(temp.substr(0, temp.indexOf("hsl")) + (hasAlpha ? "hsla(" : "hsl("), bv[0], _parseChange(ev[0], bv[0]), ",", false, true)
  46077. .appendXtra("", bv[1], _parseChange(ev[1], bv[1]), "%,", false)
  46078. .appendXtra("", bv[2], _parseChange(ev[2], bv[2]), (hasAlpha ? "%," : "%" + str), false);
  46079. } else {
  46080. pt.appendXtra(temp.substr(0, temp.indexOf("rgb")) + (hasAlpha ? "rgba(" : "rgb("), bv[0], ev[0] - bv[0], ",", true, true)
  46081. .appendXtra("", bv[1], ev[1] - bv[1], ",", true)
  46082. .appendXtra("", bv[2], ev[2] - bv[2], (hasAlpha ? "," : str), true);
  46083. }
  46084. if (hasAlpha) {
  46085. bv = (bv.length < 4) ? 1 : bv[3];
  46086. pt.appendXtra("", bv, ((ev.length < 4) ? 1 : ev[3]) - bv, str, false);
  46087. }
  46088. }
  46089. _colorExp.lastIndex = 0; //otherwise the test() on the RegExp could move the lastIndex and taint future results.
  46090. } else {
  46091. bnums = bv.match(_numExp); //gets each group of numbers in the beginning value string and drops them into an array
  46092. //if no number is found, treat it as a non-tweening value and just append the string to the current xs.
  46093. if (!bnums) {
  46094. pt["xs" + pt.l] += (pt.l || pt["xs" + pt.l]) ? " " + ev : ev;
  46095. //loop through all the numbers that are found and construct the extra values on the pt.
  46096. } else {
  46097. enums = ev.match(_relNumExp); //get each group of numbers in the end value string and drop them into an array. We allow relative values too, like +=50 or -=.5
  46098. if (!enums || enums.length !== bnums.length) {
  46099. //DEBUG: _log("mismatched formatting detected on " + p + " (" + b + " vs " + e + ")");
  46100. return pt;
  46101. }
  46102. ni = 0;
  46103. for (xi = 0; xi < bnums.length; xi++) {
  46104. cv = bnums[xi];
  46105. temp = bv.indexOf(cv, ni);
  46106. pt.appendXtra(bv.substr(ni, temp - ni), Number(cv), _parseChange(enums[xi], cv), "", (autoRound && bv.substr(temp + cv.length, 2) === "px"), (xi === 0));
  46107. ni = temp + cv.length;
  46108. }
  46109. pt["xs" + pt.l] += bv.substr(ni);
  46110. }
  46111. }
  46112. }
  46113. //if there are relative values ("+=" or "-=" prefix), we need to adjust the ending value to eliminate the prefixes and combine the values properly.
  46114. if (e.indexOf("=") !== -1) if (pt.data) {
  46115. str = pt.xs0 + pt.data.s;
  46116. for (i = 1; i < pt.l; i++) {
  46117. str += pt["xs" + i] + pt.data["xn" + i];
  46118. }
  46119. pt.e = str + pt["xs" + i];
  46120. }
  46121. if (!pt.l) {
  46122. pt.type = -1;
  46123. pt.xs0 = pt.e;
  46124. }
  46125. return pt.xfirst || pt;
  46126. },
  46127. i = 9;
  46128. p = CSSPropTween.prototype;
  46129. p.l = p.pr = 0; //length (number of extra properties like xn1, xn2, xn3, etc.
  46130. while (--i > 0) {
  46131. p["xn" + i] = 0;
  46132. p["xs" + i] = "";
  46133. }
  46134. p.xs0 = "";
  46135. p._next = p._prev = p.xfirst = p.data = p.plugin = p.setRatio = p.rxp = null;
  46136. /**
  46137. * Appends and extra tweening value to a CSSPropTween and automatically manages any prefix and suffix strings. The first extra value is stored in the s and c of the main CSSPropTween instance, but thereafter any extras are stored in the xn1, xn2, xn3, etc. The prefixes and suffixes are stored in the xs0, xs1, xs2, etc. properties. For example, if I walk through a clip value like "rect(10px, 5px, 0px, 20px)", the values would be stored like this:
  46138. * xs0:"rect(", s:10, xs1:"px, ", xn1:5, xs2:"px, ", xn2:0, xs3:"px, ", xn3:20, xn4:"px)"
  46139. * And they'd all get joined together when the CSSPlugin renders (in the setRatio() method).
  46140. * @param {string=} pfx Prefix (if any)
  46141. * @param {!number} s Starting value
  46142. * @param {!number} c Change in numeric value over the course of the entire tween. For example, if the start is 5 and the end is 100, the change would be 95.
  46143. * @param {string=} sfx Suffix (if any)
  46144. * @param {boolean=} r Round (if true).
  46145. * @param {boolean=} pad If true, this extra value should be separated by the previous one by a space. If there is no previous extra and pad is true, it will automatically drop the space.
  46146. * @return {CSSPropTween} returns itself so that multiple methods can be chained together.
  46147. */
  46148. p.appendXtra = function(pfx, s, c, sfx, r, pad) {
  46149. var pt = this,
  46150. l = pt.l;
  46151. pt["xs" + l] += (pad && (l || pt["xs" + l])) ? " " + pfx : pfx || "";
  46152. if (!c) if (l !== 0 && !pt.plugin) { //typically we'll combine non-changing values right into the xs to optimize performance, but we don't combine them when there's a plugin that will be tweening the values because it may depend on the values being split apart, like for a bezier, if a value doesn't change between the first and second iteration but then it does on the 3rd, we'll run into trouble because there's no xn slot for that value!
  46153. pt["xs" + l] += s + (sfx || "");
  46154. return pt;
  46155. }
  46156. pt.l++;
  46157. pt.type = pt.setRatio ? 2 : 1;
  46158. pt["xs" + pt.l] = sfx || "";
  46159. if (l > 0) {
  46160. pt.data["xn" + l] = s + c;
  46161. pt.rxp["xn" + l] = r; //round extra property (we need to tap into this in the _parseToProxy() method)
  46162. pt["xn" + l] = s;
  46163. if (!pt.plugin) {
  46164. pt.xfirst = new CSSPropTween(pt, "xn" + l, s, c, pt.xfirst || pt, 0, pt.n, r, pt.pr);
  46165. pt.xfirst.xs0 = 0; //just to ensure that the property stays numeric which helps modern browsers speed up processing. Remember, in the setRatio() method, we do pt.t[pt.p] = val + pt.xs0 so if pt.xs0 is "" (the default), it'll cast the end value as a string. When a property is a number sometimes and a string sometimes, it prevents the compiler from locking in the data type, slowing things down slightly.
  46166. }
  46167. return pt;
  46168. }
  46169. pt.data = {s:s + c};
  46170. pt.rxp = {};
  46171. pt.s = s;
  46172. pt.c = c;
  46173. pt.r = r;
  46174. return pt;
  46175. };
  46176. /**
  46177. * @constructor A SpecialProp is basically a css property that needs to be treated in a non-standard way, like if it may contain a complex value like boxShadow:"5px 10px 15px rgb(255, 102, 51)" or if it is associated with another plugin like ThrowPropsPlugin or BezierPlugin. Every SpecialProp is associated with a particular property name like "boxShadow" or "throwProps" or "bezier" and it will intercept those values in the vars object that's passed to the CSSPlugin and handle them accordingly.
  46178. * @param {!string} p Property name (like "boxShadow" or "throwProps")
  46179. * @param {Object=} options An object containing any of the following configuration options:
  46180. * - defaultValue: the default value
  46181. * - parser: A function that should be called when the associated property name is found in the vars. This function should return a CSSPropTween instance and it should ensure that it is properly inserted into the linked list. It will receive 4 paramters: 1) The target, 2) The value defined in the vars, 3) The CSSPlugin instance (whose _firstPT should be used for the linked list), and 4) A computed style object if one was calculated (this is a speed optimization that allows retrieval of starting values quicker)
  46182. * - formatter: a function that formats any value received for this special property (for example, boxShadow could take "5px 5px red" and format it to "5px 5px 0px 0px red" so that both the beginning and ending values have a common order and quantity of values.)
  46183. * - prefix: if true, we'll determine whether or not this property requires a vendor prefix (like Webkit or Moz or ms or O)
  46184. * - color: set this to true if the value for this SpecialProp may contain color-related values like rgb(), rgba(), etc.
  46185. * - priority: priority in the linked list order. Higher priority SpecialProps will be updated before lower priority ones. The default priority is 0.
  46186. * - multi: if true, the formatter should accommodate a comma-delimited list of values, like boxShadow could have multiple boxShadows listed out.
  46187. * - collapsible: if true, the formatter should treat the value like it's a top/right/bottom/left value that could be collapsed, like "5px" would apply to all, "5px, 10px" would use 5px for top/bottom and 10px for right/left, etc.
  46188. * - keyword: a special keyword that can [optionally] be found inside the value (like "inset" for boxShadow). This allows us to validate beginning/ending values to make sure they match (if the keyword is found in one, it'll be added to the other for consistency by default).
  46189. */
  46190. var SpecialProp = function(p, options) {
  46191. options = options || {};
  46192. this.p = options.prefix ? _checkPropPrefix(p) || p : p;
  46193. _specialProps[p] = _specialProps[this.p] = this;
  46194. this.format = options.formatter || _getFormatter(options.defaultValue, options.color, options.collapsible, options.multi);
  46195. if (options.parser) {
  46196. this.parse = options.parser;
  46197. }
  46198. this.clrs = options.color;
  46199. this.multi = options.multi;
  46200. this.keyword = options.keyword;
  46201. this.dflt = options.defaultValue;
  46202. this.pr = options.priority || 0;
  46203. },
  46204. //shortcut for creating a new SpecialProp that can accept multiple properties as a comma-delimited list (helps minification). dflt can be an array for multiple values (we don't do a comma-delimited list because the default value may contain commas, like rect(0px,0px,0px,0px)). We attach this method to the SpecialProp class/object instead of using a private _createSpecialProp() method so that we can tap into it externally if necessary, like from another plugin.
  46205. _registerComplexSpecialProp = _internals._registerComplexSpecialProp = function(p, options, defaults) {
  46206. if (typeof(options) !== "object") {
  46207. options = {parser:defaults}; //to make backwards compatible with older versions of BezierPlugin and ThrowPropsPlugin
  46208. }
  46209. var a = p.split(","),
  46210. d = options.defaultValue,
  46211. i, temp;
  46212. defaults = defaults || [d];
  46213. for (i = 0; i < a.length; i++) {
  46214. options.prefix = (i === 0 && options.prefix);
  46215. options.defaultValue = defaults[i] || d;
  46216. temp = new SpecialProp(a[i], options);
  46217. }
  46218. },
  46219. //creates a placeholder special prop for a plugin so that the property gets caught the first time a tween of it is attempted, and at that time it makes the plugin register itself, thus taking over for all future tweens of that property. This allows us to not mandate that things load in a particular order and it also allows us to log() an error that informs the user when they attempt to tween an external plugin-related property without loading its .js file.
  46220. _registerPluginProp = _internals._registerPluginProp = function(p) {
  46221. if (!_specialProps[p]) {
  46222. var pluginName = p.charAt(0).toUpperCase() + p.substr(1) + "Plugin";
  46223. _registerComplexSpecialProp(p, {parser:function(t, e, p, cssp, pt, plugin, vars) {
  46224. var pluginClass = _globals.com.greensock.plugins[pluginName];
  46225. if (!pluginClass) {
  46226. _log("Error: " + pluginName + " js file not loaded.");
  46227. return pt;
  46228. }
  46229. pluginClass._cssRegister();
  46230. return _specialProps[p].parse(t, e, p, cssp, pt, plugin, vars);
  46231. }});
  46232. }
  46233. };
  46234. p = SpecialProp.prototype;
  46235. /**
  46236. * Alias for _parseComplex() that automatically plugs in certain values for this SpecialProp, like its property name, whether or not colors should be sensed, the default value, and priority. It also looks for any keyword that the SpecialProp defines (like "inset" for boxShadow) and ensures that the beginning and ending values have the same number of values for SpecialProps where multi is true (like boxShadow and textShadow can have a comma-delimited list)
  46237. * @param {!Object} t target element
  46238. * @param {(string|number|object)} b beginning value
  46239. * @param {(string|number|object)} e ending (destination) value
  46240. * @param {CSSPropTween=} pt next CSSPropTween in the linked list
  46241. * @param {TweenPlugin=} plugin If another plugin will be tweening the complex value, that TweenPlugin instance goes here.
  46242. * @param {function=} setRatio If a custom setRatio() method should be used to handle this complex value, that goes here.
  46243. * @return {CSSPropTween=} First CSSPropTween in the linked list
  46244. */
  46245. p.parseComplex = function(t, b, e, pt, plugin, setRatio) {
  46246. var kwd = this.keyword,
  46247. i, ba, ea, l, bi, ei;
  46248. //if this SpecialProp's value can contain a comma-delimited list of values (like boxShadow or textShadow), we must parse them in a special way, and look for a keyword (like "inset" for boxShadow) and ensure that the beginning and ending BOTH have it if the end defines it as such. We also must ensure that there are an equal number of values specified (we can't tween 1 boxShadow to 3 for example)
  46249. if (this.multi) if (_commasOutsideParenExp.test(e) || _commasOutsideParenExp.test(b)) {
  46250. ba = b.replace(_commasOutsideParenExp, "|").split("|");
  46251. ea = e.replace(_commasOutsideParenExp, "|").split("|");
  46252. } else if (kwd) {
  46253. ba = [b];
  46254. ea = [e];
  46255. }
  46256. if (ea) {
  46257. l = (ea.length > ba.length) ? ea.length : ba.length;
  46258. for (i = 0; i < l; i++) {
  46259. b = ba[i] = ba[i] || this.dflt;
  46260. e = ea[i] = ea[i] || this.dflt;
  46261. if (kwd) {
  46262. bi = b.indexOf(kwd);
  46263. ei = e.indexOf(kwd);
  46264. if (bi !== ei) {
  46265. if (ei === -1) { //if the keyword isn't in the end value, remove it from the beginning one.
  46266. ba[i] = ba[i].split(kwd).join("");
  46267. } else if (bi === -1) { //if the keyword isn't in the beginning, add it.
  46268. ba[i] += " " + kwd;
  46269. }
  46270. }
  46271. }
  46272. }
  46273. b = ba.join(", ");
  46274. e = ea.join(", ");
  46275. }
  46276. return _parseComplex(t, this.p, b, e, this.clrs, this.dflt, pt, this.pr, plugin, setRatio);
  46277. };
  46278. /**
  46279. * Accepts a target and end value and spits back a CSSPropTween that has been inserted into the CSSPlugin's linked list and conforms with all the conventions we use internally, like type:-1, 0, 1, or 2, setting up any extra property tweens, priority, etc. For example, if we have a boxShadow SpecialProp and call:
  46280. * this._firstPT = sp.parse(element, "5px 10px 20px rgb(2550,102,51)", "boxShadow", this);
  46281. * It should figure out the starting value of the element's boxShadow, compare it to the provided end value and create all the necessary CSSPropTweens of the appropriate types to tween the boxShadow. The CSSPropTween that gets spit back should already be inserted into the linked list (the 4th parameter is the current head, so prepend to that).
  46282. * @param {!Object} t Target object whose property is being tweened
  46283. * @param {Object} e End value as provided in the vars object (typically a string, but not always - like a throwProps would be an object).
  46284. * @param {!string} p Property name
  46285. * @param {!CSSPlugin} cssp The CSSPlugin instance that should be associated with this tween.
  46286. * @param {?CSSPropTween} pt The CSSPropTween that is the current head of the linked list (we'll prepend to it)
  46287. * @param {TweenPlugin=} plugin If a plugin will be used to tween the parsed value, this is the plugin instance.
  46288. * @param {Object=} vars Original vars object that contains the data for parsing.
  46289. * @return {CSSPropTween} The first CSSPropTween in the linked list which includes the new one(s) added by the parse() call.
  46290. */
  46291. p.parse = function(t, e, p, cssp, pt, plugin, vars) {
  46292. return this.parseComplex(t.style, this.format(_getStyle(t, this.p, _cs, false, this.dflt)), this.format(e), pt, plugin);
  46293. };
  46294. /**
  46295. * Registers a special property that should be intercepted from any "css" objects defined in tweens. This allows you to handle them however you want without CSSPlugin doing it for you. The 2nd parameter should be a function that accepts 3 parameters:
  46296. * 1) Target object whose property should be tweened (typically a DOM element)
  46297. * 2) The end/destination value (could be a string, number, object, or whatever you want)
  46298. * 3) The tween instance (you probably don't need to worry about this, but it can be useful for looking up information like the duration)
  46299. *
  46300. * Then, your function should return a function which will be called each time the tween gets rendered, passing a numeric "ratio" parameter to your function that indicates the change factor (usually between 0 and 1). For example:
  46301. *
  46302. * CSSPlugin.registerSpecialProp("myCustomProp", function(target, value, tween) {
  46303. * var start = target.style.width;
  46304. * return function(ratio) {
  46305. * target.style.width = (start + value * ratio) + "px";
  46306. * console.log("set width to " + target.style.width);
  46307. * }
  46308. * }, 0);
  46309. *
  46310. * Then, when I do this tween, it will trigger my special property:
  46311. *
  46312. * TweenLite.to(element, 1, {css:{myCustomProp:100}});
  46313. *
  46314. * In the example, of course, we're just changing the width, but you can do anything you want.
  46315. *
  46316. * @param {!string} name Property name (or comma-delimited list of property names) that should be intercepted and handled by your function. For example, if I define "myCustomProp", then it would handle that portion of the following tween: TweenLite.to(element, 1, {css:{myCustomProp:100}})
  46317. * @param {!function(Object, Object, Object, string):function(number)} onInitTween The function that will be called when a tween of this special property is performed. The function will receive 4 parameters: 1) Target object that should be tweened, 2) Value that was passed to the tween, 3) The tween instance itself (rarely used), and 4) The property name that's being tweened. Your function should return a function that should be called on every update of the tween. That function will receive a single parameter that is a "change factor" value (typically between 0 and 1) indicating the amount of change as a ratio. You can use this to determine how to set the values appropriately in your function.
  46318. * @param {number=} priority Priority that helps the engine determine the order in which to set the properties (default: 0). Higher priority properties will be updated before lower priority ones.
  46319. */
  46320. CSSPlugin.registerSpecialProp = function(name, onInitTween, priority) {
  46321. _registerComplexSpecialProp(name, {parser:function(t, e, p, cssp, pt, plugin, vars) {
  46322. var rv = new CSSPropTween(t, p, 0, 0, pt, 2, p, false, priority);
  46323. rv.plugin = plugin;
  46324. rv.setRatio = onInitTween(t, e, cssp._tween, p);
  46325. return rv;
  46326. }, priority:priority});
  46327. };
  46328. //transform-related methods and properties
  46329. CSSPlugin.useSVGTransformAttr = true; //Safari and Firefox both have some rendering bugs when applying CSS transforms to SVG elements, so default to using the "transform" attribute instead (users can override this).
  46330. var _transformProps = ("scaleX,scaleY,scaleZ,x,y,z,skewX,skewY,rotation,rotationX,rotationY,perspective,xPercent,yPercent").split(","),
  46331. _transformProp = _checkPropPrefix("transform"), //the Javascript (camelCase) transform property, like msTransform, WebkitTransform, MozTransform, or OTransform.
  46332. _transformPropCSS = _prefixCSS + "transform",
  46333. _transformOriginProp = _checkPropPrefix("transformOrigin"),
  46334. _supports3D = (_checkPropPrefix("perspective") !== null),
  46335. Transform = _internals.Transform = function() {
  46336. this.perspective = parseFloat(CSSPlugin.defaultTransformPerspective) || 0;
  46337. this.force3D = (CSSPlugin.defaultForce3D === false || !_supports3D) ? false : CSSPlugin.defaultForce3D || "auto";
  46338. },
  46339. _SVGElement = _gsScope.SVGElement,
  46340. _useSVGTransformAttr,
  46341. //Some browsers (like Firefox and IE) don't honor transform-origin properly in SVG elements, so we need to manually adjust the matrix accordingly. We feature detect here rather than always doing the conversion for certain browsers because they may fix the problem at some point in the future.
  46342. _createSVG = function(type, container, attributes) {
  46343. var element = _doc.createElementNS("http://www.w3.org/2000/svg", type),
  46344. reg = /([a-z])([A-Z])/g,
  46345. p;
  46346. for (p in attributes) {
  46347. element.setAttributeNS(null, p.replace(reg, "$1-$2").toLowerCase(), attributes[p]);
  46348. }
  46349. container.appendChild(element);
  46350. return element;
  46351. },
  46352. _docElement = _doc.documentElement || {},
  46353. _forceSVGTransformAttr = (function() {
  46354. //IE and Android stock don't support CSS transforms on SVG elements, so we must write them to the "transform" attribute. We populate this variable in the _parseTransform() method, and only if/when we come across an SVG element
  46355. var force = _ieVers || (/Android/i.test(_agent) && !_gsScope.chrome),
  46356. svg, rect, width;
  46357. if (_doc.createElementNS && !force) { //IE8 and earlier doesn't support SVG anyway
  46358. svg = _createSVG("svg", _docElement);
  46359. rect = _createSVG("rect", svg, {width:100, height:50, x:100});
  46360. width = rect.getBoundingClientRect().width;
  46361. rect.style[_transformOriginProp] = "50% 50%";
  46362. rect.style[_transformProp] = "scaleX(0.5)";
  46363. force = (width === rect.getBoundingClientRect().width && !(_isFirefox && _supports3D)); //note: Firefox fails the test even though it does support CSS transforms in 3D. Since we can't push 3D stuff into the transform attribute, we force Firefox to pass the test here (as long as it does truly support 3D).
  46364. _docElement.removeChild(svg);
  46365. }
  46366. return force;
  46367. })(),
  46368. _parseSVGOrigin = function(e, local, decoratee, absolute, smoothOrigin, skipRecord) {
  46369. var tm = e._gsTransform,
  46370. m = _getMatrix(e, true),
  46371. v, x, y, xOrigin, yOrigin, a, b, c, d, tx, ty, determinant, xOriginOld, yOriginOld;
  46372. if (tm) {
  46373. xOriginOld = tm.xOrigin; //record the original values before we alter them.
  46374. yOriginOld = tm.yOrigin;
  46375. }
  46376. if (!absolute || (v = absolute.split(" ")).length < 2) {
  46377. b = e.getBBox();
  46378. if (b.x === 0 && b.y === 0 && b.width + b.height === 0) { //some browsers (like Firefox) misreport the bounds if the element has zero width and height (it just assumes it's at x:0, y:0), thus we need to manually grab the position in that case.
  46379. b = {x: parseFloat(e.hasAttribute("x") ? e.getAttribute("x") : e.hasAttribute("cx") ? e.getAttribute("cx") : 0) || 0, y: parseFloat(e.hasAttribute("y") ? e.getAttribute("y") : e.hasAttribute("cy") ? e.getAttribute("cy") : 0) || 0, width:0, height:0};
  46380. }
  46381. local = _parsePosition(local).split(" ");
  46382. v = [(local[0].indexOf("%") !== -1 ? parseFloat(local[0]) / 100 * b.width : parseFloat(local[0])) + b.x,
  46383. (local[1].indexOf("%") !== -1 ? parseFloat(local[1]) / 100 * b.height : parseFloat(local[1])) + b.y];
  46384. }
  46385. decoratee.xOrigin = xOrigin = parseFloat(v[0]);
  46386. decoratee.yOrigin = yOrigin = parseFloat(v[1]);
  46387. if (absolute && m !== _identity2DMatrix) { //if svgOrigin is being set, we must invert the matrix and determine where the absolute point is, factoring in the current transforms. Otherwise, the svgOrigin would be based on the element's non-transformed position on the canvas.
  46388. a = m[0];
  46389. b = m[1];
  46390. c = m[2];
  46391. d = m[3];
  46392. tx = m[4];
  46393. ty = m[5];
  46394. determinant = (a * d - b * c);
  46395. if (determinant) { //if it's zero (like if scaleX and scaleY are zero), skip it to avoid errors with dividing by zero.
  46396. x = xOrigin * (d / determinant) + yOrigin * (-c / determinant) + ((c * ty - d * tx) / determinant);
  46397. y = xOrigin * (-b / determinant) + yOrigin * (a / determinant) - ((a * ty - b * tx) / determinant);
  46398. xOrigin = decoratee.xOrigin = v[0] = x;
  46399. yOrigin = decoratee.yOrigin = v[1] = y;
  46400. }
  46401. }
  46402. if (tm) { //avoid jump when transformOrigin is changed - adjust the x/y values accordingly
  46403. if (skipRecord) {
  46404. decoratee.xOffset = tm.xOffset;
  46405. decoratee.yOffset = tm.yOffset;
  46406. tm = decoratee;
  46407. }
  46408. if (smoothOrigin || (smoothOrigin !== false && CSSPlugin.defaultSmoothOrigin !== false)) {
  46409. x = xOrigin - xOriginOld;
  46410. y = yOrigin - yOriginOld;
  46411. //originally, we simply adjusted the x and y values, but that would cause problems if, for example, you created a rotational tween part-way through an x/y tween. Managing the offset in a separate variable gives us ultimate flexibility.
  46412. //tm.x -= x - (x * m[0] + y * m[2]);
  46413. //tm.y -= y - (x * m[1] + y * m[3]);
  46414. tm.xOffset += (x * m[0] + y * m[2]) - x;
  46415. tm.yOffset += (x * m[1] + y * m[3]) - y;
  46416. } else {
  46417. tm.xOffset = tm.yOffset = 0;
  46418. }
  46419. }
  46420. if (!skipRecord) {
  46421. e.setAttribute("data-svg-origin", v.join(" "));
  46422. }
  46423. },
  46424. _getBBoxHack = function(swapIfPossible) { //works around issues in some browsers (like Firefox) that don't correctly report getBBox() on SVG elements inside a <defs> element and/or <mask>. We try creating an SVG, adding it to the documentElement and toss the element in there so that it's definitely part of the rendering tree, then grab the bbox and if it works, we actually swap out the original getBBox() method for our own that does these extra steps whenever getBBox is needed. This helps ensure that performance is optimal (only do all these extra steps when absolutely necessary...most elements don't need it).
  46425. var svg = _createElement("svg", this.ownerSVGElement.getAttribute("xmlns") || "http://www.w3.org/2000/svg"),
  46426. oldParent = this.parentNode,
  46427. oldSibling = this.nextSibling,
  46428. oldCSS = this.style.cssText,
  46429. bbox;
  46430. _docElement.appendChild(svg);
  46431. svg.appendChild(this);
  46432. this.style.display = "block";
  46433. if (swapIfPossible) {
  46434. try {
  46435. bbox = this.getBBox();
  46436. this._originalGetBBox = this.getBBox;
  46437. this.getBBox = _getBBoxHack;
  46438. } catch (e) { }
  46439. } else if (this._originalGetBBox) {
  46440. bbox = this._originalGetBBox();
  46441. }
  46442. if (oldSibling) {
  46443. oldParent.insertBefore(this, oldSibling);
  46444. } else {
  46445. oldParent.appendChild(this);
  46446. }
  46447. _docElement.removeChild(svg);
  46448. this.style.cssText = oldCSS;
  46449. return bbox;
  46450. },
  46451. _getBBox = function(e) {
  46452. try {
  46453. return e.getBBox(); //Firefox throws errors if you try calling getBBox() on an SVG element that's not rendered (like in a <symbol> or <defs>). https://bugzilla.mozilla.org/show_bug.cgi?id=612118
  46454. } catch (error) {
  46455. return _getBBoxHack.call(e, true);
  46456. }
  46457. },
  46458. _isSVG = function(e) { //reports if the element is an SVG on which getBBox() actually works
  46459. return !!(_SVGElement && e.getCTM && _getBBox(e) && (!e.parentNode || e.ownerSVGElement));
  46460. },
  46461. _identity2DMatrix = [1,0,0,1,0,0],
  46462. _getMatrix = function(e, force2D) {
  46463. var tm = e._gsTransform || new Transform(),
  46464. rnd = 100000,
  46465. style = e.style,
  46466. isDefault, s, m, n, dec, none;
  46467. if (_transformProp) {
  46468. s = _getStyle(e, _transformPropCSS, null, true);
  46469. } else if (e.currentStyle) {
  46470. //for older versions of IE, we need to interpret the filter portion that is in the format: progid:DXImageTransform.Microsoft.Matrix(M11=6.123233995736766e-17, M12=-1, M21=1, M22=6.123233995736766e-17, sizingMethod='auto expand') Notice that we need to swap b and c compared to a normal matrix.
  46471. s = e.currentStyle.filter.match(_ieGetMatrixExp);
  46472. s = (s && s.length === 4) ? [s[0].substr(4), Number(s[2].substr(4)), Number(s[1].substr(4)), s[3].substr(4), (tm.x || 0), (tm.y || 0)].join(",") : "";
  46473. }
  46474. isDefault = (!s || s === "none" || s === "matrix(1, 0, 0, 1, 0, 0)");
  46475. if (_transformProp && ((none = (_getComputedStyle(e).display === "none")) || !e.parentNode)) {
  46476. if (none) { //browsers don't report transforms accurately unless the element is in the DOM and has a display value that's not "none". Firefox and Microsoft browsers have a partial bug where they'll report transforms even if display:none BUT not any percentage-based values like translate(-50%, 8px) will be reported as if it's translate(0, 8px).
  46477. n = style.display;
  46478. style.display = "block";
  46479. }
  46480. if (!e.parentNode) {
  46481. dec = 1; //flag
  46482. _docElement.appendChild(e);
  46483. }
  46484. s = _getStyle(e, _transformPropCSS, null, true);
  46485. isDefault = (!s || s === "none" || s === "matrix(1, 0, 0, 1, 0, 0)");
  46486. if (n) {
  46487. style.display = n;
  46488. } else if (none) {
  46489. _removeProp(style, "display");
  46490. }
  46491. if (dec) {
  46492. _docElement.removeChild(e);
  46493. }
  46494. }
  46495. if (tm.svg || (e.getCTM && _isSVG(e))) {
  46496. if (isDefault && (style[_transformProp] + "").indexOf("matrix") !== -1) { //some browsers (like Chrome 40) don't correctly report transforms that are applied inline on an SVG element (they don't get included in the computed style), so we double-check here and accept matrix values
  46497. s = style[_transformProp];
  46498. isDefault = 0;
  46499. }
  46500. m = e.getAttribute("transform");
  46501. if (isDefault && m) {
  46502. if (m.indexOf("matrix") !== -1) { //just in case there's a "transform" value specified as an attribute instead of CSS style. Accept either a matrix() or simple translate() value though.
  46503. s = m;
  46504. isDefault = 0;
  46505. } else if (m.indexOf("translate") !== -1) {
  46506. s = "matrix(1,0,0,1," + m.match(/(?:\-|\b)[\d\-\.e]+\b/gi).join(",") + ")";
  46507. isDefault = 0;
  46508. }
  46509. }
  46510. }
  46511. if (isDefault) {
  46512. return _identity2DMatrix;
  46513. }
  46514. //split the matrix values out into an array (m for matrix)
  46515. m = (s || "").match(_numExp) || [];
  46516. i = m.length;
  46517. while (--i > -1) {
  46518. n = Number(m[i]);
  46519. m[i] = (dec = n - (n |= 0)) ? ((dec * rnd + (dec < 0 ? -0.5 : 0.5)) | 0) / rnd + n : n; //convert strings to Numbers and round to 5 decimal places to avoid issues with tiny numbers. Roughly 20x faster than Number.toFixed(). We also must make sure to round before dividing so that values like 0.9999999999 become 1 to avoid glitches in browser rendering and interpretation of flipped/rotated 3D matrices. And don't just multiply the number by rnd, floor it, and then divide by rnd because the bitwise operations max out at a 32-bit signed integer, thus it could get clipped at a relatively low value (like 22,000.00000 for example).
  46520. }
  46521. return (force2D && m.length > 6) ? [m[0], m[1], m[4], m[5], m[12], m[13]] : m;
  46522. },
  46523. /**
  46524. * Parses the transform values for an element, returning an object with x, y, z, scaleX, scaleY, scaleZ, rotation, rotationX, rotationY, skewX, and skewY properties. Note: by default (for performance reasons), all skewing is combined into skewX and rotation but skewY still has a place in the transform object so that we can record how much of the skew is attributed to skewX vs skewY. Remember, a skewY of 10 looks the same as a rotation of 10 and skewX of -10.
  46525. * @param {!Object} t target element
  46526. * @param {Object=} cs computed style object (optional)
  46527. * @param {boolean=} rec if true, the transform values will be recorded to the target element's _gsTransform object, like target._gsTransform = {x:0, y:0, z:0, scaleX:1...}
  46528. * @param {boolean=} parse if true, we'll ignore any _gsTransform values that already exist on the element, and force a reparsing of the css (calculated style)
  46529. * @return {object} object containing all of the transform properties/values like {x:0, y:0, z:0, scaleX:1...}
  46530. */
  46531. _getTransform = _internals.getTransform = function(t, cs, rec, parse) {
  46532. if (t._gsTransform && rec && !parse) {
  46533. return t._gsTransform; //if the element already has a _gsTransform, use that. Note: some browsers don't accurately return the calculated style for the transform (particularly for SVG), so it's almost always safest to just use the values we've already applied rather than re-parsing things.
  46534. }
  46535. var tm = rec ? t._gsTransform || new Transform() : new Transform(),
  46536. invX = (tm.scaleX < 0), //in order to interpret things properly, we need to know if the user applied a negative scaleX previously so that we can adjust the rotation and skewX accordingly. Otherwise, if we always interpret a flipped matrix as affecting scaleY and the user only wants to tween the scaleX on multiple sequential tweens, it would keep the negative scaleY without that being the user's intent.
  46537. min = 0.00002,
  46538. rnd = 100000,
  46539. zOrigin = _supports3D ? parseFloat(_getStyle(t, _transformOriginProp, cs, false, "0 0 0").split(" ")[2]) || tm.zOrigin || 0 : 0,
  46540. defaultTransformPerspective = parseFloat(CSSPlugin.defaultTransformPerspective) || 0,
  46541. m, i, scaleX, scaleY, rotation, skewX;
  46542. tm.svg = !!(t.getCTM && _isSVG(t));
  46543. if (tm.svg) {
  46544. _parseSVGOrigin(t, _getStyle(t, _transformOriginProp, cs, false, "50% 50%") + "", tm, t.getAttribute("data-svg-origin"));
  46545. _useSVGTransformAttr = CSSPlugin.useSVGTransformAttr || _forceSVGTransformAttr;
  46546. }
  46547. m = _getMatrix(t);
  46548. if (m !== _identity2DMatrix) {
  46549. if (m.length === 16) {
  46550. //we'll only look at these position-related 6 variables first because if x/y/z all match, it's relatively safe to assume we don't need to re-parse everything which risks losing important rotational information (like rotationX:180 plus rotationY:180 would look the same as rotation:180 - there's no way to know for sure which direction was taken based solely on the matrix3d() values)
  46551. var a11 = m[0], a21 = m[1], a31 = m[2], a41 = m[3],
  46552. a12 = m[4], a22 = m[5], a32 = m[6], a42 = m[7],
  46553. a13 = m[8], a23 = m[9], a33 = m[10],
  46554. a14 = m[12], a24 = m[13], a34 = m[14],
  46555. a43 = m[11],
  46556. angle = Math.atan2(a32, a33),
  46557. t1, t2, t3, t4, cos, sin;
  46558. //we manually compensate for non-zero z component of transformOrigin to work around bugs in Safari
  46559. if (tm.zOrigin) {
  46560. a34 = -tm.zOrigin;
  46561. a14 = a13*a34-m[12];
  46562. a24 = a23*a34-m[13];
  46563. a34 = a33*a34+tm.zOrigin-m[14];
  46564. }
  46565. //note for possible future consolidation: rotationX: Math.atan2(a32, a33), rotationY: Math.atan2(-a31, Math.sqrt(a33 * a33 + a32 * a32)), rotation: Math.atan2(a21, a11), skew: Math.atan2(a12, a22). However, it doesn't seem to be quite as reliable as the full-on backwards rotation procedure.
  46566. tm.rotationX = angle * _RAD2DEG;
  46567. //rotationX
  46568. if (angle) {
  46569. cos = Math.cos(-angle);
  46570. sin = Math.sin(-angle);
  46571. t1 = a12*cos+a13*sin;
  46572. t2 = a22*cos+a23*sin;
  46573. t3 = a32*cos+a33*sin;
  46574. a13 = a12*-sin+a13*cos;
  46575. a23 = a22*-sin+a23*cos;
  46576. a33 = a32*-sin+a33*cos;
  46577. a43 = a42*-sin+a43*cos;
  46578. a12 = t1;
  46579. a22 = t2;
  46580. a32 = t3;
  46581. }
  46582. //rotationY
  46583. angle = Math.atan2(-a31, a33);
  46584. tm.rotationY = angle * _RAD2DEG;
  46585. if (angle) {
  46586. cos = Math.cos(-angle);
  46587. sin = Math.sin(-angle);
  46588. t1 = a11*cos-a13*sin;
  46589. t2 = a21*cos-a23*sin;
  46590. t3 = a31*cos-a33*sin;
  46591. a23 = a21*sin+a23*cos;
  46592. a33 = a31*sin+a33*cos;
  46593. a43 = a41*sin+a43*cos;
  46594. a11 = t1;
  46595. a21 = t2;
  46596. a31 = t3;
  46597. }
  46598. //rotationZ
  46599. angle = Math.atan2(a21, a11);
  46600. tm.rotation = angle * _RAD2DEG;
  46601. if (angle) {
  46602. cos = Math.cos(angle);
  46603. sin = Math.sin(angle);
  46604. t1 = a11*cos+a21*sin;
  46605. t2 = a12*cos+a22*sin;
  46606. t3 = a13*cos+a23*sin;
  46607. a21 = a21*cos-a11*sin;
  46608. a22 = a22*cos-a12*sin;
  46609. a23 = a23*cos-a13*sin;
  46610. a11 = t1;
  46611. a12 = t2;
  46612. a13 = t3;
  46613. }
  46614. if (tm.rotationX && Math.abs(tm.rotationX) + Math.abs(tm.rotation) > 359.9) { //when rotationY is set, it will often be parsed as 180 degrees different than it should be, and rotationX and rotation both being 180 (it looks the same), so we adjust for that here.
  46615. tm.rotationX = tm.rotation = 0;
  46616. tm.rotationY = 180 - tm.rotationY;
  46617. }
  46618. //skewX
  46619. angle = Math.atan2(a12, a22);
  46620. //scales
  46621. tm.scaleX = ((Math.sqrt(a11 * a11 + a21 * a21 + a31 * a31) * rnd + 0.5) | 0) / rnd;
  46622. tm.scaleY = ((Math.sqrt(a22 * a22 + a32 * a32) * rnd + 0.5) | 0) / rnd;
  46623. tm.scaleZ = ((Math.sqrt(a13 * a13 + a23 * a23 + a33 * a33) * rnd + 0.5) | 0) / rnd;
  46624. a11 /= tm.scaleX;
  46625. a12 /= tm.scaleY;
  46626. a21 /= tm.scaleX;
  46627. a22 /= tm.scaleY;
  46628. if (Math.abs(angle) > min) {
  46629. tm.skewX = angle * _RAD2DEG;
  46630. a12 = 0; //unskews
  46631. if (tm.skewType !== "simple") {
  46632. tm.scaleY *= 1 / Math.cos(angle); //by default, we compensate the scale based on the skew so that the element maintains a similar proportion when skewed, so we have to alter the scaleY here accordingly to match the default (non-adjusted) skewing that CSS does (stretching more and more as it skews).
  46633. }
  46634. } else {
  46635. tm.skewX = 0;
  46636. }
  46637. /* //for testing purposes
  46638. var transform = "matrix3d(",
  46639. comma = ",",
  46640. zero = "0";
  46641. a13 /= tm.scaleZ;
  46642. a23 /= tm.scaleZ;
  46643. a31 /= tm.scaleX;
  46644. a32 /= tm.scaleY;
  46645. a33 /= tm.scaleZ;
  46646. transform += ((a11 < min && a11 > -min) ? zero : a11) + comma + ((a21 < min && a21 > -min) ? zero : a21) + comma + ((a31 < min && a31 > -min) ? zero : a31);
  46647. transform += comma + ((a41 < min && a41 > -min) ? zero : a41) + comma + ((a12 < min && a12 > -min) ? zero : a12) + comma + ((a22 < min && a22 > -min) ? zero : a22);
  46648. transform += comma + ((a32 < min && a32 > -min) ? zero : a32) + comma + ((a42 < min && a42 > -min) ? zero : a42) + comma + ((a13 < min && a13 > -min) ? zero : a13);
  46649. transform += comma + ((a23 < min && a23 > -min) ? zero : a23) + comma + ((a33 < min && a33 > -min) ? zero : a33) + comma + ((a43 < min && a43 > -min) ? zero : a43) + comma;
  46650. transform += a14 + comma + a24 + comma + a34 + comma + (tm.perspective ? (1 + (-a34 / tm.perspective)) : 1) + ")";
  46651. console.log(transform);
  46652. document.querySelector(".test").style[_transformProp] = transform;
  46653. */
  46654. tm.perspective = a43 ? 1 / ((a43 < 0) ? -a43 : a43) : 0;
  46655. tm.x = a14;
  46656. tm.y = a24;
  46657. tm.z = a34;
  46658. if (tm.svg) {
  46659. tm.x -= tm.xOrigin - (tm.xOrigin * a11 - tm.yOrigin * a12);
  46660. tm.y -= tm.yOrigin - (tm.yOrigin * a21 - tm.xOrigin * a22);
  46661. }
  46662. } else if ((!_supports3D || parse || !m.length || tm.x !== m[4] || tm.y !== m[5] || (!tm.rotationX && !tm.rotationY))) { //sometimes a 6-element matrix is returned even when we performed 3D transforms, like if rotationX and rotationY are 180. In cases like this, we still need to honor the 3D transforms. If we just rely on the 2D info, it could affect how the data is interpreted, like scaleY might get set to -1 or rotation could get offset by 180 degrees. For example, do a TweenLite.to(element, 1, {css:{rotationX:180, rotationY:180}}) and then later, TweenLite.to(element, 1, {css:{rotationX:0}}) and without this conditional logic in place, it'd jump to a state of being unrotated when the 2nd tween starts. Then again, we need to honor the fact that the user COULD alter the transforms outside of CSSPlugin, like by manually applying new css, so we try to sense that by looking at x and y because if those changed, we know the changes were made outside CSSPlugin and we force a reinterpretation of the matrix values. Also, in Webkit browsers, if the element's "display" is "none", its calculated style value will always return empty, so if we've already recorded the values in the _gsTransform object, we'll just rely on those.
  46663. var k = (m.length >= 6),
  46664. a = k ? m[0] : 1,
  46665. b = m[1] || 0,
  46666. c = m[2] || 0,
  46667. d = k ? m[3] : 1;
  46668. tm.x = m[4] || 0;
  46669. tm.y = m[5] || 0;
  46670. scaleX = Math.sqrt(a * a + b * b);
  46671. scaleY = Math.sqrt(d * d + c * c);
  46672. rotation = (a || b) ? Math.atan2(b, a) * _RAD2DEG : tm.rotation || 0; //note: if scaleX is 0, we cannot accurately measure rotation. Same for skewX with a scaleY of 0. Therefore, we default to the previously recorded value (or zero if that doesn't exist).
  46673. skewX = (c || d) ? Math.atan2(c, d) * _RAD2DEG + rotation : tm.skewX || 0;
  46674. tm.scaleX = scaleX;
  46675. tm.scaleY = scaleY;
  46676. tm.rotation = rotation;
  46677. tm.skewX = skewX;
  46678. if (_supports3D) {
  46679. tm.rotationX = tm.rotationY = tm.z = 0;
  46680. tm.perspective = defaultTransformPerspective;
  46681. tm.scaleZ = 1;
  46682. }
  46683. if (tm.svg) {
  46684. tm.x -= tm.xOrigin - (tm.xOrigin * a + tm.yOrigin * c);
  46685. tm.y -= tm.yOrigin - (tm.xOrigin * b + tm.yOrigin * d);
  46686. }
  46687. }
  46688. if (Math.abs(tm.skewX) > 90 && Math.abs(tm.skewX) < 270) {
  46689. if (invX) {
  46690. tm.scaleX *= -1;
  46691. tm.skewX += (tm.rotation <= 0) ? 180 : -180;
  46692. tm.rotation += (tm.rotation <= 0) ? 180 : -180;
  46693. } else {
  46694. tm.scaleY *= -1;
  46695. tm.skewX += (tm.skewX <= 0) ? 180 : -180;
  46696. }
  46697. }
  46698. tm.zOrigin = zOrigin;
  46699. //some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 0 in these cases. The conditional logic here is faster than calling Math.abs(). Also, browsers tend to render a SLIGHTLY rotated object in a fuzzy way, so we need to snap to exactly 0 when appropriate.
  46700. for (i in tm) {
  46701. if (tm[i] < min) if (tm[i] > -min) {
  46702. tm[i] = 0;
  46703. }
  46704. }
  46705. }
  46706. //DEBUG: _log("parsed rotation of " + t.getAttribute("id")+": "+(tm.rotationX)+", "+(tm.rotationY)+", "+(tm.rotation)+", scale: "+tm.scaleX+", "+tm.scaleY+", "+tm.scaleZ+", position: "+tm.x+", "+tm.y+", "+tm.z+", perspective: "+tm.perspective+ ", origin: "+ tm.xOrigin+ ","+ tm.yOrigin);
  46707. if (rec) {
  46708. t._gsTransform = tm; //record to the object's _gsTransform which we use so that tweens can control individual properties independently (we need all the properties to accurately recompose the matrix in the setRatio() method)
  46709. if (tm.svg) { //if we're supposed to apply transforms to the SVG element's "transform" attribute, make sure there aren't any CSS transforms applied or they'll override the attribute ones. Also clear the transform attribute if we're using CSS, just to be clean.
  46710. if (_useSVGTransformAttr && t.style[_transformProp]) {
  46711. TweenLite.delayedCall(0.001, function(){ //if we apply this right away (before anything has rendered), we risk there being no transforms for a brief moment and it also interferes with adjusting the transformOrigin in a tween with immediateRender:true (it'd try reading the matrix and it wouldn't have the appropriate data in place because we just removed it).
  46712. _removeProp(t.style, _transformProp);
  46713. });
  46714. } else if (!_useSVGTransformAttr && t.getAttribute("transform")) {
  46715. TweenLite.delayedCall(0.001, function(){
  46716. t.removeAttribute("transform");
  46717. });
  46718. }
  46719. }
  46720. }
  46721. return tm;
  46722. },
  46723. //for setting 2D transforms in IE6, IE7, and IE8 (must use a "filter" to emulate the behavior of modern day browser transforms)
  46724. _setIETransformRatio = function(v) {
  46725. var t = this.data, //refers to the element's _gsTransform object
  46726. ang = -t.rotation * _DEG2RAD,
  46727. skew = ang + t.skewX * _DEG2RAD,
  46728. rnd = 100000,
  46729. a = ((Math.cos(ang) * t.scaleX * rnd) | 0) / rnd,
  46730. b = ((Math.sin(ang) * t.scaleX * rnd) | 0) / rnd,
  46731. c = ((Math.sin(skew) * -t.scaleY * rnd) | 0) / rnd,
  46732. d = ((Math.cos(skew) * t.scaleY * rnd) | 0) / rnd,
  46733. style = this.t.style,
  46734. cs = this.t.currentStyle,
  46735. filters, val;
  46736. if (!cs) {
  46737. return;
  46738. }
  46739. val = b; //just for swapping the variables an inverting them (reused "val" to avoid creating another variable in memory). IE's filter matrix uses a non-standard matrix configuration (angle goes the opposite way, and b and c are reversed and inverted)
  46740. b = -c;
  46741. c = -val;
  46742. filters = cs.filter;
  46743. style.filter = ""; //remove filters so that we can accurately measure offsetWidth/offsetHeight
  46744. var w = this.t.offsetWidth,
  46745. h = this.t.offsetHeight,
  46746. clip = (cs.position !== "absolute"),
  46747. m = "progid:DXImageTransform.Microsoft.Matrix(M11=" + a + ", M12=" + b + ", M21=" + c + ", M22=" + d,
  46748. ox = t.x + (w * t.xPercent / 100),
  46749. oy = t.y + (h * t.yPercent / 100),
  46750. dx, dy;
  46751. //if transformOrigin is being used, adjust the offset x and y
  46752. if (t.ox != null) {
  46753. dx = ((t.oxp) ? w * t.ox * 0.01 : t.ox) - w / 2;
  46754. dy = ((t.oyp) ? h * t.oy * 0.01 : t.oy) - h / 2;
  46755. ox += dx - (dx * a + dy * b);
  46756. oy += dy - (dx * c + dy * d);
  46757. }
  46758. if (!clip) {
  46759. m += ", sizingMethod='auto expand')";
  46760. } else {
  46761. dx = (w / 2);
  46762. dy = (h / 2);
  46763. //translate to ensure that transformations occur around the correct origin (default is center).
  46764. m += ", Dx=" + (dx - (dx * a + dy * b) + ox) + ", Dy=" + (dy - (dx * c + dy * d) + oy) + ")";
  46765. }
  46766. if (filters.indexOf("DXImageTransform.Microsoft.Matrix(") !== -1) {
  46767. style.filter = filters.replace(_ieSetMatrixExp, m);
  46768. } else {
  46769. style.filter = m + " " + filters; //we must always put the transform/matrix FIRST (before alpha(opacity=xx)) to avoid an IE bug that slices part of the object when rotation is applied with alpha.
  46770. }
  46771. //at the end or beginning of the tween, if the matrix is normal (1, 0, 0, 1) and opacity is 100 (or doesn't exist), remove the filter to improve browser performance.
  46772. if (v === 0 || v === 1) if (a === 1) if (b === 0) if (c === 0) if (d === 1) if (!clip || m.indexOf("Dx=0, Dy=0") !== -1) if (!_opacityExp.test(filters) || parseFloat(RegExp.$1) === 100) if (filters.indexOf("gradient(" && filters.indexOf("Alpha")) === -1) {
  46773. style.removeAttribute("filter");
  46774. }
  46775. //we must set the margins AFTER applying the filter in order to avoid some bugs in IE8 that could (in rare scenarios) cause them to be ignored intermittently (vibration).
  46776. if (!clip) {
  46777. var mult = (_ieVers < 8) ? 1 : -1, //in Internet Explorer 7 and before, the box model is broken, causing the browser to treat the width/height of the actual rotated filtered image as the width/height of the box itself, but Microsoft corrected that in IE8. We must use a negative offset in IE8 on the right/bottom
  46778. marg, prop, dif;
  46779. dx = t.ieOffsetX || 0;
  46780. dy = t.ieOffsetY || 0;
  46781. t.ieOffsetX = Math.round((w - ((a < 0 ? -a : a) * w + (b < 0 ? -b : b) * h)) / 2 + ox);
  46782. t.ieOffsetY = Math.round((h - ((d < 0 ? -d : d) * h + (c < 0 ? -c : c) * w)) / 2 + oy);
  46783. for (i = 0; i < 4; i++) {
  46784. prop = _margins[i];
  46785. marg = cs[prop];
  46786. //we need to get the current margin in case it is being tweened separately (we want to respect that tween's changes)
  46787. val = (marg.indexOf("px") !== -1) ? parseFloat(marg) : _convertToPixels(this.t, prop, parseFloat(marg), marg.replace(_suffixExp, "")) || 0;
  46788. if (val !== t[prop]) {
  46789. dif = (i < 2) ? -t.ieOffsetX : -t.ieOffsetY; //if another tween is controlling a margin, we cannot only apply the difference in the ieOffsets, so we essentially zero-out the dx and dy here in that case. We record the margin(s) later so that we can keep comparing them, making this code very flexible.
  46790. } else {
  46791. dif = (i < 2) ? dx - t.ieOffsetX : dy - t.ieOffsetY;
  46792. }
  46793. style[prop] = (t[prop] = Math.round( val - dif * ((i === 0 || i === 2) ? 1 : mult) )) + "px";
  46794. }
  46795. }
  46796. },
  46797. /* translates a super small decimal to a string WITHOUT scientific notation
  46798. _safeDecimal = function(n) {
  46799. var s = (n < 0 ? -n : n) + "",
  46800. a = s.split("e-");
  46801. return (n < 0 ? "-0." : "0.") + new Array(parseInt(a[1], 10) || 0).join("0") + a[0].split(".").join("");
  46802. },
  46803. */
  46804. _setTransformRatio = _internals.set3DTransformRatio = _internals.setTransformRatio = function(v) {
  46805. var t = this.data, //refers to the element's _gsTransform object
  46806. style = this.t.style,
  46807. angle = t.rotation,
  46808. rotationX = t.rotationX,
  46809. rotationY = t.rotationY,
  46810. sx = t.scaleX,
  46811. sy = t.scaleY,
  46812. sz = t.scaleZ,
  46813. x = t.x,
  46814. y = t.y,
  46815. z = t.z,
  46816. isSVG = t.svg,
  46817. perspective = t.perspective,
  46818. force3D = t.force3D,
  46819. skewY = t.skewY,
  46820. skewX = t.skewX,
  46821. t1, a11, a12, a13, a21, a22, a23, a31, a32, a33, a41, a42, a43,
  46822. zOrigin, min, cos, sin, t2, transform, comma, zero, skew, rnd;
  46823. if (skewY) { //for performance reasons, we combine all skewing into the skewX and rotation values. Remember, a skewY of 10 degrees looks the same as a rotation of 10 degrees plus a skewX of 10 degrees.
  46824. skewX += skewY;
  46825. angle += skewY;
  46826. }
  46827. //check to see if we should render as 2D (and SVGs must use 2D when _useSVGTransformAttr is true)
  46828. if (((((v === 1 || v === 0) && force3D === "auto" && (this.tween._totalTime === this.tween._totalDuration || !this.tween._totalTime)) || !force3D) && !z && !perspective && !rotationY && !rotationX && sz === 1) || (_useSVGTransformAttr && isSVG) || !_supports3D) { //on the final render (which could be 0 for a from tween), if there are no 3D aspects, render in 2D to free up memory and improve performance especially on mobile devices. Check the tween's totalTime/totalDuration too in order to make sure it doesn't happen between repeats if it's a repeating tween.
  46829. //2D
  46830. if (angle || skewX || isSVG) {
  46831. angle *= _DEG2RAD;
  46832. skew = skewX * _DEG2RAD;
  46833. rnd = 100000;
  46834. a11 = Math.cos(angle) * sx;
  46835. a21 = Math.sin(angle) * sx;
  46836. a12 = Math.sin(angle - skew) * -sy;
  46837. a22 = Math.cos(angle - skew) * sy;
  46838. if (skew && t.skewType === "simple") { //by default, we compensate skewing on the other axis to make it look more natural, but you can set the skewType to "simple" to use the uncompensated skewing that CSS does
  46839. t1 = Math.tan(skew - skewY * _DEG2RAD);
  46840. t1 = Math.sqrt(1 + t1 * t1);
  46841. a12 *= t1;
  46842. a22 *= t1;
  46843. if (skewY) {
  46844. t1 = Math.tan(skewY * _DEG2RAD);
  46845. t1 = Math.sqrt(1 + t1 * t1);
  46846. a11 *= t1;
  46847. a21 *= t1;
  46848. }
  46849. }
  46850. if (isSVG) {
  46851. x += t.xOrigin - (t.xOrigin * a11 + t.yOrigin * a12) + t.xOffset;
  46852. y += t.yOrigin - (t.xOrigin * a21 + t.yOrigin * a22) + t.yOffset;
  46853. if (_useSVGTransformAttr && (t.xPercent || t.yPercent)) { //The SVG spec doesn't support percentage-based translation in the "transform" attribute, so we merge it into the matrix to simulate it.
  46854. min = this.t.getBBox();
  46855. x += t.xPercent * 0.01 * min.width;
  46856. y += t.yPercent * 0.01 * min.height;
  46857. }
  46858. min = 0.000001;
  46859. if (x < min) if (x > -min) {
  46860. x = 0;
  46861. }
  46862. if (y < min) if (y > -min) {
  46863. y = 0;
  46864. }
  46865. }
  46866. transform = (((a11 * rnd) | 0) / rnd) + "," + (((a21 * rnd) | 0) / rnd) + "," + (((a12 * rnd) | 0) / rnd) + "," + (((a22 * rnd) | 0) / rnd) + "," + x + "," + y + ")";
  46867. if (isSVG && _useSVGTransformAttr) {
  46868. this.t.setAttribute("transform", "matrix(" + transform);
  46869. } else {
  46870. //some browsers have a hard time with very small values like 2.4492935982947064e-16 (notice the "e-" towards the end) and would render the object slightly off. So we round to 5 decimal places.
  46871. style[_transformProp] = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix(" : "matrix(") + transform;
  46872. }
  46873. } else {
  46874. style[_transformProp] = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix(" : "matrix(") + sx + ",0,0," + sy + "," + x + "," + y + ")";
  46875. }
  46876. return;
  46877. }
  46878. if (_isFirefox) { //Firefox has a bug (at least in v25) that causes it to render the transparent part of 32-bit PNG images as black when displayed inside an iframe and the 3D scale is very small and doesn't change sufficiently enough between renders (like if you use a Power4.easeInOut to scale from 0 to 1 where the beginning values only change a tiny amount to begin the tween before accelerating). In this case, we force the scale to be 0.00002 instead which is visually the same but works around the Firefox issue.
  46879. min = 0.0001;
  46880. if (sx < min && sx > -min) {
  46881. sx = sz = 0.00002;
  46882. }
  46883. if (sy < min && sy > -min) {
  46884. sy = sz = 0.00002;
  46885. }
  46886. if (perspective && !t.z && !t.rotationX && !t.rotationY) { //Firefox has a bug that causes elements to have an odd super-thin, broken/dotted black border on elements that have a perspective set but aren't utilizing 3D space (no rotationX, rotationY, or z).
  46887. perspective = 0;
  46888. }
  46889. }
  46890. if (angle || skewX) {
  46891. angle *= _DEG2RAD;
  46892. cos = a11 = Math.cos(angle);
  46893. sin = a21 = Math.sin(angle);
  46894. if (skewX) {
  46895. angle -= skewX * _DEG2RAD;
  46896. cos = Math.cos(angle);
  46897. sin = Math.sin(angle);
  46898. if (t.skewType === "simple") { //by default, we compensate skewing on the other axis to make it look more natural, but you can set the skewType to "simple" to use the uncompensated skewing that CSS does
  46899. t1 = Math.tan((skewX - skewY) * _DEG2RAD);
  46900. t1 = Math.sqrt(1 + t1 * t1);
  46901. cos *= t1;
  46902. sin *= t1;
  46903. if (t.skewY) {
  46904. t1 = Math.tan(skewY * _DEG2RAD);
  46905. t1 = Math.sqrt(1 + t1 * t1);
  46906. a11 *= t1;
  46907. a21 *= t1;
  46908. }
  46909. }
  46910. }
  46911. a12 = -sin;
  46912. a22 = cos;
  46913. } else if (!rotationY && !rotationX && sz === 1 && !perspective && !isSVG) { //if we're only translating and/or 2D scaling, this is faster...
  46914. style[_transformProp] = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) translate3d(" : "translate3d(") + x + "px," + y + "px," + z +"px)" + ((sx !== 1 || sy !== 1) ? " scale(" + sx + "," + sy + ")" : "");
  46915. return;
  46916. } else {
  46917. a11 = a22 = 1;
  46918. a12 = a21 = 0;
  46919. }
  46920. // KEY INDEX AFFECTS a[row][column]
  46921. // a11 0 rotation, rotationY, scaleX
  46922. // a21 1 rotation, rotationY, scaleX
  46923. // a31 2 rotationY, scaleX
  46924. // a41 3 rotationY, scaleX
  46925. // a12 4 rotation, skewX, rotationX, scaleY
  46926. // a22 5 rotation, skewX, rotationX, scaleY
  46927. // a32 6 rotationX, scaleY
  46928. // a42 7 rotationX, scaleY
  46929. // a13 8 rotationY, rotationX, scaleZ
  46930. // a23 9 rotationY, rotationX, scaleZ
  46931. // a33 10 rotationY, rotationX, scaleZ
  46932. // a43 11 rotationY, rotationX, perspective, scaleZ
  46933. // a14 12 x, zOrigin, svgOrigin
  46934. // a24 13 y, zOrigin, svgOrigin
  46935. // a34 14 z, zOrigin
  46936. // a44 15
  46937. // rotation: Math.atan2(a21, a11)
  46938. // rotationY: Math.atan2(a13, a33) (or Math.atan2(a13, a11))
  46939. // rotationX: Math.atan2(a32, a33)
  46940. a33 = 1;
  46941. a13 = a23 = a31 = a32 = a41 = a42 = 0;
  46942. a43 = (perspective) ? -1 / perspective : 0;
  46943. zOrigin = t.zOrigin;
  46944. min = 0.000001; //threshold below which browsers use scientific notation which won't work.
  46945. comma = ",";
  46946. zero = "0";
  46947. angle = rotationY * _DEG2RAD;
  46948. if (angle) {
  46949. cos = Math.cos(angle);
  46950. sin = Math.sin(angle);
  46951. a31 = -sin;
  46952. a41 = a43*-sin;
  46953. a13 = a11*sin;
  46954. a23 = a21*sin;
  46955. a33 = cos;
  46956. a43 *= cos;
  46957. a11 *= cos;
  46958. a21 *= cos;
  46959. }
  46960. angle = rotationX * _DEG2RAD;
  46961. if (angle) {
  46962. cos = Math.cos(angle);
  46963. sin = Math.sin(angle);
  46964. t1 = a12*cos+a13*sin;
  46965. t2 = a22*cos+a23*sin;
  46966. a32 = a33*sin;
  46967. a42 = a43*sin;
  46968. a13 = a12*-sin+a13*cos;
  46969. a23 = a22*-sin+a23*cos;
  46970. a33 = a33*cos;
  46971. a43 = a43*cos;
  46972. a12 = t1;
  46973. a22 = t2;
  46974. }
  46975. if (sz !== 1) {
  46976. a13*=sz;
  46977. a23*=sz;
  46978. a33*=sz;
  46979. a43*=sz;
  46980. }
  46981. if (sy !== 1) {
  46982. a12*=sy;
  46983. a22*=sy;
  46984. a32*=sy;
  46985. a42*=sy;
  46986. }
  46987. if (sx !== 1) {
  46988. a11*=sx;
  46989. a21*=sx;
  46990. a31*=sx;
  46991. a41*=sx;
  46992. }
  46993. if (zOrigin || isSVG) {
  46994. if (zOrigin) {
  46995. x += a13*-zOrigin;
  46996. y += a23*-zOrigin;
  46997. z += a33*-zOrigin+zOrigin;
  46998. }
  46999. if (isSVG) { //due to bugs in some browsers, we need to manage the transform-origin of SVG manually
  47000. x += t.xOrigin - (t.xOrigin * a11 + t.yOrigin * a12) + t.xOffset;
  47001. y += t.yOrigin - (t.xOrigin * a21 + t.yOrigin * a22) + t.yOffset;
  47002. }
  47003. if (x < min && x > -min) {
  47004. x = zero;
  47005. }
  47006. if (y < min && y > -min) {
  47007. y = zero;
  47008. }
  47009. if (z < min && z > -min) {
  47010. z = 0; //don't use string because we calculate perspective later and need the number.
  47011. }
  47012. }
  47013. //optimized way of concatenating all the values into a string. If we do it all in one shot, it's slower because of the way browsers have to create temp strings and the way it affects memory. If we do it piece-by-piece with +=, it's a bit slower too. We found that doing it in these sized chunks works best overall:
  47014. transform = ((t.xPercent || t.yPercent) ? "translate(" + t.xPercent + "%," + t.yPercent + "%) matrix3d(" : "matrix3d(");
  47015. transform += ((a11 < min && a11 > -min) ? zero : a11) + comma + ((a21 < min && a21 > -min) ? zero : a21) + comma + ((a31 < min && a31 > -min) ? zero : a31);
  47016. transform += comma + ((a41 < min && a41 > -min) ? zero : a41) + comma + ((a12 < min && a12 > -min) ? zero : a12) + comma + ((a22 < min && a22 > -min) ? zero : a22);
  47017. if (rotationX || rotationY || sz !== 1) { //performance optimization (often there's no rotationX or rotationY, so we can skip these calculations)
  47018. transform += comma + ((a32 < min && a32 > -min) ? zero : a32) + comma + ((a42 < min && a42 > -min) ? zero : a42) + comma + ((a13 < min && a13 > -min) ? zero : a13);
  47019. transform += comma + ((a23 < min && a23 > -min) ? zero : a23) + comma + ((a33 < min && a33 > -min) ? zero : a33) + comma + ((a43 < min && a43 > -min) ? zero : a43) + comma;
  47020. } else {
  47021. transform += ",0,0,0,0,1,0,";
  47022. }
  47023. transform += x + comma + y + comma + z + comma + (perspective ? (1 + (-z / perspective)) : 1) + ")";
  47024. style[_transformProp] = transform;
  47025. };
  47026. p = Transform.prototype;
  47027. p.x = p.y = p.z = p.skewX = p.skewY = p.rotation = p.rotationX = p.rotationY = p.zOrigin = p.xPercent = p.yPercent = p.xOffset = p.yOffset = 0;
  47028. p.scaleX = p.scaleY = p.scaleZ = 1;
  47029. _registerComplexSpecialProp("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,svgOrigin,transformPerspective,directionalRotation,parseTransform,force3D,skewType,xPercent,yPercent,smoothOrigin", {parser:function(t, e, parsingProp, cssp, pt, plugin, vars) {
  47030. if (cssp._lastParsedTransform === vars) { return pt; } //only need to parse the transform once, and only if the browser supports it.
  47031. cssp._lastParsedTransform = vars;
  47032. var scaleFunc = (vars.scale && typeof(vars.scale) === "function") ? vars.scale : 0, //if there's a function-based "scale" value, swap in the resulting numeric value temporarily. Otherwise, if it's called for both scaleX and scaleY independently, they may not match (like if the function uses Math.random()).
  47033. swapFunc;
  47034. if (typeof(vars[parsingProp]) === "function") { //whatever property triggers the initial parsing might be a function-based value in which case it already got called in parse(), thus we don't want to call it again in here. The most efficient way to avoid this is to temporarily swap the value directly into the vars object, and then after we do all our parsing in this function, we'll swap it back again.
  47035. swapFunc = vars[parsingProp];
  47036. vars[parsingProp] = e;
  47037. }
  47038. if (scaleFunc) {
  47039. vars.scale = scaleFunc(_index, t);
  47040. }
  47041. var originalGSTransform = t._gsTransform,
  47042. style = t.style,
  47043. min = 0.000001,
  47044. i = _transformProps.length,
  47045. v = vars,
  47046. endRotations = {},
  47047. transformOriginString = "transformOrigin",
  47048. m1 = _getTransform(t, _cs, true, v.parseTransform),
  47049. orig = v.transform && ((typeof(v.transform) === "function") ? v.transform(_index, _target) : v.transform),
  47050. m2, copy, has3D, hasChange, dr, x, y, matrix, p;
  47051. m1.skewType = v.skewType || m1.skewType || CSSPlugin.defaultSkewType;
  47052. cssp._transform = m1;
  47053. if (orig && typeof(orig) === "string" && _transformProp) { //for values like transform:"rotate(60deg) scale(0.5, 0.8)"
  47054. copy = _tempDiv.style; //don't use the original target because it might be SVG in which case some browsers don't report computed style correctly.
  47055. copy[_transformProp] = orig;
  47056. copy.display = "block"; //if display is "none", the browser often refuses to report the transform properties correctly.
  47057. copy.position = "absolute";
  47058. _doc.body.appendChild(_tempDiv);
  47059. m2 = _getTransform(_tempDiv, null, false);
  47060. if (m1.skewType === "simple") { //the default _getTransform() reports the skewX/scaleY as if skewType is "compensated", thus we need to adjust that here if skewType is "simple".
  47061. m2.scaleY *= Math.cos(m2.skewX * _DEG2RAD);
  47062. }
  47063. if (m1.svg) { //if it's an SVG element, x/y part of the matrix will be affected by whatever we use as the origin and the offsets, so compensate here...
  47064. x = m1.xOrigin;
  47065. y = m1.yOrigin;
  47066. m2.x -= m1.xOffset;
  47067. m2.y -= m1.yOffset;
  47068. if (v.transformOrigin || v.svgOrigin) { //if this tween is altering the origin, we must factor that in here. The actual work of recording the transformOrigin values and setting up the PropTween is done later (still inside this function) so we cannot leave the changes intact here - we only want to update the x/y accordingly.
  47069. orig = {};
  47070. _parseSVGOrigin(t, _parsePosition(v.transformOrigin), orig, v.svgOrigin, v.smoothOrigin, true);
  47071. x = orig.xOrigin;
  47072. y = orig.yOrigin;
  47073. m2.x -= orig.xOffset - m1.xOffset;
  47074. m2.y -= orig.yOffset - m1.yOffset;
  47075. }
  47076. if (x || y) {
  47077. matrix = _getMatrix(_tempDiv, true);
  47078. m2.x -= x - (x * matrix[0] + y * matrix[2]);
  47079. m2.y -= y - (x * matrix[1] + y * matrix[3]);
  47080. }
  47081. }
  47082. _doc.body.removeChild(_tempDiv);
  47083. if (!m2.perspective) {
  47084. m2.perspective = m1.perspective; //tweening to no perspective gives very unintuitive results - just keep the same perspective in that case.
  47085. }
  47086. if (v.xPercent != null) {
  47087. m2.xPercent = _parseVal(v.xPercent, m1.xPercent);
  47088. }
  47089. if (v.yPercent != null) {
  47090. m2.yPercent = _parseVal(v.yPercent, m1.yPercent);
  47091. }
  47092. } else if (typeof(v) === "object") { //for values like scaleX, scaleY, rotation, x, y, skewX, and skewY or transform:{...} (object)
  47093. m2 = {scaleX:_parseVal((v.scaleX != null) ? v.scaleX : v.scale, m1.scaleX),
  47094. scaleY:_parseVal((v.scaleY != null) ? v.scaleY : v.scale, m1.scaleY),
  47095. scaleZ:_parseVal(v.scaleZ, m1.scaleZ),
  47096. x:_parseVal(v.x, m1.x),
  47097. y:_parseVal(v.y, m1.y),
  47098. z:_parseVal(v.z, m1.z),
  47099. xPercent:_parseVal(v.xPercent, m1.xPercent),
  47100. yPercent:_parseVal(v.yPercent, m1.yPercent),
  47101. perspective:_parseVal(v.transformPerspective, m1.perspective)};
  47102. dr = v.directionalRotation;
  47103. if (dr != null) {
  47104. if (typeof(dr) === "object") {
  47105. for (copy in dr) {
  47106. v[copy] = dr[copy];
  47107. }
  47108. } else {
  47109. v.rotation = dr;
  47110. }
  47111. }
  47112. if (typeof(v.x) === "string" && v.x.indexOf("%") !== -1) {
  47113. m2.x = 0;
  47114. m2.xPercent = _parseVal(v.x, m1.xPercent);
  47115. }
  47116. if (typeof(v.y) === "string" && v.y.indexOf("%") !== -1) {
  47117. m2.y = 0;
  47118. m2.yPercent = _parseVal(v.y, m1.yPercent);
  47119. }
  47120. m2.rotation = _parseAngle(("rotation" in v) ? v.rotation : ("shortRotation" in v) ? v.shortRotation + "_short" : ("rotationZ" in v) ? v.rotationZ : m1.rotation, m1.rotation, "rotation", endRotations);
  47121. if (_supports3D) {
  47122. m2.rotationX = _parseAngle(("rotationX" in v) ? v.rotationX : ("shortRotationX" in v) ? v.shortRotationX + "_short" : m1.rotationX || 0, m1.rotationX, "rotationX", endRotations);
  47123. m2.rotationY = _parseAngle(("rotationY" in v) ? v.rotationY : ("shortRotationY" in v) ? v.shortRotationY + "_short" : m1.rotationY || 0, m1.rotationY, "rotationY", endRotations);
  47124. }
  47125. m2.skewX = _parseAngle(v.skewX, m1.skewX);
  47126. m2.skewY = _parseAngle(v.skewY, m1.skewY);
  47127. }
  47128. if (_supports3D && v.force3D != null) {
  47129. m1.force3D = v.force3D;
  47130. hasChange = true;
  47131. }
  47132. has3D = (m1.force3D || m1.z || m1.rotationX || m1.rotationY || m2.z || m2.rotationX || m2.rotationY || m2.perspective);
  47133. if (!has3D && v.scale != null) {
  47134. m2.scaleZ = 1; //no need to tween scaleZ.
  47135. }
  47136. while (--i > -1) {
  47137. p = _transformProps[i];
  47138. orig = m2[p] - m1[p];
  47139. if (orig > min || orig < -min || v[p] != null || _forcePT[p] != null) {
  47140. hasChange = true;
  47141. pt = new CSSPropTween(m1, p, m1[p], orig, pt);
  47142. if (p in endRotations) {
  47143. pt.e = endRotations[p]; //directional rotations typically have compensated values during the tween, but we need to make sure they end at exactly what the user requested
  47144. }
  47145. pt.xs0 = 0; //ensures the value stays numeric in setRatio()
  47146. pt.plugin = plugin;
  47147. cssp._overwriteProps.push(pt.n);
  47148. }
  47149. }
  47150. orig = v.transformOrigin;
  47151. if (m1.svg && (orig || v.svgOrigin)) {
  47152. x = m1.xOffset; //when we change the origin, in order to prevent things from jumping we adjust the x/y so we must record those here so that we can create PropTweens for them and flip them at the same time as the origin
  47153. y = m1.yOffset;
  47154. _parseSVGOrigin(t, _parsePosition(orig), m2, v.svgOrigin, v.smoothOrigin);
  47155. pt = _addNonTweeningNumericPT(m1, "xOrigin", (originalGSTransform ? m1 : m2).xOrigin, m2.xOrigin, pt, transformOriginString); //note: if there wasn't a transformOrigin defined yet, just start with the destination one; it's wasteful otherwise, and it causes problems with fromTo() tweens. For example, TweenLite.to("#wheel", 3, {rotation:180, transformOrigin:"50% 50%", delay:1}); TweenLite.fromTo("#wheel", 3, {scale:0.5, transformOrigin:"50% 50%"}, {scale:1, delay:2}); would cause a jump when the from values revert at the beginning of the 2nd tween.
  47156. pt = _addNonTweeningNumericPT(m1, "yOrigin", (originalGSTransform ? m1 : m2).yOrigin, m2.yOrigin, pt, transformOriginString);
  47157. if (x !== m1.xOffset || y !== m1.yOffset) {
  47158. pt = _addNonTweeningNumericPT(m1, "xOffset", (originalGSTransform ? x : m1.xOffset), m1.xOffset, pt, transformOriginString);
  47159. pt = _addNonTweeningNumericPT(m1, "yOffset", (originalGSTransform ? y : m1.yOffset), m1.yOffset, pt, transformOriginString);
  47160. }
  47161. orig = "0px 0px"; //certain browsers (like firefox) completely botch transform-origin, so we must remove it to prevent it from contaminating transforms. We manage it ourselves with xOrigin and yOrigin
  47162. }
  47163. if (orig || (_supports3D && has3D && m1.zOrigin)) { //if anything 3D is happening and there's a transformOrigin with a z component that's non-zero, we must ensure that the transformOrigin's z-component is set to 0 so that we can manually do those calculations to get around Safari bugs. Even if the user didn't specifically define a "transformOrigin" in this particular tween (maybe they did it via css directly).
  47164. if (_transformProp) {
  47165. hasChange = true;
  47166. p = _transformOriginProp;
  47167. orig = (orig || _getStyle(t, p, _cs, false, "50% 50%")) + ""; //cast as string to avoid errors
  47168. pt = new CSSPropTween(style, p, 0, 0, pt, -1, transformOriginString);
  47169. pt.b = style[p];
  47170. pt.plugin = plugin;
  47171. if (_supports3D) {
  47172. copy = m1.zOrigin;
  47173. orig = orig.split(" ");
  47174. m1.zOrigin = ((orig.length > 2 && !(copy !== 0 && orig[2] === "0px")) ? parseFloat(orig[2]) : copy) || 0; //Safari doesn't handle the z part of transformOrigin correctly, so we'll manually handle it in the _set3DTransformRatio() method.
  47175. pt.xs0 = pt.e = orig[0] + " " + (orig[1] || "50%") + " 0px"; //we must define a z value of 0px specifically otherwise iOS 5 Safari will stick with the old one (if one was defined)!
  47176. pt = new CSSPropTween(m1, "zOrigin", 0, 0, pt, -1, pt.n); //we must create a CSSPropTween for the _gsTransform.zOrigin so that it gets reset properly at the beginning if the tween runs backward (as opposed to just setting m1.zOrigin here)
  47177. pt.b = copy;
  47178. pt.xs0 = pt.e = m1.zOrigin;
  47179. } else {
  47180. pt.xs0 = pt.e = orig;
  47181. }
  47182. //for older versions of IE (6-8), we need to manually calculate things inside the setRatio() function. We record origin x and y (ox and oy) and whether or not the values are percentages (oxp and oyp).
  47183. } else {
  47184. _parsePosition(orig + "", m1);
  47185. }
  47186. }
  47187. if (hasChange) {
  47188. cssp._transformType = (!(m1.svg && _useSVGTransformAttr) && (has3D || this._transformType === 3)) ? 3 : 2; //quicker than calling cssp._enableTransforms();
  47189. }
  47190. if (swapFunc) {
  47191. vars[parsingProp] = swapFunc;
  47192. }
  47193. if (scaleFunc) {
  47194. vars.scale = scaleFunc;
  47195. }
  47196. return pt;
  47197. }, prefix:true});
  47198. _registerComplexSpecialProp("boxShadow", {defaultValue:"0px 0px 0px 0px #999", prefix:true, color:true, multi:true, keyword:"inset"});
  47199. _registerComplexSpecialProp("borderRadius", {defaultValue:"0px", parser:function(t, e, p, cssp, pt, plugin) {
  47200. e = this.format(e);
  47201. var props = ["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"],
  47202. style = t.style,
  47203. ea1, i, es2, bs2, bs, es, bn, en, w, h, esfx, bsfx, rel, hn, vn, em;
  47204. w = parseFloat(t.offsetWidth);
  47205. h = parseFloat(t.offsetHeight);
  47206. ea1 = e.split(" ");
  47207. for (i = 0; i < props.length; i++) { //if we're dealing with percentages, we must convert things separately for the horizontal and vertical axis!
  47208. if (this.p.indexOf("border")) { //older browsers used a prefix
  47209. props[i] = _checkPropPrefix(props[i]);
  47210. }
  47211. bs = bs2 = _getStyle(t, props[i], _cs, false, "0px");
  47212. if (bs.indexOf(" ") !== -1) {
  47213. bs2 = bs.split(" ");
  47214. bs = bs2[0];
  47215. bs2 = bs2[1];
  47216. }
  47217. es = es2 = ea1[i];
  47218. bn = parseFloat(bs);
  47219. bsfx = bs.substr((bn + "").length);
  47220. rel = (es.charAt(1) === "=");
  47221. if (rel) {
  47222. en = parseInt(es.charAt(0)+"1", 10);
  47223. es = es.substr(2);
  47224. en *= parseFloat(es);
  47225. esfx = es.substr((en + "").length - (en < 0 ? 1 : 0)) || "";
  47226. } else {
  47227. en = parseFloat(es);
  47228. esfx = es.substr((en + "").length);
  47229. }
  47230. if (esfx === "") {
  47231. esfx = _suffixMap[p] || bsfx;
  47232. }
  47233. if (esfx !== bsfx) {
  47234. hn = _convertToPixels(t, "borderLeft", bn, bsfx); //horizontal number (we use a bogus "borderLeft" property just because the _convertToPixels() method searches for the keywords "Left", "Right", "Top", and "Bottom" to determine of it's a horizontal or vertical property, and we need "border" in the name so that it knows it should measure relative to the element itself, not its parent.
  47235. vn = _convertToPixels(t, "borderTop", bn, bsfx); //vertical number
  47236. if (esfx === "%") {
  47237. bs = (hn / w * 100) + "%";
  47238. bs2 = (vn / h * 100) + "%";
  47239. } else if (esfx === "em") {
  47240. em = _convertToPixels(t, "borderLeft", 1, "em");
  47241. bs = (hn / em) + "em";
  47242. bs2 = (vn / em) + "em";
  47243. } else {
  47244. bs = hn + "px";
  47245. bs2 = vn + "px";
  47246. }
  47247. if (rel) {
  47248. es = (parseFloat(bs) + en) + esfx;
  47249. es2 = (parseFloat(bs2) + en) + esfx;
  47250. }
  47251. }
  47252. pt = _parseComplex(style, props[i], bs + " " + bs2, es + " " + es2, false, "0px", pt);
  47253. }
  47254. return pt;
  47255. }, prefix:true, formatter:_getFormatter("0px 0px 0px 0px", false, true)});
  47256. _registerComplexSpecialProp("borderBottomLeftRadius,borderBottomRightRadius,borderTopLeftRadius,borderTopRightRadius", {defaultValue:"0px", parser:function(t, e, p, cssp, pt, plugin) {
  47257. return _parseComplex(t.style, p, this.format(_getStyle(t, p, _cs, false, "0px 0px")), this.format(e), false, "0px", pt);
  47258. }, prefix:true, formatter:_getFormatter("0px 0px", false, true)});
  47259. _registerComplexSpecialProp("backgroundPosition", {defaultValue:"0 0", parser:function(t, e, p, cssp, pt, plugin) {
  47260. var bp = "background-position",
  47261. cs = (_cs || _getComputedStyle(t, null)),
  47262. bs = this.format( ((cs) ? _ieVers ? cs.getPropertyValue(bp + "-x") + " " + cs.getPropertyValue(bp + "-y") : cs.getPropertyValue(bp) : t.currentStyle.backgroundPositionX + " " + t.currentStyle.backgroundPositionY) || "0 0"), //Internet Explorer doesn't report background-position correctly - we must query background-position-x and background-position-y and combine them (even in IE10). Before IE9, we must do the same with the currentStyle object and use camelCase
  47263. es = this.format(e),
  47264. ba, ea, i, pct, overlap, src;
  47265. if ((bs.indexOf("%") !== -1) !== (es.indexOf("%") !== -1) && es.split(",").length < 2) {
  47266. src = _getStyle(t, "backgroundImage").replace(_urlExp, "");
  47267. if (src && src !== "none") {
  47268. ba = bs.split(" ");
  47269. ea = es.split(" ");
  47270. _tempImg.setAttribute("src", src); //set the temp IMG's src to the background-image so that we can measure its width/height
  47271. i = 2;
  47272. while (--i > -1) {
  47273. bs = ba[i];
  47274. pct = (bs.indexOf("%") !== -1);
  47275. if (pct !== (ea[i].indexOf("%") !== -1)) {
  47276. overlap = (i === 0) ? t.offsetWidth - _tempImg.width : t.offsetHeight - _tempImg.height;
  47277. ba[i] = pct ? (parseFloat(bs) / 100 * overlap) + "px" : (parseFloat(bs) / overlap * 100) + "%";
  47278. }
  47279. }
  47280. bs = ba.join(" ");
  47281. }
  47282. }
  47283. return this.parseComplex(t.style, bs, es, pt, plugin);
  47284. }, formatter:_parsePosition});
  47285. _registerComplexSpecialProp("backgroundSize", {defaultValue:"0 0", formatter:function(v) {
  47286. v += ""; //ensure it's a string
  47287. return _parsePosition(v.indexOf(" ") === -1 ? v + " " + v : v); //if set to something like "100% 100%", Safari typically reports the computed style as just "100%" (no 2nd value), but we should ensure that there are two values, so copy the first one. Otherwise, it'd be interpreted as "100% 0" (wrong).
  47288. }});
  47289. _registerComplexSpecialProp("perspective", {defaultValue:"0px", prefix:true});
  47290. _registerComplexSpecialProp("perspectiveOrigin", {defaultValue:"50% 50%", prefix:true});
  47291. _registerComplexSpecialProp("transformStyle", {prefix:true});
  47292. _registerComplexSpecialProp("backfaceVisibility", {prefix:true});
  47293. _registerComplexSpecialProp("userSelect", {prefix:true});
  47294. _registerComplexSpecialProp("margin", {parser:_getEdgeParser("marginTop,marginRight,marginBottom,marginLeft")});
  47295. _registerComplexSpecialProp("padding", {parser:_getEdgeParser("paddingTop,paddingRight,paddingBottom,paddingLeft")});
  47296. _registerComplexSpecialProp("clip", {defaultValue:"rect(0px,0px,0px,0px)", parser:function(t, e, p, cssp, pt, plugin){
  47297. var b, cs, delim;
  47298. if (_ieVers < 9) { //IE8 and earlier don't report a "clip" value in the currentStyle - instead, the values are split apart into clipTop, clipRight, clipBottom, and clipLeft. Also, in IE7 and earlier, the values inside rect() are space-delimited, not comma-delimited.
  47299. cs = t.currentStyle;
  47300. delim = _ieVers < 8 ? " " : ",";
  47301. b = "rect(" + cs.clipTop + delim + cs.clipRight + delim + cs.clipBottom + delim + cs.clipLeft + ")";
  47302. e = this.format(e).split(",").join(delim);
  47303. } else {
  47304. b = this.format(_getStyle(t, this.p, _cs, false, this.dflt));
  47305. e = this.format(e);
  47306. }
  47307. return this.parseComplex(t.style, b, e, pt, plugin);
  47308. }});
  47309. _registerComplexSpecialProp("textShadow", {defaultValue:"0px 0px 0px #999", color:true, multi:true});
  47310. _registerComplexSpecialProp("autoRound,strictUnits", {parser:function(t, e, p, cssp, pt) {return pt;}}); //just so that we can ignore these properties (not tween them)
  47311. _registerComplexSpecialProp("border", {defaultValue:"0px solid #000", parser:function(t, e, p, cssp, pt, plugin) {
  47312. var bw = _getStyle(t, "borderTopWidth", _cs, false, "0px"),
  47313. end = this.format(e).split(" "),
  47314. esfx = end[0].replace(_suffixExp, "");
  47315. if (esfx !== "px") { //if we're animating to a non-px value, we need to convert the beginning width to that unit.
  47316. bw = (parseFloat(bw) / _convertToPixels(t, "borderTopWidth", 1, esfx)) + esfx;
  47317. }
  47318. return this.parseComplex(t.style, this.format(bw + " " + _getStyle(t, "borderTopStyle", _cs, false, "solid") + " " + _getStyle(t, "borderTopColor", _cs, false, "#000")), end.join(" "), pt, plugin);
  47319. }, color:true, formatter:function(v) {
  47320. var a = v.split(" ");
  47321. return a[0] + " " + (a[1] || "solid") + " " + (v.match(_colorExp) || ["#000"])[0];
  47322. }});
  47323. _registerComplexSpecialProp("borderWidth", {parser:_getEdgeParser("borderTopWidth,borderRightWidth,borderBottomWidth,borderLeftWidth")}); //Firefox doesn't pick up on borderWidth set in style sheets (only inline).
  47324. _registerComplexSpecialProp("float,cssFloat,styleFloat", {parser:function(t, e, p, cssp, pt, plugin) {
  47325. var s = t.style,
  47326. prop = ("cssFloat" in s) ? "cssFloat" : "styleFloat";
  47327. return new CSSPropTween(s, prop, 0, 0, pt, -1, p, false, 0, s[prop], e);
  47328. }});
  47329. //opacity-related
  47330. var _setIEOpacityRatio = function(v) {
  47331. var t = this.t, //refers to the element's style property
  47332. filters = t.filter || _getStyle(this.data, "filter") || "",
  47333. val = (this.s + this.c * v) | 0,
  47334. skip;
  47335. if (val === 100) { //for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters.
  47336. if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) {
  47337. t.removeAttribute("filter");
  47338. skip = (!_getStyle(this.data, "filter")); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check.
  47339. } else {
  47340. t.filter = filters.replace(_alphaFilterExp, "");
  47341. skip = true;
  47342. }
  47343. }
  47344. if (!skip) {
  47345. if (this.xn1) {
  47346. t.filter = filters = filters || ("alpha(opacity=" + val + ")"); //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame.
  47347. }
  47348. if (filters.indexOf("pacity") === -1) { //only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues
  47349. if (val !== 0 || !this.xn1) { //bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween)
  47350. t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly.
  47351. }
  47352. } else {
  47353. t.filter = filters.replace(_opacityExp, "opacity=" + val);
  47354. }
  47355. }
  47356. };
  47357. _registerComplexSpecialProp("opacity,alpha,autoAlpha", {defaultValue:"1", parser:function(t, e, p, cssp, pt, plugin) {
  47358. var b = parseFloat(_getStyle(t, "opacity", _cs, false, "1")),
  47359. style = t.style,
  47360. isAutoAlpha = (p === "autoAlpha");
  47361. if (typeof(e) === "string" && e.charAt(1) === "=") {
  47362. e = ((e.charAt(0) === "-") ? -1 : 1) * parseFloat(e.substr(2)) + b;
  47363. }
  47364. if (isAutoAlpha && b === 1 && _getStyle(t, "visibility", _cs) === "hidden" && e !== 0) { //if visibility is initially set to "hidden", we should interpret that as intent to make opacity 0 (a convenience)
  47365. b = 0;
  47366. }
  47367. if (_supportsOpacity) {
  47368. pt = new CSSPropTween(style, "opacity", b, e - b, pt);
  47369. } else {
  47370. pt = new CSSPropTween(style, "opacity", b * 100, (e - b) * 100, pt);
  47371. pt.xn1 = isAutoAlpha ? 1 : 0; //we need to record whether or not this is an autoAlpha so that in the setRatio(), we know to duplicate the setting of the alpha in order to work around a bug in IE7 and IE8 that prevents changes to "visibility" from taking effect if the filter is changed to a different alpha(opacity) at the same time. Setting it to the SAME value first, then the new value works around the IE7/8 bug.
  47372. style.zoom = 1; //helps correct an IE issue.
  47373. pt.type = 2;
  47374. pt.b = "alpha(opacity=" + pt.s + ")";
  47375. pt.e = "alpha(opacity=" + (pt.s + pt.c) + ")";
  47376. pt.data = t;
  47377. pt.plugin = plugin;
  47378. pt.setRatio = _setIEOpacityRatio;
  47379. }
  47380. if (isAutoAlpha) { //we have to create the "visibility" PropTween after the opacity one in the linked list so that they run in the order that works properly in IE8 and earlier
  47381. pt = new CSSPropTween(style, "visibility", 0, 0, pt, -1, null, false, 0, ((b !== 0) ? "inherit" : "hidden"), ((e === 0) ? "hidden" : "inherit"));
  47382. pt.xs0 = "inherit";
  47383. cssp._overwriteProps.push(pt.n);
  47384. cssp._overwriteProps.push(p);
  47385. }
  47386. return pt;
  47387. }});
  47388. var _removeProp = function(s, p) {
  47389. if (p) {
  47390. if (s.removeProperty) {
  47391. if (p.substr(0,2) === "ms" || p.substr(0,6) === "webkit") { //Microsoft and some Webkit browsers don't conform to the standard of capitalizing the first prefix character, so we adjust so that when we prefix the caps with a dash, it's correct (otherwise it'd be "ms-transform" instead of "-ms-transform" for IE9, for example)
  47392. p = "-" + p;
  47393. }
  47394. s.removeProperty(p.replace(_capsExp, "-$1").toLowerCase());
  47395. } else { //note: old versions of IE use "removeAttribute()" instead of "removeProperty()"
  47396. s.removeAttribute(p);
  47397. }
  47398. }
  47399. },
  47400. _setClassNameRatio = function(v) {
  47401. this.t._gsClassPT = this;
  47402. if (v === 1 || v === 0) {
  47403. this.t.setAttribute("class", (v === 0) ? this.b : this.e);
  47404. var mpt = this.data, //first MiniPropTween
  47405. s = this.t.style;
  47406. while (mpt) {
  47407. if (!mpt.v) {
  47408. _removeProp(s, mpt.p);
  47409. } else {
  47410. s[mpt.p] = mpt.v;
  47411. }
  47412. mpt = mpt._next;
  47413. }
  47414. if (v === 1 && this.t._gsClassPT === this) {
  47415. this.t._gsClassPT = null;
  47416. }
  47417. } else if (this.t.getAttribute("class") !== this.e) {
  47418. this.t.setAttribute("class", this.e);
  47419. }
  47420. };
  47421. _registerComplexSpecialProp("className", {parser:function(t, e, p, cssp, pt, plugin, vars) {
  47422. var b = t.getAttribute("class") || "", //don't use t.className because it doesn't work consistently on SVG elements; getAttribute("class") and setAttribute("class", value") is more reliable.
  47423. cssText = t.style.cssText,
  47424. difData, bs, cnpt, cnptLookup, mpt;
  47425. pt = cssp._classNamePT = new CSSPropTween(t, p, 0, 0, pt, 2);
  47426. pt.setRatio = _setClassNameRatio;
  47427. pt.pr = -11;
  47428. _hasPriority = true;
  47429. pt.b = b;
  47430. bs = _getAllStyles(t, _cs);
  47431. //if there's a className tween already operating on the target, force it to its end so that the necessary inline styles are removed and the class name is applied before we determine the end state (we don't want inline styles interfering that were there just for class-specific values)
  47432. cnpt = t._gsClassPT;
  47433. if (cnpt) {
  47434. cnptLookup = {};
  47435. mpt = cnpt.data; //first MiniPropTween which stores the inline styles - we need to force these so that the inline styles don't contaminate things. Otherwise, there's a small chance that a tween could start and the inline values match the destination values and they never get cleaned.
  47436. while (mpt) {
  47437. cnptLookup[mpt.p] = 1;
  47438. mpt = mpt._next;
  47439. }
  47440. cnpt.setRatio(1);
  47441. }
  47442. t._gsClassPT = pt;
  47443. pt.e = (e.charAt(1) !== "=") ? e : b.replace(new RegExp("(?:\\s|^)" + e.substr(2) + "(?![\\w-])"), "") + ((e.charAt(0) === "+") ? " " + e.substr(2) : "");
  47444. t.setAttribute("class", pt.e);
  47445. difData = _cssDif(t, bs, _getAllStyles(t), vars, cnptLookup);
  47446. t.setAttribute("class", b);
  47447. pt.data = difData.firstMPT;
  47448. t.style.cssText = cssText; //we recorded cssText before we swapped classes and ran _getAllStyles() because in cases when a className tween is overwritten, we remove all the related tweening properties from that class change (otherwise class-specific stuff can't override properties we've directly set on the target's style object due to specificity).
  47449. pt = pt.xfirst = cssp.parse(t, difData.difs, pt, plugin); //we record the CSSPropTween as the xfirst so that we can handle overwriting propertly (if "className" gets overwritten, we must kill all the properties associated with the className part of the tween, so we can loop through from xfirst to the pt itself)
  47450. return pt;
  47451. }});
  47452. var _setClearPropsRatio = function(v) {
  47453. if (v === 1 || v === 0) if (this.data._totalTime === this.data._totalDuration && this.data.data !== "isFromStart") { //this.data refers to the tween. Only clear at the END of the tween (remember, from() tweens make the ratio go from 1 to 0, so we can't just check that and if the tween is the zero-duration one that's created internally to render the starting values in a from() tween, ignore that because otherwise, for example, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in).
  47454. var s = this.t.style,
  47455. transformParse = _specialProps.transform.parse,
  47456. a, p, i, clearTransform, transform;
  47457. if (this.e === "all") {
  47458. s.cssText = "";
  47459. clearTransform = true;
  47460. } else {
  47461. a = this.e.split(" ").join("").split(",");
  47462. i = a.length;
  47463. while (--i > -1) {
  47464. p = a[i];
  47465. if (_specialProps[p]) {
  47466. if (_specialProps[p].parse === transformParse) {
  47467. clearTransform = true;
  47468. } else {
  47469. p = (p === "transformOrigin") ? _transformOriginProp : _specialProps[p].p; //ensures that special properties use the proper browser-specific property name, like "scaleX" might be "-webkit-transform" or "boxShadow" might be "-moz-box-shadow"
  47470. }
  47471. }
  47472. _removeProp(s, p);
  47473. }
  47474. }
  47475. if (clearTransform) {
  47476. _removeProp(s, _transformProp);
  47477. transform = this.t._gsTransform;
  47478. if (transform) {
  47479. if (transform.svg) {
  47480. this.t.removeAttribute("data-svg-origin");
  47481. this.t.removeAttribute("transform");
  47482. }
  47483. delete this.t._gsTransform;
  47484. }
  47485. }
  47486. }
  47487. };
  47488. _registerComplexSpecialProp("clearProps", {parser:function(t, e, p, cssp, pt) {
  47489. pt = new CSSPropTween(t, p, 0, 0, pt, 2);
  47490. pt.setRatio = _setClearPropsRatio;
  47491. pt.e = e;
  47492. pt.pr = -10;
  47493. pt.data = cssp._tween;
  47494. _hasPriority = true;
  47495. return pt;
  47496. }});
  47497. p = "bezier,throwProps,physicsProps,physics2D".split(",");
  47498. i = p.length;
  47499. while (i--) {
  47500. _registerPluginProp(p[i]);
  47501. }
  47502. p = CSSPlugin.prototype;
  47503. p._firstPT = p._lastParsedTransform = p._transform = null;
  47504. //gets called when the tween renders for the first time. This kicks everything off, recording start/end values, etc.
  47505. p._onInitTween = function(target, vars, tween, index) {
  47506. if (!target.nodeType) { //css is only for dom elements
  47507. return false;
  47508. }
  47509. this._target = _target = target;
  47510. this._tween = tween;
  47511. this._vars = vars;
  47512. _index = index;
  47513. _autoRound = vars.autoRound;
  47514. _hasPriority = false;
  47515. _suffixMap = vars.suffixMap || CSSPlugin.suffixMap;
  47516. _cs = _getComputedStyle(target, "");
  47517. _overwriteProps = this._overwriteProps;
  47518. var style = target.style,
  47519. v, pt, pt2, first, last, next, zIndex, tpt, threeD;
  47520. if (_reqSafariFix) if (style.zIndex === "") {
  47521. v = _getStyle(target, "zIndex", _cs);
  47522. if (v === "auto" || v === "") {
  47523. //corrects a bug in [non-Android] Safari that prevents it from repainting elements in their new positions if they don't have a zIndex set. We also can't just apply this inside _parseTransform() because anything that's moved in any way (like using "left" or "top" instead of transforms like "x" and "y") can be affected, so it is best to ensure that anything that's tweening has a z-index. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly. Plus zIndex is less memory-intensive.
  47524. this._addLazySet(style, "zIndex", 0);
  47525. }
  47526. }
  47527. if (typeof(vars) === "string") {
  47528. first = style.cssText;
  47529. v = _getAllStyles(target, _cs);
  47530. style.cssText = first + ";" + vars;
  47531. v = _cssDif(target, v, _getAllStyles(target)).difs;
  47532. if (!_supportsOpacity && _opacityValExp.test(vars)) {
  47533. v.opacity = parseFloat( RegExp.$1 );
  47534. }
  47535. vars = v;
  47536. style.cssText = first;
  47537. }
  47538. if (vars.className) { //className tweens will combine any differences they find in the css with the vars that are passed in, so {className:"myClass", scale:0.5, left:20} would work.
  47539. this._firstPT = pt = _specialProps.className.parse(target, vars.className, "className", this, null, null, vars);
  47540. } else {
  47541. this._firstPT = pt = this.parse(target, vars, null);
  47542. }
  47543. if (this._transformType) {
  47544. threeD = (this._transformType === 3);
  47545. if (!_transformProp) {
  47546. style.zoom = 1; //helps correct an IE issue.
  47547. } else if (_isSafari) {
  47548. _reqSafariFix = true;
  47549. //if zIndex isn't set, iOS Safari doesn't repaint things correctly sometimes (seemingly at random).
  47550. if (style.zIndex === "") {
  47551. zIndex = _getStyle(target, "zIndex", _cs);
  47552. if (zIndex === "auto" || zIndex === "") {
  47553. this._addLazySet(style, "zIndex", 0);
  47554. }
  47555. }
  47556. //Setting WebkitBackfaceVisibility corrects 3 bugs:
  47557. // 1) [non-Android] Safari skips rendering changes to "top" and "left" that are made on the same frame/render as a transform update.
  47558. // 2) iOS Safari sometimes neglects to repaint elements in their new positions. Setting "WebkitPerspective" to a non-zero value worked too except that on iOS Safari things would flicker randomly.
  47559. // 3) Safari sometimes displayed odd artifacts when tweening the transform (or WebkitTransform) property, like ghosts of the edges of the element remained. Definitely a browser bug.
  47560. //Note: we allow the user to override the auto-setting by defining WebkitBackfaceVisibility in the vars of the tween.
  47561. if (_isSafariLT6) {
  47562. this._addLazySet(style, "WebkitBackfaceVisibility", this._vars.WebkitBackfaceVisibility || (threeD ? "visible" : "hidden"));
  47563. }
  47564. }
  47565. pt2 = pt;
  47566. while (pt2 && pt2._next) {
  47567. pt2 = pt2._next;
  47568. }
  47569. tpt = new CSSPropTween(target, "transform", 0, 0, null, 2);
  47570. this._linkCSSP(tpt, null, pt2);
  47571. tpt.setRatio = _transformProp ? _setTransformRatio : _setIETransformRatio;
  47572. tpt.data = this._transform || _getTransform(target, _cs, true);
  47573. tpt.tween = tween;
  47574. tpt.pr = -1; //ensures that the transforms get applied after the components are updated.
  47575. _overwriteProps.pop(); //we don't want to force the overwrite of all "transform" tweens of the target - we only care about individual transform properties like scaleX, rotation, etc. The CSSPropTween constructor automatically adds the property to _overwriteProps which is why we need to pop() here.
  47576. }
  47577. if (_hasPriority) {
  47578. //reorders the linked list in order of pr (priority)
  47579. while (pt) {
  47580. next = pt._next;
  47581. pt2 = first;
  47582. while (pt2 && pt2.pr > pt.pr) {
  47583. pt2 = pt2._next;
  47584. }
  47585. if ((pt._prev = pt2 ? pt2._prev : last)) {
  47586. pt._prev._next = pt;
  47587. } else {
  47588. first = pt;
  47589. }
  47590. if ((pt._next = pt2)) {
  47591. pt2._prev = pt;
  47592. } else {
  47593. last = pt;
  47594. }
  47595. pt = next;
  47596. }
  47597. this._firstPT = first;
  47598. }
  47599. return true;
  47600. };
  47601. p.parse = function(target, vars, pt, plugin) {
  47602. var style = target.style,
  47603. p, sp, bn, en, bs, es, bsfx, esfx, isStr, rel;
  47604. for (p in vars) {
  47605. es = vars[p]; //ending value string
  47606. if (typeof(es) === "function") {
  47607. es = es(_index, _target);
  47608. }
  47609. sp = _specialProps[p]; //SpecialProp lookup.
  47610. if (sp) {
  47611. pt = sp.parse(target, es, p, this, pt, plugin, vars);
  47612. } else if (p.substr(0,2) === "--") { //for tweening CSS variables (which always start with "--"). To maximize performance and simplicity, we bypass CSSPlugin altogether and just add a normal property tween to the tween instance itself.
  47613. this._tween._propLookup[p] = this._addTween.call(this._tween, target.style, "setProperty", _getComputedStyle(target).getPropertyValue(p) + "", es + "", p, false, p);
  47614. continue;
  47615. } else {
  47616. bs = _getStyle(target, p, _cs) + "";
  47617. isStr = (typeof(es) === "string");
  47618. if (p === "color" || p === "fill" || p === "stroke" || p.indexOf("Color") !== -1 || (isStr && _rgbhslExp.test(es))) { //Opera uses background: to define color sometimes in addition to backgroundColor:
  47619. if (!isStr) {
  47620. es = _parseColor(es);
  47621. es = ((es.length > 3) ? "rgba(" : "rgb(") + es.join(",") + ")";
  47622. }
  47623. pt = _parseComplex(style, p, bs, es, true, "transparent", pt, 0, plugin);
  47624. } else if (isStr && _complexExp.test(es)) {
  47625. pt = _parseComplex(style, p, bs, es, true, null, pt, 0, plugin);
  47626. } else {
  47627. bn = parseFloat(bs);
  47628. bsfx = (bn || bn === 0) ? bs.substr((bn + "").length) : ""; //remember, bs could be non-numeric like "normal" for fontWeight, so we should default to a blank suffix in that case.
  47629. if (bs === "" || bs === "auto") {
  47630. if (p === "width" || p === "height") {
  47631. bn = _getDimension(target, p, _cs);
  47632. bsfx = "px";
  47633. } else if (p === "left" || p === "top") {
  47634. bn = _calculateOffset(target, p, _cs);
  47635. bsfx = "px";
  47636. } else {
  47637. bn = (p !== "opacity") ? 0 : 1;
  47638. bsfx = "";
  47639. }
  47640. }
  47641. rel = (isStr && es.charAt(1) === "=");
  47642. if (rel) {
  47643. en = parseInt(es.charAt(0) + "1", 10);
  47644. es = es.substr(2);
  47645. en *= parseFloat(es);
  47646. esfx = es.replace(_suffixExp, "");
  47647. } else {
  47648. en = parseFloat(es);
  47649. esfx = isStr ? es.replace(_suffixExp, "") : "";
  47650. }
  47651. if (esfx === "") {
  47652. esfx = (p in _suffixMap) ? _suffixMap[p] : bsfx; //populate the end suffix, prioritizing the map, then if none is found, use the beginning suffix.
  47653. }
  47654. es = (en || en === 0) ? (rel ? en + bn : en) + esfx : vars[p]; //ensures that any += or -= prefixes are taken care of. Record the end value before normalizing the suffix because we always want to end the tween on exactly what they intended even if it doesn't match the beginning value's suffix.
  47655. //if the beginning/ending suffixes don't match, normalize them...
  47656. if (bsfx !== esfx) if (esfx !== "" || p === "lineHeight") if (en || en === 0) if (bn) { //note: if the beginning value (bn) is 0, we don't need to convert units!
  47657. bn = _convertToPixels(target, p, bn, bsfx);
  47658. if (esfx === "%") {
  47659. bn /= _convertToPixels(target, p, 100, "%") / 100;
  47660. if (vars.strictUnits !== true) { //some browsers report only "px" values instead of allowing "%" with getComputedStyle(), so we assume that if we're tweening to a %, we should start there too unless strictUnits:true is defined. This approach is particularly useful for responsive designs that use from() tweens.
  47661. bs = bn + "%";
  47662. }
  47663. } else if (esfx === "em" || esfx === "rem" || esfx === "vw" || esfx === "vh") {
  47664. bn /= _convertToPixels(target, p, 1, esfx);
  47665. //otherwise convert to pixels.
  47666. } else if (esfx !== "px") {
  47667. en = _convertToPixels(target, p, en, esfx);
  47668. esfx = "px"; //we don't use bsfx after this, so we don't need to set it to px too.
  47669. }
  47670. if (rel) if (en || en === 0) {
  47671. es = (en + bn) + esfx; //the changes we made affect relative calculations, so adjust the end value here.
  47672. }
  47673. }
  47674. if (rel) {
  47675. en += bn;
  47676. }
  47677. if ((bn || bn === 0) && (en || en === 0)) { //faster than isNaN(). Also, previously we required en !== bn but that doesn't really gain much performance and it prevents _parseToProxy() from working properly if beginning and ending values match but need to get tweened by an external plugin anyway. For example, a bezier tween where the target starts at left:0 and has these points: [{left:50},{left:0}] wouldn't work properly because when parsing the last point, it'd match the first (current) one and a non-tweening CSSPropTween would be recorded when we actually need a normal tween (type:0) so that things get updated during the tween properly.
  47678. pt = new CSSPropTween(style, p, bn, en - bn, pt, 0, p, (_autoRound !== false && (esfx === "px" || p === "zIndex")), 0, bs, es);
  47679. pt.xs0 = esfx;
  47680. //DEBUG: _log("tween "+p+" from "+pt.b+" ("+bn+esfx+") to "+pt.e+" with suffix: "+pt.xs0);
  47681. } else if (style[p] === undefined || !es && (es + "" === "NaN" || es == null)) {
  47682. _log("invalid " + p + " tween value: " + vars[p]);
  47683. } else {
  47684. pt = new CSSPropTween(style, p, en || bn || 0, 0, pt, -1, p, false, 0, bs, es);
  47685. pt.xs0 = (es === "none" && (p === "display" || p.indexOf("Style") !== -1)) ? bs : es; //intermediate value should typically be set immediately (end value) except for "display" or things like borderTopStyle, borderBottomStyle, etc. which should use the beginning value during the tween.
  47686. //DEBUG: _log("non-tweening value "+p+": "+pt.xs0);
  47687. }
  47688. }
  47689. }
  47690. if (plugin) if (pt && !pt.plugin) {
  47691. pt.plugin = plugin;
  47692. }
  47693. }
  47694. return pt;
  47695. };
  47696. //gets called every time the tween updates, passing the new ratio (typically a value between 0 and 1, but not always (for example, if an Elastic.easeOut is used, the value can jump above 1 mid-tween). It will always start and 0 and end at 1.
  47697. p.setRatio = function(v) {
  47698. var pt = this._firstPT,
  47699. min = 0.000001,
  47700. val, str, i;
  47701. //at the end of the tween, we set the values to exactly what we received in order to make sure non-tweening values (like "position" or "float" or whatever) are set and so that if the beginning/ending suffixes (units) didn't match and we normalized to px, the value that the user passed in is used here. We check to see if the tween is at its beginning in case it's a from() tween in which case the ratio will actually go from 1 to 0 over the course of the tween (backwards).
  47702. if (v === 1 && (this._tween._time === this._tween._duration || this._tween._time === 0)) {
  47703. while (pt) {
  47704. if (pt.type !== 2) {
  47705. if (pt.r && pt.type !== -1) {
  47706. val = Math.round(pt.s + pt.c);
  47707. if (!pt.type) {
  47708. pt.t[pt.p] = val + pt.xs0;
  47709. } else if (pt.type === 1) { //complex value (one that typically has multiple numbers inside a string, like "rect(5px,10px,20px,25px)"
  47710. i = pt.l;
  47711. str = pt.xs0 + val + pt.xs1;
  47712. for (i = 1; i < pt.l; i++) {
  47713. str += pt["xn"+i] + pt["xs"+(i+1)];
  47714. }
  47715. pt.t[pt.p] = str;
  47716. }
  47717. } else {
  47718. pt.t[pt.p] = pt.e;
  47719. }
  47720. } else {
  47721. pt.setRatio(v);
  47722. }
  47723. pt = pt._next;
  47724. }
  47725. } else if (v || !(this._tween._time === this._tween._duration || this._tween._time === 0) || this._tween._rawPrevTime === -0.000001) {
  47726. while (pt) {
  47727. val = pt.c * v + pt.s;
  47728. if (pt.r) {
  47729. val = Math.round(val);
  47730. } else if (val < min) if (val > -min) {
  47731. val = 0;
  47732. }
  47733. if (!pt.type) {
  47734. pt.t[pt.p] = val + pt.xs0;
  47735. } else if (pt.type === 1) { //complex value (one that typically has multiple numbers inside a string, like "rect(5px,10px,20px,25px)"
  47736. i = pt.l;
  47737. if (i === 2) {
  47738. pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2;
  47739. } else if (i === 3) {
  47740. pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3;
  47741. } else if (i === 4) {
  47742. pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4;
  47743. } else if (i === 5) {
  47744. pt.t[pt.p] = pt.xs0 + val + pt.xs1 + pt.xn1 + pt.xs2 + pt.xn2 + pt.xs3 + pt.xn3 + pt.xs4 + pt.xn4 + pt.xs5;
  47745. } else {
  47746. str = pt.xs0 + val + pt.xs1;
  47747. for (i = 1; i < pt.l; i++) {
  47748. str += pt["xn"+i] + pt["xs"+(i+1)];
  47749. }
  47750. pt.t[pt.p] = str;
  47751. }
  47752. } else if (pt.type === -1) { //non-tweening value
  47753. pt.t[pt.p] = pt.xs0;
  47754. } else if (pt.setRatio) { //custom setRatio() for things like SpecialProps, external plugins, etc.
  47755. pt.setRatio(v);
  47756. }
  47757. pt = pt._next;
  47758. }
  47759. //if the tween is reversed all the way back to the beginning, we need to restore the original values which may have different units (like % instead of px or em or whatever).
  47760. } else {
  47761. while (pt) {
  47762. if (pt.type !== 2) {
  47763. pt.t[pt.p] = pt.b;
  47764. } else {
  47765. pt.setRatio(v);
  47766. }
  47767. pt = pt._next;
  47768. }
  47769. }
  47770. };
  47771. /**
  47772. * @private
  47773. * Forces rendering of the target's transforms (rotation, scale, etc.) whenever the CSSPlugin's setRatio() is called.
  47774. * Basically, this tells the CSSPlugin to create a CSSPropTween (type 2) after instantiation that runs last in the linked
  47775. * list and calls the appropriate (3D or 2D) rendering function. We separate this into its own method so that we can call
  47776. * it from other plugins like BezierPlugin if, for example, it needs to apply an autoRotation and this CSSPlugin
  47777. * doesn't have any transform-related properties of its own. You can call this method as many times as you
  47778. * want and it won't create duplicate CSSPropTweens.
  47779. *
  47780. * @param {boolean} threeD if true, it should apply 3D tweens (otherwise, just 2D ones are fine and typically faster)
  47781. */
  47782. p._enableTransforms = function(threeD) {
  47783. this._transform = this._transform || _getTransform(this._target, _cs, true); //ensures that the element has a _gsTransform property with the appropriate values.
  47784. this._transformType = (!(this._transform.svg && _useSVGTransformAttr) && (threeD || this._transformType === 3)) ? 3 : 2;
  47785. };
  47786. var lazySet = function(v) {
  47787. this.t[this.p] = this.e;
  47788. this.data._linkCSSP(this, this._next, null, true); //we purposefully keep this._next even though it'd make sense to null it, but this is a performance optimization, as this happens during the while (pt) {} loop in setRatio() at the bottom of which it sets pt = pt._next, so if we null it, the linked list will be broken in that loop.
  47789. };
  47790. /** @private Gives us a way to set a value on the first render (and only the first render). **/
  47791. p._addLazySet = function(t, p, v) {
  47792. var pt = this._firstPT = new CSSPropTween(t, p, 0, 0, this._firstPT, 2);
  47793. pt.e = v;
  47794. pt.setRatio = lazySet;
  47795. pt.data = this;
  47796. };
  47797. /** @private **/
  47798. p._linkCSSP = function(pt, next, prev, remove) {
  47799. if (pt) {
  47800. if (next) {
  47801. next._prev = pt;
  47802. }
  47803. if (pt._next) {
  47804. pt._next._prev = pt._prev;
  47805. }
  47806. if (pt._prev) {
  47807. pt._prev._next = pt._next;
  47808. } else if (this._firstPT === pt) {
  47809. this._firstPT = pt._next;
  47810. remove = true; //just to prevent resetting this._firstPT 5 lines down in case pt._next is null. (optimized for speed)
  47811. }
  47812. if (prev) {
  47813. prev._next = pt;
  47814. } else if (!remove && this._firstPT === null) {
  47815. this._firstPT = pt;
  47816. }
  47817. pt._next = next;
  47818. pt._prev = prev;
  47819. }
  47820. return pt;
  47821. };
  47822. p._mod = function(lookup) {
  47823. var pt = this._firstPT;
  47824. while (pt) {
  47825. if (typeof(lookup[pt.p]) === "function" && lookup[pt.p] === Math.round) { //only gets called by RoundPropsPlugin (ModifyPlugin manages all the rendering internally for CSSPlugin properties that need modification). Remember, we handle rounding a bit differently in this plugin for performance reasons, leveraging "r" as an indicator that the value should be rounded internally..
  47826. pt.r = 1;
  47827. }
  47828. pt = pt._next;
  47829. }
  47830. };
  47831. //we need to make sure that if alpha or autoAlpha is killed, opacity is too. And autoAlpha affects the "visibility" property.
  47832. p._kill = function(lookup) {
  47833. var copy = lookup,
  47834. pt, p, xfirst;
  47835. if (lookup.autoAlpha || lookup.alpha) {
  47836. copy = {};
  47837. for (p in lookup) { //copy the lookup so that we're not changing the original which may be passed elsewhere.
  47838. copy[p] = lookup[p];
  47839. }
  47840. copy.opacity = 1;
  47841. if (copy.autoAlpha) {
  47842. copy.visibility = 1;
  47843. }
  47844. }
  47845. if (lookup.className && (pt = this._classNamePT)) { //for className tweens, we need to kill any associated CSSPropTweens too; a linked list starts at the className's "xfirst".
  47846. xfirst = pt.xfirst;
  47847. if (xfirst && xfirst._prev) {
  47848. this._linkCSSP(xfirst._prev, pt._next, xfirst._prev._prev); //break off the prev
  47849. } else if (xfirst === this._firstPT) {
  47850. this._firstPT = pt._next;
  47851. }
  47852. if (pt._next) {
  47853. this._linkCSSP(pt._next, pt._next._next, xfirst._prev);
  47854. }
  47855. this._classNamePT = null;
  47856. }
  47857. pt = this._firstPT;
  47858. while (pt) {
  47859. if (pt.plugin && pt.plugin !== p && pt.plugin._kill) { //for plugins that are registered with CSSPlugin, we should notify them of the kill.
  47860. pt.plugin._kill(lookup);
  47861. p = pt.plugin;
  47862. }
  47863. pt = pt._next;
  47864. }
  47865. return TweenPlugin.prototype._kill.call(this, copy);
  47866. };
  47867. //used by cascadeTo() for gathering all the style properties of each child element into an array for comparison.
  47868. var _getChildStyles = function(e, props, targets) {
  47869. var children, i, child, type;
  47870. if (e.slice) {
  47871. i = e.length;
  47872. while (--i > -1) {
  47873. _getChildStyles(e[i], props, targets);
  47874. }
  47875. return;
  47876. }
  47877. children = e.childNodes;
  47878. i = children.length;
  47879. while (--i > -1) {
  47880. child = children[i];
  47881. type = child.type;
  47882. if (child.style) {
  47883. props.push(_getAllStyles(child));
  47884. if (targets) {
  47885. targets.push(child);
  47886. }
  47887. }
  47888. if ((type === 1 || type === 9 || type === 11) && child.childNodes.length) {
  47889. _getChildStyles(child, props, targets);
  47890. }
  47891. }
  47892. };
  47893. /**
  47894. * Typically only useful for className tweens that may affect child elements, this method creates a TweenLite
  47895. * and then compares the style properties of all the target's child elements at the tween's start and end, and
  47896. * if any are different, it also creates tweens for those and returns an array containing ALL of the resulting
  47897. * tweens (so that you can easily add() them to a TimelineLite, for example). The reason this functionality is
  47898. * wrapped into a separate static method of CSSPlugin instead of being integrated into all regular className tweens
  47899. * is because it creates entirely new tweens that may have completely different targets than the original tween,
  47900. * so if they were all lumped into the original tween instance, it would be inconsistent with the rest of the API
  47901. * and it would create other problems. For example:
  47902. * - If I create a tween of elementA, that tween instance may suddenly change its target to include 50 other elements (unintuitive if I specifically defined the target I wanted)
  47903. * - We can't just create new independent tweens because otherwise, what happens if the original/parent tween is reversed or pause or dropped into a TimelineLite for tight control? You'd expect that tween's behavior to affect all the others.
  47904. * - Analyzing every style property of every child before and after the tween is an expensive operation when there are many children, so this behavior shouldn't be imposed on all className tweens by default, especially since it's probably rare that this extra functionality is needed.
  47905. *
  47906. * @param {Object} target object to be tweened
  47907. * @param {number} Duration in seconds (or frames for frames-based tweens)
  47908. * @param {Object} Object containing the end values, like {className:"newClass", ease:Linear.easeNone}
  47909. * @return {Array} An array of TweenLite instances
  47910. */
  47911. CSSPlugin.cascadeTo = function(target, duration, vars) {
  47912. var tween = TweenLite.to(target, duration, vars),
  47913. results = [tween],
  47914. b = [],
  47915. e = [],
  47916. targets = [],
  47917. _reservedProps = TweenLite._internals.reservedProps,
  47918. i, difs, p, from;
  47919. target = tween._targets || tween.target;
  47920. _getChildStyles(target, b, targets);
  47921. tween.render(duration, true, true);
  47922. _getChildStyles(target, e);
  47923. tween.render(0, true, true);
  47924. tween._enabled(true);
  47925. i = targets.length;
  47926. while (--i > -1) {
  47927. difs = _cssDif(targets[i], b[i], e[i]);
  47928. if (difs.firstMPT) {
  47929. difs = difs.difs;
  47930. for (p in vars) {
  47931. if (_reservedProps[p]) {
  47932. difs[p] = vars[p];
  47933. }
  47934. }
  47935. from = {};
  47936. for (p in difs) {
  47937. from[p] = b[i][p];
  47938. }
  47939. results.push(TweenLite.fromTo(targets[i], duration, from, difs));
  47940. }
  47941. }
  47942. return results;
  47943. };
  47944. TweenPlugin.activate([CSSPlugin]);
  47945. return CSSPlugin;
  47946. }, true);
  47947. /*
  47948. * ----------------------------------------------------------------
  47949. * RoundPropsPlugin
  47950. * ----------------------------------------------------------------
  47951. */
  47952. (function() {
  47953. var RoundPropsPlugin = _gsScope._gsDefine.plugin({
  47954. propName: "roundProps",
  47955. version: "1.6.0",
  47956. priority: -1,
  47957. API: 2,
  47958. //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
  47959. init: function(target, value, tween) {
  47960. this._tween = tween;
  47961. return true;
  47962. }
  47963. }),
  47964. _roundLinkedList = function(node) {
  47965. while (node) {
  47966. if (!node.f && !node.blob) {
  47967. node.m = Math.round;
  47968. }
  47969. node = node._next;
  47970. }
  47971. },
  47972. p = RoundPropsPlugin.prototype;
  47973. p._onInitAllProps = function() {
  47974. var tween = this._tween,
  47975. rp = (tween.vars.roundProps.join) ? tween.vars.roundProps : tween.vars.roundProps.split(","),
  47976. i = rp.length,
  47977. lookup = {},
  47978. rpt = tween._propLookup.roundProps,
  47979. prop, pt, next;
  47980. while (--i > -1) {
  47981. lookup[rp[i]] = Math.round;
  47982. }
  47983. i = rp.length;
  47984. while (--i > -1) {
  47985. prop = rp[i];
  47986. pt = tween._firstPT;
  47987. while (pt) {
  47988. next = pt._next; //record here, because it may get removed
  47989. if (pt.pg) {
  47990. pt.t._mod(lookup);
  47991. } else if (pt.n === prop) {
  47992. if (pt.f === 2 && pt.t) { //a blob (text containing multiple numeric values)
  47993. _roundLinkedList(pt.t._firstPT);
  47994. } else {
  47995. this._add(pt.t, prop, pt.s, pt.c);
  47996. //remove from linked list
  47997. if (next) {
  47998. next._prev = pt._prev;
  47999. }
  48000. if (pt._prev) {
  48001. pt._prev._next = next;
  48002. } else if (tween._firstPT === pt) {
  48003. tween._firstPT = next;
  48004. }
  48005. pt._next = pt._prev = null;
  48006. tween._propLookup[prop] = rpt;
  48007. }
  48008. }
  48009. pt = next;
  48010. }
  48011. }
  48012. return false;
  48013. };
  48014. p._add = function(target, p, s, c) {
  48015. this._addTween(target, p, s, s + c, p, Math.round);
  48016. this._overwriteProps.push(p);
  48017. };
  48018. }());
  48019. /*
  48020. * ----------------------------------------------------------------
  48021. * AttrPlugin
  48022. * ----------------------------------------------------------------
  48023. */
  48024. (function() {
  48025. _gsScope._gsDefine.plugin({
  48026. propName: "attr",
  48027. API: 2,
  48028. version: "0.6.1",
  48029. //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
  48030. init: function(target, value, tween, index) {
  48031. var p, end;
  48032. if (typeof(target.setAttribute) !== "function") {
  48033. return false;
  48034. }
  48035. for (p in value) {
  48036. end = value[p];
  48037. if (typeof(end) === "function") {
  48038. end = end(index, target);
  48039. }
  48040. this._addTween(target, "setAttribute", target.getAttribute(p) + "", end + "", p, false, p);
  48041. this._overwriteProps.push(p);
  48042. }
  48043. return true;
  48044. }
  48045. });
  48046. }());
  48047. /*
  48048. * ----------------------------------------------------------------
  48049. * DirectionalRotationPlugin
  48050. * ----------------------------------------------------------------
  48051. */
  48052. _gsScope._gsDefine.plugin({
  48053. propName: "directionalRotation",
  48054. version: "0.3.1",
  48055. API: 2,
  48056. //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run.
  48057. init: function(target, value, tween, index) {
  48058. if (typeof(value) !== "object") {
  48059. value = {rotation:value};
  48060. }
  48061. this.finals = {};
  48062. var cap = (value.useRadians === true) ? Math.PI * 2 : 360,
  48063. min = 0.000001,
  48064. p, v, start, end, dif, split;
  48065. for (p in value) {
  48066. if (p !== "useRadians") {
  48067. end = value[p];
  48068. if (typeof(end) === "function") {
  48069. end = end(index, target);
  48070. }
  48071. split = (end + "").split("_");
  48072. v = split[0];
  48073. start = parseFloat( (typeof(target[p]) !== "function") ? target[p] : target[ ((p.indexOf("set") || typeof(target["get" + p.substr(3)]) !== "function") ? p : "get" + p.substr(3)) ]() );
  48074. end = this.finals[p] = (typeof(v) === "string" && v.charAt(1) === "=") ? start + parseInt(v.charAt(0) + "1", 10) * Number(v.substr(2)) : Number(v) || 0;
  48075. dif = end - start;
  48076. if (split.length) {
  48077. v = split.join("_");
  48078. if (v.indexOf("short") !== -1) {
  48079. dif = dif % cap;
  48080. if (dif !== dif % (cap / 2)) {
  48081. dif = (dif < 0) ? dif + cap : dif - cap;
  48082. }
  48083. }
  48084. if (v.indexOf("_cw") !== -1 && dif < 0) {
  48085. dif = ((dif + cap * 9999999999) % cap) - ((dif / cap) | 0) * cap;
  48086. } else if (v.indexOf("ccw") !== -1 && dif > 0) {
  48087. dif = ((dif - cap * 9999999999) % cap) - ((dif / cap) | 0) * cap;
  48088. }
  48089. }
  48090. if (dif > min || dif < -min) {
  48091. this._addTween(target, p, start, start + dif, p);
  48092. this._overwriteProps.push(p);
  48093. }
  48094. }
  48095. }
  48096. return true;
  48097. },
  48098. //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.)
  48099. set: function(ratio) {
  48100. var pt;
  48101. if (ratio !== 1) {
  48102. this._super.setRatio.call(this, ratio);
  48103. } else {
  48104. pt = this._firstPT;
  48105. while (pt) {
  48106. if (pt.f) {
  48107. pt.t[pt.p](this.finals[pt.p]);
  48108. } else {
  48109. pt.t[pt.p] = this.finals[pt.p];
  48110. }
  48111. pt = pt._next;
  48112. }
  48113. }
  48114. }
  48115. })._autoCSS = true;
  48116. /*
  48117. * ----------------------------------------------------------------
  48118. * EasePack
  48119. * ----------------------------------------------------------------
  48120. */
  48121. _gsScope._gsDefine("easing.Back", ["easing.Ease"], function(Ease) {
  48122. var w = (_gsScope.GreenSockGlobals || _gsScope),
  48123. gs = w.com.greensock,
  48124. _2PI = Math.PI * 2,
  48125. _HALF_PI = Math.PI / 2,
  48126. _class = gs._class,
  48127. _create = function(n, f) {
  48128. var C = _class("easing." + n, function(){}, true),
  48129. p = C.prototype = new Ease();
  48130. p.constructor = C;
  48131. p.getRatio = f;
  48132. return C;
  48133. },
  48134. _easeReg = Ease.register || function(){}, //put an empty function in place just as a safety measure in case someone loads an OLD version of TweenLite.js where Ease.register doesn't exist.
  48135. _wrap = function(name, EaseOut, EaseIn, EaseInOut, aliases) {
  48136. var C = _class("easing."+name, {
  48137. easeOut:new EaseOut(),
  48138. easeIn:new EaseIn(),
  48139. easeInOut:new EaseInOut()
  48140. }, true);
  48141. _easeReg(C, name);
  48142. return C;
  48143. },
  48144. EasePoint = function(time, value, next) {
  48145. this.t = time;
  48146. this.v = value;
  48147. if (next) {
  48148. this.next = next;
  48149. next.prev = this;
  48150. this.c = next.v - value;
  48151. this.gap = next.t - time;
  48152. }
  48153. },
  48154. //Back
  48155. _createBack = function(n, f) {
  48156. var C = _class("easing." + n, function(overshoot) {
  48157. this._p1 = (overshoot || overshoot === 0) ? overshoot : 1.70158;
  48158. this._p2 = this._p1 * 1.525;
  48159. }, true),
  48160. p = C.prototype = new Ease();
  48161. p.constructor = C;
  48162. p.getRatio = f;
  48163. p.config = function(overshoot) {
  48164. return new C(overshoot);
  48165. };
  48166. return C;
  48167. },
  48168. Back = _wrap("Back",
  48169. _createBack("BackOut", function(p) {
  48170. return ((p = p - 1) * p * ((this._p1 + 1) * p + this._p1) + 1);
  48171. }),
  48172. _createBack("BackIn", function(p) {
  48173. return p * p * ((this._p1 + 1) * p - this._p1);
  48174. }),
  48175. _createBack("BackInOut", function(p) {
  48176. return ((p *= 2) < 1) ? 0.5 * p * p * ((this._p2 + 1) * p - this._p2) : 0.5 * ((p -= 2) * p * ((this._p2 + 1) * p + this._p2) + 2);
  48177. })
  48178. ),
  48179. //SlowMo
  48180. SlowMo = _class("easing.SlowMo", function(linearRatio, power, yoyoMode) {
  48181. power = (power || power === 0) ? power : 0.7;
  48182. if (linearRatio == null) {
  48183. linearRatio = 0.7;
  48184. } else if (linearRatio > 1) {
  48185. linearRatio = 1;
  48186. }
  48187. this._p = (linearRatio !== 1) ? power : 0;
  48188. this._p1 = (1 - linearRatio) / 2;
  48189. this._p2 = linearRatio;
  48190. this._p3 = this._p1 + this._p2;
  48191. this._calcEnd = (yoyoMode === true);
  48192. }, true),
  48193. p = SlowMo.prototype = new Ease(),
  48194. SteppedEase, RoughEase, _createElastic;
  48195. p.constructor = SlowMo;
  48196. p.getRatio = function(p) {
  48197. var r = p + (0.5 - p) * this._p;
  48198. if (p < this._p1) {
  48199. return this._calcEnd ? 1 - ((p = 1 - (p / this._p1)) * p) : r - ((p = 1 - (p / this._p1)) * p * p * p * r);
  48200. } else if (p > this._p3) {
  48201. return this._calcEnd ? 1 - (p = (p - this._p3) / this._p1) * p : r + ((p - r) * (p = (p - this._p3) / this._p1) * p * p * p);
  48202. }
  48203. return this._calcEnd ? 1 : r;
  48204. };
  48205. SlowMo.ease = new SlowMo(0.7, 0.7);
  48206. p.config = SlowMo.config = function(linearRatio, power, yoyoMode) {
  48207. return new SlowMo(linearRatio, power, yoyoMode);
  48208. };
  48209. //SteppedEase
  48210. SteppedEase = _class("easing.SteppedEase", function(steps, immediateStart) {
  48211. steps = steps || 1;
  48212. this._p1 = 1 / steps;
  48213. this._p2 = steps + (immediateStart ? 0 : 1);
  48214. this._p3 = immediateStart ? 1 : 0;
  48215. }, true);
  48216. p = SteppedEase.prototype = new Ease();
  48217. p.constructor = SteppedEase;
  48218. p.getRatio = function(p) {
  48219. if (p < 0) {
  48220. p = 0;
  48221. } else if (p >= 1) {
  48222. p = 0.999999999;
  48223. }
  48224. return (((this._p2 * p) | 0) + this._p3) * this._p1;
  48225. };
  48226. p.config = SteppedEase.config = function(steps, immediateStart) {
  48227. return new SteppedEase(steps, immediateStart);
  48228. };
  48229. //RoughEase
  48230. RoughEase = _class("easing.RoughEase", function(vars) {
  48231. vars = vars || {};
  48232. var taper = vars.taper || "none",
  48233. a = [],
  48234. cnt = 0,
  48235. points = (vars.points || 20) | 0,
  48236. i = points,
  48237. randomize = (vars.randomize !== false),
  48238. clamp = (vars.clamp === true),
  48239. template = (vars.template instanceof Ease) ? vars.template : null,
  48240. strength = (typeof(vars.strength) === "number") ? vars.strength * 0.4 : 0.4,
  48241. x, y, bump, invX, obj, pnt;
  48242. while (--i > -1) {
  48243. x = randomize ? Math.random() : (1 / points) * i;
  48244. y = template ? template.getRatio(x) : x;
  48245. if (taper === "none") {
  48246. bump = strength;
  48247. } else if (taper === "out") {
  48248. invX = 1 - x;
  48249. bump = invX * invX * strength;
  48250. } else if (taper === "in") {
  48251. bump = x * x * strength;
  48252. } else if (x < 0.5) { //"both" (start)
  48253. invX = x * 2;
  48254. bump = invX * invX * 0.5 * strength;
  48255. } else { //"both" (end)
  48256. invX = (1 - x) * 2;
  48257. bump = invX * invX * 0.5 * strength;
  48258. }
  48259. if (randomize) {
  48260. y += (Math.random() * bump) - (bump * 0.5);
  48261. } else if (i % 2) {
  48262. y += bump * 0.5;
  48263. } else {
  48264. y -= bump * 0.5;
  48265. }
  48266. if (clamp) {
  48267. if (y > 1) {
  48268. y = 1;
  48269. } else if (y < 0) {
  48270. y = 0;
  48271. }
  48272. }
  48273. a[cnt++] = {x:x, y:y};
  48274. }
  48275. a.sort(function(a, b) {
  48276. return a.x - b.x;
  48277. });
  48278. pnt = new EasePoint(1, 1, null);
  48279. i = points;
  48280. while (--i > -1) {
  48281. obj = a[i];
  48282. pnt = new EasePoint(obj.x, obj.y, pnt);
  48283. }
  48284. this._prev = new EasePoint(0, 0, (pnt.t !== 0) ? pnt : pnt.next);
  48285. }, true);
  48286. p = RoughEase.prototype = new Ease();
  48287. p.constructor = RoughEase;
  48288. p.getRatio = function(p) {
  48289. var pnt = this._prev;
  48290. if (p > pnt.t) {
  48291. while (pnt.next && p >= pnt.t) {
  48292. pnt = pnt.next;
  48293. }
  48294. pnt = pnt.prev;
  48295. } else {
  48296. while (pnt.prev && p <= pnt.t) {
  48297. pnt = pnt.prev;
  48298. }
  48299. }
  48300. this._prev = pnt;
  48301. return (pnt.v + ((p - pnt.t) / pnt.gap) * pnt.c);
  48302. };
  48303. p.config = function(vars) {
  48304. return new RoughEase(vars);
  48305. };
  48306. RoughEase.ease = new RoughEase();
  48307. //Bounce
  48308. _wrap("Bounce",
  48309. _create("BounceOut", function(p) {
  48310. if (p < 1 / 2.75) {
  48311. return 7.5625 * p * p;
  48312. } else if (p < 2 / 2.75) {
  48313. return 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
  48314. } else if (p < 2.5 / 2.75) {
  48315. return 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
  48316. }
  48317. return 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
  48318. }),
  48319. _create("BounceIn", function(p) {
  48320. if ((p = 1 - p) < 1 / 2.75) {
  48321. return 1 - (7.5625 * p * p);
  48322. } else if (p < 2 / 2.75) {
  48323. return 1 - (7.5625 * (p -= 1.5 / 2.75) * p + 0.75);
  48324. } else if (p < 2.5 / 2.75) {
  48325. return 1 - (7.5625 * (p -= 2.25 / 2.75) * p + 0.9375);
  48326. }
  48327. return 1 - (7.5625 * (p -= 2.625 / 2.75) * p + 0.984375);
  48328. }),
  48329. _create("BounceInOut", function(p) {
  48330. var invert = (p < 0.5);
  48331. if (invert) {
  48332. p = 1 - (p * 2);
  48333. } else {
  48334. p = (p * 2) - 1;
  48335. }
  48336. if (p < 1 / 2.75) {
  48337. p = 7.5625 * p * p;
  48338. } else if (p < 2 / 2.75) {
  48339. p = 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
  48340. } else if (p < 2.5 / 2.75) {
  48341. p = 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
  48342. } else {
  48343. p = 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
  48344. }
  48345. return invert ? (1 - p) * 0.5 : p * 0.5 + 0.5;
  48346. })
  48347. );
  48348. //CIRC
  48349. _wrap("Circ",
  48350. _create("CircOut", function(p) {
  48351. return Math.sqrt(1 - (p = p - 1) * p);
  48352. }),
  48353. _create("CircIn", function(p) {
  48354. return -(Math.sqrt(1 - (p * p)) - 1);
  48355. }),
  48356. _create("CircInOut", function(p) {
  48357. return ((p*=2) < 1) ? -0.5 * (Math.sqrt(1 - p * p) - 1) : 0.5 * (Math.sqrt(1 - (p -= 2) * p) + 1);
  48358. })
  48359. );
  48360. //Elastic
  48361. _createElastic = function(n, f, def) {
  48362. var C = _class("easing." + n, function(amplitude, period) {
  48363. this._p1 = (amplitude >= 1) ? amplitude : 1; //note: if amplitude is < 1, we simply adjust the period for a more natural feel. Otherwise the math doesn't work right and the curve starts at 1.
  48364. this._p2 = (period || def) / (amplitude < 1 ? amplitude : 1);
  48365. this._p3 = this._p2 / _2PI * (Math.asin(1 / this._p1) || 0);
  48366. this._p2 = _2PI / this._p2; //precalculate to optimize
  48367. }, true),
  48368. p = C.prototype = new Ease();
  48369. p.constructor = C;
  48370. p.getRatio = f;
  48371. p.config = function(amplitude, period) {
  48372. return new C(amplitude, period);
  48373. };
  48374. return C;
  48375. };
  48376. _wrap("Elastic",
  48377. _createElastic("ElasticOut", function(p) {
  48378. return this._p1 * Math.pow(2, -10 * p) * Math.sin( (p - this._p3) * this._p2 ) + 1;
  48379. }, 0.3),
  48380. _createElastic("ElasticIn", function(p) {
  48381. return -(this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * this._p2 ));
  48382. }, 0.3),
  48383. _createElastic("ElasticInOut", function(p) {
  48384. return ((p *= 2) < 1) ? -0.5 * (this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * this._p2)) : this._p1 * Math.pow(2, -10 *(p -= 1)) * Math.sin( (p - this._p3) * this._p2 ) * 0.5 + 1;
  48385. }, 0.45)
  48386. );
  48387. //Expo
  48388. _wrap("Expo",
  48389. _create("ExpoOut", function(p) {
  48390. return 1 - Math.pow(2, -10 * p);
  48391. }),
  48392. _create("ExpoIn", function(p) {
  48393. return Math.pow(2, 10 * (p - 1)) - 0.001;
  48394. }),
  48395. _create("ExpoInOut", function(p) {
  48396. return ((p *= 2) < 1) ? 0.5 * Math.pow(2, 10 * (p - 1)) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
  48397. })
  48398. );
  48399. //Sine
  48400. _wrap("Sine",
  48401. _create("SineOut", function(p) {
  48402. return Math.sin(p * _HALF_PI);
  48403. }),
  48404. _create("SineIn", function(p) {
  48405. return -Math.cos(p * _HALF_PI) + 1;
  48406. }),
  48407. _create("SineInOut", function(p) {
  48408. return -0.5 * (Math.cos(Math.PI * p) - 1);
  48409. })
  48410. );
  48411. _class("easing.EaseLookup", {
  48412. find:function(s) {
  48413. return Ease.map[s];
  48414. }
  48415. }, true);
  48416. //register the non-standard eases
  48417. _easeReg(w.SlowMo, "SlowMo", "ease,");
  48418. _easeReg(RoughEase, "RoughEase", "ease,");
  48419. _easeReg(SteppedEase, "SteppedEase", "ease,");
  48420. return Back;
  48421. }, true);
  48422. });
  48423. if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); } //necessary in case TweenLite was already loaded separately.
  48424. /*
  48425. * ----------------------------------------------------------------
  48426. * Base classes like TweenLite, SimpleTimeline, Ease, Ticker, etc.
  48427. * ----------------------------------------------------------------
  48428. */
  48429. (function(window, moduleName) {
  48430. "use strict";
  48431. var _exports = {},
  48432. _doc = window.document,
  48433. _globals = window.GreenSockGlobals = window.GreenSockGlobals || window;
  48434. if (_globals.TweenLite) {
  48435. return; //in case the core set of classes is already loaded, don't instantiate twice.
  48436. }
  48437. var _namespace = function(ns) {
  48438. var a = ns.split("."),
  48439. p = _globals, i;
  48440. for (i = 0; i < a.length; i++) {
  48441. p[a[i]] = p = p[a[i]] || {};
  48442. }
  48443. return p;
  48444. },
  48445. gs = _namespace("com.greensock"),
  48446. _tinyNum = 0.0000000001,
  48447. _slice = function(a) { //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
  48448. var b = [],
  48449. l = a.length,
  48450. i;
  48451. for (i = 0; i !== l; b.push(a[i++])) {}
  48452. return b;
  48453. },
  48454. _emptyFunc = function() {},
  48455. _isArray = (function() { //works around issues in iframe environments where the Array global isn't shared, thus if the object originates in a different window/iframe, "(obj instanceof Array)" will evaluate false. We added some speed optimizations to avoid Object.prototype.toString.call() unless it's absolutely necessary because it's VERY slow (like 20x slower)
  48456. var toString = Object.prototype.toString,
  48457. array = toString.call([]);
  48458. return function(obj) {
  48459. return obj != null && (obj instanceof Array || (typeof(obj) === "object" && !!obj.push && toString.call(obj) === array));
  48460. };
  48461. }()),
  48462. a, i, p, _ticker, _tickerActive,
  48463. _defLookup = {},
  48464. /**
  48465. * @constructor
  48466. * Defines a GreenSock class, optionally with an array of dependencies that must be instantiated first and passed into the definition.
  48467. * This allows users to load GreenSock JS files in any order even if they have interdependencies (like CSSPlugin extends TweenPlugin which is
  48468. * inside TweenLite.js, but if CSSPlugin is loaded first, it should wait to run its code until TweenLite.js loads and instantiates TweenPlugin
  48469. * and then pass TweenPlugin to CSSPlugin's definition). This is all done automatically and internally.
  48470. *
  48471. * Every definition will be added to a "com.greensock" global object (typically window, but if a window.GreenSockGlobals object is found,
  48472. * it will go there as of v1.7). For example, TweenLite will be found at window.com.greensock.TweenLite and since it's a global class that should be available anywhere,
  48473. * it is ALSO referenced at window.TweenLite. However some classes aren't considered global, like the base com.greensock.core.Animation class, so
  48474. * those will only be at the package like window.com.greensock.core.Animation. Again, if you define a GreenSockGlobals object on the window, everything
  48475. * gets tucked neatly inside there instead of on the window directly. This allows you to do advanced things like load multiple versions of GreenSock
  48476. * files and put them into distinct objects (imagine a banner ad uses a newer version but the main site uses an older one). In that case, you could
  48477. * sandbox the banner one like:
  48478. *
  48479. * <script>
  48480. * var gs = window.GreenSockGlobals = {}; //the newer version we're about to load could now be referenced in a "gs" object, like gs.TweenLite.to(...). Use whatever alias you want as long as it's unique, "gs" or "banner" or whatever.
  48481. * </script>
  48482. * <script src="js/greensock/v1.7/TweenMax.js"></script>
  48483. * <script>
  48484. * window.GreenSockGlobals = window._gsQueue = window._gsDefine = null; //reset it back to null (along with the special _gsQueue variable) so that the next load of TweenMax affects the window and we can reference things directly like TweenLite.to(...)
  48485. * </script>
  48486. * <script src="js/greensock/v1.6/TweenMax.js"></script>
  48487. * <script>
  48488. * gs.TweenLite.to(...); //would use v1.7
  48489. * TweenLite.to(...); //would use v1.6
  48490. * </script>
  48491. *
  48492. * @param {!string} ns The namespace of the class definition, leaving off "com.greensock." as that's assumed. For example, "TweenLite" or "plugins.CSSPlugin" or "easing.Back".
  48493. * @param {!Array.<string>} dependencies An array of dependencies (described as their namespaces minus "com.greensock." prefix). For example ["TweenLite","plugins.TweenPlugin","core.Animation"]
  48494. * @param {!function():Object} func The function that should be called and passed the resolved dependencies which will return the actual class for this definition.
  48495. * @param {boolean=} global If true, the class will be added to the global scope (typically window unless you define a window.GreenSockGlobals object)
  48496. */
  48497. Definition = function(ns, dependencies, func, global) {
  48498. this.sc = (_defLookup[ns]) ? _defLookup[ns].sc : []; //subclasses
  48499. _defLookup[ns] = this;
  48500. this.gsClass = null;
  48501. this.func = func;
  48502. var _classes = [];
  48503. this.check = function(init) {
  48504. var i = dependencies.length,
  48505. missing = i,
  48506. cur, a, n, cl;
  48507. while (--i > -1) {
  48508. if ((cur = _defLookup[dependencies[i]] || new Definition(dependencies[i], [])).gsClass) {
  48509. _classes[i] = cur.gsClass;
  48510. missing--;
  48511. } else if (init) {
  48512. cur.sc.push(this);
  48513. }
  48514. }
  48515. if (missing === 0 && func) {
  48516. a = ("com.greensock." + ns).split(".");
  48517. n = a.pop();
  48518. cl = _namespace(a.join("."))[n] = this.gsClass = func.apply(func, _classes);
  48519. //exports to multiple environments
  48520. if (global) {
  48521. _globals[n] = _exports[n] = cl; //provides a way to avoid global namespace pollution. By default, the main classes like TweenLite, Power1, Strong, etc. are added to window unless a GreenSockGlobals is defined. So if you want to have things added to a custom object instead, just do something like window.GreenSockGlobals = {} before loading any GreenSock files. You can even set up an alias like window.GreenSockGlobals = windows.gs = {} so that you can access everything like gs.TweenLite. Also remember that ALL classes are added to the window.com.greensock object (in their respective packages, like com.greensock.easing.Power1, com.greensock.TweenLite, etc.)
  48522. if (typeof(module) !== "undefined" && module.exports) { //node
  48523. if (ns === moduleName) {
  48524. module.exports = _exports[moduleName] = cl;
  48525. for (i in _exports) {
  48526. cl[i] = _exports[i];
  48527. }
  48528. } else if (_exports[moduleName]) {
  48529. _exports[moduleName][n] = cl;
  48530. }
  48531. } else if (typeof(define) === "function" && define.amd){ //AMD
  48532. define((window.GreenSockAMDPath ? window.GreenSockAMDPath + "/" : "") + ns.split(".").pop(), [], function() { return cl; });
  48533. }
  48534. }
  48535. for (i = 0; i < this.sc.length; i++) {
  48536. this.sc[i].check();
  48537. }
  48538. }
  48539. };
  48540. this.check(true);
  48541. },
  48542. //used to create Definition instances (which basically registers a class that has dependencies).
  48543. _gsDefine = window._gsDefine = function(ns, dependencies, func, global) {
  48544. return new Definition(ns, dependencies, func, global);
  48545. },
  48546. //a quick way to create a class that doesn't have any dependencies. Returns the class, but first registers it in the GreenSock namespace so that other classes can grab it (other classes might be dependent on the class).
  48547. _class = gs._class = function(ns, func, global) {
  48548. func = func || function() {};
  48549. _gsDefine(ns, [], function(){ return func; }, global);
  48550. return func;
  48551. };
  48552. _gsDefine.globals = _globals;
  48553. /*
  48554. * ----------------------------------------------------------------
  48555. * Ease
  48556. * ----------------------------------------------------------------
  48557. */
  48558. var _baseParams = [0, 0, 1, 1],
  48559. Ease = _class("easing.Ease", function(func, extraParams, type, power) {
  48560. this._func = func;
  48561. this._type = type || 0;
  48562. this._power = power || 0;
  48563. this._params = extraParams ? _baseParams.concat(extraParams) : _baseParams;
  48564. }, true),
  48565. _easeMap = Ease.map = {},
  48566. _easeReg = Ease.register = function(ease, names, types, create) {
  48567. var na = names.split(","),
  48568. i = na.length,
  48569. ta = (types || "easeIn,easeOut,easeInOut").split(","),
  48570. e, name, j, type;
  48571. while (--i > -1) {
  48572. name = na[i];
  48573. e = create ? _class("easing."+name, null, true) : gs.easing[name] || {};
  48574. j = ta.length;
  48575. while (--j > -1) {
  48576. type = ta[j];
  48577. _easeMap[name + "." + type] = _easeMap[type + name] = e[type] = ease.getRatio ? ease : ease[type] || new ease();
  48578. }
  48579. }
  48580. };
  48581. p = Ease.prototype;
  48582. p._calcEnd = false;
  48583. p.getRatio = function(p) {
  48584. if (this._func) {
  48585. this._params[0] = p;
  48586. return this._func.apply(null, this._params);
  48587. }
  48588. var t = this._type,
  48589. pw = this._power,
  48590. r = (t === 1) ? 1 - p : (t === 2) ? p : (p < 0.5) ? p * 2 : (1 - p) * 2;
  48591. if (pw === 1) {
  48592. r *= r;
  48593. } else if (pw === 2) {
  48594. r *= r * r;
  48595. } else if (pw === 3) {
  48596. r *= r * r * r;
  48597. } else if (pw === 4) {
  48598. r *= r * r * r * r;
  48599. }
  48600. return (t === 1) ? 1 - r : (t === 2) ? r : (p < 0.5) ? r / 2 : 1 - (r / 2);
  48601. };
  48602. //create all the standard eases like Linear, Quad, Cubic, Quart, Quint, Strong, Power0, Power1, Power2, Power3, and Power4 (each with easeIn, easeOut, and easeInOut)
  48603. a = ["Linear","Quad","Cubic","Quart","Quint,Strong"];
  48604. i = a.length;
  48605. while (--i > -1) {
  48606. p = a[i]+",Power"+i;
  48607. _easeReg(new Ease(null,null,1,i), p, "easeOut", true);
  48608. _easeReg(new Ease(null,null,2,i), p, "easeIn" + ((i === 0) ? ",easeNone" : ""));
  48609. _easeReg(new Ease(null,null,3,i), p, "easeInOut");
  48610. }
  48611. _easeMap.linear = gs.easing.Linear.easeIn;
  48612. _easeMap.swing = gs.easing.Quad.easeInOut; //for jQuery folks
  48613. /*
  48614. * ----------------------------------------------------------------
  48615. * EventDispatcher
  48616. * ----------------------------------------------------------------
  48617. */
  48618. var EventDispatcher = _class("events.EventDispatcher", function(target) {
  48619. this._listeners = {};
  48620. this._eventTarget = target || this;
  48621. });
  48622. p = EventDispatcher.prototype;
  48623. p.addEventListener = function(type, callback, scope, useParam, priority) {
  48624. priority = priority || 0;
  48625. var list = this._listeners[type],
  48626. index = 0,
  48627. listener, i;
  48628. if (this === _ticker && !_tickerActive) {
  48629. _ticker.wake();
  48630. }
  48631. if (list == null) {
  48632. this._listeners[type] = list = [];
  48633. }
  48634. i = list.length;
  48635. while (--i > -1) {
  48636. listener = list[i];
  48637. if (listener.c === callback && listener.s === scope) {
  48638. list.splice(i, 1);
  48639. } else if (index === 0 && listener.pr < priority) {
  48640. index = i + 1;
  48641. }
  48642. }
  48643. list.splice(index, 0, {c:callback, s:scope, up:useParam, pr:priority});
  48644. };
  48645. p.removeEventListener = function(type, callback) {
  48646. var list = this._listeners[type], i;
  48647. if (list) {
  48648. i = list.length;
  48649. while (--i > -1) {
  48650. if (list[i].c === callback) {
  48651. list.splice(i, 1);
  48652. return;
  48653. }
  48654. }
  48655. }
  48656. };
  48657. p.dispatchEvent = function(type) {
  48658. var list = this._listeners[type],
  48659. i, t, listener;
  48660. if (list) {
  48661. i = list.length;
  48662. if (i > 1) {
  48663. list = list.slice(0); //in case addEventListener() is called from within a listener/callback (otherwise the index could change, resulting in a skip)
  48664. }
  48665. t = this._eventTarget;
  48666. while (--i > -1) {
  48667. listener = list[i];
  48668. if (listener) {
  48669. if (listener.up) {
  48670. listener.c.call(listener.s || t, {type:type, target:t});
  48671. } else {
  48672. listener.c.call(listener.s || t);
  48673. }
  48674. }
  48675. }
  48676. }
  48677. };
  48678. /*
  48679. * ----------------------------------------------------------------
  48680. * Ticker
  48681. * ----------------------------------------------------------------
  48682. */
  48683. var _reqAnimFrame = window.requestAnimationFrame,
  48684. _cancelAnimFrame = window.cancelAnimationFrame,
  48685. _getTime = Date.now || function() {return new Date().getTime();},
  48686. _lastUpdate = _getTime();
  48687. //now try to determine the requestAnimationFrame and cancelAnimationFrame functions and if none are found, we'll use a setTimeout()/clearTimeout() polyfill.
  48688. a = ["ms","moz","webkit","o"];
  48689. i = a.length;
  48690. while (--i > -1 && !_reqAnimFrame) {
  48691. _reqAnimFrame = window[a[i] + "RequestAnimationFrame"];
  48692. _cancelAnimFrame = window[a[i] + "CancelAnimationFrame"] || window[a[i] + "CancelRequestAnimationFrame"];
  48693. }
  48694. _class("Ticker", function(fps, useRAF) {
  48695. var _self = this,
  48696. _startTime = _getTime(),
  48697. _useRAF = (useRAF !== false && _reqAnimFrame) ? "auto" : false,
  48698. _lagThreshold = 500,
  48699. _adjustedLag = 33,
  48700. _tickWord = "tick", //helps reduce gc burden
  48701. _fps, _req, _id, _gap, _nextTime,
  48702. _tick = function(manual) {
  48703. var elapsed = _getTime() - _lastUpdate,
  48704. overlap, dispatch;
  48705. if (elapsed > _lagThreshold) {
  48706. _startTime += elapsed - _adjustedLag;
  48707. }
  48708. _lastUpdate += elapsed;
  48709. _self.time = (_lastUpdate - _startTime) / 1000;
  48710. overlap = _self.time - _nextTime;
  48711. if (!_fps || overlap > 0 || manual === true) {
  48712. _self.frame++;
  48713. _nextTime += overlap + (overlap >= _gap ? 0.004 : _gap - overlap);
  48714. dispatch = true;
  48715. }
  48716. if (manual !== true) { //make sure the request is made before we dispatch the "tick" event so that timing is maintained. Otherwise, if processing the "tick" requires a bunch of time (like 15ms) and we're using a setTimeout() that's based on 16.7ms, it'd technically take 31.7ms between frames otherwise.
  48717. _id = _req(_tick);
  48718. }
  48719. if (dispatch) {
  48720. _self.dispatchEvent(_tickWord);
  48721. }
  48722. };
  48723. EventDispatcher.call(_self);
  48724. _self.time = _self.frame = 0;
  48725. _self.tick = function() {
  48726. _tick(true);
  48727. };
  48728. _self.lagSmoothing = function(threshold, adjustedLag) {
  48729. _lagThreshold = threshold || (1 / _tinyNum); //zero should be interpreted as basically unlimited
  48730. _adjustedLag = Math.min(adjustedLag, _lagThreshold, 0);
  48731. };
  48732. _self.sleep = function() {
  48733. if (_id == null) {
  48734. return;
  48735. }
  48736. if (!_useRAF || !_cancelAnimFrame) {
  48737. clearTimeout(_id);
  48738. } else {
  48739. _cancelAnimFrame(_id);
  48740. }
  48741. _req = _emptyFunc;
  48742. _id = null;
  48743. if (_self === _ticker) {
  48744. _tickerActive = false;
  48745. }
  48746. };
  48747. _self.wake = function(seamless) {
  48748. if (_id !== null) {
  48749. _self.sleep();
  48750. } else if (seamless) {
  48751. _startTime += -_lastUpdate + (_lastUpdate = _getTime());
  48752. } else if (_self.frame > 10) { //don't trigger lagSmoothing if we're just waking up, and make sure that at least 10 frames have elapsed because of the iOS bug that we work around below with the 1.5-second setTimout().
  48753. _lastUpdate = _getTime() - _lagThreshold + 5;
  48754. }
  48755. _req = (_fps === 0) ? _emptyFunc : (!_useRAF || !_reqAnimFrame) ? function(f) { return setTimeout(f, ((_nextTime - _self.time) * 1000 + 1) | 0); } : _reqAnimFrame;
  48756. if (_self === _ticker) {
  48757. _tickerActive = true;
  48758. }
  48759. _tick(2);
  48760. };
  48761. _self.fps = function(value) {
  48762. if (!arguments.length) {
  48763. return _fps;
  48764. }
  48765. _fps = value;
  48766. _gap = 1 / (_fps || 60);
  48767. _nextTime = this.time + _gap;
  48768. _self.wake();
  48769. };
  48770. _self.useRAF = function(value) {
  48771. if (!arguments.length) {
  48772. return _useRAF;
  48773. }
  48774. _self.sleep();
  48775. _useRAF = value;
  48776. _self.fps(_fps);
  48777. };
  48778. _self.fps(fps);
  48779. //a bug in iOS 6 Safari occasionally prevents the requestAnimationFrame from working initially, so we use a 1.5-second timeout that automatically falls back to setTimeout() if it senses this condition.
  48780. setTimeout(function() {
  48781. if (_useRAF === "auto" && _self.frame < 5 && _doc.visibilityState !== "hidden") {
  48782. _self.useRAF(false);
  48783. }
  48784. }, 1500);
  48785. });
  48786. p = gs.Ticker.prototype = new gs.events.EventDispatcher();
  48787. p.constructor = gs.Ticker;
  48788. /*
  48789. * ----------------------------------------------------------------
  48790. * Animation
  48791. * ----------------------------------------------------------------
  48792. */
  48793. var Animation = _class("core.Animation", function(duration, vars) {
  48794. this.vars = vars = vars || {};
  48795. this._duration = this._totalDuration = duration || 0;
  48796. this._delay = Number(vars.delay) || 0;
  48797. this._timeScale = 1;
  48798. this._active = (vars.immediateRender === true);
  48799. this.data = vars.data;
  48800. this._reversed = (vars.reversed === true);
  48801. if (!_rootTimeline) {
  48802. return;
  48803. }
  48804. if (!_tickerActive) { //some browsers (like iOS 6 Safari) shut down JavaScript execution when the tab is disabled and they [occasionally] neglect to start up requestAnimationFrame again when returning - this code ensures that the engine starts up again properly.
  48805. _ticker.wake();
  48806. }
  48807. var tl = this.vars.useFrames ? _rootFramesTimeline : _rootTimeline;
  48808. tl.add(this, tl._time);
  48809. if (this.vars.paused) {
  48810. this.paused(true);
  48811. }
  48812. });
  48813. _ticker = Animation.ticker = new gs.Ticker();
  48814. p = Animation.prototype;
  48815. p._dirty = p._gc = p._initted = p._paused = false;
  48816. p._totalTime = p._time = 0;
  48817. p._rawPrevTime = -1;
  48818. p._next = p._last = p._onUpdate = p._timeline = p.timeline = null;
  48819. p._paused = false;
  48820. //some browsers (like iOS) occasionally drop the requestAnimationFrame event when the user switches to a different tab and then comes back again, so we use a 2-second setTimeout() to sense if/when that condition occurs and then wake() the ticker.
  48821. var _checkTimeout = function() {
  48822. if (_tickerActive && _getTime() - _lastUpdate > 2000 && _doc.visibilityState !== "hidden") {
  48823. _ticker.wake();
  48824. }
  48825. var t = setTimeout(_checkTimeout, 2000);
  48826. if (t.unref) {
  48827. // allows a node process to exit even if the timeout’s callback hasn't been invoked. Without it, the node process could hang as this function is called every two seconds.
  48828. t.unref();
  48829. }
  48830. };
  48831. _checkTimeout();
  48832. p.play = function(from, suppressEvents) {
  48833. if (from != null) {
  48834. this.seek(from, suppressEvents);
  48835. }
  48836. return this.reversed(false).paused(false);
  48837. };
  48838. p.pause = function(atTime, suppressEvents) {
  48839. if (atTime != null) {
  48840. this.seek(atTime, suppressEvents);
  48841. }
  48842. return this.paused(true);
  48843. };
  48844. p.resume = function(from, suppressEvents) {
  48845. if (from != null) {
  48846. this.seek(from, suppressEvents);
  48847. }
  48848. return this.paused(false);
  48849. };
  48850. p.seek = function(time, suppressEvents) {
  48851. return this.totalTime(Number(time), suppressEvents !== false);
  48852. };
  48853. p.restart = function(includeDelay, suppressEvents) {
  48854. return this.reversed(false).paused(false).totalTime(includeDelay ? -this._delay : 0, (suppressEvents !== false), true);
  48855. };
  48856. p.reverse = function(from, suppressEvents) {
  48857. if (from != null) {
  48858. this.seek((from || this.totalDuration()), suppressEvents);
  48859. }
  48860. return this.reversed(true).paused(false);
  48861. };
  48862. p.render = function(time, suppressEvents, force) {
  48863. //stub - we override this method in subclasses.
  48864. };
  48865. p.invalidate = function() {
  48866. this._time = this._totalTime = 0;
  48867. this._initted = this._gc = false;
  48868. this._rawPrevTime = -1;
  48869. if (this._gc || !this.timeline) {
  48870. this._enabled(true);
  48871. }
  48872. return this;
  48873. };
  48874. p.isActive = function() {
  48875. var tl = this._timeline, //the 2 root timelines won't have a _timeline; they're always active.
  48876. startTime = this._startTime,
  48877. rawTime;
  48878. return (!tl || (!this._gc && !this._paused && tl.isActive() && (rawTime = tl.rawTime(true)) >= startTime && rawTime < startTime + this.totalDuration() / this._timeScale - 0.0000001));
  48879. };
  48880. p._enabled = function (enabled, ignoreTimeline) {
  48881. if (!_tickerActive) {
  48882. _ticker.wake();
  48883. }
  48884. this._gc = !enabled;
  48885. this._active = this.isActive();
  48886. if (ignoreTimeline !== true) {
  48887. if (enabled && !this.timeline) {
  48888. this._timeline.add(this, this._startTime - this._delay);
  48889. } else if (!enabled && this.timeline) {
  48890. this._timeline._remove(this, true);
  48891. }
  48892. }
  48893. return false;
  48894. };
  48895. p._kill = function(vars, target) {
  48896. return this._enabled(false, false);
  48897. };
  48898. p.kill = function(vars, target) {
  48899. this._kill(vars, target);
  48900. return this;
  48901. };
  48902. p._uncache = function(includeSelf) {
  48903. var tween = includeSelf ? this : this.timeline;
  48904. while (tween) {
  48905. tween._dirty = true;
  48906. tween = tween.timeline;
  48907. }
  48908. return this;
  48909. };
  48910. p._swapSelfInParams = function(params) {
  48911. var i = params.length,
  48912. copy = params.concat();
  48913. while (--i > -1) {
  48914. if (params[i] === "{self}") {
  48915. copy[i] = this;
  48916. }
  48917. }
  48918. return copy;
  48919. };
  48920. p._callback = function(type) {
  48921. var v = this.vars,
  48922. callback = v[type],
  48923. params = v[type + "Params"],
  48924. scope = v[type + "Scope"] || v.callbackScope || this,
  48925. l = params ? params.length : 0;
  48926. switch (l) { //speed optimization; call() is faster than apply() so use it when there are only a few parameters (which is by far most common). Previously we simply did var v = this.vars; v[type].apply(v[type + "Scope"] || v.callbackScope || this, v[type + "Params"] || _blankArray);
  48927. case 0: callback.call(scope); break;
  48928. case 1: callback.call(scope, params[0]); break;
  48929. case 2: callback.call(scope, params[0], params[1]); break;
  48930. default: callback.apply(scope, params);
  48931. }
  48932. };
  48933. //----Animation getters/setters --------------------------------------------------------
  48934. p.eventCallback = function(type, callback, params, scope) {
  48935. if ((type || "").substr(0,2) === "on") {
  48936. var v = this.vars;
  48937. if (arguments.length === 1) {
  48938. return v[type];
  48939. }
  48940. if (callback == null) {
  48941. delete v[type];
  48942. } else {
  48943. v[type] = callback;
  48944. v[type + "Params"] = (_isArray(params) && params.join("").indexOf("{self}") !== -1) ? this._swapSelfInParams(params) : params;
  48945. v[type + "Scope"] = scope;
  48946. }
  48947. if (type === "onUpdate") {
  48948. this._onUpdate = callback;
  48949. }
  48950. }
  48951. return this;
  48952. };
  48953. p.delay = function(value) {
  48954. if (!arguments.length) {
  48955. return this._delay;
  48956. }
  48957. if (this._timeline.smoothChildTiming) {
  48958. this.startTime( this._startTime + value - this._delay );
  48959. }
  48960. this._delay = value;
  48961. return this;
  48962. };
  48963. p.duration = function(value) {
  48964. if (!arguments.length) {
  48965. this._dirty = false;
  48966. return this._duration;
  48967. }
  48968. this._duration = this._totalDuration = value;
  48969. this._uncache(true); //true in case it's a TweenMax or TimelineMax that has a repeat - we'll need to refresh the totalDuration.
  48970. if (this._timeline.smoothChildTiming) if (this._time > 0) if (this._time < this._duration) if (value !== 0) {
  48971. this.totalTime(this._totalTime * (value / this._duration), true);
  48972. }
  48973. return this;
  48974. };
  48975. p.totalDuration = function(value) {
  48976. this._dirty = false;
  48977. return (!arguments.length) ? this._totalDuration : this.duration(value);
  48978. };
  48979. p.time = function(value, suppressEvents) {
  48980. if (!arguments.length) {
  48981. return this._time;
  48982. }
  48983. if (this._dirty) {
  48984. this.totalDuration();
  48985. }
  48986. return this.totalTime((value > this._duration) ? this._duration : value, suppressEvents);
  48987. };
  48988. p.totalTime = function(time, suppressEvents, uncapped) {
  48989. if (!_tickerActive) {
  48990. _ticker.wake();
  48991. }
  48992. if (!arguments.length) {
  48993. return this._totalTime;
  48994. }
  48995. if (this._timeline) {
  48996. if (time < 0 && !uncapped) {
  48997. time += this.totalDuration();
  48998. }
  48999. if (this._timeline.smoothChildTiming) {
  49000. if (this._dirty) {
  49001. this.totalDuration();
  49002. }
  49003. var totalDuration = this._totalDuration,
  49004. tl = this._timeline;
  49005. if (time > totalDuration && !uncapped) {
  49006. time = totalDuration;
  49007. }
  49008. this._startTime = (this._paused ? this._pauseTime : tl._time) - ((!this._reversed ? time : totalDuration - time) / this._timeScale);
  49009. if (!tl._dirty) { //for performance improvement. If the parent's cache is already dirty, it already took care of marking the ancestors as dirty too, so skip the function call here.
  49010. this._uncache(false);
  49011. }
  49012. //in case any of the ancestor timelines had completed but should now be enabled, we should reset their totalTime() which will also ensure that they're lined up properly and enabled. Skip for animations that are on the root (wasteful). Example: a TimelineLite.exportRoot() is performed when there's a paused tween on the root, the export will not complete until that tween is unpaused, but imagine a child gets restarted later, after all [unpaused] tweens have completed. The startTime of that child would get pushed out, but one of the ancestors may have completed.
  49013. if (tl._timeline) {
  49014. while (tl._timeline) {
  49015. if (tl._timeline._time !== (tl._startTime + tl._totalTime) / tl._timeScale) {
  49016. tl.totalTime(tl._totalTime, true);
  49017. }
  49018. tl = tl._timeline;
  49019. }
  49020. }
  49021. }
  49022. if (this._gc) {
  49023. this._enabled(true, false);
  49024. }
  49025. if (this._totalTime !== time || this._duration === 0) {
  49026. if (_lazyTweens.length) {
  49027. _lazyRender();
  49028. }
  49029. this.render(time, suppressEvents, false);
  49030. if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when someone calls seek() or time() or progress(), they expect an immediate render.
  49031. _lazyRender();
  49032. }
  49033. }
  49034. }
  49035. return this;
  49036. };
  49037. p.progress = p.totalProgress = function(value, suppressEvents) {
  49038. var duration = this.duration();
  49039. return (!arguments.length) ? (duration ? this._time / duration : this.ratio) : this.totalTime(duration * value, suppressEvents);
  49040. };
  49041. p.startTime = function(value) {
  49042. if (!arguments.length) {
  49043. return this._startTime;
  49044. }
  49045. if (value !== this._startTime) {
  49046. this._startTime = value;
  49047. if (this.timeline) if (this.timeline._sortChildren) {
  49048. this.timeline.add(this, value - this._delay); //ensures that any necessary re-sequencing of Animations in the timeline occurs to make sure the rendering order is correct.
  49049. }
  49050. }
  49051. return this;
  49052. };
  49053. p.endTime = function(includeRepeats) {
  49054. return this._startTime + ((includeRepeats != false) ? this.totalDuration() : this.duration()) / this._timeScale;
  49055. };
  49056. p.timeScale = function(value) {
  49057. if (!arguments.length) {
  49058. return this._timeScale;
  49059. }
  49060. value = value || _tinyNum; //can't allow zero because it'll throw the math off
  49061. if (this._timeline && this._timeline.smoothChildTiming) {
  49062. var pauseTime = this._pauseTime,
  49063. t = (pauseTime || pauseTime === 0) ? pauseTime : this._timeline.totalTime();
  49064. this._startTime = t - ((t - this._startTime) * this._timeScale / value);
  49065. }
  49066. this._timeScale = value;
  49067. return this._uncache(false);
  49068. };
  49069. p.reversed = function(value) {
  49070. if (!arguments.length) {
  49071. return this._reversed;
  49072. }
  49073. if (value != this._reversed) {
  49074. this._reversed = value;
  49075. this.totalTime(((this._timeline && !this._timeline.smoothChildTiming) ? this.totalDuration() - this._totalTime : this._totalTime), true);
  49076. }
  49077. return this;
  49078. };
  49079. p.paused = function(value) {
  49080. if (!arguments.length) {
  49081. return this._paused;
  49082. }
  49083. var tl = this._timeline,
  49084. raw, elapsed;
  49085. if (value != this._paused) if (tl) {
  49086. if (!_tickerActive && !value) {
  49087. _ticker.wake();
  49088. }
  49089. raw = tl.rawTime();
  49090. elapsed = raw - this._pauseTime;
  49091. if (!value && tl.smoothChildTiming) {
  49092. this._startTime += elapsed;
  49093. this._uncache(false);
  49094. }
  49095. this._pauseTime = value ? raw : null;
  49096. this._paused = value;
  49097. this._active = this.isActive();
  49098. if (!value && elapsed !== 0 && this._initted && this.duration()) {
  49099. raw = tl.smoothChildTiming ? this._totalTime : (raw - this._startTime) / this._timeScale;
  49100. this.render(raw, (raw === this._totalTime), true); //in case the target's properties changed via some other tween or manual update by the user, we should force a render.
  49101. }
  49102. }
  49103. if (this._gc && !value) {
  49104. this._enabled(true, false);
  49105. }
  49106. return this;
  49107. };
  49108. /*
  49109. * ----------------------------------------------------------------
  49110. * SimpleTimeline
  49111. * ----------------------------------------------------------------
  49112. */
  49113. var SimpleTimeline = _class("core.SimpleTimeline", function(vars) {
  49114. Animation.call(this, 0, vars);
  49115. this.autoRemoveChildren = this.smoothChildTiming = true;
  49116. });
  49117. p = SimpleTimeline.prototype = new Animation();
  49118. p.constructor = SimpleTimeline;
  49119. p.kill()._gc = false;
  49120. p._first = p._last = p._recent = null;
  49121. p._sortChildren = false;
  49122. p.add = p.insert = function(child, position, align, stagger) {
  49123. var prevTween, st;
  49124. child._startTime = Number(position || 0) + child._delay;
  49125. if (child._paused) if (this !== child._timeline) { //we only adjust the _pauseTime if it wasn't in this timeline already. Remember, sometimes a tween will be inserted again into the same timeline when its startTime is changed so that the tweens in the TimelineLite/Max are re-ordered properly in the linked list (so everything renders in the proper order).
  49126. child._pauseTime = child._startTime + ((this.rawTime() - child._startTime) / child._timeScale);
  49127. }
  49128. if (child.timeline) {
  49129. child.timeline._remove(child, true); //removes from existing timeline so that it can be properly added to this one.
  49130. }
  49131. child.timeline = child._timeline = this;
  49132. if (child._gc) {
  49133. child._enabled(true, true);
  49134. }
  49135. prevTween = this._last;
  49136. if (this._sortChildren) {
  49137. st = child._startTime;
  49138. while (prevTween && prevTween._startTime > st) {
  49139. prevTween = prevTween._prev;
  49140. }
  49141. }
  49142. if (prevTween) {
  49143. child._next = prevTween._next;
  49144. prevTween._next = child;
  49145. } else {
  49146. child._next = this._first;
  49147. this._first = child;
  49148. }
  49149. if (child._next) {
  49150. child._next._prev = child;
  49151. } else {
  49152. this._last = child;
  49153. }
  49154. child._prev = prevTween;
  49155. this._recent = child;
  49156. if (this._timeline) {
  49157. this._uncache(true);
  49158. }
  49159. return this;
  49160. };
  49161. p._remove = function(tween, skipDisable) {
  49162. if (tween.timeline === this) {
  49163. if (!skipDisable) {
  49164. tween._enabled(false, true);
  49165. }
  49166. if (tween._prev) {
  49167. tween._prev._next = tween._next;
  49168. } else if (this._first === tween) {
  49169. this._first = tween._next;
  49170. }
  49171. if (tween._next) {
  49172. tween._next._prev = tween._prev;
  49173. } else if (this._last === tween) {
  49174. this._last = tween._prev;
  49175. }
  49176. tween._next = tween._prev = tween.timeline = null;
  49177. if (tween === this._recent) {
  49178. this._recent = this._last;
  49179. }
  49180. if (this._timeline) {
  49181. this._uncache(true);
  49182. }
  49183. }
  49184. return this;
  49185. };
  49186. p.render = function(time, suppressEvents, force) {
  49187. var tween = this._first,
  49188. next;
  49189. this._totalTime = this._time = this._rawPrevTime = time;
  49190. while (tween) {
  49191. next = tween._next; //record it here because the value could change after rendering...
  49192. if (tween._active || (time >= tween._startTime && !tween._paused && !tween._gc)) {
  49193. if (!tween._reversed) {
  49194. tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
  49195. } else {
  49196. tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
  49197. }
  49198. }
  49199. tween = next;
  49200. }
  49201. };
  49202. p.rawTime = function() {
  49203. if (!_tickerActive) {
  49204. _ticker.wake();
  49205. }
  49206. return this._totalTime;
  49207. };
  49208. /*
  49209. * ----------------------------------------------------------------
  49210. * TweenLite
  49211. * ----------------------------------------------------------------
  49212. */
  49213. var TweenLite = _class("TweenLite", function(target, duration, vars) {
  49214. Animation.call(this, duration, vars);
  49215. this.render = TweenLite.prototype.render; //speed optimization (avoid prototype lookup on this "hot" method)
  49216. if (target == null) {
  49217. throw "Cannot tween a null target.";
  49218. }
  49219. this.target = target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target;
  49220. var isSelector = (target.jquery || (target.length && target !== window && target[0] && (target[0] === window || (target[0].nodeType && target[0].style && !target.nodeType)))),
  49221. overwrite = this.vars.overwrite,
  49222. i, targ, targets;
  49223. this._overwrite = overwrite = (overwrite == null) ? _overwriteLookup[TweenLite.defaultOverwrite] : (typeof(overwrite) === "number") ? overwrite >> 0 : _overwriteLookup[overwrite];
  49224. if ((isSelector || target instanceof Array || (target.push && _isArray(target))) && typeof(target[0]) !== "number") {
  49225. this._targets = targets = _slice(target); //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
  49226. this._propLookup = [];
  49227. this._siblings = [];
  49228. for (i = 0; i < targets.length; i++) {
  49229. targ = targets[i];
  49230. if (!targ) {
  49231. targets.splice(i--, 1);
  49232. continue;
  49233. } else if (typeof(targ) === "string") {
  49234. targ = targets[i--] = TweenLite.selector(targ); //in case it's an array of strings
  49235. if (typeof(targ) === "string") {
  49236. targets.splice(i+1, 1); //to avoid an endless loop (can't imagine why the selector would return a string, but just in case)
  49237. }
  49238. continue;
  49239. } else if (targ.length && targ !== window && targ[0] && (targ[0] === window || (targ[0].nodeType && targ[0].style && !targ.nodeType))) { //in case the user is passing in an array of selector objects (like jQuery objects), we need to check one more level and pull things out if necessary. Also note that <select> elements pass all the criteria regarding length and the first child having style, so we must also check to ensure the target isn't an HTML node itself.
  49240. targets.splice(i--, 1);
  49241. this._targets = targets = targets.concat(_slice(targ));
  49242. continue;
  49243. }
  49244. this._siblings[i] = _register(targ, this, false);
  49245. if (overwrite === 1) if (this._siblings[i].length > 1) {
  49246. _applyOverwrite(targ, this, null, 1, this._siblings[i]);
  49247. }
  49248. }
  49249. } else {
  49250. this._propLookup = {};
  49251. this._siblings = _register(target, this, false);
  49252. if (overwrite === 1) if (this._siblings.length > 1) {
  49253. _applyOverwrite(target, this, null, 1, this._siblings);
  49254. }
  49255. }
  49256. if (this.vars.immediateRender || (duration === 0 && this._delay === 0 && this.vars.immediateRender !== false)) {
  49257. this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
  49258. this.render(Math.min(0, -this._delay)); //in case delay is negative
  49259. }
  49260. }, true),
  49261. _isSelector = function(v) {
  49262. return (v && v.length && v !== window && v[0] && (v[0] === window || (v[0].nodeType && v[0].style && !v.nodeType))); //we cannot check "nodeType" if the target is window from within an iframe, otherwise it will trigger a security error in some browsers like Firefox.
  49263. },
  49264. _autoCSS = function(vars, target) {
  49265. var css = {},
  49266. p;
  49267. for (p in vars) {
  49268. if (!_reservedProps[p] && (!(p in target) || p === "transform" || p === "x" || p === "y" || p === "width" || p === "height" || p === "className" || p === "border") && (!_plugins[p] || (_plugins[p] && _plugins[p]._autoCSS))) { //note: <img> elements contain read-only "x" and "y" properties. We should also prioritize editing css width/height rather than the element's properties.
  49269. css[p] = vars[p];
  49270. delete vars[p];
  49271. }
  49272. }
  49273. vars.css = css;
  49274. };
  49275. p = TweenLite.prototype = new Animation();
  49276. p.constructor = TweenLite;
  49277. p.kill()._gc = false;
  49278. //----TweenLite defaults, overwrite management, and root updates ----------------------------------------------------
  49279. p.ratio = 0;
  49280. p._firstPT = p._targets = p._overwrittenProps = p._startAt = null;
  49281. p._notifyPluginsOfEnabled = p._lazy = false;
  49282. TweenLite.version = "1.20.2";
  49283. TweenLite.defaultEase = p._ease = new Ease(null, null, 1, 1);
  49284. TweenLite.defaultOverwrite = "auto";
  49285. TweenLite.ticker = _ticker;
  49286. TweenLite.autoSleep = 120;
  49287. TweenLite.lagSmoothing = function(threshold, adjustedLag) {
  49288. _ticker.lagSmoothing(threshold, adjustedLag);
  49289. };
  49290. TweenLite.selector = window.$ || window.jQuery || function(e) {
  49291. var selector = window.$ || window.jQuery;
  49292. if (selector) {
  49293. TweenLite.selector = selector;
  49294. return selector(e);
  49295. }
  49296. return (typeof(_doc) === "undefined") ? e : (_doc.querySelectorAll ? _doc.querySelectorAll(e) : _doc.getElementById((e.charAt(0) === "#") ? e.substr(1) : e));
  49297. };
  49298. var _lazyTweens = [],
  49299. _lazyLookup = {},
  49300. _numbersExp = /(?:(-|-=|\+=)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig,
  49301. _relExp = /[\+-]=-?[\.\d]/,
  49302. //_nonNumbersExp = /(?:([\-+](?!(\d|=)))|[^\d\-+=e]|(e(?![\-+][\d])))+/ig,
  49303. _setRatio = function(v) {
  49304. var pt = this._firstPT,
  49305. min = 0.000001,
  49306. val;
  49307. while (pt) {
  49308. val = !pt.blob ? pt.c * v + pt.s : (v === 1 && this.end) ? this.end : v ? this.join("") : this.start;
  49309. if (pt.m) {
  49310. val = pt.m(val, this._target || pt.t);
  49311. } else if (val < min) if (val > -min && !pt.blob) { //prevents issues with converting very small numbers to strings in the browser
  49312. val = 0;
  49313. }
  49314. if (!pt.f) {
  49315. pt.t[pt.p] = val;
  49316. } else if (pt.fp) {
  49317. pt.t[pt.p](pt.fp, val);
  49318. } else {
  49319. pt.t[pt.p](val);
  49320. }
  49321. pt = pt._next;
  49322. }
  49323. },
  49324. //compares two strings (start/end), finds the numbers that are different and spits back an array representing the whole value but with the changing values isolated as elements. For example, "rgb(0,0,0)" and "rgb(100,50,0)" would become ["rgb(", 0, ",", 50, ",0)"]. Notice it merges the parts that are identical (performance optimization). The array also has a linked list of PropTweens attached starting with _firstPT that contain the tweening data (t, p, s, c, f, etc.). It also stores the starting value as a "start" property so that we can revert to it if/when necessary, like when a tween rewinds fully. If the quantity of numbers differs between the start and end, it will always prioritize the end value(s). The pt parameter is optional - it's for a PropTween that will be appended to the end of the linked list and is typically for actually setting the value after all of the elements have been updated (with array.join("")).
  49325. _blobDif = function(start, end, filter, pt) {
  49326. var a = [],
  49327. charIndex = 0,
  49328. s = "",
  49329. color = 0,
  49330. startNums, endNums, num, i, l, nonNumbers, currentNum;
  49331. a.start = start;
  49332. a.end = end;
  49333. start = a[0] = start + ""; //ensure values are strings
  49334. end = a[1] = end + "";
  49335. if (filter) {
  49336. filter(a); //pass an array with the starting and ending values and let the filter do whatever it needs to the values.
  49337. start = a[0];
  49338. end = a[1];
  49339. }
  49340. a.length = 0;
  49341. startNums = start.match(_numbersExp) || [];
  49342. endNums = end.match(_numbersExp) || [];
  49343. if (pt) {
  49344. pt._next = null;
  49345. pt.blob = 1;
  49346. a._firstPT = a._applyPT = pt; //apply last in the linked list (which means inserting it first)
  49347. }
  49348. l = endNums.length;
  49349. for (i = 0; i < l; i++) {
  49350. currentNum = endNums[i];
  49351. nonNumbers = end.substr(charIndex, end.indexOf(currentNum, charIndex)-charIndex);
  49352. s += (nonNumbers || !i) ? nonNumbers : ","; //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case.
  49353. charIndex += nonNumbers.length;
  49354. if (color) { //sense rgba() values and round them.
  49355. color = (color + 1) % 5;
  49356. } else if (nonNumbers.substr(-5) === "rgba(") {
  49357. color = 1;
  49358. }
  49359. if (currentNum === startNums[i] || startNums.length <= i) {
  49360. s += currentNum;
  49361. } else {
  49362. if (s) {
  49363. a.push(s);
  49364. s = "";
  49365. }
  49366. num = parseFloat(startNums[i]);
  49367. a.push(num);
  49368. a._firstPT = {_next: a._firstPT, t:a, p: a.length-1, s:num, c:((currentNum.charAt(1) === "=") ? parseInt(currentNum.charAt(0) + "1", 10) * parseFloat(currentNum.substr(2)) : (parseFloat(currentNum) - num)) || 0, f:0, m:(color && color < 4) ? Math.round : 0};
  49369. //note: we don't set _prev because we'll never need to remove individual PropTweens from this list.
  49370. }
  49371. charIndex += currentNum.length;
  49372. }
  49373. s += end.substr(charIndex);
  49374. if (s) {
  49375. a.push(s);
  49376. }
  49377. a.setRatio = _setRatio;
  49378. if (_relExp.test(end)) { //if the end string contains relative values, delete it so that on the final render (in _setRatio()), we don't actually set it to the string with += or -= characters (forces it to use the calculated value).
  49379. a.end = 0;
  49380. }
  49381. return a;
  49382. },
  49383. //note: "funcParam" is only necessary for function-based getters/setters that require an extra parameter like getAttribute("width") and setAttribute("width", value). In this example, funcParam would be "width". Used by AttrPlugin for example.
  49384. _addPropTween = function(target, prop, start, end, overwriteProp, mod, funcParam, stringFilter, index) {
  49385. if (typeof(end) === "function") {
  49386. end = end(index || 0, target);
  49387. }
  49388. var type = typeof(target[prop]),
  49389. getterName = (type !== "function") ? "" : ((prop.indexOf("set") || typeof(target["get" + prop.substr(3)]) !== "function") ? prop : "get" + prop.substr(3)),
  49390. s = (start !== "get") ? start : !getterName ? target[prop] : funcParam ? target[getterName](funcParam) : target[getterName](),
  49391. isRelative = (typeof(end) === "string" && end.charAt(1) === "="),
  49392. pt = {t:target, p:prop, s:s, f:(type === "function"), pg:0, n:overwriteProp || prop, m:(!mod ? 0 : (typeof(mod) === "function") ? mod : Math.round), pr:0, c:isRelative ? parseInt(end.charAt(0) + "1", 10) * parseFloat(end.substr(2)) : (parseFloat(end) - s) || 0},
  49393. blob;
  49394. if (typeof(s) !== "number" || (typeof(end) !== "number" && !isRelative)) {
  49395. if (funcParam || isNaN(s) || (!isRelative && isNaN(end)) || typeof(s) === "boolean" || typeof(end) === "boolean") {
  49396. //a blob (string that has multiple numbers in it)
  49397. pt.fp = funcParam;
  49398. blob = _blobDif(s, (isRelative ? parseFloat(pt.s) + pt.c : end), stringFilter || TweenLite.defaultStringFilter, pt);
  49399. pt = {t: blob, p: "setRatio", s: 0, c: 1, f: 2, pg: 0, n: overwriteProp || prop, pr: 0, m: 0}; //"2" indicates it's a Blob property tween. Needed for RoundPropsPlugin for example.
  49400. } else {
  49401. pt.s = parseFloat(s);
  49402. if (!isRelative) {
  49403. pt.c = (parseFloat(end) - pt.s) || 0;
  49404. }
  49405. }
  49406. }
  49407. if (pt.c) { //only add it to the linked list if there's a change.
  49408. if ((pt._next = this._firstPT)) {
  49409. pt._next._prev = pt;
  49410. }
  49411. this._firstPT = pt;
  49412. return pt;
  49413. }
  49414. },
  49415. _internals = TweenLite._internals = {isArray:_isArray, isSelector:_isSelector, lazyTweens:_lazyTweens, blobDif:_blobDif}, //gives us a way to expose certain private values to other GreenSock classes without contaminating tha main TweenLite object.
  49416. _plugins = TweenLite._plugins = {},
  49417. _tweenLookup = _internals.tweenLookup = {},
  49418. _tweenLookupNum = 0,
  49419. _reservedProps = _internals.reservedProps = {ease:1, delay:1, overwrite:1, onComplete:1, onCompleteParams:1, onCompleteScope:1, useFrames:1, runBackwards:1, startAt:1, onUpdate:1, onUpdateParams:1, onUpdateScope:1, onStart:1, onStartParams:1, onStartScope:1, onReverseComplete:1, onReverseCompleteParams:1, onReverseCompleteScope:1, onRepeat:1, onRepeatParams:1, onRepeatScope:1, easeParams:1, yoyo:1, immediateRender:1, repeat:1, repeatDelay:1, data:1, paused:1, reversed:1, autoCSS:1, lazy:1, onOverwrite:1, callbackScope:1, stringFilter:1, id:1, yoyoEase:1},
  49420. _overwriteLookup = {none:0, all:1, auto:2, concurrent:3, allOnStart:4, preexisting:5, "true":1, "false":0},
  49421. _rootFramesTimeline = Animation._rootFramesTimeline = new SimpleTimeline(),
  49422. _rootTimeline = Animation._rootTimeline = new SimpleTimeline(),
  49423. _nextGCFrame = 30,
  49424. _lazyRender = _internals.lazyRender = function() {
  49425. var i = _lazyTweens.length,
  49426. tween;
  49427. _lazyLookup = {};
  49428. while (--i > -1) {
  49429. tween = _lazyTweens[i];
  49430. if (tween && tween._lazy !== false) {
  49431. tween.render(tween._lazy[0], tween._lazy[1], true);
  49432. tween._lazy = false;
  49433. }
  49434. }
  49435. _lazyTweens.length = 0;
  49436. };
  49437. _rootTimeline._startTime = _ticker.time;
  49438. _rootFramesTimeline._startTime = _ticker.frame;
  49439. _rootTimeline._active = _rootFramesTimeline._active = true;
  49440. setTimeout(_lazyRender, 1); //on some mobile devices, there isn't a "tick" before code runs which means any lazy renders wouldn't run before the next official "tick".
  49441. Animation._updateRoot = TweenLite.render = function() {
  49442. var i, a, p;
  49443. if (_lazyTweens.length) { //if code is run outside of the requestAnimationFrame loop, there may be tweens queued AFTER the engine refreshed, so we need to ensure any pending renders occur before we refresh again.
  49444. _lazyRender();
  49445. }
  49446. _rootTimeline.render((_ticker.time - _rootTimeline._startTime) * _rootTimeline._timeScale, false, false);
  49447. _rootFramesTimeline.render((_ticker.frame - _rootFramesTimeline._startTime) * _rootFramesTimeline._timeScale, false, false);
  49448. if (_lazyTweens.length) {
  49449. _lazyRender();
  49450. }
  49451. if (_ticker.frame >= _nextGCFrame) { //dump garbage every 120 frames or whatever the user sets TweenLite.autoSleep to
  49452. _nextGCFrame = _ticker.frame + (parseInt(TweenLite.autoSleep, 10) || 120);
  49453. for (p in _tweenLookup) {
  49454. a = _tweenLookup[p].tweens;
  49455. i = a.length;
  49456. while (--i > -1) {
  49457. if (a[i]._gc) {
  49458. a.splice(i, 1);
  49459. }
  49460. }
  49461. if (a.length === 0) {
  49462. delete _tweenLookup[p];
  49463. }
  49464. }
  49465. //if there are no more tweens in the root timelines, or if they're all paused, make the _timer sleep to reduce load on the CPU slightly
  49466. p = _rootTimeline._first;
  49467. if (!p || p._paused) if (TweenLite.autoSleep && !_rootFramesTimeline._first && _ticker._listeners.tick.length === 1) {
  49468. while (p && p._paused) {
  49469. p = p._next;
  49470. }
  49471. if (!p) {
  49472. _ticker.sleep();
  49473. }
  49474. }
  49475. }
  49476. };
  49477. _ticker.addEventListener("tick", Animation._updateRoot);
  49478. var _register = function(target, tween, scrub) {
  49479. var id = target._gsTweenID, a, i;
  49480. if (!_tweenLookup[id || (target._gsTweenID = id = "t" + (_tweenLookupNum++))]) {
  49481. _tweenLookup[id] = {target:target, tweens:[]};
  49482. }
  49483. if (tween) {
  49484. a = _tweenLookup[id].tweens;
  49485. a[(i = a.length)] = tween;
  49486. if (scrub) {
  49487. while (--i > -1) {
  49488. if (a[i] === tween) {
  49489. a.splice(i, 1);
  49490. }
  49491. }
  49492. }
  49493. }
  49494. return _tweenLookup[id].tweens;
  49495. },
  49496. _onOverwrite = function(overwrittenTween, overwritingTween, target, killedProps) {
  49497. var func = overwrittenTween.vars.onOverwrite, r1, r2;
  49498. if (func) {
  49499. r1 = func(overwrittenTween, overwritingTween, target, killedProps);
  49500. }
  49501. func = TweenLite.onOverwrite;
  49502. if (func) {
  49503. r2 = func(overwrittenTween, overwritingTween, target, killedProps);
  49504. }
  49505. return (r1 !== false && r2 !== false);
  49506. },
  49507. _applyOverwrite = function(target, tween, props, mode, siblings) {
  49508. var i, changed, curTween, l;
  49509. if (mode === 1 || mode >= 4) {
  49510. l = siblings.length;
  49511. for (i = 0; i < l; i++) {
  49512. if ((curTween = siblings[i]) !== tween) {
  49513. if (!curTween._gc) {
  49514. if (curTween._kill(null, target, tween)) {
  49515. changed = true;
  49516. }
  49517. }
  49518. } else if (mode === 5) {
  49519. break;
  49520. }
  49521. }
  49522. return changed;
  49523. }
  49524. //NOTE: Add 0.0000000001 to overcome floating point errors that can cause the startTime to be VERY slightly off (when a tween's time() is set for example)
  49525. var startTime = tween._startTime + _tinyNum,
  49526. overlaps = [],
  49527. oCount = 0,
  49528. zeroDur = (tween._duration === 0),
  49529. globalStart;
  49530. i = siblings.length;
  49531. while (--i > -1) {
  49532. if ((curTween = siblings[i]) === tween || curTween._gc || curTween._paused) {
  49533. //ignore
  49534. } else if (curTween._timeline !== tween._timeline) {
  49535. globalStart = globalStart || _checkOverlap(tween, 0, zeroDur);
  49536. if (_checkOverlap(curTween, globalStart, zeroDur) === 0) {
  49537. overlaps[oCount++] = curTween;
  49538. }
  49539. } else if (curTween._startTime <= startTime) if (curTween._startTime + curTween.totalDuration() / curTween._timeScale > startTime) if (!((zeroDur || !curTween._initted) && startTime - curTween._startTime <= 0.0000000002)) {
  49540. overlaps[oCount++] = curTween;
  49541. }
  49542. }
  49543. i = oCount;
  49544. while (--i > -1) {
  49545. curTween = overlaps[i];
  49546. if (mode === 2) if (curTween._kill(props, target, tween)) {
  49547. changed = true;
  49548. }
  49549. if (mode !== 2 || (!curTween._firstPT && curTween._initted)) {
  49550. if (mode !== 2 && !_onOverwrite(curTween, tween)) {
  49551. continue;
  49552. }
  49553. if (curTween._enabled(false, false)) { //if all property tweens have been overwritten, kill the tween.
  49554. changed = true;
  49555. }
  49556. }
  49557. }
  49558. return changed;
  49559. },
  49560. _checkOverlap = function(tween, reference, zeroDur) {
  49561. var tl = tween._timeline,
  49562. ts = tl._timeScale,
  49563. t = tween._startTime;
  49564. while (tl._timeline) {
  49565. t += tl._startTime;
  49566. ts *= tl._timeScale;
  49567. if (tl._paused) {
  49568. return -100;
  49569. }
  49570. tl = tl._timeline;
  49571. }
  49572. t /= ts;
  49573. return (t > reference) ? t - reference : ((zeroDur && t === reference) || (!tween._initted && t - reference < 2 * _tinyNum)) ? _tinyNum : ((t += tween.totalDuration() / tween._timeScale / ts) > reference + _tinyNum) ? 0 : t - reference - _tinyNum;
  49574. };
  49575. //---- TweenLite instance methods -----------------------------------------------------------------------------
  49576. p._init = function() {
  49577. var v = this.vars,
  49578. op = this._overwrittenProps,
  49579. dur = this._duration,
  49580. immediate = !!v.immediateRender,
  49581. ease = v.ease,
  49582. i, initPlugins, pt, p, startVars, l;
  49583. if (v.startAt) {
  49584. if (this._startAt) {
  49585. this._startAt.render(-1, true); //if we've run a startAt previously (when the tween instantiated), we should revert it so that the values re-instantiate correctly particularly for relative tweens. Without this, a TweenLite.fromTo(obj, 1, {x:"+=100"}, {x:"-=100"}), for example, would actually jump to +=200 because the startAt would run twice, doubling the relative change.
  49586. this._startAt.kill();
  49587. }
  49588. startVars = {};
  49589. for (p in v.startAt) { //copy the properties/values into a new object to avoid collisions, like var to = {x:0}, from = {x:500}; timeline.fromTo(e, 1, from, to).fromTo(e, 1, to, from);
  49590. startVars[p] = v.startAt[p];
  49591. }
  49592. startVars.overwrite = false;
  49593. startVars.immediateRender = true;
  49594. startVars.lazy = (immediate && v.lazy !== false);
  49595. startVars.startAt = startVars.delay = null; //no nesting of startAt objects allowed (otherwise it could cause an infinite loop).
  49596. startVars.onUpdate = v.onUpdate;
  49597. startVars.onUpdateScope = v.onUpdateScope || v.callbackScope || this;
  49598. this._startAt = TweenLite.to(this.target, 0, startVars);
  49599. if (immediate) {
  49600. if (this._time > 0) {
  49601. this._startAt = null; //tweens that render immediately (like most from() and fromTo() tweens) shouldn't revert when their parent timeline's playhead goes backward past the startTime because the initial render could have happened anytime and it shouldn't be directly correlated to this tween's startTime. Imagine setting up a complex animation where the beginning states of various objects are rendered immediately but the tween doesn't happen for quite some time - if we revert to the starting values as soon as the playhead goes backward past the tween's startTime, it will throw things off visually. Reversion should only happen in TimelineLite/Max instances where immediateRender was false (which is the default in the convenience methods like from()).
  49602. } else if (dur !== 0) {
  49603. return; //we skip initialization here so that overwriting doesn't occur until the tween actually begins. Otherwise, if you create several immediateRender:true tweens of the same target/properties to drop into a TimelineLite or TimelineMax, the last one created would overwrite the first ones because they didn't get placed into the timeline yet before the first render occurs and kicks in overwriting.
  49604. }
  49605. }
  49606. } else if (v.runBackwards && dur !== 0) {
  49607. //from() tweens must be handled uniquely: their beginning values must be rendered but we don't want overwriting to occur yet (when time is still 0). Wait until the tween actually begins before doing all the routines like overwriting. At that time, we should render at the END of the tween to ensure that things initialize correctly (remember, from() tweens go backwards)
  49608. if (this._startAt) {
  49609. this._startAt.render(-1, true);
  49610. this._startAt.kill();
  49611. this._startAt = null;
  49612. } else {
  49613. if (this._time !== 0) { //in rare cases (like if a from() tween runs and then is invalidate()-ed), immediateRender could be true but the initial forced-render gets skipped, so there's no need to force the render in this context when the _time is greater than 0
  49614. immediate = false;
  49615. }
  49616. pt = {};
  49617. for (p in v) { //copy props into a new object and skip any reserved props, otherwise onComplete or onUpdate or onStart could fire. We should, however, permit autoCSS to go through.
  49618. if (!_reservedProps[p] || p === "autoCSS") {
  49619. pt[p] = v[p];
  49620. }
  49621. }
  49622. pt.overwrite = 0;
  49623. pt.data = "isFromStart"; //we tag the tween with as "isFromStart" so that if [inside a plugin] we need to only do something at the very END of a tween, we have a way of identifying this tween as merely the one that's setting the beginning values for a "from()" tween. For example, clearProps in CSSPlugin should only get applied at the very END of a tween and without this tag, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in.
  49624. pt.lazy = (immediate && v.lazy !== false);
  49625. pt.immediateRender = immediate; //zero-duration tweens render immediately by default, but if we're not specifically instructed to render this tween immediately, we should skip this and merely _init() to record the starting values (rendering them immediately would push them to completion which is wasteful in that case - we'd have to render(-1) immediately after)
  49626. this._startAt = TweenLite.to(this.target, 0, pt);
  49627. if (!immediate) {
  49628. this._startAt._init(); //ensures that the initial values are recorded
  49629. this._startAt._enabled(false); //no need to have the tween render on the next cycle. Disable it because we'll always manually control the renders of the _startAt tween.
  49630. if (this.vars.immediateRender) {
  49631. this._startAt = null;
  49632. }
  49633. } else if (this._time === 0) {
  49634. return;
  49635. }
  49636. }
  49637. }
  49638. this._ease = ease = (!ease) ? TweenLite.defaultEase : (ease instanceof Ease) ? ease : (typeof(ease) === "function") ? new Ease(ease, v.easeParams) : _easeMap[ease] || TweenLite.defaultEase;
  49639. if (v.easeParams instanceof Array && ease.config) {
  49640. this._ease = ease.config.apply(ease, v.easeParams);
  49641. }
  49642. this._easeType = this._ease._type;
  49643. this._easePower = this._ease._power;
  49644. this._firstPT = null;
  49645. if (this._targets) {
  49646. l = this._targets.length;
  49647. for (i = 0; i < l; i++) {
  49648. if ( this._initProps( this._targets[i], (this._propLookup[i] = {}), this._siblings[i], (op ? op[i] : null), i) ) {
  49649. initPlugins = true;
  49650. }
  49651. }
  49652. } else {
  49653. initPlugins = this._initProps(this.target, this._propLookup, this._siblings, op, 0);
  49654. }
  49655. if (initPlugins) {
  49656. TweenLite._onPluginEvent("_onInitAllProps", this); //reorders the array in order of priority. Uses a static TweenPlugin method in order to minimize file size in TweenLite
  49657. }
  49658. if (op) if (!this._firstPT) if (typeof(this.target) !== "function") { //if all tweening properties have been overwritten, kill the tween. If the target is a function, it's probably a delayedCall so let it live.
  49659. this._enabled(false, false);
  49660. }
  49661. if (v.runBackwards) {
  49662. pt = this._firstPT;
  49663. while (pt) {
  49664. pt.s += pt.c;
  49665. pt.c = -pt.c;
  49666. pt = pt._next;
  49667. }
  49668. }
  49669. this._onUpdate = v.onUpdate;
  49670. this._initted = true;
  49671. };
  49672. p._initProps = function(target, propLookup, siblings, overwrittenProps, index) {
  49673. var p, i, initPlugins, plugin, pt, v;
  49674. if (target == null) {
  49675. return false;
  49676. }
  49677. if (_lazyLookup[target._gsTweenID]) {
  49678. _lazyRender(); //if other tweens of the same target have recently initted but haven't rendered yet, we've got to force the render so that the starting values are correct (imagine populating a timeline with a bunch of sequential tweens and then jumping to the end)
  49679. }
  49680. if (!this.vars.css) if (target.style) if (target !== window && target.nodeType) if (_plugins.css) if (this.vars.autoCSS !== false) { //it's so common to use TweenLite/Max to animate the css of DOM elements, we assume that if the target is a DOM element, that's what is intended (a convenience so that users don't have to wrap things in css:{}, although we still recommend it for a slight performance boost and better specificity). Note: we cannot check "nodeType" on the window inside an iframe.
  49681. _autoCSS(this.vars, target);
  49682. }
  49683. for (p in this.vars) {
  49684. v = this.vars[p];
  49685. if (_reservedProps[p]) {
  49686. if (v) if ((v instanceof Array) || (v.push && _isArray(v))) if (v.join("").indexOf("{self}") !== -1) {
  49687. this.vars[p] = v = this._swapSelfInParams(v, this);
  49688. }
  49689. } else if (_plugins[p] && (plugin = new _plugins[p]())._onInitTween(target, this.vars[p], this, index)) {
  49690. //t - target [object]
  49691. //p - property [string]
  49692. //s - start [number]
  49693. //c - change [number]
  49694. //f - isFunction [boolean]
  49695. //n - name [string]
  49696. //pg - isPlugin [boolean]
  49697. //pr - priority [number]
  49698. //m - mod [function | 0]
  49699. this._firstPT = pt = {_next:this._firstPT, t:plugin, p:"setRatio", s:0, c:1, f:1, n:p, pg:1, pr:plugin._priority, m:0};
  49700. i = plugin._overwriteProps.length;
  49701. while (--i > -1) {
  49702. propLookup[plugin._overwriteProps[i]] = this._firstPT;
  49703. }
  49704. if (plugin._priority || plugin._onInitAllProps) {
  49705. initPlugins = true;
  49706. }
  49707. if (plugin._onDisable || plugin._onEnable) {
  49708. this._notifyPluginsOfEnabled = true;
  49709. }
  49710. if (pt._next) {
  49711. pt._next._prev = pt;
  49712. }
  49713. } else {
  49714. propLookup[p] = _addPropTween.call(this, target, p, "get", v, p, 0, null, this.vars.stringFilter, index);
  49715. }
  49716. }
  49717. if (overwrittenProps) if (this._kill(overwrittenProps, target)) { //another tween may have tried to overwrite properties of this tween before init() was called (like if two tweens start at the same time, the one created second will run first)
  49718. return this._initProps(target, propLookup, siblings, overwrittenProps, index);
  49719. }
  49720. if (this._overwrite > 1) if (this._firstPT) if (siblings.length > 1) if (_applyOverwrite(target, this, propLookup, this._overwrite, siblings)) {
  49721. this._kill(propLookup, target);
  49722. return this._initProps(target, propLookup, siblings, overwrittenProps, index);
  49723. }
  49724. if (this._firstPT) if ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration)) { //zero duration tweens don't lazy render by default; everything else does.
  49725. _lazyLookup[target._gsTweenID] = true;
  49726. }
  49727. return initPlugins;
  49728. };
  49729. p.render = function(time, suppressEvents, force) {
  49730. var prevTime = this._time,
  49731. duration = this._duration,
  49732. prevRawPrevTime = this._rawPrevTime,
  49733. isComplete, callback, pt, rawPrevTime;
  49734. if (time >= duration - 0.0000001 && time >= 0) { //to work around occasional floating point math artifacts.
  49735. this._totalTime = this._time = duration;
  49736. this.ratio = this._ease._calcEnd ? this._ease.getRatio(1) : 1;
  49737. if (!this._reversed ) {
  49738. isComplete = true;
  49739. callback = "onComplete";
  49740. force = (force || this._timeline.autoRemoveChildren); //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
  49741. }
  49742. if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
  49743. if (this._startTime === this._timeline._duration) { //if a zero-duration tween is at the VERY end of a timeline and that timeline renders at its end, it will typically add a tiny bit of cushion to the render time to prevent rounding errors from getting in the way of tweens rendering their VERY end. If we then reverse() that timeline, the zero-duration tween will trigger its onReverseComplete even though technically the playhead didn't pass over it again. It's a very specific edge case we must accommodate.
  49744. time = 0;
  49745. }
  49746. if (prevRawPrevTime < 0 || (time <= 0 && time >= -0.0000001) || (prevRawPrevTime === _tinyNum && this.data !== "isPause")) if (prevRawPrevTime !== time) { //note: when this.data is "isPause", it's a callback added by addPause() on a timeline that we should not be triggered when LEAVING its exact start time. In other words, tl.addPause(1).play(1) shouldn't pause.
  49747. force = true;
  49748. if (prevRawPrevTime > _tinyNum) {
  49749. callback = "onReverseComplete";
  49750. }
  49751. }
  49752. this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  49753. }
  49754. } else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
  49755. this._totalTime = this._time = 0;
  49756. this.ratio = this._ease._calcEnd ? this._ease.getRatio(0) : 0;
  49757. if (prevTime !== 0 || (duration === 0 && prevRawPrevTime > 0)) {
  49758. callback = "onReverseComplete";
  49759. isComplete = this._reversed;
  49760. }
  49761. if (time < 0) {
  49762. this._active = false;
  49763. if (duration === 0) if (this._initted || !this.vars.lazy || force) { //zero-duration tweens are tricky because we must discern the momentum/direction of time in order to determine whether the starting values should be rendered or the ending values. If the "playhead" of its timeline goes past the zero-duration tween in the forward direction or lands directly on it, the end values should be rendered, but if the timeline's "playhead" moves past it in the backward direction (from a postitive time to a negative time), the starting values must be rendered.
  49764. if (prevRawPrevTime >= 0 && !(prevRawPrevTime === _tinyNum && this.data === "isPause")) {
  49765. force = true;
  49766. }
  49767. this._rawPrevTime = rawPrevTime = (!suppressEvents || time || prevRawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
  49768. }
  49769. }
  49770. if (!this._initted || (this._startAt && this._startAt.progress())) { //if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately. Also, we check progress() because if startAt has already rendered at its end, we should force a render at its beginning. Otherwise, if you put the playhead directly on top of where a fromTo({immediateRender:false}) starts, and then move it backwards, the from() won't revert its values.
  49771. force = true;
  49772. }
  49773. } else {
  49774. this._totalTime = this._time = time;
  49775. if (this._easeType) {
  49776. var r = time / duration, type = this._easeType, pow = this._easePower;
  49777. if (type === 1 || (type === 3 && r >= 0.5)) {
  49778. r = 1 - r;
  49779. }
  49780. if (type === 3) {
  49781. r *= 2;
  49782. }
  49783. if (pow === 1) {
  49784. r *= r;
  49785. } else if (pow === 2) {
  49786. r *= r * r;
  49787. } else if (pow === 3) {
  49788. r *= r * r * r;
  49789. } else if (pow === 4) {
  49790. r *= r * r * r * r;
  49791. }
  49792. if (type === 1) {
  49793. this.ratio = 1 - r;
  49794. } else if (type === 2) {
  49795. this.ratio = r;
  49796. } else if (time / duration < 0.5) {
  49797. this.ratio = r / 2;
  49798. } else {
  49799. this.ratio = 1 - (r / 2);
  49800. }
  49801. } else {
  49802. this.ratio = this._ease.getRatio(time / duration);
  49803. }
  49804. }
  49805. if (this._time === prevTime && !force) {
  49806. return;
  49807. } else if (!this._initted) {
  49808. this._init();
  49809. if (!this._initted || this._gc) { //immediateRender tweens typically won't initialize until the playhead advances (_time is greater than 0) in order to ensure that overwriting occurs properly. Also, if all of the tweening properties have been overwritten (which would cause _gc to be true, as set in _init()), we shouldn't continue otherwise an onStart callback could be called for example.
  49810. return;
  49811. } else if (!force && this._firstPT && ((this.vars.lazy !== false && this._duration) || (this.vars.lazy && !this._duration))) {
  49812. this._time = this._totalTime = prevTime;
  49813. this._rawPrevTime = prevRawPrevTime;
  49814. _lazyTweens.push(this);
  49815. this._lazy = [time, suppressEvents];
  49816. return;
  49817. }
  49818. //_ease is initially set to defaultEase, so now that init() has run, _ease is set properly and we need to recalculate the ratio. Overall this is faster than using conditional logic earlier in the method to avoid having to set ratio twice because we only init() once but renderTime() gets called VERY frequently.
  49819. if (this._time && !isComplete) {
  49820. this.ratio = this._ease.getRatio(this._time / duration);
  49821. } else if (isComplete && this._ease._calcEnd) {
  49822. this.ratio = this._ease.getRatio((this._time === 0) ? 0 : 1);
  49823. }
  49824. }
  49825. if (this._lazy !== false) { //in case a lazy render is pending, we should flush it because the new render is occurring now (imagine a lazy tween instantiating and then immediately the user calls tween.seek(tween.duration()), skipping to the end - the end render would be forced, and then if we didn't flush the lazy render, it'd fire AFTER the seek(), rendering it at the wrong time.
  49826. this._lazy = false;
  49827. }
  49828. if (!this._active) if (!this._paused && this._time !== prevTime && time >= 0) {
  49829. this._active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
  49830. }
  49831. if (prevTime === 0) {
  49832. if (this._startAt) {
  49833. if (time >= 0) {
  49834. this._startAt.render(time, suppressEvents, force);
  49835. } else if (!callback) {
  49836. callback = "_dummyGS"; //if no callback is defined, use a dummy value just so that the condition at the end evaluates as true because _startAt should render AFTER the normal render loop when the time is negative. We could handle this in a more intuitive way, of course, but the render loop is the MOST important thing to optimize, so this technique allows us to avoid adding extra conditional logic in a high-frequency area.
  49837. }
  49838. }
  49839. if (this.vars.onStart) if (this._time !== 0 || duration === 0) if (!suppressEvents) {
  49840. this._callback("onStart");
  49841. }
  49842. }
  49843. pt = this._firstPT;
  49844. while (pt) {
  49845. if (pt.f) {
  49846. pt.t[pt.p](pt.c * this.ratio + pt.s);
  49847. } else {
  49848. pt.t[pt.p] = pt.c * this.ratio + pt.s;
  49849. }
  49850. pt = pt._next;
  49851. }
  49852. if (this._onUpdate) {
  49853. if (time < 0) if (this._startAt && time !== -0.0001) { //if the tween is positioned at the VERY beginning (_startTime 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
  49854. this._startAt.render(time, suppressEvents, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.
  49855. }
  49856. if (!suppressEvents) if (this._time !== prevTime || isComplete || force) {
  49857. this._callback("onUpdate");
  49858. }
  49859. }
  49860. if (callback) if (!this._gc || force) { //check _gc because there's a chance that kill() could be called in an onUpdate
  49861. if (time < 0 && this._startAt && !this._onUpdate && time !== -0.0001) { //-0.0001 is a special value that we use when looping back to the beginning of a repeated TimelineMax, in which case we shouldn't render the _startAt values.
  49862. this._startAt.render(time, suppressEvents, force);
  49863. }
  49864. if (isComplete) {
  49865. if (this._timeline.autoRemoveChildren) {
  49866. this._enabled(false, false);
  49867. }
  49868. this._active = false;
  49869. }
  49870. if (!suppressEvents && this.vars[callback]) {
  49871. this._callback(callback);
  49872. }
  49873. if (duration === 0 && this._rawPrevTime === _tinyNum && rawPrevTime !== _tinyNum) { //the onComplete or onReverseComplete could trigger movement of the playhead and for zero-duration tweens (which must discern direction) that land directly back on their start time, we don't want to fire again on the next render. Think of several addPause()'s in a timeline that forces the playhead to a certain spot, but what if it's already paused and another tween is tweening the "time" of the timeline? Each time it moves [forward] past that spot, it would move back, and since suppressEvents is true, it'd reset _rawPrevTime to _tinyNum so that when it begins again, the callback would fire (so ultimately it could bounce back and forth during that tween). Again, this is a very uncommon scenario, but possible nonetheless.
  49874. this._rawPrevTime = 0;
  49875. }
  49876. }
  49877. };
  49878. p._kill = function(vars, target, overwritingTween) {
  49879. if (vars === "all") {
  49880. vars = null;
  49881. }
  49882. if (vars == null) if (target == null || target === this.target) {
  49883. this._lazy = false;
  49884. return this._enabled(false, false);
  49885. }
  49886. target = (typeof(target) !== "string") ? (target || this._targets || this.target) : TweenLite.selector(target) || target;
  49887. var simultaneousOverwrite = (overwritingTween && this._time && overwritingTween._startTime === this._startTime && this._timeline === overwritingTween._timeline),
  49888. i, overwrittenProps, p, pt, propLookup, changed, killProps, record, killed;
  49889. if ((_isArray(target) || _isSelector(target)) && typeof(target[0]) !== "number") {
  49890. i = target.length;
  49891. while (--i > -1) {
  49892. if (this._kill(vars, target[i], overwritingTween)) {
  49893. changed = true;
  49894. }
  49895. }
  49896. } else {
  49897. if (this._targets) {
  49898. i = this._targets.length;
  49899. while (--i > -1) {
  49900. if (target === this._targets[i]) {
  49901. propLookup = this._propLookup[i] || {};
  49902. this._overwrittenProps = this._overwrittenProps || [];
  49903. overwrittenProps = this._overwrittenProps[i] = vars ? this._overwrittenProps[i] || {} : "all";
  49904. break;
  49905. }
  49906. }
  49907. } else if (target !== this.target) {
  49908. return false;
  49909. } else {
  49910. propLookup = this._propLookup;
  49911. overwrittenProps = this._overwrittenProps = vars ? this._overwrittenProps || {} : "all";
  49912. }
  49913. if (propLookup) {
  49914. killProps = vars || propLookup;
  49915. record = (vars !== overwrittenProps && overwrittenProps !== "all" && vars !== propLookup && (typeof(vars) !== "object" || !vars._tempKill)); //_tempKill is a super-secret way to delete a particular tweening property but NOT have it remembered as an official overwritten property (like in BezierPlugin)
  49916. if (overwritingTween && (TweenLite.onOverwrite || this.vars.onOverwrite)) {
  49917. for (p in killProps) {
  49918. if (propLookup[p]) {
  49919. if (!killed) {
  49920. killed = [];
  49921. }
  49922. killed.push(p);
  49923. }
  49924. }
  49925. if ((killed || !vars) && !_onOverwrite(this, overwritingTween, target, killed)) { //if the onOverwrite returned false, that means the user wants to override the overwriting (cancel it).
  49926. return false;
  49927. }
  49928. }
  49929. for (p in killProps) {
  49930. if ((pt = propLookup[p])) {
  49931. if (simultaneousOverwrite) { //if another tween overwrites this one and they both start at exactly the same time, yet this tween has already rendered once (for example, at 0.001) because it's first in the queue, we should revert the values to where they were at 0 so that the starting values aren't contaminated on the overwriting tween.
  49932. if (pt.f) {
  49933. pt.t[pt.p](pt.s);
  49934. } else {
  49935. pt.t[pt.p] = pt.s;
  49936. }
  49937. changed = true;
  49938. }
  49939. if (pt.pg && pt.t._kill(killProps)) {
  49940. changed = true; //some plugins need to be notified so they can perform cleanup tasks first
  49941. }
  49942. if (!pt.pg || pt.t._overwriteProps.length === 0) {
  49943. if (pt._prev) {
  49944. pt._prev._next = pt._next;
  49945. } else if (pt === this._firstPT) {
  49946. this._firstPT = pt._next;
  49947. }
  49948. if (pt._next) {
  49949. pt._next._prev = pt._prev;
  49950. }
  49951. pt._next = pt._prev = null;
  49952. }
  49953. delete propLookup[p];
  49954. }
  49955. if (record) {
  49956. overwrittenProps[p] = 1;
  49957. }
  49958. }
  49959. if (!this._firstPT && this._initted) { //if all tweening properties are killed, kill the tween. Without this line, if there's a tween with multiple targets and then you killTweensOf() each target individually, the tween would technically still remain active and fire its onComplete even though there aren't any more properties tweening.
  49960. this._enabled(false, false);
  49961. }
  49962. }
  49963. }
  49964. return changed;
  49965. };
  49966. p.invalidate = function() {
  49967. if (this._notifyPluginsOfEnabled) {
  49968. TweenLite._onPluginEvent("_onDisable", this);
  49969. }
  49970. this._firstPT = this._overwrittenProps = this._startAt = this._onUpdate = null;
  49971. this._notifyPluginsOfEnabled = this._active = this._lazy = false;
  49972. this._propLookup = (this._targets) ? {} : [];
  49973. Animation.prototype.invalidate.call(this);
  49974. if (this.vars.immediateRender) {
  49975. this._time = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)
  49976. this.render(Math.min(0, -this._delay)); //in case delay is negative.
  49977. }
  49978. return this;
  49979. };
  49980. p._enabled = function(enabled, ignoreTimeline) {
  49981. if (!_tickerActive) {
  49982. _ticker.wake();
  49983. }
  49984. if (enabled && this._gc) {
  49985. var targets = this._targets,
  49986. i;
  49987. if (targets) {
  49988. i = targets.length;
  49989. while (--i > -1) {
  49990. this._siblings[i] = _register(targets[i], this, true);
  49991. }
  49992. } else {
  49993. this._siblings = _register(this.target, this, true);
  49994. }
  49995. }
  49996. Animation.prototype._enabled.call(this, enabled, ignoreTimeline);
  49997. if (this._notifyPluginsOfEnabled) if (this._firstPT) {
  49998. return TweenLite._onPluginEvent((enabled ? "_onEnable" : "_onDisable"), this);
  49999. }
  50000. return false;
  50001. };
  50002. //----TweenLite static methods -----------------------------------------------------
  50003. TweenLite.to = function(target, duration, vars) {
  50004. return new TweenLite(target, duration, vars);
  50005. };
  50006. TweenLite.from = function(target, duration, vars) {
  50007. vars.runBackwards = true;
  50008. vars.immediateRender = (vars.immediateRender != false);
  50009. return new TweenLite(target, duration, vars);
  50010. };
  50011. TweenLite.fromTo = function(target, duration, fromVars, toVars) {
  50012. toVars.startAt = fromVars;
  50013. toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
  50014. return new TweenLite(target, duration, toVars);
  50015. };
  50016. TweenLite.delayedCall = function(delay, callback, params, scope, useFrames) {
  50017. return new TweenLite(callback, 0, {delay:delay, onComplete:callback, onCompleteParams:params, callbackScope:scope, onReverseComplete:callback, onReverseCompleteParams:params, immediateRender:false, lazy:false, useFrames:useFrames, overwrite:0});
  50018. };
  50019. TweenLite.set = function(target, vars) {
  50020. return new TweenLite(target, 0, vars);
  50021. };
  50022. TweenLite.getTweensOf = function(target, onlyActive) {
  50023. if (target == null) { return []; }
  50024. target = (typeof(target) !== "string") ? target : TweenLite.selector(target) || target;
  50025. var i, a, j, t;
  50026. if ((_isArray(target) || _isSelector(target)) && typeof(target[0]) !== "number") {
  50027. i = target.length;
  50028. a = [];
  50029. while (--i > -1) {
  50030. a = a.concat(TweenLite.getTweensOf(target[i], onlyActive));
  50031. }
  50032. i = a.length;
  50033. //now get rid of any duplicates (tweens of arrays of objects could cause duplicates)
  50034. while (--i > -1) {
  50035. t = a[i];
  50036. j = i;
  50037. while (--j > -1) {
  50038. if (t === a[j]) {
  50039. a.splice(i, 1);
  50040. }
  50041. }
  50042. }
  50043. } else if (target._gsTweenID) {
  50044. a = _register(target).concat();
  50045. i = a.length;
  50046. while (--i > -1) {
  50047. if (a[i]._gc || (onlyActive && !a[i].isActive())) {
  50048. a.splice(i, 1);
  50049. }
  50050. }
  50051. }
  50052. return a || [];
  50053. };
  50054. TweenLite.killTweensOf = TweenLite.killDelayedCallsTo = function(target, onlyActive, vars) {
  50055. if (typeof(onlyActive) === "object") {
  50056. vars = onlyActive; //for backwards compatibility (before "onlyActive" parameter was inserted)
  50057. onlyActive = false;
  50058. }
  50059. var a = TweenLite.getTweensOf(target, onlyActive),
  50060. i = a.length;
  50061. while (--i > -1) {
  50062. a[i]._kill(vars, target);
  50063. }
  50064. };
  50065. /*
  50066. * ----------------------------------------------------------------
  50067. * TweenPlugin (could easily be split out as a separate file/class, but included for ease of use (so that people don't need to include another script call before loading plugins which is easy to forget)
  50068. * ----------------------------------------------------------------
  50069. */
  50070. var TweenPlugin = _class("plugins.TweenPlugin", function(props, priority) {
  50071. this._overwriteProps = (props || "").split(",");
  50072. this._propName = this._overwriteProps[0];
  50073. this._priority = priority || 0;
  50074. this._super = TweenPlugin.prototype;
  50075. }, true);
  50076. p = TweenPlugin.prototype;
  50077. TweenPlugin.version = "1.19.0";
  50078. TweenPlugin.API = 2;
  50079. p._firstPT = null;
  50080. p._addTween = _addPropTween;
  50081. p.setRatio = _setRatio;
  50082. p._kill = function(lookup) {
  50083. var a = this._overwriteProps,
  50084. pt = this._firstPT,
  50085. i;
  50086. if (lookup[this._propName] != null) {
  50087. this._overwriteProps = [];
  50088. } else {
  50089. i = a.length;
  50090. while (--i > -1) {
  50091. if (lookup[a[i]] != null) {
  50092. a.splice(i, 1);
  50093. }
  50094. }
  50095. }
  50096. while (pt) {
  50097. if (lookup[pt.n] != null) {
  50098. if (pt._next) {
  50099. pt._next._prev = pt._prev;
  50100. }
  50101. if (pt._prev) {
  50102. pt._prev._next = pt._next;
  50103. pt._prev = null;
  50104. } else if (this._firstPT === pt) {
  50105. this._firstPT = pt._next;
  50106. }
  50107. }
  50108. pt = pt._next;
  50109. }
  50110. return false;
  50111. };
  50112. p._mod = p._roundProps = function(lookup) {
  50113. var pt = this._firstPT,
  50114. val;
  50115. while (pt) {
  50116. val = lookup[this._propName] || (pt.n != null && lookup[ pt.n.split(this._propName + "_").join("") ]);
  50117. if (val && typeof(val) === "function") { //some properties that are very plugin-specific add a prefix named after the _propName plus an underscore, so we need to ignore that extra stuff here.
  50118. if (pt.f === 2) {
  50119. pt.t._applyPT.m = val;
  50120. } else {
  50121. pt.m = val;
  50122. }
  50123. }
  50124. pt = pt._next;
  50125. }
  50126. };
  50127. TweenLite._onPluginEvent = function(type, tween) {
  50128. var pt = tween._firstPT,
  50129. changed, pt2, first, last, next;
  50130. if (type === "_onInitAllProps") {
  50131. //sorts the PropTween linked list in order of priority because some plugins need to render earlier/later than others, like MotionBlurPlugin applies its effects after all x/y/alpha tweens have rendered on each frame.
  50132. while (pt) {
  50133. next = pt._next;
  50134. pt2 = first;
  50135. while (pt2 && pt2.pr > pt.pr) {
  50136. pt2 = pt2._next;
  50137. }
  50138. if ((pt._prev = pt2 ? pt2._prev : last)) {
  50139. pt._prev._next = pt;
  50140. } else {
  50141. first = pt;
  50142. }
  50143. if ((pt._next = pt2)) {
  50144. pt2._prev = pt;
  50145. } else {
  50146. last = pt;
  50147. }
  50148. pt = next;
  50149. }
  50150. pt = tween._firstPT = first;
  50151. }
  50152. while (pt) {
  50153. if (pt.pg) if (typeof(pt.t[type]) === "function") if (pt.t[type]()) {
  50154. changed = true;
  50155. }
  50156. pt = pt._next;
  50157. }
  50158. return changed;
  50159. };
  50160. TweenPlugin.activate = function(plugins) {
  50161. var i = plugins.length;
  50162. while (--i > -1) {
  50163. if (plugins[i].API === TweenPlugin.API) {
  50164. _plugins[(new plugins[i]())._propName] = plugins[i];
  50165. }
  50166. }
  50167. return true;
  50168. };
  50169. //provides a more concise way to define plugins that have no dependencies besides TweenPlugin and TweenLite, wrapping common boilerplate stuff into one function (added in 1.9.0). You don't NEED to use this to define a plugin - the old way still works and can be useful in certain (rare) situations.
  50170. _gsDefine.plugin = function(config) {
  50171. if (!config || !config.propName || !config.init || !config.API) { throw "illegal plugin definition."; }
  50172. var propName = config.propName,
  50173. priority = config.priority || 0,
  50174. overwriteProps = config.overwriteProps,
  50175. map = {init:"_onInitTween", set:"setRatio", kill:"_kill", round:"_mod", mod:"_mod", initAll:"_onInitAllProps"},
  50176. Plugin = _class("plugins." + propName.charAt(0).toUpperCase() + propName.substr(1) + "Plugin",
  50177. function() {
  50178. TweenPlugin.call(this, propName, priority);
  50179. this._overwriteProps = overwriteProps || [];
  50180. }, (config.global === true)),
  50181. p = Plugin.prototype = new TweenPlugin(propName),
  50182. prop;
  50183. p.constructor = Plugin;
  50184. Plugin.API = config.API;
  50185. for (prop in map) {
  50186. if (typeof(config[prop]) === "function") {
  50187. p[map[prop]] = config[prop];
  50188. }
  50189. }
  50190. Plugin.version = config.version;
  50191. TweenPlugin.activate([Plugin]);
  50192. return Plugin;
  50193. };
  50194. //now run through all the dependencies discovered and if any are missing, log that to the console as a warning. This is why it's best to have TweenLite load last - it can check all the dependencies for you.
  50195. a = window._gsQueue;
  50196. if (a) {
  50197. for (i = 0; i < a.length; i++) {
  50198. a[i]();
  50199. }
  50200. for (p in _defLookup) {
  50201. if (!_defLookup[p].func) {
  50202. window.console.log("GSAP encountered missing dependency: " + p);
  50203. }
  50204. }
  50205. }
  50206. _tickerActive = false; //ensures that the first official animation forces a ticker.tick() to update the time when it is instantiated
  50207. })((typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window, "TweenMax");
  50208. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  50209. },{}],213:[function(require,module,exports){
  50210. /*!
  50211. * html2canvas 1.0.0-rc.7 <https://html2canvas.hertzen.com>
  50212. * Copyright (c) 2020 Niklas von Hertzen <https://hertzen.com>
  50213. * Released under MIT License
  50214. */
  50215. (function (global, factory) {
  50216. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  50217. typeof define === 'function' && define.amd ? define(factory) :
  50218. (global = global || self, global.html2canvas = factory());
  50219. }(this, function () { 'use strict';
  50220. /*! *****************************************************************************
  50221. Copyright (c) Microsoft Corporation. All rights reserved.
  50222. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  50223. this file except in compliance with the License. You may obtain a copy of the
  50224. License at http://www.apache.org/licenses/LICENSE-2.0
  50225. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50226. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  50227. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  50228. MERCHANTABLITY OR NON-INFRINGEMENT.
  50229. See the Apache Version 2.0 License for specific language governing permissions
  50230. and limitations under the License.
  50231. ***************************************************************************** */
  50232. /* global Reflect, Promise */
  50233. var extendStatics = function(d, b) {
  50234. extendStatics = Object.setPrototypeOf ||
  50235. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  50236. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  50237. return extendStatics(d, b);
  50238. };
  50239. function __extends(d, b) {
  50240. extendStatics(d, b);
  50241. function __() { this.constructor = d; }
  50242. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  50243. }
  50244. var __assign = function() {
  50245. __assign = Object.assign || function __assign(t) {
  50246. for (var s, i = 1, n = arguments.length; i < n; i++) {
  50247. s = arguments[i];
  50248. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  50249. }
  50250. return t;
  50251. };
  50252. return __assign.apply(this, arguments);
  50253. };
  50254. function __awaiter(thisArg, _arguments, P, generator) {
  50255. return new (P || (P = Promise))(function (resolve, reject) {
  50256. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  50257. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  50258. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  50259. step((generator = generator.apply(thisArg, _arguments || [])).next());
  50260. });
  50261. }
  50262. function __generator(thisArg, body) {
  50263. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  50264. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  50265. function verb(n) { return function (v) { return step([n, v]); }; }
  50266. function step(op) {
  50267. if (f) throw new TypeError("Generator is already executing.");
  50268. while (_) try {
  50269. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  50270. if (y = 0, t) op = [op[0] & 2, t.value];
  50271. switch (op[0]) {
  50272. case 0: case 1: t = op; break;
  50273. case 4: _.label++; return { value: op[1], done: false };
  50274. case 5: _.label++; y = op[1]; op = [0]; continue;
  50275. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  50276. default:
  50277. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  50278. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  50279. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  50280. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  50281. if (t[2]) _.ops.pop();
  50282. _.trys.pop(); continue;
  50283. }
  50284. op = body.call(thisArg, _);
  50285. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  50286. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  50287. }
  50288. }
  50289. var Bounds = /** @class */ (function () {
  50290. function Bounds(x, y, w, h) {
  50291. this.left = x;
  50292. this.top = y;
  50293. this.width = w;
  50294. this.height = h;
  50295. }
  50296. Bounds.prototype.add = function (x, y, w, h) {
  50297. return new Bounds(this.left + x, this.top + y, this.width + w, this.height + h);
  50298. };
  50299. Bounds.fromClientRect = function (clientRect) {
  50300. return new Bounds(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  50301. };
  50302. return Bounds;
  50303. }());
  50304. var parseBounds = function (node) {
  50305. return Bounds.fromClientRect(node.getBoundingClientRect());
  50306. };
  50307. var parseDocumentSize = function (document) {
  50308. var body = document.body;
  50309. var documentElement = document.documentElement;
  50310. if (!body || !documentElement) {
  50311. throw new Error("Unable to get document size");
  50312. }
  50313. var width = Math.max(Math.max(body.scrollWidth, documentElement.scrollWidth), Math.max(body.offsetWidth, documentElement.offsetWidth), Math.max(body.clientWidth, documentElement.clientWidth));
  50314. var height = Math.max(Math.max(body.scrollHeight, documentElement.scrollHeight), Math.max(body.offsetHeight, documentElement.offsetHeight), Math.max(body.clientHeight, documentElement.clientHeight));
  50315. return new Bounds(0, 0, width, height);
  50316. };
  50317. /*
  50318. * css-line-break 1.1.1 <https://github.com/niklasvh/css-line-break#readme>
  50319. * Copyright (c) 2019 Niklas von Hertzen <https://hertzen.com>
  50320. * Released under MIT License
  50321. */
  50322. var toCodePoints = function (str) {
  50323. var codePoints = [];
  50324. var i = 0;
  50325. var length = str.length;
  50326. while (i < length) {
  50327. var value = str.charCodeAt(i++);
  50328. if (value >= 0xd800 && value <= 0xdbff && i < length) {
  50329. var extra = str.charCodeAt(i++);
  50330. if ((extra & 0xfc00) === 0xdc00) {
  50331. codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
  50332. }
  50333. else {
  50334. codePoints.push(value);
  50335. i--;
  50336. }
  50337. }
  50338. else {
  50339. codePoints.push(value);
  50340. }
  50341. }
  50342. return codePoints;
  50343. };
  50344. var fromCodePoint = function () {
  50345. var codePoints = [];
  50346. for (var _i = 0; _i < arguments.length; _i++) {
  50347. codePoints[_i] = arguments[_i];
  50348. }
  50349. if (String.fromCodePoint) {
  50350. return String.fromCodePoint.apply(String, codePoints);
  50351. }
  50352. var length = codePoints.length;
  50353. if (!length) {
  50354. return '';
  50355. }
  50356. var codeUnits = [];
  50357. var index = -1;
  50358. var result = '';
  50359. while (++index < length) {
  50360. var codePoint = codePoints[index];
  50361. if (codePoint <= 0xffff) {
  50362. codeUnits.push(codePoint);
  50363. }
  50364. else {
  50365. codePoint -= 0x10000;
  50366. codeUnits.push((codePoint >> 10) + 0xd800, codePoint % 0x400 + 0xdc00);
  50367. }
  50368. if (index + 1 === length || codeUnits.length > 0x4000) {
  50369. result += String.fromCharCode.apply(String, codeUnits);
  50370. codeUnits.length = 0;
  50371. }
  50372. }
  50373. return result;
  50374. };
  50375. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  50376. // Use a lookup table to find the index.
  50377. var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  50378. for (var i = 0; i < chars.length; i++) {
  50379. lookup[chars.charCodeAt(i)] = i;
  50380. }
  50381. var decode = function (base64) {
  50382. var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
  50383. if (base64[base64.length - 1] === '=') {
  50384. bufferLength--;
  50385. if (base64[base64.length - 2] === '=') {
  50386. bufferLength--;
  50387. }
  50388. }
  50389. var buffer = typeof ArrayBuffer !== 'undefined' &&
  50390. typeof Uint8Array !== 'undefined' &&
  50391. typeof Uint8Array.prototype.slice !== 'undefined'
  50392. ? new ArrayBuffer(bufferLength)
  50393. : new Array(bufferLength);
  50394. var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
  50395. for (i = 0; i < len; i += 4) {
  50396. encoded1 = lookup[base64.charCodeAt(i)];
  50397. encoded2 = lookup[base64.charCodeAt(i + 1)];
  50398. encoded3 = lookup[base64.charCodeAt(i + 2)];
  50399. encoded4 = lookup[base64.charCodeAt(i + 3)];
  50400. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  50401. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  50402. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  50403. }
  50404. return buffer;
  50405. };
  50406. var polyUint16Array = function (buffer) {
  50407. var length = buffer.length;
  50408. var bytes = [];
  50409. for (var i = 0; i < length; i += 2) {
  50410. bytes.push((buffer[i + 1] << 8) | buffer[i]);
  50411. }
  50412. return bytes;
  50413. };
  50414. var polyUint32Array = function (buffer) {
  50415. var length = buffer.length;
  50416. var bytes = [];
  50417. for (var i = 0; i < length; i += 4) {
  50418. bytes.push((buffer[i + 3] << 24) | (buffer[i + 2] << 16) | (buffer[i + 1] << 8) | buffer[i]);
  50419. }
  50420. return bytes;
  50421. };
  50422. /** Shift size for getting the index-2 table offset. */
  50423. var UTRIE2_SHIFT_2 = 5;
  50424. /** Shift size for getting the index-1 table offset. */
  50425. var UTRIE2_SHIFT_1 = 6 + 5;
  50426. /**
  50427. * Shift size for shifting left the index array values.
  50428. * Increases possible data size with 16-bit index values at the cost
  50429. * of compactability.
  50430. * This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY.
  50431. */
  50432. var UTRIE2_INDEX_SHIFT = 2;
  50433. /**
  50434. * Difference between the two shift sizes,
  50435. * for getting an index-1 offset from an index-2 offset. 6=11-5
  50436. */
  50437. var UTRIE2_SHIFT_1_2 = UTRIE2_SHIFT_1 - UTRIE2_SHIFT_2;
  50438. /**
  50439. * The part of the index-2 table for U+D800..U+DBFF stores values for
  50440. * lead surrogate code _units_ not code _points_.
  50441. * Values for lead surrogate code _points_ are indexed with this portion of the table.
  50442. * Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.)
  50443. */
  50444. var UTRIE2_LSCP_INDEX_2_OFFSET = 0x10000 >> UTRIE2_SHIFT_2;
  50445. /** Number of entries in a data block. 32=0x20 */
  50446. var UTRIE2_DATA_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_2;
  50447. /** Mask for getting the lower bits for the in-data-block offset. */
  50448. var UTRIE2_DATA_MASK = UTRIE2_DATA_BLOCK_LENGTH - 1;
  50449. var UTRIE2_LSCP_INDEX_2_LENGTH = 0x400 >> UTRIE2_SHIFT_2;
  50450. /** Count the lengths of both BMP pieces. 2080=0x820 */
  50451. var UTRIE2_INDEX_2_BMP_LENGTH = UTRIE2_LSCP_INDEX_2_OFFSET + UTRIE2_LSCP_INDEX_2_LENGTH;
  50452. /**
  50453. * The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
  50454. * Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2.
  50455. */
  50456. var UTRIE2_UTF8_2B_INDEX_2_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH;
  50457. var UTRIE2_UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */
  50458. /**
  50459. * The index-1 table, only used for supplementary code points, at offset 2112=0x840.
  50460. * Variable length, for code points up to highStart, where the last single-value range starts.
  50461. * Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1.
  50462. * (For 0x100000 supplementary code points U+10000..U+10ffff.)
  50463. *
  50464. * The part of the index-2 table for supplementary code points starts
  50465. * after this index-1 table.
  50466. *
  50467. * Both the index-1 table and the following part of the index-2 table
  50468. * are omitted completely if there is only BMP data.
  50469. */
  50470. var UTRIE2_INDEX_1_OFFSET = UTRIE2_UTF8_2B_INDEX_2_OFFSET + UTRIE2_UTF8_2B_INDEX_2_LENGTH;
  50471. /**
  50472. * Number of index-1 entries for the BMP. 32=0x20
  50473. * This part of the index-1 table is omitted from the serialized form.
  50474. */
  50475. var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> UTRIE2_SHIFT_1;
  50476. /** Number of entries in an index-2 block. 64=0x40 */
  50477. var UTRIE2_INDEX_2_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_1_2;
  50478. /** Mask for getting the lower bits for the in-index-2-block offset. */
  50479. var UTRIE2_INDEX_2_MASK = UTRIE2_INDEX_2_BLOCK_LENGTH - 1;
  50480. var slice16 = function (view, start, end) {
  50481. if (view.slice) {
  50482. return view.slice(start, end);
  50483. }
  50484. return new Uint16Array(Array.prototype.slice.call(view, start, end));
  50485. };
  50486. var slice32 = function (view, start, end) {
  50487. if (view.slice) {
  50488. return view.slice(start, end);
  50489. }
  50490. return new Uint32Array(Array.prototype.slice.call(view, start, end));
  50491. };
  50492. var createTrieFromBase64 = function (base64) {
  50493. var buffer = decode(base64);
  50494. var view32 = Array.isArray(buffer) ? polyUint32Array(buffer) : new Uint32Array(buffer);
  50495. var view16 = Array.isArray(buffer) ? polyUint16Array(buffer) : new Uint16Array(buffer);
  50496. var headerLength = 24;
  50497. var index = slice16(view16, headerLength / 2, view32[4] / 2);
  50498. var data = view32[5] === 2
  50499. ? slice16(view16, (headerLength + view32[4]) / 2)
  50500. : slice32(view32, Math.ceil((headerLength + view32[4]) / 4));
  50501. return new Trie(view32[0], view32[1], view32[2], view32[3], index, data);
  50502. };
  50503. var Trie = /** @class */ (function () {
  50504. function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) {
  50505. this.initialValue = initialValue;
  50506. this.errorValue = errorValue;
  50507. this.highStart = highStart;
  50508. this.highValueIndex = highValueIndex;
  50509. this.index = index;
  50510. this.data = data;
  50511. }
  50512. /**
  50513. * Get the value for a code point as stored in the Trie.
  50514. *
  50515. * @param codePoint the code point
  50516. * @return the value
  50517. */
  50518. Trie.prototype.get = function (codePoint) {
  50519. var ix;
  50520. if (codePoint >= 0) {
  50521. if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) {
  50522. // Ordinary BMP code point, excluding leading surrogates.
  50523. // BMP uses a single level lookup. BMP index starts at offset 0 in the Trie2 index.
  50524. // 16 bit data is stored in the index array itself.
  50525. ix = this.index[codePoint >> UTRIE2_SHIFT_2];
  50526. ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
  50527. return this.data[ix];
  50528. }
  50529. if (codePoint <= 0xffff) {
  50530. // Lead Surrogate Code Point. A Separate index section is stored for
  50531. // lead surrogate code units and code points.
  50532. // The main index has the code unit data.
  50533. // For this function, we need the code point data.
  50534. // Note: this expression could be refactored for slightly improved efficiency, but
  50535. // surrogate code points will be so rare in practice that it's not worth it.
  50536. ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2)];
  50537. ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
  50538. return this.data[ix];
  50539. }
  50540. if (codePoint < this.highStart) {
  50541. // Supplemental code point, use two-level lookup.
  50542. ix = UTRIE2_INDEX_1_OFFSET - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH + (codePoint >> UTRIE2_SHIFT_1);
  50543. ix = this.index[ix];
  50544. ix += (codePoint >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK;
  50545. ix = this.index[ix];
  50546. ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
  50547. return this.data[ix];
  50548. }
  50549. if (codePoint <= 0x10ffff) {
  50550. return this.data[this.highValueIndex];
  50551. }
  50552. }
  50553. // Fall through. The code point is outside of the legal range of 0..0x10ffff.
  50554. return this.errorValue;
  50555. };
  50556. return Trie;
  50557. }());
  50558. var base64 = 'KwAAAAAAAAAACA4AIDoAAPAfAAACAAAAAAAIABAAGABAAEgAUABYAF4AZgBeAGYAYABoAHAAeABeAGYAfACEAIAAiACQAJgAoACoAK0AtQC9AMUAXgBmAF4AZgBeAGYAzQDVAF4AZgDRANkA3gDmAOwA9AD8AAQBDAEUARoBIgGAAIgAJwEvATcBPwFFAU0BTAFUAVwBZAFsAXMBewGDATAAiwGTAZsBogGkAawBtAG8AcIBygHSAdoB4AHoAfAB+AH+AQYCDgIWAv4BHgImAi4CNgI+AkUCTQJTAlsCYwJrAnECeQKBAk0CiQKRApkCoQKoArACuALAAsQCzAIwANQC3ALkAjAA7AL0AvwCAQMJAxADGAMwACADJgMuAzYDPgOAAEYDSgNSA1IDUgNaA1oDYANiA2IDgACAAGoDgAByA3YDfgOAAIQDgACKA5IDmgOAAIAAogOqA4AAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAK8DtwOAAIAAvwPHA88D1wPfAyAD5wPsA/QD/AOAAIAABAQMBBIEgAAWBB4EJgQuBDMEIAM7BEEEXgBJBCADUQRZBGEEaQQwADAAcQQ+AXkEgQSJBJEEgACYBIAAoASoBK8EtwQwAL8ExQSAAIAAgACAAIAAgACgAM0EXgBeAF4AXgBeAF4AXgBeANUEXgDZBOEEXgDpBPEE+QQBBQkFEQUZBSEFKQUxBTUFPQVFBUwFVAVcBV4AYwVeAGsFcwV7BYMFiwWSBV4AmgWgBacFXgBeAF4AXgBeAKsFXgCyBbEFugW7BcIFwgXIBcIFwgXQBdQF3AXkBesF8wX7BQMGCwYTBhsGIwYrBjMGOwZeAD8GRwZNBl4AVAZbBl4AXgBeAF4AXgBeAF4AXgBeAF4AXgBeAGMGXgBqBnEGXgBeAF4AXgBeAF4AXgBeAF4AXgB5BoAG4wSGBo4GkwaAAIADHgR5AF4AXgBeAJsGgABGA4AAowarBrMGswagALsGwwbLBjAA0wbaBtoG3QbaBtoG2gbaBtoG2gblBusG8wb7BgMHCwcTBxsHCwcjBysHMAc1BzUHOgdCB9oGSgdSB1oHYAfaBloHaAfaBlIH2gbaBtoG2gbaBtoG2gbaBjUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHbQdeAF4ANQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQd1B30HNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B4MH2gaKB68EgACAAIAAgACAAIAAgACAAI8HlwdeAJ8HpweAAIAArwe3B14AXgC/B8UHygcwANAH2AfgB4AA6AfwBz4B+AcACFwBCAgPCBcIogEYAR8IJwiAAC8INwg/CCADRwhPCFcIXwhnCEoDGgSAAIAAgABvCHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIfQh3CHgIeQh6CHsIfAh9CHcIeAh5CHoIewh8CH0Idwh4CHkIegh7CHwIhAiLCI4IMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlggwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAANQc1BzUHNQc1BzUHNQc1BzUHNQc1B54INQc1B6II2gaqCLIIugiAAIAAvgjGCIAAgACAAIAAgACAAIAAgACAAIAAywiHAYAA0wiAANkI3QjlCO0I9Aj8CIAAgACAAAIJCgkSCRoJIgknCTYHLwk3CZYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiWCJYIlgiAAIAAAAFAAXgBeAGAAcABeAHwAQACQAKAArQC9AJ4AXgBeAE0A3gBRAN4A7AD8AMwBGgEAAKcBNwEFAUwBXAF4QkhCmEKnArcCgAHHAsABz4LAAcABwAHAAd+C6ABoAG+C/4LAAcABwAHAAc+DF4MAAcAB54M3gweDV4Nng3eDaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAEeDqABVg6WDqABoQ6gAaABoAHXDvcONw/3DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DvcO9w73DncPAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcAB7cPPwlGCU4JMACAAIAAgABWCV4JYQmAAGkJcAl4CXwJgAkwADAAMAAwAIgJgACLCZMJgACZCZ8JowmrCYAAswkwAF4AXgB8AIAAuwkABMMJyQmAAM4JgADVCTAAMAAwADAAgACAAIAAgACAAIAAgACAAIAAqwYWBNkIMAAwADAAMADdCeAJ6AnuCR4E9gkwAP4JBQoNCjAAMACAABUK0wiAAB0KJAosCjQKgAAwADwKQwqAAEsKvQmdCVMKWwowADAAgACAALcEMACAAGMKgABrCjAAMAAwADAAMAAwADAAMAAwADAAMAAeBDAAMAAwADAAMAAwADAAMAAwADAAMAAwAIkEPQFzCnoKiQSCCooKkAqJBJgKoAqkCokEGAGsCrQKvArBCjAAMADJCtEKFQHZCuEK/gHpCvEKMAAwADAAMACAAIwE+QowAIAAPwEBCzAAMAAwADAAMACAAAkLEQswAIAAPwEZCyELgAAOCCkLMAAxCzkLMAAwADAAMAAwADAAXgBeAEELMAAwADAAMAAwADAAMAAwAEkLTQtVC4AAXAtkC4AAiQkwADAAMAAwADAAMAAwADAAbAtxC3kLgAuFC4sLMAAwAJMLlwufCzAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAApwswADAAMACAAIAAgACvC4AAgACAAIAAgACAALcLMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAvwuAAMcLgACAAIAAgACAAIAAyguAAIAAgACAAIAA0QswADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAANkLgACAAIAA4AswADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACJCR4E6AswADAAhwHwC4AA+AsADAgMEAwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMACAAIAAGAwdDCUMMAAwAC0MNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQw1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHPQwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADUHNQc1BzUHNQc1BzUHNQc2BzAAMAA5DDUHNQc1BzUHNQc1BzUHNQc1BzUHNQdFDDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAgACAAIAATQxSDFoMMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAF4AXgBeAF4AXgBeAF4AYgxeAGoMXgBxDHkMfwxeAIUMXgBeAI0MMAAwADAAMAAwAF4AXgCVDJ0MMAAwADAAMABeAF4ApQxeAKsMswy7DF4Awgy9DMoMXgBeAF4AXgBeAF4AXgBeAF4AXgDRDNkMeQBqCeAM3Ax8AOYM7Az0DPgMXgBeAF4AXgBeAF4AXgBeAF4AXgBeAF4AXgBeAF4AXgCgAAANoAAHDQ4NFg0wADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAeDSYNMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIAAgACAAIAAgACAAC4NMABeAF4ANg0wADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAD4NRg1ODVYNXg1mDTAAbQ0wADAAMAAwADAAMAAwADAA2gbaBtoG2gbaBtoG2gbaBnUNeg3CBYANwgWFDdoGjA3aBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gaUDZwNpA2oDdoG2gawDbcNvw3HDdoG2gbPDdYN3A3fDeYN2gbsDfMN2gbaBvoN/g3aBgYODg7aBl4AXgBeABYOXgBeACUG2gYeDl4AJA5eACwO2w3aBtoGMQ45DtoG2gbaBtoGQQ7aBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gZJDjUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B1EO2gY1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQdZDjUHNQc1BzUHNQc1B2EONQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHaA41BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B3AO2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gY1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1BzUHNQc1B2EO2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gZJDtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBtoG2gbaBkkOeA6gAKAAoAAwADAAMAAwAKAAoACgAKAAoACgAKAAgA4wADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAD//wQABAAEAAQABAAEAAQABAAEAA0AAwABAAEAAgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAKABMAFwAeABsAGgAeABcAFgASAB4AGwAYAA8AGAAcAEsASwBLAEsASwBLAEsASwBLAEsAGAAYAB4AHgAeABMAHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAFgAbABIAHgAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYADQARAB4ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAUABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkAFgAaABsAGwAbAB4AHQAdAB4ATwAXAB4ADQAeAB4AGgAbAE8ATwAOAFAAHQAdAB0ATwBPABcATwBPAE8AFgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAFAATwBAAE8ATwBPAEAATwBQAFAATwBQAB4AHgAeAB4AHgAeAB0AHQAdAB0AHgAdAB4ADgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgBQAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkACQAJAAkACQAJAAkABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAFAAHgAeAB4AKwArAFAAUABQAFAAGABQACsAKwArACsAHgAeAFAAHgBQAFAAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUAAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAYAA0AKwArAB4AHgAbACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAB4ABAAEAB4ABAAEABMABAArACsAKwArACsAKwArACsAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAKwArACsAKwArAFYAVgBWAB4AHgArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AGgAaABoAGAAYAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQAEwAEACsAEwATAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABLAEsASwBLAEsASwBLAEsASwBLABoAGQAZAB4AUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABMAUAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABABQAFAABAAEAB4ABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUAAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAFAABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQAUABQAB4AHgAYABMAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAFAABAAEAAQABAAEAFAABAAEAAQAUAAEAAQABAAEAAQAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArACsAHgArAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAAQABAANAA0ASwBLAEsASwBLAEsASwBLAEsASwAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAKwArACsAUABQAFAAUAArACsABABQAAQABAAEAAQABAAEAAQAKwArAAQABAArACsABAAEAAQAUAArACsAKwArACsAKwArACsABAArACsAKwArAFAAUAArAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAGgAaAFAAUABQAFAAUABMAB4AGwBQAB4AKwArACsABAAEAAQAKwBQAFAAUABQAFAAUAArACsAKwArAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUAArAFAAUAArACsABAArAAQABAAEAAQABAArACsAKwArAAQABAArACsABAAEAAQAKwArACsABAArACsAKwArACsAKwArAFAAUABQAFAAKwBQACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwAEAAQAUABQAFAABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUABQAFAAUAArACsABABQAAQABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQAKwArAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwAeABsAKwArACsAKwArACsAKwBQAAQABAAEAAQABAAEACsABAAEAAQAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwArAAQABAArACsABAAEAAQAKwArACsAKwArACsAKwArAAQABAArACsAKwArAFAAUAArAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwAeAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwAEAFAAKwBQAFAAUABQAFAAUAArACsAKwBQAFAAUAArAFAAUABQAFAAKwArACsAUABQACsAUAArAFAAUAArACsAKwBQAFAAKwArACsAUABQAFAAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAAQABAAEAAQAKwArACsABAAEAAQAKwAEAAQABAAEACsAKwBQACsAKwArACsAKwArAAQAKwArACsAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAB4AHgAeAB4AHgAeABsAHgArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABAArACsAKwArACsAKwArAAQABAArAFAAUABQACsAKwArACsAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAB4AUAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABAArACsAKwArACsAKwArAAQABAArACsAKwArACsAKwArAFAAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABABQAB4AKwArACsAKwBQAFAAUAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQABoAUABQAFAAUABQAFAAKwArAAQABAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQACsAUAArACsAUABQAFAAUABQAFAAUAArACsAKwAEACsAKwArACsABAAEAAQABAAEAAQAKwAEACsABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgAqACsAKwArACsAGwBcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAeAEsASwBLAEsASwBLAEsASwBLAEsADQANACsAKwArACsAKwBcAFwAKwBcACsAKwBcAFwAKwBcACsAKwBcACsAKwArACsAKwArAFwAXABcAFwAKwBcAFwAXABcAFwAXABcACsAXABcAFwAKwBcACsAXAArACsAXABcACsAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgArACoAKgBcACsAKwBcAFwAXABcAFwAKwBcACsAKgAqACoAKgAqACoAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAFwAXABcAFwAUAAOAA4ADgAOAB4ADgAOAAkADgAOAA0ACQATABMAEwATABMACQAeABMAHgAeAB4ABAAEAB4AHgAeAB4AHgAeAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUAANAAQAHgAEAB4ABAAWABEAFgARAAQABABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAAQABAAEAAQABAANAAQABABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsADQANAB4AHgAeAB4AHgAeAAQAHgAeAB4AHgAeAB4AKwAeAB4ADgAOAA0ADgAeAB4AHgAeAB4ACQAJACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqAFwASwBLAEsASwBLAEsASwBLAEsASwANAA0AHgAeAB4AHgBcAFwAXABcAFwAXAAqACoAKgAqAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAKgAqACoAKgAqACoAKgBcAFwAXAAqACoAKgAqAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAXAAqAEsASwBLAEsASwBLAEsASwBLAEsAKgAqACoAKgAqACoAUABQAFAAUABQAFAAKwBQACsAKwArACsAKwBQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQACsAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwAEAAQABAAeAA0AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYAEQArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAADQANAA0AUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAA0ADQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQACsABAAEACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoADQANABUAXAANAB4ADQAbAFwAKgArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAB4AHgATABMADQANAA4AHgATABMAHgAEAAQABAAJACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAUABQAFAAUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwAeACsAKwArABMAEwBLAEsASwBLAEsASwBLAEsASwBLAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwBcAFwAXABcAFwAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBcACsAKwArACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEACsAKwAeAB4AXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgArACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgArACsABABLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKgAqACoAKgAqACoAKgBcACoAKgAqACoAKgAqACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAUABQAFAAUABQAFAAUAArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsADQANAB4ADQANAA0ADQAeAB4AHgAeAB4AHgAeAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAHgAeAB4AHgBQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwANAA0ADQANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwBQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAA0AUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsABAAEAAQAHgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAUABQAFAABABQAFAAUABQAAQABAAEAFAAUAAEAAQABAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAKwBQACsAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAHgAeAB4AHgAeAB4AHgAeAFAAHgAeAB4AUABQAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAKwArAB4AHgAeAB4AHgAeACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAUABQAFAAKwAeAB4AHgAeAB4AHgAeAA4AHgArAA0ADQANAA0ADQANAA0ACQANAA0ADQAIAAQACwAEAAQADQAJAA0ADQAMAB0AHQAeABcAFwAWABcAFwAXABYAFwAdAB0AHgAeABQAFAAUAA0AAQABAAQABAAEAAQABAAJABoAGgAaABoAGgAaABoAGgAeABcAFwAdABUAFQAeAB4AHgAeAB4AHgAYABYAEQAVABUAFQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgANAB4ADQANAA0ADQAeAA0ADQANAAcAHgAeAB4AHgArAAQABAAEAAQABAAEAAQABAAEAAQAUABQACsAKwBPAFAAUABQAFAAUAAeAB4AHgAWABEATwBQAE8ATwBPAE8AUABQAFAAUABQAB4AHgAeABYAEQArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAGwAbABsAGwAbABsAGwAaABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAaABsAGwAbABsAGgAbABsAGgAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgBQABoAHgAdAB4AUAAeABoAHgAeAB4AHgAeAB4AHgAeAB4ATwAeAFAAGwAeAB4AUABQAFAAUABQAB4AHgAeAB0AHQAeAFAAHgBQAB4AUAAeAFAATwBQAFAAHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AUABQAFAAUABPAE8AUABQAFAAUABQAE8AUABQAE8AUABPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBQAFAAUABQAE8ATwBPAE8ATwBPAE8ATwBPAE8AUABQAFAAUABQAFAAUABQAFAAHgAeAFAAUABQAFAATwAeAB4AKwArACsAKwAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB0AHQAeAB4AHgAdAB0AHgAeAB0AHgAeAB4AHQAeAB0AGwAbAB4AHQAeAB4AHgAeAB0AHgAeAB0AHQAdAB0AHgAeAB0AHgAdAB4AHQAdAB0AHQAdAB0AHgAdAB4AHgAeAB4AHgAdAB0AHQAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAdAB4AHgAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHgAdAB0AHQAdAB4AHgAdAB0AHgAeAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHQAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABQAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAlACUAHgAeAB4AHgAeAB4AHgAeAB4AFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBQAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeAB4AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAdAB0AHQAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAeAB4AHgAeAB0AHQAeAB4AHgAeAB0AHQAdAB4AHgAdAB4AHgAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB0AHQAeAB4AHQAeAB4AHgAeAB0AHQAeAB4AHgAeACUAJQAdAB0AJQAeACUAJQAlACAAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAHgAeAB4AHgAdAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHQAdAB0AHgAdACUAHQAdAB4AHQAdAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAHQAdAB0AHQAlAB4AJQAlACUAHQAlACUAHQAdAB0AJQAlAB0AHQAlAB0AHQAlACUAJQAeAB0AHgAeAB4AHgAdAB0AJQAdAB0AHQAdAB0AHQAlACUAJQAlACUAHQAlACUAIAAlAB0AHQAlACUAJQAlACUAJQAlACUAHgAeAB4AJQAlACAAIAAgACAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeABcAFwAXABcAFwAXAB4AEwATACUAHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAWABEAFgARAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAeAB4AKwArACsAKwArABMADQANAA0AUAATAA0AUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUAANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAA0ADQANAA0ADQANAA0ADQAeAA0AFgANAB4AHgAXABcAHgAeABcAFwAWABEAFgARABYAEQAWABEADQANAA0ADQATAFAADQANAB4ADQANAB4AHgAeAB4AHgAMAAwADQANAA0AHgANAA0AFgANAA0ADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArAA0AEQARACUAJQBHAFcAVwAWABEAFgARABYAEQAWABEAFgARACUAJQAWABEAFgARABYAEQAWABEAFQAWABEAEQAlAFcAVwBXAFcAVwBXAFcAVwBXAAQABAAEAAQABAAEACUAVwBXAFcAVwA2ACUAJQBXAFcAVwBHAEcAJQAlACUAKwBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBRAFcAUQBXAFEAVwBXAFcAVwBXAFcAUQBXAFcAVwBXAFcAVwBRAFEAKwArAAQABAAVABUARwBHAFcAFQBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBRAFcAVwBXAFcAVwBXAFEAUQBXAFcAVwBXABUAUQBHAEcAVwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwArACUAJQBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAKwArACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAE8ATwBPAE8ATwBPAE8ATwAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADQATAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQAHgBQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAeAA0ADQANAA0ADQArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAAQAUABQAFAABABQAFAAUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAeAB4AHgAeACsAKwArACsAUABQAFAAUABQAFAAHgAeABoAHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADgAOABMAEwArACsAKwArACsAKwArACsABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUAAeAB4AHgBQAA4AUAArACsAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAB4AWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYACsAKwArAAQAHgAeAB4AHgAeAB4ADQANAA0AHgAeAB4AHgArAFAASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArAB4AHgBcAFwAXABcAFwAKgBcAFwAXABcAFwAXABcAFwAXABcAEsASwBLAEsASwBLAEsASwBLAEsAXABcAFwAXABcACsAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAFAAUABQAAQAUABQAFAAUABQAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAHgANAA0ADQBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAKgAqACoAXABcACoAKgBcAFwAXABcAFwAKgAqAFwAKgBcACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAA0ADQBQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQADQAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAVABVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBUAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVACsAKwArACsAKwArACsAKwArACsAKwArAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAKwArACsAKwBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAKwArACsAKwAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArACsAKwArAFYABABWAFYAVgBWAFYAVgBWAFYAVgBWAB4AVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgArAFYAVgBWAFYAVgArAFYAKwBWAFYAKwBWAFYAKwBWAFYAVgBWAFYAVgBWAFYAVgBWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAEQAWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAaAB4AKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAGAARABEAGAAYABMAEwAWABEAFAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACUAJQAlACUAJQAWABEAFgARABYAEQAWABEAFgARABYAEQAlACUAFgARACUAJQAlACUAJQAlACUAEQAlABEAKwAVABUAEwATACUAFgARABYAEQAWABEAJQAlACUAJQAlACUAJQAlACsAJQAbABoAJQArACsAKwArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAcAKwATACUAJQAbABoAJQAlABYAEQAlACUAEQAlABEAJQBXAFcAVwBXAFcAVwBXAFcAVwBXABUAFQAlACUAJQATACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXABYAJQARACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAWACUAEQAlABYAEQARABYAEQARABUAVwBRAFEAUQBRAFEAUQBRAFEAUQBRAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcARwArACsAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXACsAKwBXAFcAVwBXAFcAVwArACsAVwBXAFcAKwArACsAGgAbACUAJQAlABsAGwArAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAAQAB0AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsADQANAA0AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQBQAFAAUABQACsAKwArACsAUABQAFAAUABQAFAAUABQAA0AUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQACsAKwArAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgBQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwBQAFAAUABQAFAABAAEAAQAKwAEAAQAKwArACsAKwArAAQABAAEAAQAUABQAFAAUAArAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsABAAEAAQAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsADQANAA0ADQANAA0ADQANAB4AKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AUABQAFAAUABQAFAAUABQAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwArACsAUABQAFAAUABQAA0ADQANAA0ADQANABQAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwANAA0ADQANAA0ADQANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQAeAB4AHgAeAB4AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsASwBLAEsASwBLAEsASwBLAEsASwANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAeAA4AUAArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAADQANAB4ADQAeAAQABAAEAB4AKwArAEsASwBLAEsASwBLAEsASwBLAEsAUAAOAFAADQANAA0AKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAA0AHgANAA0AHgAEACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAA0AKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAUAArACsAKwArACsAKwAEACsAKwArACsAKwBQAFAAUABQAFAABAAEACsAKwAEAAQABAAEAAQABAAEACsAKwArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABABQAFAAUABQAA0ADQANAA0AHgBLAEsASwBLAEsASwBLAEsASwBLACsADQArAB4AKwArAAQABAAEAAQAUABQAB4AUAArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEACsAKwAEAAQABAAEAAQABAAEAAQABAAOAA0ADQATABMAHgAeAB4ADQANAA0ADQANAA0ADQANAA0ADQANAA0ADQANAA0AUABQAFAAUAAEAAQAKwArAAQADQANAB4AUAArACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAKwAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAXABcAA0ADQANACoASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAOAB4ADQANAA0ADQAOAB4ABAArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAFAAUAArACsAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAA0ADQANACsADgAOAA4ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAFAADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAOABMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAArACsAKwAEACsABAAEACsABAAEAAQABAAEAAQABABQAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABIAEgAQwBDAEMAUABQAFAAUABDAFAAUABQAEgAQwBIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABDAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwANAA0AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAANACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQANAB4AHgAeAB4AHgAeAFAAUABQAFAADQAeACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEcARwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwArACsAKwArACsAKwArACsAKwArACsAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQACsAKwAeAAQABAANAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAHgAeAAQABAAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAEAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUAArACsAUAArACsAUABQACsAKwBQAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQACsAUABQAFAAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwAeAB4AUABQAFAAUABQACsAUAArACsAKwBQAFAAUABQAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AKwArAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAEAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAeAB4ADQANAA0ADQAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABAArAAQABAArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAEAAQABAAEAAQABAAEACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAFgAWAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArAFAAKwArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArAFAAKwBQACsAKwArACsAKwArAFAAKwArACsAKwBQACsAUAArAFAAKwBQAFAAUAArAFAAUAArAFAAKwArAFAAKwBQACsAUAArAFAAKwBQACsAUABQACsAUAArACsAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAUABQAFAAUAArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwBQAFAAUAArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAlACUAJQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeACUAJQAlACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeACUAJQAlACUAJQAeACUAJQAlACUAJQAgACAAIAAlACUAIAAlACUAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIQAhACEAIQAhACUAJQAgACAAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAgACAAIAAlACUAJQAlACAAJQAgACAAIAAgACAAIAAgACAAIAAlACUAJQAgACUAJQAlACUAIAAgACAAJQAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeACUAHgAlAB4AJQAlACUAJQAlACAAJQAlACUAJQAeACUAHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAgACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAlACUAJQAlACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAIAAgACAAJQAlACUAIAAgACAAIAAgAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFwAXABcAFQAVABUAHgAeAB4AHgAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAIAAgACAAJQAlACUAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAlACAAIAAlACUAJQAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAIAAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsA';
  50559. /* @flow */
  50560. var LETTER_NUMBER_MODIFIER = 50;
  50561. // Non-tailorable Line Breaking Classes
  50562. var BK = 1; // Cause a line break (after)
  50563. var CR = 2; // Cause a line break (after), except between CR and LF
  50564. var LF = 3; // Cause a line break (after)
  50565. var CM = 4; // Prohibit a line break between the character and the preceding character
  50566. var NL = 5; // Cause a line break (after)
  50567. var WJ = 7; // Prohibit line breaks before and after
  50568. var ZW = 8; // Provide a break opportunity
  50569. var GL = 9; // Prohibit line breaks before and after
  50570. var SP = 10; // Enable indirect line breaks
  50571. var ZWJ = 11; // Prohibit line breaks within joiner sequences
  50572. // Break Opportunities
  50573. var B2 = 12; // Provide a line break opportunity before and after the character
  50574. var BA = 13; // Generally provide a line break opportunity after the character
  50575. var BB = 14; // Generally provide a line break opportunity before the character
  50576. var HY = 15; // Provide a line break opportunity after the character, except in numeric context
  50577. var CB = 16; // Provide a line break opportunity contingent on additional information
  50578. // Characters Prohibiting Certain Breaks
  50579. var CL = 17; // Prohibit line breaks before
  50580. var CP = 18; // Prohibit line breaks before
  50581. var EX = 19; // Prohibit line breaks before
  50582. var IN = 20; // Allow only indirect line breaks between pairs
  50583. var NS = 21; // Allow only indirect line breaks before
  50584. var OP = 22; // Prohibit line breaks after
  50585. var QU = 23; // Act like they are both opening and closing
  50586. // Numeric Context
  50587. var IS = 24; // Prevent breaks after any and before numeric
  50588. var NU = 25; // Form numeric expressions for line breaking purposes
  50589. var PO = 26; // Do not break following a numeric expression
  50590. var PR = 27; // Do not break in front of a numeric expression
  50591. var SY = 28; // Prevent a break before; and allow a break after
  50592. // Other Characters
  50593. var AI = 29; // Act like AL when the resolvedEAW is N; otherwise; act as ID
  50594. var AL = 30; // Are alphabetic characters or symbols that are used with alphabetic characters
  50595. var CJ = 31; // Treat as NS or ID for strict or normal breaking.
  50596. var EB = 32; // Do not break from following Emoji Modifier
  50597. var EM = 33; // Do not break from preceding Emoji Base
  50598. var H2 = 34; // Form Korean syllable blocks
  50599. var H3 = 35; // Form Korean syllable blocks
  50600. var HL = 36; // Do not break around a following hyphen; otherwise act as Alphabetic
  50601. var ID = 37; // Break before or after; except in some numeric context
  50602. var JL = 38; // Form Korean syllable blocks
  50603. var JV = 39; // Form Korean syllable blocks
  50604. var JT = 40; // Form Korean syllable blocks
  50605. var RI = 41; // Keep pairs together. For pairs; break before and after other classes
  50606. var SA = 42; // Provide a line break opportunity contingent on additional, language-specific context analysis
  50607. var XX = 43; // Have as yet unknown line breaking behavior or unassigned code positions
  50608. var BREAK_MANDATORY = '!';
  50609. var BREAK_NOT_ALLOWED = '×';
  50610. var BREAK_ALLOWED = '÷';
  50611. var UnicodeTrie = createTrieFromBase64(base64);
  50612. var ALPHABETICS = [AL, HL];
  50613. var HARD_LINE_BREAKS = [BK, CR, LF, NL];
  50614. var SPACE = [SP, ZW];
  50615. var PREFIX_POSTFIX = [PR, PO];
  50616. var LINE_BREAKS = HARD_LINE_BREAKS.concat(SPACE);
  50617. var KOREAN_SYLLABLE_BLOCK = [JL, JV, JT, H2, H3];
  50618. var HYPHEN = [HY, BA];
  50619. var codePointsToCharacterClasses = function (codePoints, lineBreak) {
  50620. if (lineBreak === void 0) { lineBreak = 'strict'; }
  50621. var types = [];
  50622. var indicies = [];
  50623. var categories = [];
  50624. codePoints.forEach(function (codePoint, index) {
  50625. var classType = UnicodeTrie.get(codePoint);
  50626. if (classType > LETTER_NUMBER_MODIFIER) {
  50627. categories.push(true);
  50628. classType -= LETTER_NUMBER_MODIFIER;
  50629. }
  50630. else {
  50631. categories.push(false);
  50632. }
  50633. if (['normal', 'auto', 'loose'].indexOf(lineBreak) !== -1) {
  50634. // U+2010, – U+2013, 〜 U+301C, ゠ U+30A0
  50635. if ([0x2010, 0x2013, 0x301c, 0x30a0].indexOf(codePoint) !== -1) {
  50636. indicies.push(index);
  50637. return types.push(CB);
  50638. }
  50639. }
  50640. if (classType === CM || classType === ZWJ) {
  50641. // LB10 Treat any remaining combining mark or ZWJ as AL.
  50642. if (index === 0) {
  50643. indicies.push(index);
  50644. return types.push(AL);
  50645. }
  50646. // LB9 Do not break a combining character sequence; treat it as if it has the line breaking class of
  50647. // the base character in all of the following rules. Treat ZWJ as if it were CM.
  50648. var prev = types[index - 1];
  50649. if (LINE_BREAKS.indexOf(prev) === -1) {
  50650. indicies.push(indicies[index - 1]);
  50651. return types.push(prev);
  50652. }
  50653. indicies.push(index);
  50654. return types.push(AL);
  50655. }
  50656. indicies.push(index);
  50657. if (classType === CJ) {
  50658. return types.push(lineBreak === 'strict' ? NS : ID);
  50659. }
  50660. if (classType === SA) {
  50661. return types.push(AL);
  50662. }
  50663. if (classType === AI) {
  50664. return types.push(AL);
  50665. }
  50666. // For supplementary characters, a useful default is to treat characters in the range 10000..1FFFD as AL
  50667. // and characters in the ranges 20000..2FFFD and 30000..3FFFD as ID, until the implementation can be revised
  50668. // to take into account the actual line breaking properties for these characters.
  50669. if (classType === XX) {
  50670. if ((codePoint >= 0x20000 && codePoint <= 0x2fffd) || (codePoint >= 0x30000 && codePoint <= 0x3fffd)) {
  50671. return types.push(ID);
  50672. }
  50673. else {
  50674. return types.push(AL);
  50675. }
  50676. }
  50677. types.push(classType);
  50678. });
  50679. return [indicies, types, categories];
  50680. };
  50681. var isAdjacentWithSpaceIgnored = function (a, b, currentIndex, classTypes) {
  50682. var current = classTypes[currentIndex];
  50683. if (Array.isArray(a) ? a.indexOf(current) !== -1 : a === current) {
  50684. var i = currentIndex;
  50685. while (i <= classTypes.length) {
  50686. i++;
  50687. var next = classTypes[i];
  50688. if (next === b) {
  50689. return true;
  50690. }
  50691. if (next !== SP) {
  50692. break;
  50693. }
  50694. }
  50695. }
  50696. if (current === SP) {
  50697. var i = currentIndex;
  50698. while (i > 0) {
  50699. i--;
  50700. var prev = classTypes[i];
  50701. if (Array.isArray(a) ? a.indexOf(prev) !== -1 : a === prev) {
  50702. var n = currentIndex;
  50703. while (n <= classTypes.length) {
  50704. n++;
  50705. var next = classTypes[n];
  50706. if (next === b) {
  50707. return true;
  50708. }
  50709. if (next !== SP) {
  50710. break;
  50711. }
  50712. }
  50713. }
  50714. if (prev !== SP) {
  50715. break;
  50716. }
  50717. }
  50718. }
  50719. return false;
  50720. };
  50721. var previousNonSpaceClassType = function (currentIndex, classTypes) {
  50722. var i = currentIndex;
  50723. while (i >= 0) {
  50724. var type = classTypes[i];
  50725. if (type === SP) {
  50726. i--;
  50727. }
  50728. else {
  50729. return type;
  50730. }
  50731. }
  50732. return 0;
  50733. };
  50734. var _lineBreakAtIndex = function (codePoints, classTypes, indicies, index, forbiddenBreaks) {
  50735. if (indicies[index] === 0) {
  50736. return BREAK_NOT_ALLOWED;
  50737. }
  50738. var currentIndex = index - 1;
  50739. if (Array.isArray(forbiddenBreaks) && forbiddenBreaks[currentIndex] === true) {
  50740. return BREAK_NOT_ALLOWED;
  50741. }
  50742. var beforeIndex = currentIndex - 1;
  50743. var afterIndex = currentIndex + 1;
  50744. var current = classTypes[currentIndex];
  50745. // LB4 Always break after hard line breaks.
  50746. // LB5 Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks.
  50747. var before = beforeIndex >= 0 ? classTypes[beforeIndex] : 0;
  50748. var next = classTypes[afterIndex];
  50749. if (current === CR && next === LF) {
  50750. return BREAK_NOT_ALLOWED;
  50751. }
  50752. if (HARD_LINE_BREAKS.indexOf(current) !== -1) {
  50753. return BREAK_MANDATORY;
  50754. }
  50755. // LB6 Do not break before hard line breaks.
  50756. if (HARD_LINE_BREAKS.indexOf(next) !== -1) {
  50757. return BREAK_NOT_ALLOWED;
  50758. }
  50759. // LB7 Do not break before spaces or zero width space.
  50760. if (SPACE.indexOf(next) !== -1) {
  50761. return BREAK_NOT_ALLOWED;
  50762. }
  50763. // LB8 Break before any character following a zero-width space, even if one or more spaces intervene.
  50764. if (previousNonSpaceClassType(currentIndex, classTypes) === ZW) {
  50765. return BREAK_ALLOWED;
  50766. }
  50767. // LB8a Do not break between a zero width joiner and an ideograph, emoji base or emoji modifier.
  50768. if (UnicodeTrie.get(codePoints[currentIndex]) === ZWJ && (next === ID || next === EB || next === EM)) {
  50769. return BREAK_NOT_ALLOWED;
  50770. }
  50771. // LB11 Do not break before or after Word joiner and related characters.
  50772. if (current === WJ || next === WJ) {
  50773. return BREAK_NOT_ALLOWED;
  50774. }
  50775. // LB12 Do not break after NBSP and related characters.
  50776. if (current === GL) {
  50777. return BREAK_NOT_ALLOWED;
  50778. }
  50779. // LB12a Do not break before NBSP and related characters, except after spaces and hyphens.
  50780. if ([SP, BA, HY].indexOf(current) === -1 && next === GL) {
  50781. return BREAK_NOT_ALLOWED;
  50782. }
  50783. // LB13 Do not break before ‘]’ or ‘!’ or ‘;’ or ‘/’, even after spaces.
  50784. if ([CL, CP, EX, IS, SY].indexOf(next) !== -1) {
  50785. return BREAK_NOT_ALLOWED;
  50786. }
  50787. // LB14 Do not break after ‘[’, even after spaces.
  50788. if (previousNonSpaceClassType(currentIndex, classTypes) === OP) {
  50789. return BREAK_NOT_ALLOWED;
  50790. }
  50791. // LB15 Do not break within ‘”[’, even with intervening spaces.
  50792. if (isAdjacentWithSpaceIgnored(QU, OP, currentIndex, classTypes)) {
  50793. return BREAK_NOT_ALLOWED;
  50794. }
  50795. // LB16 Do not break between closing punctuation and a nonstarter (lb=NS), even with intervening spaces.
  50796. if (isAdjacentWithSpaceIgnored([CL, CP], NS, currentIndex, classTypes)) {
  50797. return BREAK_NOT_ALLOWED;
  50798. }
  50799. // LB17 Do not break within ‘——’, even with intervening spaces.
  50800. if (isAdjacentWithSpaceIgnored(B2, B2, currentIndex, classTypes)) {
  50801. return BREAK_NOT_ALLOWED;
  50802. }
  50803. // LB18 Break after spaces.
  50804. if (current === SP) {
  50805. return BREAK_ALLOWED;
  50806. }
  50807. // LB19 Do not break before or after quotation marks, such as ‘ ” ’.
  50808. if (current === QU || next === QU) {
  50809. return BREAK_NOT_ALLOWED;
  50810. }
  50811. // LB20 Break before and after unresolved CB.
  50812. if (next === CB || current === CB) {
  50813. return BREAK_ALLOWED;
  50814. }
  50815. // LB21 Do not break before hyphen-minus, other hyphens, fixed-width spaces, small kana, and other non-starters, or after acute accents.
  50816. if ([BA, HY, NS].indexOf(next) !== -1 || current === BB) {
  50817. return BREAK_NOT_ALLOWED;
  50818. }
  50819. // LB21a Don't break after Hebrew + Hyphen.
  50820. if (before === HL && HYPHEN.indexOf(current) !== -1) {
  50821. return BREAK_NOT_ALLOWED;
  50822. }
  50823. // LB21b Don’t break between Solidus and Hebrew letters.
  50824. if (current === SY && next === HL) {
  50825. return BREAK_NOT_ALLOWED;
  50826. }
  50827. // LB22 Do not break between two ellipses, or between letters, numbers or exclamations and ellipsis.
  50828. if (next === IN && ALPHABETICS.concat(IN, EX, NU, ID, EB, EM).indexOf(current) !== -1) {
  50829. return BREAK_NOT_ALLOWED;
  50830. }
  50831. // LB23 Do not break between digits and letters.
  50832. if ((ALPHABETICS.indexOf(next) !== -1 && current === NU) || (ALPHABETICS.indexOf(current) !== -1 && next === NU)) {
  50833. return BREAK_NOT_ALLOWED;
  50834. }
  50835. // LB23a Do not break between numeric prefixes and ideographs, or between ideographs and numeric postfixes.
  50836. if ((current === PR && [ID, EB, EM].indexOf(next) !== -1) ||
  50837. ([ID, EB, EM].indexOf(current) !== -1 && next === PO)) {
  50838. return BREAK_NOT_ALLOWED;
  50839. }
  50840. // LB24 Do not break between numeric prefix/postfix and letters, or between letters and prefix/postfix.
  50841. if ((ALPHABETICS.indexOf(current) !== -1 && PREFIX_POSTFIX.indexOf(next) !== -1) ||
  50842. (PREFIX_POSTFIX.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1)) {
  50843. return BREAK_NOT_ALLOWED;
  50844. }
  50845. // LB25 Do not break between the following pairs of classes relevant to numbers:
  50846. if (
  50847. // (PR | PO) × ( OP | HY )? NU
  50848. ([PR, PO].indexOf(current) !== -1 &&
  50849. (next === NU || ([OP, HY].indexOf(next) !== -1 && classTypes[afterIndex + 1] === NU))) ||
  50850. // ( OP | HY ) × NU
  50851. ([OP, HY].indexOf(current) !== -1 && next === NU) ||
  50852. // NU × (NU | SY | IS)
  50853. (current === NU && [NU, SY, IS].indexOf(next) !== -1)) {
  50854. return BREAK_NOT_ALLOWED;
  50855. }
  50856. // NU (NU | SY | IS)* × (NU | SY | IS | CL | CP)
  50857. if ([NU, SY, IS, CL, CP].indexOf(next) !== -1) {
  50858. var prevIndex = currentIndex;
  50859. while (prevIndex >= 0) {
  50860. var type = classTypes[prevIndex];
  50861. if (type === NU) {
  50862. return BREAK_NOT_ALLOWED;
  50863. }
  50864. else if ([SY, IS].indexOf(type) !== -1) {
  50865. prevIndex--;
  50866. }
  50867. else {
  50868. break;
  50869. }
  50870. }
  50871. }
  50872. // NU (NU | SY | IS)* (CL | CP)? × (PO | PR))
  50873. if ([PR, PO].indexOf(next) !== -1) {
  50874. var prevIndex = [CL, CP].indexOf(current) !== -1 ? beforeIndex : currentIndex;
  50875. while (prevIndex >= 0) {
  50876. var type = classTypes[prevIndex];
  50877. if (type === NU) {
  50878. return BREAK_NOT_ALLOWED;
  50879. }
  50880. else if ([SY, IS].indexOf(type) !== -1) {
  50881. prevIndex--;
  50882. }
  50883. else {
  50884. break;
  50885. }
  50886. }
  50887. }
  50888. // LB26 Do not break a Korean syllable.
  50889. if ((JL === current && [JL, JV, H2, H3].indexOf(next) !== -1) ||
  50890. ([JV, H2].indexOf(current) !== -1 && [JV, JT].indexOf(next) !== -1) ||
  50891. ([JT, H3].indexOf(current) !== -1 && next === JT)) {
  50892. return BREAK_NOT_ALLOWED;
  50893. }
  50894. // LB27 Treat a Korean Syllable Block the same as ID.
  50895. if ((KOREAN_SYLLABLE_BLOCK.indexOf(current) !== -1 && [IN, PO].indexOf(next) !== -1) ||
  50896. (KOREAN_SYLLABLE_BLOCK.indexOf(next) !== -1 && current === PR)) {
  50897. return BREAK_NOT_ALLOWED;
  50898. }
  50899. // LB28 Do not break between alphabetics (“at”).
  50900. if (ALPHABETICS.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) {
  50901. return BREAK_NOT_ALLOWED;
  50902. }
  50903. // LB29 Do not break between numeric punctuation and alphabetics (“e.g.”).
  50904. if (current === IS && ALPHABETICS.indexOf(next) !== -1) {
  50905. return BREAK_NOT_ALLOWED;
  50906. }
  50907. // LB30 Do not break between letters, numbers, or ordinary symbols and opening or closing parentheses.
  50908. if ((ALPHABETICS.concat(NU).indexOf(current) !== -1 && next === OP) ||
  50909. (ALPHABETICS.concat(NU).indexOf(next) !== -1 && current === CP)) {
  50910. return BREAK_NOT_ALLOWED;
  50911. }
  50912. // LB30a Break between two regional indicator symbols if and only if there are an even number of regional
  50913. // indicators preceding the position of the break.
  50914. if (current === RI && next === RI) {
  50915. var i = indicies[currentIndex];
  50916. var count = 1;
  50917. while (i > 0) {
  50918. i--;
  50919. if (classTypes[i] === RI) {
  50920. count++;
  50921. }
  50922. else {
  50923. break;
  50924. }
  50925. }
  50926. if (count % 2 !== 0) {
  50927. return BREAK_NOT_ALLOWED;
  50928. }
  50929. }
  50930. // LB30b Do not break between an emoji base and an emoji modifier.
  50931. if (current === EB && next === EM) {
  50932. return BREAK_NOT_ALLOWED;
  50933. }
  50934. return BREAK_ALLOWED;
  50935. };
  50936. var cssFormattedClasses = function (codePoints, options) {
  50937. if (!options) {
  50938. options = { lineBreak: 'normal', wordBreak: 'normal' };
  50939. }
  50940. var _a = codePointsToCharacterClasses(codePoints, options.lineBreak), indicies = _a[0], classTypes = _a[1], isLetterNumber = _a[2];
  50941. if (options.wordBreak === 'break-all' || options.wordBreak === 'break-word') {
  50942. classTypes = classTypes.map(function (type) { return ([NU, AL, SA].indexOf(type) !== -1 ? ID : type); });
  50943. }
  50944. var forbiddenBreakpoints = options.wordBreak === 'keep-all'
  50945. ? isLetterNumber.map(function (letterNumber, i) {
  50946. return letterNumber && codePoints[i] >= 0x4e00 && codePoints[i] <= 0x9fff;
  50947. })
  50948. : undefined;
  50949. return [indicies, classTypes, forbiddenBreakpoints];
  50950. };
  50951. var Break = /** @class */ (function () {
  50952. function Break(codePoints, lineBreak, start, end) {
  50953. this.codePoints = codePoints;
  50954. this.required = lineBreak === BREAK_MANDATORY;
  50955. this.start = start;
  50956. this.end = end;
  50957. }
  50958. Break.prototype.slice = function () {
  50959. return fromCodePoint.apply(void 0, this.codePoints.slice(this.start, this.end));
  50960. };
  50961. return Break;
  50962. }());
  50963. var LineBreaker = function (str, options) {
  50964. var codePoints = toCodePoints(str);
  50965. var _a = cssFormattedClasses(codePoints, options), indicies = _a[0], classTypes = _a[1], forbiddenBreakpoints = _a[2];
  50966. var length = codePoints.length;
  50967. var lastEnd = 0;
  50968. var nextIndex = 0;
  50969. return {
  50970. next: function () {
  50971. if (nextIndex >= length) {
  50972. return { done: true, value: null };
  50973. }
  50974. var lineBreak = BREAK_NOT_ALLOWED;
  50975. while (nextIndex < length &&
  50976. (lineBreak = _lineBreakAtIndex(codePoints, classTypes, indicies, ++nextIndex, forbiddenBreakpoints)) ===
  50977. BREAK_NOT_ALLOWED) { }
  50978. if (lineBreak !== BREAK_NOT_ALLOWED || nextIndex === length) {
  50979. var value = new Break(codePoints, lineBreak, lastEnd, nextIndex);
  50980. lastEnd = nextIndex;
  50981. return { value: value, done: false };
  50982. }
  50983. return { done: true, value: null };
  50984. },
  50985. };
  50986. };
  50987. // https://www.w3.org/TR/css-syntax-3
  50988. var TokenType;
  50989. (function (TokenType) {
  50990. TokenType[TokenType["STRING_TOKEN"] = 0] = "STRING_TOKEN";
  50991. TokenType[TokenType["BAD_STRING_TOKEN"] = 1] = "BAD_STRING_TOKEN";
  50992. TokenType[TokenType["LEFT_PARENTHESIS_TOKEN"] = 2] = "LEFT_PARENTHESIS_TOKEN";
  50993. TokenType[TokenType["RIGHT_PARENTHESIS_TOKEN"] = 3] = "RIGHT_PARENTHESIS_TOKEN";
  50994. TokenType[TokenType["COMMA_TOKEN"] = 4] = "COMMA_TOKEN";
  50995. TokenType[TokenType["HASH_TOKEN"] = 5] = "HASH_TOKEN";
  50996. TokenType[TokenType["DELIM_TOKEN"] = 6] = "DELIM_TOKEN";
  50997. TokenType[TokenType["AT_KEYWORD_TOKEN"] = 7] = "AT_KEYWORD_TOKEN";
  50998. TokenType[TokenType["PREFIX_MATCH_TOKEN"] = 8] = "PREFIX_MATCH_TOKEN";
  50999. TokenType[TokenType["DASH_MATCH_TOKEN"] = 9] = "DASH_MATCH_TOKEN";
  51000. TokenType[TokenType["INCLUDE_MATCH_TOKEN"] = 10] = "INCLUDE_MATCH_TOKEN";
  51001. TokenType[TokenType["LEFT_CURLY_BRACKET_TOKEN"] = 11] = "LEFT_CURLY_BRACKET_TOKEN";
  51002. TokenType[TokenType["RIGHT_CURLY_BRACKET_TOKEN"] = 12] = "RIGHT_CURLY_BRACKET_TOKEN";
  51003. TokenType[TokenType["SUFFIX_MATCH_TOKEN"] = 13] = "SUFFIX_MATCH_TOKEN";
  51004. TokenType[TokenType["SUBSTRING_MATCH_TOKEN"] = 14] = "SUBSTRING_MATCH_TOKEN";
  51005. TokenType[TokenType["DIMENSION_TOKEN"] = 15] = "DIMENSION_TOKEN";
  51006. TokenType[TokenType["PERCENTAGE_TOKEN"] = 16] = "PERCENTAGE_TOKEN";
  51007. TokenType[TokenType["NUMBER_TOKEN"] = 17] = "NUMBER_TOKEN";
  51008. TokenType[TokenType["FUNCTION"] = 18] = "FUNCTION";
  51009. TokenType[TokenType["FUNCTION_TOKEN"] = 19] = "FUNCTION_TOKEN";
  51010. TokenType[TokenType["IDENT_TOKEN"] = 20] = "IDENT_TOKEN";
  51011. TokenType[TokenType["COLUMN_TOKEN"] = 21] = "COLUMN_TOKEN";
  51012. TokenType[TokenType["URL_TOKEN"] = 22] = "URL_TOKEN";
  51013. TokenType[TokenType["BAD_URL_TOKEN"] = 23] = "BAD_URL_TOKEN";
  51014. TokenType[TokenType["CDC_TOKEN"] = 24] = "CDC_TOKEN";
  51015. TokenType[TokenType["CDO_TOKEN"] = 25] = "CDO_TOKEN";
  51016. TokenType[TokenType["COLON_TOKEN"] = 26] = "COLON_TOKEN";
  51017. TokenType[TokenType["SEMICOLON_TOKEN"] = 27] = "SEMICOLON_TOKEN";
  51018. TokenType[TokenType["LEFT_SQUARE_BRACKET_TOKEN"] = 28] = "LEFT_SQUARE_BRACKET_TOKEN";
  51019. TokenType[TokenType["RIGHT_SQUARE_BRACKET_TOKEN"] = 29] = "RIGHT_SQUARE_BRACKET_TOKEN";
  51020. TokenType[TokenType["UNICODE_RANGE_TOKEN"] = 30] = "UNICODE_RANGE_TOKEN";
  51021. TokenType[TokenType["WHITESPACE_TOKEN"] = 31] = "WHITESPACE_TOKEN";
  51022. TokenType[TokenType["EOF_TOKEN"] = 32] = "EOF_TOKEN";
  51023. })(TokenType || (TokenType = {}));
  51024. var FLAG_UNRESTRICTED = 1 << 0;
  51025. var FLAG_ID = 1 << 1;
  51026. var FLAG_INTEGER = 1 << 2;
  51027. var FLAG_NUMBER = 1 << 3;
  51028. var LINE_FEED = 0x000a;
  51029. var SOLIDUS = 0x002f;
  51030. var REVERSE_SOLIDUS = 0x005c;
  51031. var CHARACTER_TABULATION = 0x0009;
  51032. var SPACE$1 = 0x0020;
  51033. var QUOTATION_MARK = 0x0022;
  51034. var EQUALS_SIGN = 0x003d;
  51035. var NUMBER_SIGN = 0x0023;
  51036. var DOLLAR_SIGN = 0x0024;
  51037. var PERCENTAGE_SIGN = 0x0025;
  51038. var APOSTROPHE = 0x0027;
  51039. var LEFT_PARENTHESIS = 0x0028;
  51040. var RIGHT_PARENTHESIS = 0x0029;
  51041. var LOW_LINE = 0x005f;
  51042. var HYPHEN_MINUS = 0x002d;
  51043. var EXCLAMATION_MARK = 0x0021;
  51044. var LESS_THAN_SIGN = 0x003c;
  51045. var GREATER_THAN_SIGN = 0x003e;
  51046. var COMMERCIAL_AT = 0x0040;
  51047. var LEFT_SQUARE_BRACKET = 0x005b;
  51048. var RIGHT_SQUARE_BRACKET = 0x005d;
  51049. var CIRCUMFLEX_ACCENT = 0x003d;
  51050. var LEFT_CURLY_BRACKET = 0x007b;
  51051. var QUESTION_MARK = 0x003f;
  51052. var RIGHT_CURLY_BRACKET = 0x007d;
  51053. var VERTICAL_LINE = 0x007c;
  51054. var TILDE = 0x007e;
  51055. var CONTROL = 0x0080;
  51056. var REPLACEMENT_CHARACTER = 0xfffd;
  51057. var ASTERISK = 0x002a;
  51058. var PLUS_SIGN = 0x002b;
  51059. var COMMA = 0x002c;
  51060. var COLON = 0x003a;
  51061. var SEMICOLON = 0x003b;
  51062. var FULL_STOP = 0x002e;
  51063. var NULL = 0x0000;
  51064. var BACKSPACE = 0x0008;
  51065. var LINE_TABULATION = 0x000b;
  51066. var SHIFT_OUT = 0x000e;
  51067. var INFORMATION_SEPARATOR_ONE = 0x001f;
  51068. var DELETE = 0x007f;
  51069. var EOF = -1;
  51070. var ZERO = 0x0030;
  51071. var a = 0x0061;
  51072. var e = 0x0065;
  51073. var f = 0x0066;
  51074. var u = 0x0075;
  51075. var z = 0x007a;
  51076. var A = 0x0041;
  51077. var E = 0x0045;
  51078. var F = 0x0046;
  51079. var U = 0x0055;
  51080. var Z = 0x005a;
  51081. var isDigit = function (codePoint) { return codePoint >= ZERO && codePoint <= 0x0039; };
  51082. var isSurrogateCodePoint = function (codePoint) { return codePoint >= 0xd800 && codePoint <= 0xdfff; };
  51083. var isHex = function (codePoint) {
  51084. return isDigit(codePoint) || (codePoint >= A && codePoint <= F) || (codePoint >= a && codePoint <= f);
  51085. };
  51086. var isLowerCaseLetter = function (codePoint) { return codePoint >= a && codePoint <= z; };
  51087. var isUpperCaseLetter = function (codePoint) { return codePoint >= A && codePoint <= Z; };
  51088. var isLetter = function (codePoint) { return isLowerCaseLetter(codePoint) || isUpperCaseLetter(codePoint); };
  51089. var isNonASCIICodePoint = function (codePoint) { return codePoint >= CONTROL; };
  51090. var isWhiteSpace = function (codePoint) {
  51091. return codePoint === LINE_FEED || codePoint === CHARACTER_TABULATION || codePoint === SPACE$1;
  51092. };
  51093. var isNameStartCodePoint = function (codePoint) {
  51094. return isLetter(codePoint) || isNonASCIICodePoint(codePoint) || codePoint === LOW_LINE;
  51095. };
  51096. var isNameCodePoint = function (codePoint) {
  51097. return isNameStartCodePoint(codePoint) || isDigit(codePoint) || codePoint === HYPHEN_MINUS;
  51098. };
  51099. var isNonPrintableCodePoint = function (codePoint) {
  51100. return ((codePoint >= NULL && codePoint <= BACKSPACE) ||
  51101. codePoint === LINE_TABULATION ||
  51102. (codePoint >= SHIFT_OUT && codePoint <= INFORMATION_SEPARATOR_ONE) ||
  51103. codePoint === DELETE);
  51104. };
  51105. var isValidEscape = function (c1, c2) {
  51106. if (c1 !== REVERSE_SOLIDUS) {
  51107. return false;
  51108. }
  51109. return c2 !== LINE_FEED;
  51110. };
  51111. var isIdentifierStart = function (c1, c2, c3) {
  51112. if (c1 === HYPHEN_MINUS) {
  51113. return isNameStartCodePoint(c2) || isValidEscape(c2, c3);
  51114. }
  51115. else if (isNameStartCodePoint(c1)) {
  51116. return true;
  51117. }
  51118. else if (c1 === REVERSE_SOLIDUS && isValidEscape(c1, c2)) {
  51119. return true;
  51120. }
  51121. return false;
  51122. };
  51123. var isNumberStart = function (c1, c2, c3) {
  51124. if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
  51125. if (isDigit(c2)) {
  51126. return true;
  51127. }
  51128. return c2 === FULL_STOP && isDigit(c3);
  51129. }
  51130. if (c1 === FULL_STOP) {
  51131. return isDigit(c2);
  51132. }
  51133. return isDigit(c1);
  51134. };
  51135. var stringToNumber = function (codePoints) {
  51136. var c = 0;
  51137. var sign = 1;
  51138. if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) {
  51139. if (codePoints[c] === HYPHEN_MINUS) {
  51140. sign = -1;
  51141. }
  51142. c++;
  51143. }
  51144. var integers = [];
  51145. while (isDigit(codePoints[c])) {
  51146. integers.push(codePoints[c++]);
  51147. }
  51148. var int = integers.length ? parseInt(fromCodePoint.apply(void 0, integers), 10) : 0;
  51149. if (codePoints[c] === FULL_STOP) {
  51150. c++;
  51151. }
  51152. var fraction = [];
  51153. while (isDigit(codePoints[c])) {
  51154. fraction.push(codePoints[c++]);
  51155. }
  51156. var fracd = fraction.length;
  51157. var frac = fracd ? parseInt(fromCodePoint.apply(void 0, fraction), 10) : 0;
  51158. if (codePoints[c] === E || codePoints[c] === e) {
  51159. c++;
  51160. }
  51161. var expsign = 1;
  51162. if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) {
  51163. if (codePoints[c] === HYPHEN_MINUS) {
  51164. expsign = -1;
  51165. }
  51166. c++;
  51167. }
  51168. var exponent = [];
  51169. while (isDigit(codePoints[c])) {
  51170. exponent.push(codePoints[c++]);
  51171. }
  51172. var exp = exponent.length ? parseInt(fromCodePoint.apply(void 0, exponent), 10) : 0;
  51173. return sign * (int + frac * Math.pow(10, -fracd)) * Math.pow(10, expsign * exp);
  51174. };
  51175. var LEFT_PARENTHESIS_TOKEN = {
  51176. type: TokenType.LEFT_PARENTHESIS_TOKEN
  51177. };
  51178. var RIGHT_PARENTHESIS_TOKEN = {
  51179. type: TokenType.RIGHT_PARENTHESIS_TOKEN
  51180. };
  51181. var COMMA_TOKEN = { type: TokenType.COMMA_TOKEN };
  51182. var SUFFIX_MATCH_TOKEN = { type: TokenType.SUFFIX_MATCH_TOKEN };
  51183. var PREFIX_MATCH_TOKEN = { type: TokenType.PREFIX_MATCH_TOKEN };
  51184. var COLUMN_TOKEN = { type: TokenType.COLUMN_TOKEN };
  51185. var DASH_MATCH_TOKEN = { type: TokenType.DASH_MATCH_TOKEN };
  51186. var INCLUDE_MATCH_TOKEN = { type: TokenType.INCLUDE_MATCH_TOKEN };
  51187. var LEFT_CURLY_BRACKET_TOKEN = {
  51188. type: TokenType.LEFT_CURLY_BRACKET_TOKEN
  51189. };
  51190. var RIGHT_CURLY_BRACKET_TOKEN = {
  51191. type: TokenType.RIGHT_CURLY_BRACKET_TOKEN
  51192. };
  51193. var SUBSTRING_MATCH_TOKEN = { type: TokenType.SUBSTRING_MATCH_TOKEN };
  51194. var BAD_URL_TOKEN = { type: TokenType.BAD_URL_TOKEN };
  51195. var BAD_STRING_TOKEN = { type: TokenType.BAD_STRING_TOKEN };
  51196. var CDO_TOKEN = { type: TokenType.CDO_TOKEN };
  51197. var CDC_TOKEN = { type: TokenType.CDC_TOKEN };
  51198. var COLON_TOKEN = { type: TokenType.COLON_TOKEN };
  51199. var SEMICOLON_TOKEN = { type: TokenType.SEMICOLON_TOKEN };
  51200. var LEFT_SQUARE_BRACKET_TOKEN = {
  51201. type: TokenType.LEFT_SQUARE_BRACKET_TOKEN
  51202. };
  51203. var RIGHT_SQUARE_BRACKET_TOKEN = {
  51204. type: TokenType.RIGHT_SQUARE_BRACKET_TOKEN
  51205. };
  51206. var WHITESPACE_TOKEN = { type: TokenType.WHITESPACE_TOKEN };
  51207. var EOF_TOKEN = { type: TokenType.EOF_TOKEN };
  51208. var Tokenizer = /** @class */ (function () {
  51209. function Tokenizer() {
  51210. this._value = [];
  51211. }
  51212. Tokenizer.prototype.write = function (chunk) {
  51213. this._value = this._value.concat(toCodePoints(chunk));
  51214. };
  51215. Tokenizer.prototype.read = function () {
  51216. var tokens = [];
  51217. var token = this.consumeToken();
  51218. while (token !== EOF_TOKEN) {
  51219. tokens.push(token);
  51220. token = this.consumeToken();
  51221. }
  51222. return tokens;
  51223. };
  51224. Tokenizer.prototype.consumeToken = function () {
  51225. var codePoint = this.consumeCodePoint();
  51226. switch (codePoint) {
  51227. case QUOTATION_MARK:
  51228. return this.consumeStringToken(QUOTATION_MARK);
  51229. case NUMBER_SIGN:
  51230. var c1 = this.peekCodePoint(0);
  51231. var c2 = this.peekCodePoint(1);
  51232. var c3 = this.peekCodePoint(2);
  51233. if (isNameCodePoint(c1) || isValidEscape(c2, c3)) {
  51234. var flags = isIdentifierStart(c1, c2, c3) ? FLAG_ID : FLAG_UNRESTRICTED;
  51235. var value = this.consumeName();
  51236. return { type: TokenType.HASH_TOKEN, value: value, flags: flags };
  51237. }
  51238. break;
  51239. case DOLLAR_SIGN:
  51240. if (this.peekCodePoint(0) === EQUALS_SIGN) {
  51241. this.consumeCodePoint();
  51242. return SUFFIX_MATCH_TOKEN;
  51243. }
  51244. break;
  51245. case APOSTROPHE:
  51246. return this.consumeStringToken(APOSTROPHE);
  51247. case LEFT_PARENTHESIS:
  51248. return LEFT_PARENTHESIS_TOKEN;
  51249. case RIGHT_PARENTHESIS:
  51250. return RIGHT_PARENTHESIS_TOKEN;
  51251. case ASTERISK:
  51252. if (this.peekCodePoint(0) === EQUALS_SIGN) {
  51253. this.consumeCodePoint();
  51254. return SUBSTRING_MATCH_TOKEN;
  51255. }
  51256. break;
  51257. case PLUS_SIGN:
  51258. if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
  51259. this.reconsumeCodePoint(codePoint);
  51260. return this.consumeNumericToken();
  51261. }
  51262. break;
  51263. case COMMA:
  51264. return COMMA_TOKEN;
  51265. case HYPHEN_MINUS:
  51266. var e1 = codePoint;
  51267. var e2 = this.peekCodePoint(0);
  51268. var e3 = this.peekCodePoint(1);
  51269. if (isNumberStart(e1, e2, e3)) {
  51270. this.reconsumeCodePoint(codePoint);
  51271. return this.consumeNumericToken();
  51272. }
  51273. if (isIdentifierStart(e1, e2, e3)) {
  51274. this.reconsumeCodePoint(codePoint);
  51275. return this.consumeIdentLikeToken();
  51276. }
  51277. if (e2 === HYPHEN_MINUS && e3 === GREATER_THAN_SIGN) {
  51278. this.consumeCodePoint();
  51279. this.consumeCodePoint();
  51280. return CDC_TOKEN;
  51281. }
  51282. break;
  51283. case FULL_STOP:
  51284. if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
  51285. this.reconsumeCodePoint(codePoint);
  51286. return this.consumeNumericToken();
  51287. }
  51288. break;
  51289. case SOLIDUS:
  51290. if (this.peekCodePoint(0) === ASTERISK) {
  51291. this.consumeCodePoint();
  51292. while (true) {
  51293. var c = this.consumeCodePoint();
  51294. if (c === ASTERISK) {
  51295. c = this.consumeCodePoint();
  51296. if (c === SOLIDUS) {
  51297. return this.consumeToken();
  51298. }
  51299. }
  51300. if (c === EOF) {
  51301. return this.consumeToken();
  51302. }
  51303. }
  51304. }
  51305. break;
  51306. case COLON:
  51307. return COLON_TOKEN;
  51308. case SEMICOLON:
  51309. return SEMICOLON_TOKEN;
  51310. case LESS_THAN_SIGN:
  51311. if (this.peekCodePoint(0) === EXCLAMATION_MARK &&
  51312. this.peekCodePoint(1) === HYPHEN_MINUS &&
  51313. this.peekCodePoint(2) === HYPHEN_MINUS) {
  51314. this.consumeCodePoint();
  51315. this.consumeCodePoint();
  51316. return CDO_TOKEN;
  51317. }
  51318. break;
  51319. case COMMERCIAL_AT:
  51320. var a1 = this.peekCodePoint(0);
  51321. var a2 = this.peekCodePoint(1);
  51322. var a3 = this.peekCodePoint(2);
  51323. if (isIdentifierStart(a1, a2, a3)) {
  51324. var value = this.consumeName();
  51325. return { type: TokenType.AT_KEYWORD_TOKEN, value: value };
  51326. }
  51327. break;
  51328. case LEFT_SQUARE_BRACKET:
  51329. return LEFT_SQUARE_BRACKET_TOKEN;
  51330. case REVERSE_SOLIDUS:
  51331. if (isValidEscape(codePoint, this.peekCodePoint(0))) {
  51332. this.reconsumeCodePoint(codePoint);
  51333. return this.consumeIdentLikeToken();
  51334. }
  51335. break;
  51336. case RIGHT_SQUARE_BRACKET:
  51337. return RIGHT_SQUARE_BRACKET_TOKEN;
  51338. case CIRCUMFLEX_ACCENT:
  51339. if (this.peekCodePoint(0) === EQUALS_SIGN) {
  51340. this.consumeCodePoint();
  51341. return PREFIX_MATCH_TOKEN;
  51342. }
  51343. break;
  51344. case LEFT_CURLY_BRACKET:
  51345. return LEFT_CURLY_BRACKET_TOKEN;
  51346. case RIGHT_CURLY_BRACKET:
  51347. return RIGHT_CURLY_BRACKET_TOKEN;
  51348. case u:
  51349. case U:
  51350. var u1 = this.peekCodePoint(0);
  51351. var u2 = this.peekCodePoint(1);
  51352. if (u1 === PLUS_SIGN && (isHex(u2) || u2 === QUESTION_MARK)) {
  51353. this.consumeCodePoint();
  51354. this.consumeUnicodeRangeToken();
  51355. }
  51356. this.reconsumeCodePoint(codePoint);
  51357. return this.consumeIdentLikeToken();
  51358. case VERTICAL_LINE:
  51359. if (this.peekCodePoint(0) === EQUALS_SIGN) {
  51360. this.consumeCodePoint();
  51361. return DASH_MATCH_TOKEN;
  51362. }
  51363. if (this.peekCodePoint(0) === VERTICAL_LINE) {
  51364. this.consumeCodePoint();
  51365. return COLUMN_TOKEN;
  51366. }
  51367. break;
  51368. case TILDE:
  51369. if (this.peekCodePoint(0) === EQUALS_SIGN) {
  51370. this.consumeCodePoint();
  51371. return INCLUDE_MATCH_TOKEN;
  51372. }
  51373. break;
  51374. case EOF:
  51375. return EOF_TOKEN;
  51376. }
  51377. if (isWhiteSpace(codePoint)) {
  51378. this.consumeWhiteSpace();
  51379. return WHITESPACE_TOKEN;
  51380. }
  51381. if (isDigit(codePoint)) {
  51382. this.reconsumeCodePoint(codePoint);
  51383. return this.consumeNumericToken();
  51384. }
  51385. if (isNameStartCodePoint(codePoint)) {
  51386. this.reconsumeCodePoint(codePoint);
  51387. return this.consumeIdentLikeToken();
  51388. }
  51389. return { type: TokenType.DELIM_TOKEN, value: fromCodePoint(codePoint) };
  51390. };
  51391. Tokenizer.prototype.consumeCodePoint = function () {
  51392. var value = this._value.shift();
  51393. return typeof value === 'undefined' ? -1 : value;
  51394. };
  51395. Tokenizer.prototype.reconsumeCodePoint = function (codePoint) {
  51396. this._value.unshift(codePoint);
  51397. };
  51398. Tokenizer.prototype.peekCodePoint = function (delta) {
  51399. if (delta >= this._value.length) {
  51400. return -1;
  51401. }
  51402. return this._value[delta];
  51403. };
  51404. Tokenizer.prototype.consumeUnicodeRangeToken = function () {
  51405. var digits = [];
  51406. var codePoint = this.consumeCodePoint();
  51407. while (isHex(codePoint) && digits.length < 6) {
  51408. digits.push(codePoint);
  51409. codePoint = this.consumeCodePoint();
  51410. }
  51411. var questionMarks = false;
  51412. while (codePoint === QUESTION_MARK && digits.length < 6) {
  51413. digits.push(codePoint);
  51414. codePoint = this.consumeCodePoint();
  51415. questionMarks = true;
  51416. }
  51417. if (questionMarks) {
  51418. var start_1 = parseInt(fromCodePoint.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? ZERO : digit); })), 16);
  51419. var end = parseInt(fromCodePoint.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? F : digit); })), 16);
  51420. return { type: TokenType.UNICODE_RANGE_TOKEN, start: start_1, end: end };
  51421. }
  51422. var start = parseInt(fromCodePoint.apply(void 0, digits), 16);
  51423. if (this.peekCodePoint(0) === HYPHEN_MINUS && isHex(this.peekCodePoint(1))) {
  51424. this.consumeCodePoint();
  51425. codePoint = this.consumeCodePoint();
  51426. var endDigits = [];
  51427. while (isHex(codePoint) && endDigits.length < 6) {
  51428. endDigits.push(codePoint);
  51429. codePoint = this.consumeCodePoint();
  51430. }
  51431. var end = parseInt(fromCodePoint.apply(void 0, endDigits), 16);
  51432. return { type: TokenType.UNICODE_RANGE_TOKEN, start: start, end: end };
  51433. }
  51434. else {
  51435. return { type: TokenType.UNICODE_RANGE_TOKEN, start: start, end: start };
  51436. }
  51437. };
  51438. Tokenizer.prototype.consumeIdentLikeToken = function () {
  51439. var value = this.consumeName();
  51440. if (value.toLowerCase() === 'url' && this.peekCodePoint(0) === LEFT_PARENTHESIS) {
  51441. this.consumeCodePoint();
  51442. return this.consumeUrlToken();
  51443. }
  51444. else if (this.peekCodePoint(0) === LEFT_PARENTHESIS) {
  51445. this.consumeCodePoint();
  51446. return { type: TokenType.FUNCTION_TOKEN, value: value };
  51447. }
  51448. return { type: TokenType.IDENT_TOKEN, value: value };
  51449. };
  51450. Tokenizer.prototype.consumeUrlToken = function () {
  51451. var value = [];
  51452. this.consumeWhiteSpace();
  51453. if (this.peekCodePoint(0) === EOF) {
  51454. return { type: TokenType.URL_TOKEN, value: '' };
  51455. }
  51456. var next = this.peekCodePoint(0);
  51457. if (next === APOSTROPHE || next === QUOTATION_MARK) {
  51458. var stringToken = this.consumeStringToken(this.consumeCodePoint());
  51459. if (stringToken.type === TokenType.STRING_TOKEN) {
  51460. this.consumeWhiteSpace();
  51461. if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
  51462. this.consumeCodePoint();
  51463. return { type: TokenType.URL_TOKEN, value: stringToken.value };
  51464. }
  51465. }
  51466. this.consumeBadUrlRemnants();
  51467. return BAD_URL_TOKEN;
  51468. }
  51469. while (true) {
  51470. var codePoint = this.consumeCodePoint();
  51471. if (codePoint === EOF || codePoint === RIGHT_PARENTHESIS) {
  51472. return { type: TokenType.URL_TOKEN, value: fromCodePoint.apply(void 0, value) };
  51473. }
  51474. else if (isWhiteSpace(codePoint)) {
  51475. this.consumeWhiteSpace();
  51476. if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
  51477. this.consumeCodePoint();
  51478. return { type: TokenType.URL_TOKEN, value: fromCodePoint.apply(void 0, value) };
  51479. }
  51480. this.consumeBadUrlRemnants();
  51481. return BAD_URL_TOKEN;
  51482. }
  51483. else if (codePoint === QUOTATION_MARK ||
  51484. codePoint === APOSTROPHE ||
  51485. codePoint === LEFT_PARENTHESIS ||
  51486. isNonPrintableCodePoint(codePoint)) {
  51487. this.consumeBadUrlRemnants();
  51488. return BAD_URL_TOKEN;
  51489. }
  51490. else if (codePoint === REVERSE_SOLIDUS) {
  51491. if (isValidEscape(codePoint, this.peekCodePoint(0))) {
  51492. value.push(this.consumeEscapedCodePoint());
  51493. }
  51494. else {
  51495. this.consumeBadUrlRemnants();
  51496. return BAD_URL_TOKEN;
  51497. }
  51498. }
  51499. else {
  51500. value.push(codePoint);
  51501. }
  51502. }
  51503. };
  51504. Tokenizer.prototype.consumeWhiteSpace = function () {
  51505. while (isWhiteSpace(this.peekCodePoint(0))) {
  51506. this.consumeCodePoint();
  51507. }
  51508. };
  51509. Tokenizer.prototype.consumeBadUrlRemnants = function () {
  51510. while (true) {
  51511. var codePoint = this.consumeCodePoint();
  51512. if (codePoint === RIGHT_PARENTHESIS || codePoint === EOF) {
  51513. return;
  51514. }
  51515. if (isValidEscape(codePoint, this.peekCodePoint(0))) {
  51516. this.consumeEscapedCodePoint();
  51517. }
  51518. }
  51519. };
  51520. Tokenizer.prototype.consumeStringSlice = function (count) {
  51521. var SLICE_STACK_SIZE = 60000;
  51522. var value = '';
  51523. while (count > 0) {
  51524. var amount = Math.min(SLICE_STACK_SIZE, count);
  51525. value += fromCodePoint.apply(void 0, this._value.splice(0, amount));
  51526. count -= amount;
  51527. }
  51528. this._value.shift();
  51529. return value;
  51530. };
  51531. Tokenizer.prototype.consumeStringToken = function (endingCodePoint) {
  51532. var value = '';
  51533. var i = 0;
  51534. do {
  51535. var codePoint = this._value[i];
  51536. if (codePoint === EOF || codePoint === undefined || codePoint === endingCodePoint) {
  51537. value += this.consumeStringSlice(i);
  51538. return { type: TokenType.STRING_TOKEN, value: value };
  51539. }
  51540. if (codePoint === LINE_FEED) {
  51541. this._value.splice(0, i);
  51542. return BAD_STRING_TOKEN;
  51543. }
  51544. if (codePoint === REVERSE_SOLIDUS) {
  51545. var next = this._value[i + 1];
  51546. if (next !== EOF && next !== undefined) {
  51547. if (next === LINE_FEED) {
  51548. value += this.consumeStringSlice(i);
  51549. i = -1;
  51550. this._value.shift();
  51551. }
  51552. else if (isValidEscape(codePoint, next)) {
  51553. value += this.consumeStringSlice(i);
  51554. value += fromCodePoint(this.consumeEscapedCodePoint());
  51555. i = -1;
  51556. }
  51557. }
  51558. }
  51559. i++;
  51560. } while (true);
  51561. };
  51562. Tokenizer.prototype.consumeNumber = function () {
  51563. var repr = [];
  51564. var type = FLAG_INTEGER;
  51565. var c1 = this.peekCodePoint(0);
  51566. if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
  51567. repr.push(this.consumeCodePoint());
  51568. }
  51569. while (isDigit(this.peekCodePoint(0))) {
  51570. repr.push(this.consumeCodePoint());
  51571. }
  51572. c1 = this.peekCodePoint(0);
  51573. var c2 = this.peekCodePoint(1);
  51574. if (c1 === FULL_STOP && isDigit(c2)) {
  51575. repr.push(this.consumeCodePoint(), this.consumeCodePoint());
  51576. type = FLAG_NUMBER;
  51577. while (isDigit(this.peekCodePoint(0))) {
  51578. repr.push(this.consumeCodePoint());
  51579. }
  51580. }
  51581. c1 = this.peekCodePoint(0);
  51582. c2 = this.peekCodePoint(1);
  51583. var c3 = this.peekCodePoint(2);
  51584. if ((c1 === E || c1 === e) && (((c2 === PLUS_SIGN || c2 === HYPHEN_MINUS) && isDigit(c3)) || isDigit(c2))) {
  51585. repr.push(this.consumeCodePoint(), this.consumeCodePoint());
  51586. type = FLAG_NUMBER;
  51587. while (isDigit(this.peekCodePoint(0))) {
  51588. repr.push(this.consumeCodePoint());
  51589. }
  51590. }
  51591. return [stringToNumber(repr), type];
  51592. };
  51593. Tokenizer.prototype.consumeNumericToken = function () {
  51594. var _a = this.consumeNumber(), number = _a[0], flags = _a[1];
  51595. var c1 = this.peekCodePoint(0);
  51596. var c2 = this.peekCodePoint(1);
  51597. var c3 = this.peekCodePoint(2);
  51598. if (isIdentifierStart(c1, c2, c3)) {
  51599. var unit = this.consumeName();
  51600. return { type: TokenType.DIMENSION_TOKEN, number: number, flags: flags, unit: unit };
  51601. }
  51602. if (c1 === PERCENTAGE_SIGN) {
  51603. this.consumeCodePoint();
  51604. return { type: TokenType.PERCENTAGE_TOKEN, number: number, flags: flags };
  51605. }
  51606. return { type: TokenType.NUMBER_TOKEN, number: number, flags: flags };
  51607. };
  51608. Tokenizer.prototype.consumeEscapedCodePoint = function () {
  51609. var codePoint = this.consumeCodePoint();
  51610. if (isHex(codePoint)) {
  51611. var hex = fromCodePoint(codePoint);
  51612. while (isHex(this.peekCodePoint(0)) && hex.length < 6) {
  51613. hex += fromCodePoint(this.consumeCodePoint());
  51614. }
  51615. if (isWhiteSpace(this.peekCodePoint(0))) {
  51616. this.consumeCodePoint();
  51617. }
  51618. var hexCodePoint = parseInt(hex, 16);
  51619. if (hexCodePoint === 0 || isSurrogateCodePoint(hexCodePoint) || hexCodePoint > 0x10ffff) {
  51620. return REPLACEMENT_CHARACTER;
  51621. }
  51622. return hexCodePoint;
  51623. }
  51624. if (codePoint === EOF) {
  51625. return REPLACEMENT_CHARACTER;
  51626. }
  51627. return codePoint;
  51628. };
  51629. Tokenizer.prototype.consumeName = function () {
  51630. var result = '';
  51631. while (true) {
  51632. var codePoint = this.consumeCodePoint();
  51633. if (isNameCodePoint(codePoint)) {
  51634. result += fromCodePoint(codePoint);
  51635. }
  51636. else if (isValidEscape(codePoint, this.peekCodePoint(0))) {
  51637. result += fromCodePoint(this.consumeEscapedCodePoint());
  51638. }
  51639. else {
  51640. this.reconsumeCodePoint(codePoint);
  51641. return result;
  51642. }
  51643. }
  51644. };
  51645. return Tokenizer;
  51646. }());
  51647. var Parser = /** @class */ (function () {
  51648. function Parser(tokens) {
  51649. this._tokens = tokens;
  51650. }
  51651. Parser.create = function (value) {
  51652. var tokenizer = new Tokenizer();
  51653. tokenizer.write(value);
  51654. return new Parser(tokenizer.read());
  51655. };
  51656. Parser.parseValue = function (value) {
  51657. return Parser.create(value).parseComponentValue();
  51658. };
  51659. Parser.parseValues = function (value) {
  51660. return Parser.create(value).parseComponentValues();
  51661. };
  51662. Parser.prototype.parseComponentValue = function () {
  51663. var token = this.consumeToken();
  51664. while (token.type === TokenType.WHITESPACE_TOKEN) {
  51665. token = this.consumeToken();
  51666. }
  51667. if (token.type === TokenType.EOF_TOKEN) {
  51668. throw new SyntaxError("Error parsing CSS component value, unexpected EOF");
  51669. }
  51670. this.reconsumeToken(token);
  51671. var value = this.consumeComponentValue();
  51672. do {
  51673. token = this.consumeToken();
  51674. } while (token.type === TokenType.WHITESPACE_TOKEN);
  51675. if (token.type === TokenType.EOF_TOKEN) {
  51676. return value;
  51677. }
  51678. throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one");
  51679. };
  51680. Parser.prototype.parseComponentValues = function () {
  51681. var values = [];
  51682. while (true) {
  51683. var value = this.consumeComponentValue();
  51684. if (value.type === TokenType.EOF_TOKEN) {
  51685. return values;
  51686. }
  51687. values.push(value);
  51688. values.push();
  51689. }
  51690. };
  51691. Parser.prototype.consumeComponentValue = function () {
  51692. var token = this.consumeToken();
  51693. switch (token.type) {
  51694. case TokenType.LEFT_CURLY_BRACKET_TOKEN:
  51695. case TokenType.LEFT_SQUARE_BRACKET_TOKEN:
  51696. case TokenType.LEFT_PARENTHESIS_TOKEN:
  51697. return this.consumeSimpleBlock(token.type);
  51698. case TokenType.FUNCTION_TOKEN:
  51699. return this.consumeFunction(token);
  51700. }
  51701. return token;
  51702. };
  51703. Parser.prototype.consumeSimpleBlock = function (type) {
  51704. var block = { type: type, values: [] };
  51705. var token = this.consumeToken();
  51706. while (true) {
  51707. if (token.type === TokenType.EOF_TOKEN || isEndingTokenFor(token, type)) {
  51708. return block;
  51709. }
  51710. this.reconsumeToken(token);
  51711. block.values.push(this.consumeComponentValue());
  51712. token = this.consumeToken();
  51713. }
  51714. };
  51715. Parser.prototype.consumeFunction = function (functionToken) {
  51716. var cssFunction = {
  51717. name: functionToken.value,
  51718. values: [],
  51719. type: TokenType.FUNCTION
  51720. };
  51721. while (true) {
  51722. var token = this.consumeToken();
  51723. if (token.type === TokenType.EOF_TOKEN || token.type === TokenType.RIGHT_PARENTHESIS_TOKEN) {
  51724. return cssFunction;
  51725. }
  51726. this.reconsumeToken(token);
  51727. cssFunction.values.push(this.consumeComponentValue());
  51728. }
  51729. };
  51730. Parser.prototype.consumeToken = function () {
  51731. var token = this._tokens.shift();
  51732. return typeof token === 'undefined' ? EOF_TOKEN : token;
  51733. };
  51734. Parser.prototype.reconsumeToken = function (token) {
  51735. this._tokens.unshift(token);
  51736. };
  51737. return Parser;
  51738. }());
  51739. var isDimensionToken = function (token) { return token.type === TokenType.DIMENSION_TOKEN; };
  51740. var isNumberToken = function (token) { return token.type === TokenType.NUMBER_TOKEN; };
  51741. var isIdentToken = function (token) { return token.type === TokenType.IDENT_TOKEN; };
  51742. var isStringToken = function (token) { return token.type === TokenType.STRING_TOKEN; };
  51743. var isIdentWithValue = function (token, value) {
  51744. return isIdentToken(token) && token.value === value;
  51745. };
  51746. var nonWhiteSpace = function (token) { return token.type !== TokenType.WHITESPACE_TOKEN; };
  51747. var nonFunctionArgSeparator = function (token) {
  51748. return token.type !== TokenType.WHITESPACE_TOKEN && token.type !== TokenType.COMMA_TOKEN;
  51749. };
  51750. var parseFunctionArgs = function (tokens) {
  51751. var args = [];
  51752. var arg = [];
  51753. tokens.forEach(function (token) {
  51754. if (token.type === TokenType.COMMA_TOKEN) {
  51755. if (arg.length === 0) {
  51756. throw new Error("Error parsing function args, zero tokens for arg");
  51757. }
  51758. args.push(arg);
  51759. arg = [];
  51760. return;
  51761. }
  51762. if (token.type !== TokenType.WHITESPACE_TOKEN) {
  51763. arg.push(token);
  51764. }
  51765. });
  51766. if (arg.length) {
  51767. args.push(arg);
  51768. }
  51769. return args;
  51770. };
  51771. var isEndingTokenFor = function (token, type) {
  51772. if (type === TokenType.LEFT_CURLY_BRACKET_TOKEN && token.type === TokenType.RIGHT_CURLY_BRACKET_TOKEN) {
  51773. return true;
  51774. }
  51775. if (type === TokenType.LEFT_SQUARE_BRACKET_TOKEN && token.type === TokenType.RIGHT_SQUARE_BRACKET_TOKEN) {
  51776. return true;
  51777. }
  51778. return type === TokenType.LEFT_PARENTHESIS_TOKEN && token.type === TokenType.RIGHT_PARENTHESIS_TOKEN;
  51779. };
  51780. var isLength = function (token) {
  51781. return token.type === TokenType.NUMBER_TOKEN || token.type === TokenType.DIMENSION_TOKEN;
  51782. };
  51783. var isLengthPercentage = function (token) {
  51784. return token.type === TokenType.PERCENTAGE_TOKEN || isLength(token);
  51785. };
  51786. var parseLengthPercentageTuple = function (tokens) {
  51787. return tokens.length > 1 ? [tokens[0], tokens[1]] : [tokens[0]];
  51788. };
  51789. var ZERO_LENGTH = {
  51790. type: TokenType.NUMBER_TOKEN,
  51791. number: 0,
  51792. flags: FLAG_INTEGER
  51793. };
  51794. var FIFTY_PERCENT = {
  51795. type: TokenType.PERCENTAGE_TOKEN,
  51796. number: 50,
  51797. flags: FLAG_INTEGER
  51798. };
  51799. var HUNDRED_PERCENT = {
  51800. type: TokenType.PERCENTAGE_TOKEN,
  51801. number: 100,
  51802. flags: FLAG_INTEGER
  51803. };
  51804. var getAbsoluteValueForTuple = function (tuple, width, height) {
  51805. var x = tuple[0], y = tuple[1];
  51806. return [getAbsoluteValue(x, width), getAbsoluteValue(typeof y !== 'undefined' ? y : x, height)];
  51807. };
  51808. var getAbsoluteValue = function (token, parent) {
  51809. if (token.type === TokenType.PERCENTAGE_TOKEN) {
  51810. return (token.number / 100) * parent;
  51811. }
  51812. if (isDimensionToken(token)) {
  51813. switch (token.unit) {
  51814. case 'rem':
  51815. case 'em':
  51816. return 16 * token.number; // TODO use correct font-size
  51817. case 'px':
  51818. default:
  51819. return token.number;
  51820. }
  51821. }
  51822. return token.number;
  51823. };
  51824. var DEG = 'deg';
  51825. var GRAD = 'grad';
  51826. var RAD = 'rad';
  51827. var TURN = 'turn';
  51828. var angle = {
  51829. name: 'angle',
  51830. parse: function (value) {
  51831. if (value.type === TokenType.DIMENSION_TOKEN) {
  51832. switch (value.unit) {
  51833. case DEG:
  51834. return (Math.PI * value.number) / 180;
  51835. case GRAD:
  51836. return (Math.PI / 200) * value.number;
  51837. case RAD:
  51838. return value.number;
  51839. case TURN:
  51840. return Math.PI * 2 * value.number;
  51841. }
  51842. }
  51843. throw new Error("Unsupported angle type");
  51844. }
  51845. };
  51846. var isAngle = function (value) {
  51847. if (value.type === TokenType.DIMENSION_TOKEN) {
  51848. if (value.unit === DEG || value.unit === GRAD || value.unit === RAD || value.unit === TURN) {
  51849. return true;
  51850. }
  51851. }
  51852. return false;
  51853. };
  51854. var parseNamedSide = function (tokens) {
  51855. var sideOrCorner = tokens
  51856. .filter(isIdentToken)
  51857. .map(function (ident) { return ident.value; })
  51858. .join(' ');
  51859. switch (sideOrCorner) {
  51860. case 'to bottom right':
  51861. case 'to right bottom':
  51862. case 'left top':
  51863. case 'top left':
  51864. return [ZERO_LENGTH, ZERO_LENGTH];
  51865. case 'to top':
  51866. case 'bottom':
  51867. return deg(0);
  51868. case 'to bottom left':
  51869. case 'to left bottom':
  51870. case 'right top':
  51871. case 'top right':
  51872. return [ZERO_LENGTH, HUNDRED_PERCENT];
  51873. case 'to right':
  51874. case 'left':
  51875. return deg(90);
  51876. case 'to top left':
  51877. case 'to left top':
  51878. case 'right bottom':
  51879. case 'bottom right':
  51880. return [HUNDRED_PERCENT, HUNDRED_PERCENT];
  51881. case 'to bottom':
  51882. case 'top':
  51883. return deg(180);
  51884. case 'to top right':
  51885. case 'to right top':
  51886. case 'left bottom':
  51887. case 'bottom left':
  51888. return [HUNDRED_PERCENT, ZERO_LENGTH];
  51889. case 'to left':
  51890. case 'right':
  51891. return deg(270);
  51892. }
  51893. return 0;
  51894. };
  51895. var deg = function (deg) { return (Math.PI * deg) / 180; };
  51896. var color = {
  51897. name: 'color',
  51898. parse: function (value) {
  51899. if (value.type === TokenType.FUNCTION) {
  51900. var colorFunction = SUPPORTED_COLOR_FUNCTIONS[value.name];
  51901. if (typeof colorFunction === 'undefined') {
  51902. throw new Error("Attempting to parse an unsupported color function \"" + value.name + "\"");
  51903. }
  51904. return colorFunction(value.values);
  51905. }
  51906. if (value.type === TokenType.HASH_TOKEN) {
  51907. if (value.value.length === 3) {
  51908. var r = value.value.substring(0, 1);
  51909. var g = value.value.substring(1, 2);
  51910. var b = value.value.substring(2, 3);
  51911. return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), 1);
  51912. }
  51913. if (value.value.length === 4) {
  51914. var r = value.value.substring(0, 1);
  51915. var g = value.value.substring(1, 2);
  51916. var b = value.value.substring(2, 3);
  51917. var a = value.value.substring(3, 4);
  51918. return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), parseInt(a + a, 16) / 255);
  51919. }
  51920. if (value.value.length === 6) {
  51921. var r = value.value.substring(0, 2);
  51922. var g = value.value.substring(2, 4);
  51923. var b = value.value.substring(4, 6);
  51924. return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1);
  51925. }
  51926. if (value.value.length === 8) {
  51927. var r = value.value.substring(0, 2);
  51928. var g = value.value.substring(2, 4);
  51929. var b = value.value.substring(4, 6);
  51930. var a = value.value.substring(6, 8);
  51931. return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), parseInt(a, 16) / 255);
  51932. }
  51933. }
  51934. if (value.type === TokenType.IDENT_TOKEN) {
  51935. var namedColor = COLORS[value.value.toUpperCase()];
  51936. if (typeof namedColor !== 'undefined') {
  51937. return namedColor;
  51938. }
  51939. }
  51940. return COLORS.TRANSPARENT;
  51941. }
  51942. };
  51943. var isTransparent = function (color) { return (0xff & color) === 0; };
  51944. var asString = function (color) {
  51945. var alpha = 0xff & color;
  51946. var blue = 0xff & (color >> 8);
  51947. var green = 0xff & (color >> 16);
  51948. var red = 0xff & (color >> 24);
  51949. return alpha < 255 ? "rgba(" + red + "," + green + "," + blue + "," + alpha / 255 + ")" : "rgb(" + red + "," + green + "," + blue + ")";
  51950. };
  51951. var pack = function (r, g, b, a) {
  51952. return ((r << 24) | (g << 16) | (b << 8) | (Math.round(a * 255) << 0)) >>> 0;
  51953. };
  51954. var getTokenColorValue = function (token, i) {
  51955. if (token.type === TokenType.NUMBER_TOKEN) {
  51956. return token.number;
  51957. }
  51958. if (token.type === TokenType.PERCENTAGE_TOKEN) {
  51959. var max = i === 3 ? 1 : 255;
  51960. return i === 3 ? (token.number / 100) * max : Math.round((token.number / 100) * max);
  51961. }
  51962. return 0;
  51963. };
  51964. var rgb = function (args) {
  51965. var tokens = args.filter(nonFunctionArgSeparator);
  51966. if (tokens.length === 3) {
  51967. var _a = tokens.map(getTokenColorValue), r = _a[0], g = _a[1], b = _a[2];
  51968. return pack(r, g, b, 1);
  51969. }
  51970. if (tokens.length === 4) {
  51971. var _b = tokens.map(getTokenColorValue), r = _b[0], g = _b[1], b = _b[2], a = _b[3];
  51972. return pack(r, g, b, a);
  51973. }
  51974. return 0;
  51975. };
  51976. function hue2rgb(t1, t2, hue) {
  51977. if (hue < 0) {
  51978. hue += 1;
  51979. }
  51980. if (hue >= 1) {
  51981. hue -= 1;
  51982. }
  51983. if (hue < 1 / 6) {
  51984. return (t2 - t1) * hue * 6 + t1;
  51985. }
  51986. else if (hue < 1 / 2) {
  51987. return t2;
  51988. }
  51989. else if (hue < 2 / 3) {
  51990. return (t2 - t1) * 6 * (2 / 3 - hue) + t1;
  51991. }
  51992. else {
  51993. return t1;
  51994. }
  51995. }
  51996. var hsl = function (args) {
  51997. var tokens = args.filter(nonFunctionArgSeparator);
  51998. var hue = tokens[0], saturation = tokens[1], lightness = tokens[2], alpha = tokens[3];
  51999. var h = (hue.type === TokenType.NUMBER_TOKEN ? deg(hue.number) : angle.parse(hue)) / (Math.PI * 2);
  52000. var s = isLengthPercentage(saturation) ? saturation.number / 100 : 0;
  52001. var l = isLengthPercentage(lightness) ? lightness.number / 100 : 0;
  52002. var a = typeof alpha !== 'undefined' && isLengthPercentage(alpha) ? getAbsoluteValue(alpha, 1) : 1;
  52003. if (s === 0) {
  52004. return pack(l * 255, l * 255, l * 255, 1);
  52005. }
  52006. var t2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  52007. var t1 = l * 2 - t2;
  52008. var r = hue2rgb(t1, t2, h + 1 / 3);
  52009. var g = hue2rgb(t1, t2, h);
  52010. var b = hue2rgb(t1, t2, h - 1 / 3);
  52011. return pack(r * 255, g * 255, b * 255, a);
  52012. };
  52013. var SUPPORTED_COLOR_FUNCTIONS = {
  52014. hsl: hsl,
  52015. hsla: hsl,
  52016. rgb: rgb,
  52017. rgba: rgb
  52018. };
  52019. var COLORS = {
  52020. ALICEBLUE: 0xf0f8ffff,
  52021. ANTIQUEWHITE: 0xfaebd7ff,
  52022. AQUA: 0x00ffffff,
  52023. AQUAMARINE: 0x7fffd4ff,
  52024. AZURE: 0xf0ffffff,
  52025. BEIGE: 0xf5f5dcff,
  52026. BISQUE: 0xffe4c4ff,
  52027. BLACK: 0x000000ff,
  52028. BLANCHEDALMOND: 0xffebcdff,
  52029. BLUE: 0x0000ffff,
  52030. BLUEVIOLET: 0x8a2be2ff,
  52031. BROWN: 0xa52a2aff,
  52032. BURLYWOOD: 0xdeb887ff,
  52033. CADETBLUE: 0x5f9ea0ff,
  52034. CHARTREUSE: 0x7fff00ff,
  52035. CHOCOLATE: 0xd2691eff,
  52036. CORAL: 0xff7f50ff,
  52037. CORNFLOWERBLUE: 0x6495edff,
  52038. CORNSILK: 0xfff8dcff,
  52039. CRIMSON: 0xdc143cff,
  52040. CYAN: 0x00ffffff,
  52041. DARKBLUE: 0x00008bff,
  52042. DARKCYAN: 0x008b8bff,
  52043. DARKGOLDENROD: 0xb886bbff,
  52044. DARKGRAY: 0xa9a9a9ff,
  52045. DARKGREEN: 0x006400ff,
  52046. DARKGREY: 0xa9a9a9ff,
  52047. DARKKHAKI: 0xbdb76bff,
  52048. DARKMAGENTA: 0x8b008bff,
  52049. DARKOLIVEGREEN: 0x556b2fff,
  52050. DARKORANGE: 0xff8c00ff,
  52051. DARKORCHID: 0x9932ccff,
  52052. DARKRED: 0x8b0000ff,
  52053. DARKSALMON: 0xe9967aff,
  52054. DARKSEAGREEN: 0x8fbc8fff,
  52055. DARKSLATEBLUE: 0x483d8bff,
  52056. DARKSLATEGRAY: 0x2f4f4fff,
  52057. DARKSLATEGREY: 0x2f4f4fff,
  52058. DARKTURQUOISE: 0x00ced1ff,
  52059. DARKVIOLET: 0x9400d3ff,
  52060. DEEPPINK: 0xff1493ff,
  52061. DEEPSKYBLUE: 0x00bfffff,
  52062. DIMGRAY: 0x696969ff,
  52063. DIMGREY: 0x696969ff,
  52064. DODGERBLUE: 0x1e90ffff,
  52065. FIREBRICK: 0xb22222ff,
  52066. FLORALWHITE: 0xfffaf0ff,
  52067. FORESTGREEN: 0x228b22ff,
  52068. FUCHSIA: 0xff00ffff,
  52069. GAINSBORO: 0xdcdcdcff,
  52070. GHOSTWHITE: 0xf8f8ffff,
  52071. GOLD: 0xffd700ff,
  52072. GOLDENROD: 0xdaa520ff,
  52073. GRAY: 0x808080ff,
  52074. GREEN: 0x008000ff,
  52075. GREENYELLOW: 0xadff2fff,
  52076. GREY: 0x808080ff,
  52077. HONEYDEW: 0xf0fff0ff,
  52078. HOTPINK: 0xff69b4ff,
  52079. INDIANRED: 0xcd5c5cff,
  52080. INDIGO: 0x4b0082ff,
  52081. IVORY: 0xfffff0ff,
  52082. KHAKI: 0xf0e68cff,
  52083. LAVENDER: 0xe6e6faff,
  52084. LAVENDERBLUSH: 0xfff0f5ff,
  52085. LAWNGREEN: 0x7cfc00ff,
  52086. LEMONCHIFFON: 0xfffacdff,
  52087. LIGHTBLUE: 0xadd8e6ff,
  52088. LIGHTCORAL: 0xf08080ff,
  52089. LIGHTCYAN: 0xe0ffffff,
  52090. LIGHTGOLDENRODYELLOW: 0xfafad2ff,
  52091. LIGHTGRAY: 0xd3d3d3ff,
  52092. LIGHTGREEN: 0x90ee90ff,
  52093. LIGHTGREY: 0xd3d3d3ff,
  52094. LIGHTPINK: 0xffb6c1ff,
  52095. LIGHTSALMON: 0xffa07aff,
  52096. LIGHTSEAGREEN: 0x20b2aaff,
  52097. LIGHTSKYBLUE: 0x87cefaff,
  52098. LIGHTSLATEGRAY: 0x778899ff,
  52099. LIGHTSLATEGREY: 0x778899ff,
  52100. LIGHTSTEELBLUE: 0xb0c4deff,
  52101. LIGHTYELLOW: 0xffffe0ff,
  52102. LIME: 0x00ff00ff,
  52103. LIMEGREEN: 0x32cd32ff,
  52104. LINEN: 0xfaf0e6ff,
  52105. MAGENTA: 0xff00ffff,
  52106. MAROON: 0x800000ff,
  52107. MEDIUMAQUAMARINE: 0x66cdaaff,
  52108. MEDIUMBLUE: 0x0000cdff,
  52109. MEDIUMORCHID: 0xba55d3ff,
  52110. MEDIUMPURPLE: 0x9370dbff,
  52111. MEDIUMSEAGREEN: 0x3cb371ff,
  52112. MEDIUMSLATEBLUE: 0x7b68eeff,
  52113. MEDIUMSPRINGGREEN: 0x00fa9aff,
  52114. MEDIUMTURQUOISE: 0x48d1ccff,
  52115. MEDIUMVIOLETRED: 0xc71585ff,
  52116. MIDNIGHTBLUE: 0x191970ff,
  52117. MINTCREAM: 0xf5fffaff,
  52118. MISTYROSE: 0xffe4e1ff,
  52119. MOCCASIN: 0xffe4b5ff,
  52120. NAVAJOWHITE: 0xffdeadff,
  52121. NAVY: 0x000080ff,
  52122. OLDLACE: 0xfdf5e6ff,
  52123. OLIVE: 0x808000ff,
  52124. OLIVEDRAB: 0x6b8e23ff,
  52125. ORANGE: 0xffa500ff,
  52126. ORANGERED: 0xff4500ff,
  52127. ORCHID: 0xda70d6ff,
  52128. PALEGOLDENROD: 0xeee8aaff,
  52129. PALEGREEN: 0x98fb98ff,
  52130. PALETURQUOISE: 0xafeeeeff,
  52131. PALEVIOLETRED: 0xdb7093ff,
  52132. PAPAYAWHIP: 0xffefd5ff,
  52133. PEACHPUFF: 0xffdab9ff,
  52134. PERU: 0xcd853fff,
  52135. PINK: 0xffc0cbff,
  52136. PLUM: 0xdda0ddff,
  52137. POWDERBLUE: 0xb0e0e6ff,
  52138. PURPLE: 0x800080ff,
  52139. REBECCAPURPLE: 0x663399ff,
  52140. RED: 0xff0000ff,
  52141. ROSYBROWN: 0xbc8f8fff,
  52142. ROYALBLUE: 0x4169e1ff,
  52143. SADDLEBROWN: 0x8b4513ff,
  52144. SALMON: 0xfa8072ff,
  52145. SANDYBROWN: 0xf4a460ff,
  52146. SEAGREEN: 0x2e8b57ff,
  52147. SEASHELL: 0xfff5eeff,
  52148. SIENNA: 0xa0522dff,
  52149. SILVER: 0xc0c0c0ff,
  52150. SKYBLUE: 0x87ceebff,
  52151. SLATEBLUE: 0x6a5acdff,
  52152. SLATEGRAY: 0x708090ff,
  52153. SLATEGREY: 0x708090ff,
  52154. SNOW: 0xfffafaff,
  52155. SPRINGGREEN: 0x00ff7fff,
  52156. STEELBLUE: 0x4682b4ff,
  52157. TAN: 0xd2b48cff,
  52158. TEAL: 0x008080ff,
  52159. THISTLE: 0xd8bfd8ff,
  52160. TOMATO: 0xff6347ff,
  52161. TRANSPARENT: 0x00000000,
  52162. TURQUOISE: 0x40e0d0ff,
  52163. VIOLET: 0xee82eeff,
  52164. WHEAT: 0xf5deb3ff,
  52165. WHITE: 0xffffffff,
  52166. WHITESMOKE: 0xf5f5f5ff,
  52167. YELLOW: 0xffff00ff,
  52168. YELLOWGREEN: 0x9acd32ff
  52169. };
  52170. var PropertyDescriptorParsingType;
  52171. (function (PropertyDescriptorParsingType) {
  52172. PropertyDescriptorParsingType[PropertyDescriptorParsingType["VALUE"] = 0] = "VALUE";
  52173. PropertyDescriptorParsingType[PropertyDescriptorParsingType["LIST"] = 1] = "LIST";
  52174. PropertyDescriptorParsingType[PropertyDescriptorParsingType["IDENT_VALUE"] = 2] = "IDENT_VALUE";
  52175. PropertyDescriptorParsingType[PropertyDescriptorParsingType["TYPE_VALUE"] = 3] = "TYPE_VALUE";
  52176. PropertyDescriptorParsingType[PropertyDescriptorParsingType["TOKEN_VALUE"] = 4] = "TOKEN_VALUE";
  52177. })(PropertyDescriptorParsingType || (PropertyDescriptorParsingType = {}));
  52178. var BACKGROUND_CLIP;
  52179. (function (BACKGROUND_CLIP) {
  52180. BACKGROUND_CLIP[BACKGROUND_CLIP["BORDER_BOX"] = 0] = "BORDER_BOX";
  52181. BACKGROUND_CLIP[BACKGROUND_CLIP["PADDING_BOX"] = 1] = "PADDING_BOX";
  52182. BACKGROUND_CLIP[BACKGROUND_CLIP["CONTENT_BOX"] = 2] = "CONTENT_BOX";
  52183. })(BACKGROUND_CLIP || (BACKGROUND_CLIP = {}));
  52184. var backgroundClip = {
  52185. name: 'background-clip',
  52186. initialValue: 'border-box',
  52187. prefix: false,
  52188. type: PropertyDescriptorParsingType.LIST,
  52189. parse: function (tokens) {
  52190. return tokens.map(function (token) {
  52191. if (isIdentToken(token)) {
  52192. switch (token.value) {
  52193. case 'padding-box':
  52194. return BACKGROUND_CLIP.PADDING_BOX;
  52195. case 'content-box':
  52196. return BACKGROUND_CLIP.CONTENT_BOX;
  52197. }
  52198. }
  52199. return BACKGROUND_CLIP.BORDER_BOX;
  52200. });
  52201. }
  52202. };
  52203. var backgroundColor = {
  52204. name: "background-color",
  52205. initialValue: 'transparent',
  52206. prefix: false,
  52207. type: PropertyDescriptorParsingType.TYPE_VALUE,
  52208. format: 'color'
  52209. };
  52210. var parseColorStop = function (args) {
  52211. var color$1 = color.parse(args[0]);
  52212. var stop = args[1];
  52213. return stop && isLengthPercentage(stop) ? { color: color$1, stop: stop } : { color: color$1, stop: null };
  52214. };
  52215. var processColorStops = function (stops, lineLength) {
  52216. var first = stops[0];
  52217. var last = stops[stops.length - 1];
  52218. if (first.stop === null) {
  52219. first.stop = ZERO_LENGTH;
  52220. }
  52221. if (last.stop === null) {
  52222. last.stop = HUNDRED_PERCENT;
  52223. }
  52224. var processStops = [];
  52225. var previous = 0;
  52226. for (var i = 0; i < stops.length; i++) {
  52227. var stop_1 = stops[i].stop;
  52228. if (stop_1 !== null) {
  52229. var absoluteValue = getAbsoluteValue(stop_1, lineLength);
  52230. if (absoluteValue > previous) {
  52231. processStops.push(absoluteValue);
  52232. }
  52233. else {
  52234. processStops.push(previous);
  52235. }
  52236. previous = absoluteValue;
  52237. }
  52238. else {
  52239. processStops.push(null);
  52240. }
  52241. }
  52242. var gapBegin = null;
  52243. for (var i = 0; i < processStops.length; i++) {
  52244. var stop_2 = processStops[i];
  52245. if (stop_2 === null) {
  52246. if (gapBegin === null) {
  52247. gapBegin = i;
  52248. }
  52249. }
  52250. else if (gapBegin !== null) {
  52251. var gapLength = i - gapBegin;
  52252. var beforeGap = processStops[gapBegin - 1];
  52253. var gapValue = (stop_2 - beforeGap) / (gapLength + 1);
  52254. for (var g = 1; g <= gapLength; g++) {
  52255. processStops[gapBegin + g - 1] = gapValue * g;
  52256. }
  52257. gapBegin = null;
  52258. }
  52259. }
  52260. return stops.map(function (_a, i) {
  52261. var color = _a.color;
  52262. return { color: color, stop: Math.max(Math.min(1, processStops[i] / lineLength), 0) };
  52263. });
  52264. };
  52265. var getAngleFromCorner = function (corner, width, height) {
  52266. var centerX = width / 2;
  52267. var centerY = height / 2;
  52268. var x = getAbsoluteValue(corner[0], width) - centerX;
  52269. var y = centerY - getAbsoluteValue(corner[1], height);
  52270. return (Math.atan2(y, x) + Math.PI * 2) % (Math.PI * 2);
  52271. };
  52272. var calculateGradientDirection = function (angle, width, height) {
  52273. var radian = typeof angle === 'number' ? angle : getAngleFromCorner(angle, width, height);
  52274. var lineLength = Math.abs(width * Math.sin(radian)) + Math.abs(height * Math.cos(radian));
  52275. var halfWidth = width / 2;
  52276. var halfHeight = height / 2;
  52277. var halfLineLength = lineLength / 2;
  52278. var yDiff = Math.sin(radian - Math.PI / 2) * halfLineLength;
  52279. var xDiff = Math.cos(radian - Math.PI / 2) * halfLineLength;
  52280. return [lineLength, halfWidth - xDiff, halfWidth + xDiff, halfHeight - yDiff, halfHeight + yDiff];
  52281. };
  52282. var distance = function (a, b) { return Math.sqrt(a * a + b * b); };
  52283. var findCorner = function (width, height, x, y, closest) {
  52284. var corners = [[0, 0], [0, height], [width, 0], [width, height]];
  52285. return corners.reduce(function (stat, corner) {
  52286. var cx = corner[0], cy = corner[1];
  52287. var d = distance(x - cx, y - cy);
  52288. if (closest ? d < stat.optimumDistance : d > stat.optimumDistance) {
  52289. return {
  52290. optimumCorner: corner,
  52291. optimumDistance: d
  52292. };
  52293. }
  52294. return stat;
  52295. }, {
  52296. optimumDistance: closest ? Infinity : -Infinity,
  52297. optimumCorner: null
  52298. }).optimumCorner;
  52299. };
  52300. var calculateRadius = function (gradient, x, y, width, height) {
  52301. var rx = 0;
  52302. var ry = 0;
  52303. switch (gradient.size) {
  52304. case CSSRadialExtent.CLOSEST_SIDE:
  52305. // The ending shape is sized so that that it exactly meets the side of the gradient box closest to the gradient’s center.
  52306. // If the shape is an ellipse, it exactly meets the closest side in each dimension.
  52307. if (gradient.shape === CSSRadialShape.CIRCLE) {
  52308. rx = ry = Math.min(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height));
  52309. }
  52310. else if (gradient.shape === CSSRadialShape.ELLIPSE) {
  52311. rx = Math.min(Math.abs(x), Math.abs(x - width));
  52312. ry = Math.min(Math.abs(y), Math.abs(y - height));
  52313. }
  52314. break;
  52315. case CSSRadialExtent.CLOSEST_CORNER:
  52316. // The ending shape is sized so that that it passes through the corner of the gradient box closest to the gradient’s center.
  52317. // If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified.
  52318. if (gradient.shape === CSSRadialShape.CIRCLE) {
  52319. rx = ry = Math.min(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height));
  52320. }
  52321. else if (gradient.shape === CSSRadialShape.ELLIPSE) {
  52322. // Compute the ratio ry/rx (which is to be the same as for "closest-side")
  52323. var c = Math.min(Math.abs(y), Math.abs(y - height)) / Math.min(Math.abs(x), Math.abs(x - width));
  52324. var _a = findCorner(width, height, x, y, true), cx = _a[0], cy = _a[1];
  52325. rx = distance(cx - x, (cy - y) / c);
  52326. ry = c * rx;
  52327. }
  52328. break;
  52329. case CSSRadialExtent.FARTHEST_SIDE:
  52330. // Same as closest-side, except the ending shape is sized based on the farthest side(s)
  52331. if (gradient.shape === CSSRadialShape.CIRCLE) {
  52332. rx = ry = Math.max(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height));
  52333. }
  52334. else if (gradient.shape === CSSRadialShape.ELLIPSE) {
  52335. rx = Math.max(Math.abs(x), Math.abs(x - width));
  52336. ry = Math.max(Math.abs(y), Math.abs(y - height));
  52337. }
  52338. break;
  52339. case CSSRadialExtent.FARTHEST_CORNER:
  52340. // Same as closest-corner, except the ending shape is sized based on the farthest corner.
  52341. // If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified.
  52342. if (gradient.shape === CSSRadialShape.CIRCLE) {
  52343. rx = ry = Math.max(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height));
  52344. }
  52345. else if (gradient.shape === CSSRadialShape.ELLIPSE) {
  52346. // Compute the ratio ry/rx (which is to be the same as for "farthest-side")
  52347. var c = Math.max(Math.abs(y), Math.abs(y - height)) / Math.max(Math.abs(x), Math.abs(x - width));
  52348. var _b = findCorner(width, height, x, y, false), cx = _b[0], cy = _b[1];
  52349. rx = distance(cx - x, (cy - y) / c);
  52350. ry = c * rx;
  52351. }
  52352. break;
  52353. }
  52354. if (Array.isArray(gradient.size)) {
  52355. rx = getAbsoluteValue(gradient.size[0], width);
  52356. ry = gradient.size.length === 2 ? getAbsoluteValue(gradient.size[1], height) : rx;
  52357. }
  52358. return [rx, ry];
  52359. };
  52360. var linearGradient = function (tokens) {
  52361. var angle$1 = deg(180);
  52362. var stops = [];
  52363. parseFunctionArgs(tokens).forEach(function (arg, i) {
  52364. if (i === 0) {
  52365. var firstToken = arg[0];
  52366. if (firstToken.type === TokenType.IDENT_TOKEN && firstToken.value === 'to') {
  52367. angle$1 = parseNamedSide(arg);
  52368. return;
  52369. }
  52370. else if (isAngle(firstToken)) {
  52371. angle$1 = angle.parse(firstToken);
  52372. return;
  52373. }
  52374. }
  52375. var colorStop = parseColorStop(arg);
  52376. stops.push(colorStop);
  52377. });
  52378. return { angle: angle$1, stops: stops, type: CSSImageType.LINEAR_GRADIENT };
  52379. };
  52380. var prefixLinearGradient = function (tokens) {
  52381. var angle$1 = deg(180);
  52382. var stops = [];
  52383. parseFunctionArgs(tokens).forEach(function (arg, i) {
  52384. if (i === 0) {
  52385. var firstToken = arg[0];
  52386. if (firstToken.type === TokenType.IDENT_TOKEN &&
  52387. ['top', 'left', 'right', 'bottom'].indexOf(firstToken.value) !== -1) {
  52388. angle$1 = parseNamedSide(arg);
  52389. return;
  52390. }
  52391. else if (isAngle(firstToken)) {
  52392. angle$1 = (angle.parse(firstToken) + deg(270)) % deg(360);
  52393. return;
  52394. }
  52395. }
  52396. var colorStop = parseColorStop(arg);
  52397. stops.push(colorStop);
  52398. });
  52399. return {
  52400. angle: angle$1,
  52401. stops: stops,
  52402. type: CSSImageType.LINEAR_GRADIENT
  52403. };
  52404. };
  52405. var testRangeBounds = function (document) {
  52406. var TEST_HEIGHT = 123;
  52407. if (document.createRange) {
  52408. var range = document.createRange();
  52409. if (range.getBoundingClientRect) {
  52410. var testElement = document.createElement('boundtest');
  52411. testElement.style.height = TEST_HEIGHT + "px";
  52412. testElement.style.display = 'block';
  52413. document.body.appendChild(testElement);
  52414. range.selectNode(testElement);
  52415. var rangeBounds = range.getBoundingClientRect();
  52416. var rangeHeight = Math.round(rangeBounds.height);
  52417. document.body.removeChild(testElement);
  52418. if (rangeHeight === TEST_HEIGHT) {
  52419. return true;
  52420. }
  52421. }
  52422. }
  52423. return false;
  52424. };
  52425. var testCORS = function () { return typeof new Image().crossOrigin !== 'undefined'; };
  52426. var testResponseType = function () { return typeof new XMLHttpRequest().responseType === 'string'; };
  52427. var testSVG = function (document) {
  52428. var img = new Image();
  52429. var canvas = document.createElement('canvas');
  52430. var ctx = canvas.getContext('2d');
  52431. if (!ctx) {
  52432. return false;
  52433. }
  52434. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  52435. try {
  52436. ctx.drawImage(img, 0, 0);
  52437. canvas.toDataURL();
  52438. }
  52439. catch (e) {
  52440. return false;
  52441. }
  52442. return true;
  52443. };
  52444. var isGreenPixel = function (data) {
  52445. return data[0] === 0 && data[1] === 255 && data[2] === 0 && data[3] === 255;
  52446. };
  52447. var testForeignObject = function (document) {
  52448. var canvas = document.createElement('canvas');
  52449. var size = 100;
  52450. canvas.width = size;
  52451. canvas.height = size;
  52452. var ctx = canvas.getContext('2d');
  52453. if (!ctx) {
  52454. return Promise.reject(false);
  52455. }
  52456. ctx.fillStyle = 'rgb(0, 255, 0)';
  52457. ctx.fillRect(0, 0, size, size);
  52458. var img = new Image();
  52459. var greenImageSrc = canvas.toDataURL();
  52460. img.src = greenImageSrc;
  52461. var svg = createForeignObjectSVG(size, size, 0, 0, img);
  52462. ctx.fillStyle = 'red';
  52463. ctx.fillRect(0, 0, size, size);
  52464. return loadSerializedSVG(svg)
  52465. .then(function (img) {
  52466. ctx.drawImage(img, 0, 0);
  52467. var data = ctx.getImageData(0, 0, size, size).data;
  52468. ctx.fillStyle = 'red';
  52469. ctx.fillRect(0, 0, size, size);
  52470. var node = document.createElement('div');
  52471. node.style.backgroundImage = "url(" + greenImageSrc + ")";
  52472. node.style.height = size + "px";
  52473. // Firefox 55 does not render inline <img /> tags
  52474. return isGreenPixel(data)
  52475. ? loadSerializedSVG(createForeignObjectSVG(size, size, 0, 0, node))
  52476. : Promise.reject(false);
  52477. })
  52478. .then(function (img) {
  52479. ctx.drawImage(img, 0, 0);
  52480. // Edge does not render background-images
  52481. return isGreenPixel(ctx.getImageData(0, 0, size, size).data);
  52482. })
  52483. .catch(function () { return false; });
  52484. };
  52485. var createForeignObjectSVG = function (width, height, x, y, node) {
  52486. var xmlns = 'http://www.w3.org/2000/svg';
  52487. var svg = document.createElementNS(xmlns, 'svg');
  52488. var foreignObject = document.createElementNS(xmlns, 'foreignObject');
  52489. svg.setAttributeNS(null, 'width', width.toString());
  52490. svg.setAttributeNS(null, 'height', height.toString());
  52491. foreignObject.setAttributeNS(null, 'width', '100%');
  52492. foreignObject.setAttributeNS(null, 'height', '100%');
  52493. foreignObject.setAttributeNS(null, 'x', x.toString());
  52494. foreignObject.setAttributeNS(null, 'y', y.toString());
  52495. foreignObject.setAttributeNS(null, 'externalResourcesRequired', 'true');
  52496. svg.appendChild(foreignObject);
  52497. foreignObject.appendChild(node);
  52498. return svg;
  52499. };
  52500. var loadSerializedSVG = function (svg) {
  52501. return new Promise(function (resolve, reject) {
  52502. var img = new Image();
  52503. img.onload = function () { return resolve(img); };
  52504. img.onerror = reject;
  52505. img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg));
  52506. });
  52507. };
  52508. var FEATURES = {
  52509. get SUPPORT_RANGE_BOUNDS() {
  52510. var value = testRangeBounds(document);
  52511. Object.defineProperty(FEATURES, 'SUPPORT_RANGE_BOUNDS', { value: value });
  52512. return value;
  52513. },
  52514. get SUPPORT_SVG_DRAWING() {
  52515. var value = testSVG(document);
  52516. Object.defineProperty(FEATURES, 'SUPPORT_SVG_DRAWING', { value: value });
  52517. return value;
  52518. },
  52519. get SUPPORT_FOREIGNOBJECT_DRAWING() {
  52520. var value = typeof Array.from === 'function' && typeof window.fetch === 'function'
  52521. ? testForeignObject(document)
  52522. : Promise.resolve(false);
  52523. Object.defineProperty(FEATURES, 'SUPPORT_FOREIGNOBJECT_DRAWING', { value: value });
  52524. return value;
  52525. },
  52526. get SUPPORT_CORS_IMAGES() {
  52527. var value = testCORS();
  52528. Object.defineProperty(FEATURES, 'SUPPORT_CORS_IMAGES', { value: value });
  52529. return value;
  52530. },
  52531. get SUPPORT_RESPONSE_TYPE() {
  52532. var value = testResponseType();
  52533. Object.defineProperty(FEATURES, 'SUPPORT_RESPONSE_TYPE', { value: value });
  52534. return value;
  52535. },
  52536. get SUPPORT_CORS_XHR() {
  52537. var value = 'withCredentials' in new XMLHttpRequest();
  52538. Object.defineProperty(FEATURES, 'SUPPORT_CORS_XHR', { value: value });
  52539. return value;
  52540. }
  52541. };
  52542. var Logger = /** @class */ (function () {
  52543. function Logger(_a) {
  52544. var id = _a.id, enabled = _a.enabled;
  52545. this.id = id;
  52546. this.enabled = enabled;
  52547. this.start = Date.now();
  52548. }
  52549. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  52550. Logger.prototype.debug = function () {
  52551. var args = [];
  52552. for (var _i = 0; _i < arguments.length; _i++) {
  52553. args[_i] = arguments[_i];
  52554. }
  52555. if (this.enabled) {
  52556. // eslint-disable-next-line no-console
  52557. if (typeof window !== 'undefined' && window.console && typeof console.debug === 'function') {
  52558. // eslint-disable-next-line no-console
  52559. console.debug.apply(console, [this.id, this.getTime() + "ms"].concat(args));
  52560. }
  52561. else {
  52562. this.info.apply(this, args);
  52563. }
  52564. }
  52565. };
  52566. Logger.prototype.getTime = function () {
  52567. return Date.now() - this.start;
  52568. };
  52569. Logger.create = function (options) {
  52570. Logger.instances[options.id] = new Logger(options);
  52571. };
  52572. Logger.destroy = function (id) {
  52573. delete Logger.instances[id];
  52574. };
  52575. Logger.getInstance = function (id) {
  52576. var instance = Logger.instances[id];
  52577. if (typeof instance === 'undefined') {
  52578. throw new Error("No logger instance found with id " + id);
  52579. }
  52580. return instance;
  52581. };
  52582. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  52583. Logger.prototype.info = function () {
  52584. var args = [];
  52585. for (var _i = 0; _i < arguments.length; _i++) {
  52586. args[_i] = arguments[_i];
  52587. }
  52588. if (this.enabled) {
  52589. // eslint-disable-next-line no-console
  52590. if (typeof window !== 'undefined' && window.console && typeof console.info === 'function') {
  52591. // eslint-disable-next-line no-console
  52592. console.info.apply(console, [this.id, this.getTime() + "ms"].concat(args));
  52593. }
  52594. }
  52595. };
  52596. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  52597. Logger.prototype.error = function () {
  52598. var args = [];
  52599. for (var _i = 0; _i < arguments.length; _i++) {
  52600. args[_i] = arguments[_i];
  52601. }
  52602. if (this.enabled) {
  52603. // eslint-disable-next-line no-console
  52604. if (typeof window !== 'undefined' && window.console && typeof console.error === 'function') {
  52605. // eslint-disable-next-line no-console
  52606. console.error.apply(console, [this.id, this.getTime() + "ms"].concat(args));
  52607. }
  52608. else {
  52609. this.info.apply(this, args);
  52610. }
  52611. }
  52612. };
  52613. Logger.instances = {};
  52614. return Logger;
  52615. }());
  52616. var CacheStorage = /** @class */ (function () {
  52617. function CacheStorage() {
  52618. }
  52619. CacheStorage.create = function (name, options) {
  52620. return (CacheStorage._caches[name] = new Cache(name, options));
  52621. };
  52622. CacheStorage.destroy = function (name) {
  52623. delete CacheStorage._caches[name];
  52624. };
  52625. CacheStorage.open = function (name) {
  52626. var cache = CacheStorage._caches[name];
  52627. if (typeof cache !== 'undefined') {
  52628. return cache;
  52629. }
  52630. throw new Error("Cache with key \"" + name + "\" not found");
  52631. };
  52632. CacheStorage.getOrigin = function (url) {
  52633. var link = CacheStorage._link;
  52634. if (!link) {
  52635. return 'about:blank';
  52636. }
  52637. link.href = url;
  52638. link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
  52639. return link.protocol + link.hostname + link.port;
  52640. };
  52641. CacheStorage.isSameOrigin = function (src) {
  52642. return CacheStorage.getOrigin(src) === CacheStorage._origin;
  52643. };
  52644. CacheStorage.setContext = function (window) {
  52645. CacheStorage._link = window.document.createElement('a');
  52646. CacheStorage._origin = CacheStorage.getOrigin(window.location.href);
  52647. };
  52648. CacheStorage.getInstance = function () {
  52649. var current = CacheStorage._current;
  52650. if (current === null) {
  52651. throw new Error("No cache instance attached");
  52652. }
  52653. return current;
  52654. };
  52655. CacheStorage.attachInstance = function (cache) {
  52656. CacheStorage._current = cache;
  52657. };
  52658. CacheStorage.detachInstance = function () {
  52659. CacheStorage._current = null;
  52660. };
  52661. CacheStorage._caches = {};
  52662. CacheStorage._origin = 'about:blank';
  52663. CacheStorage._current = null;
  52664. return CacheStorage;
  52665. }());
  52666. var Cache = /** @class */ (function () {
  52667. function Cache(id, options) {
  52668. this.id = id;
  52669. this._options = options;
  52670. this._cache = {};
  52671. }
  52672. Cache.prototype.addImage = function (src) {
  52673. var result = Promise.resolve();
  52674. if (this.has(src)) {
  52675. return result;
  52676. }
  52677. if (isBlobImage(src) || isRenderable(src)) {
  52678. this._cache[src] = this.loadImage(src);
  52679. return result;
  52680. }
  52681. return result;
  52682. };
  52683. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  52684. Cache.prototype.match = function (src) {
  52685. return this._cache[src];
  52686. };
  52687. Cache.prototype.loadImage = function (key) {
  52688. return __awaiter(this, void 0, void 0, function () {
  52689. var isSameOrigin, useCORS, useProxy, src;
  52690. var _this = this;
  52691. return __generator(this, function (_a) {
  52692. switch (_a.label) {
  52693. case 0:
  52694. isSameOrigin = CacheStorage.isSameOrigin(key);
  52695. useCORS = !isInlineImage(key) && this._options.useCORS === true && FEATURES.SUPPORT_CORS_IMAGES && !isSameOrigin;
  52696. useProxy = !isInlineImage(key) &&
  52697. !isSameOrigin &&
  52698. typeof this._options.proxy === 'string' &&
  52699. FEATURES.SUPPORT_CORS_XHR &&
  52700. !useCORS;
  52701. if (!isSameOrigin && this._options.allowTaint === false && !isInlineImage(key) && !useProxy && !useCORS) {
  52702. return [2 /*return*/];
  52703. }
  52704. src = key;
  52705. if (!useProxy) return [3 /*break*/, 2];
  52706. return [4 /*yield*/, this.proxy(src)];
  52707. case 1:
  52708. src = _a.sent();
  52709. _a.label = 2;
  52710. case 2:
  52711. Logger.getInstance(this.id).debug("Added image " + key.substring(0, 256));
  52712. return [4 /*yield*/, new Promise(function (resolve, reject) {
  52713. var img = new Image();
  52714. img.onload = function () { return resolve(img); };
  52715. img.onerror = reject;
  52716. //ios safari 10.3 taints canvas with data urls unless crossOrigin is set to anonymous
  52717. if (isInlineBase64Image(src) || useCORS) {
  52718. img.crossOrigin = 'anonymous';
  52719. }
  52720. img.src = src;
  52721. if (img.complete === true) {
  52722. // Inline XML images may fail to parse, throwing an Error later on
  52723. setTimeout(function () { return resolve(img); }, 500);
  52724. }
  52725. if (_this._options.imageTimeout > 0) {
  52726. setTimeout(function () { return reject("Timed out (" + _this._options.imageTimeout + "ms) loading image"); }, _this._options.imageTimeout);
  52727. }
  52728. })];
  52729. case 3: return [2 /*return*/, _a.sent()];
  52730. }
  52731. });
  52732. });
  52733. };
  52734. Cache.prototype.has = function (key) {
  52735. return typeof this._cache[key] !== 'undefined';
  52736. };
  52737. Cache.prototype.keys = function () {
  52738. return Promise.resolve(Object.keys(this._cache));
  52739. };
  52740. Cache.prototype.proxy = function (src) {
  52741. var _this = this;
  52742. var proxy = this._options.proxy;
  52743. if (!proxy) {
  52744. throw new Error('No proxy defined');
  52745. }
  52746. var key = src.substring(0, 256);
  52747. return new Promise(function (resolve, reject) {
  52748. var responseType = FEATURES.SUPPORT_RESPONSE_TYPE ? 'blob' : 'text';
  52749. var xhr = new XMLHttpRequest();
  52750. xhr.onload = function () {
  52751. if (xhr.status === 200) {
  52752. if (responseType === 'text') {
  52753. resolve(xhr.response);
  52754. }
  52755. else {
  52756. var reader_1 = new FileReader();
  52757. reader_1.addEventListener('load', function () { return resolve(reader_1.result); }, false);
  52758. reader_1.addEventListener('error', function (e) { return reject(e); }, false);
  52759. reader_1.readAsDataURL(xhr.response);
  52760. }
  52761. }
  52762. else {
  52763. reject("Failed to proxy resource " + key + " with status code " + xhr.status);
  52764. }
  52765. };
  52766. xhr.onerror = reject;
  52767. xhr.open('GET', proxy + "?url=" + encodeURIComponent(src) + "&responseType=" + responseType);
  52768. if (responseType !== 'text' && xhr instanceof XMLHttpRequest) {
  52769. xhr.responseType = responseType;
  52770. }
  52771. if (_this._options.imageTimeout) {
  52772. var timeout_1 = _this._options.imageTimeout;
  52773. xhr.timeout = timeout_1;
  52774. xhr.ontimeout = function () { return reject("Timed out (" + timeout_1 + "ms) proxying " + key); };
  52775. }
  52776. xhr.send();
  52777. });
  52778. };
  52779. return Cache;
  52780. }());
  52781. var INLINE_SVG = /^data:image\/svg\+xml/i;
  52782. var INLINE_BASE64 = /^data:image\/.*;base64,/i;
  52783. var INLINE_IMG = /^data:image\/.*/i;
  52784. var isRenderable = function (src) { return FEATURES.SUPPORT_SVG_DRAWING || !isSVG(src); };
  52785. var isInlineImage = function (src) { return INLINE_IMG.test(src); };
  52786. var isInlineBase64Image = function (src) { return INLINE_BASE64.test(src); };
  52787. var isBlobImage = function (src) { return src.substr(0, 4) === 'blob'; };
  52788. var isSVG = function (src) { return src.substr(-3).toLowerCase() === 'svg' || INLINE_SVG.test(src); };
  52789. var webkitGradient = function (tokens) {
  52790. var angle = deg(180);
  52791. var stops = [];
  52792. var type = CSSImageType.LINEAR_GRADIENT;
  52793. var shape = CSSRadialShape.CIRCLE;
  52794. var size = CSSRadialExtent.FARTHEST_CORNER;
  52795. var position = [];
  52796. parseFunctionArgs(tokens).forEach(function (arg, i) {
  52797. var firstToken = arg[0];
  52798. if (i === 0) {
  52799. if (isIdentToken(firstToken) && firstToken.value === 'linear') {
  52800. type = CSSImageType.LINEAR_GRADIENT;
  52801. return;
  52802. }
  52803. else if (isIdentToken(firstToken) && firstToken.value === 'radial') {
  52804. type = CSSImageType.RADIAL_GRADIENT;
  52805. return;
  52806. }
  52807. }
  52808. if (firstToken.type === TokenType.FUNCTION) {
  52809. if (firstToken.name === 'from') {
  52810. var color$1 = color.parse(firstToken.values[0]);
  52811. stops.push({ stop: ZERO_LENGTH, color: color$1 });
  52812. }
  52813. else if (firstToken.name === 'to') {
  52814. var color$1 = color.parse(firstToken.values[0]);
  52815. stops.push({ stop: HUNDRED_PERCENT, color: color$1 });
  52816. }
  52817. else if (firstToken.name === 'color-stop') {
  52818. var values = firstToken.values.filter(nonFunctionArgSeparator);
  52819. if (values.length === 2) {
  52820. var color$1 = color.parse(values[1]);
  52821. var stop_1 = values[0];
  52822. if (isNumberToken(stop_1)) {
  52823. stops.push({
  52824. stop: { type: TokenType.PERCENTAGE_TOKEN, number: stop_1.number * 100, flags: stop_1.flags },
  52825. color: color$1
  52826. });
  52827. }
  52828. }
  52829. }
  52830. }
  52831. });
  52832. return type === CSSImageType.LINEAR_GRADIENT
  52833. ? {
  52834. angle: (angle + deg(180)) % deg(360),
  52835. stops: stops,
  52836. type: type
  52837. }
  52838. : { size: size, shape: shape, stops: stops, position: position, type: type };
  52839. };
  52840. var CLOSEST_SIDE = 'closest-side';
  52841. var FARTHEST_SIDE = 'farthest-side';
  52842. var CLOSEST_CORNER = 'closest-corner';
  52843. var FARTHEST_CORNER = 'farthest-corner';
  52844. var CIRCLE = 'circle';
  52845. var ELLIPSE = 'ellipse';
  52846. var COVER = 'cover';
  52847. var CONTAIN = 'contain';
  52848. var radialGradient = function (tokens) {
  52849. var shape = CSSRadialShape.CIRCLE;
  52850. var size = CSSRadialExtent.FARTHEST_CORNER;
  52851. var stops = [];
  52852. var position = [];
  52853. parseFunctionArgs(tokens).forEach(function (arg, i) {
  52854. var isColorStop = true;
  52855. if (i === 0) {
  52856. var isAtPosition_1 = false;
  52857. isColorStop = arg.reduce(function (acc, token) {
  52858. if (isAtPosition_1) {
  52859. if (isIdentToken(token)) {
  52860. switch (token.value) {
  52861. case 'center':
  52862. position.push(FIFTY_PERCENT);
  52863. return acc;
  52864. case 'top':
  52865. case 'left':
  52866. position.push(ZERO_LENGTH);
  52867. return acc;
  52868. case 'right':
  52869. case 'bottom':
  52870. position.push(HUNDRED_PERCENT);
  52871. return acc;
  52872. }
  52873. }
  52874. else if (isLengthPercentage(token) || isLength(token)) {
  52875. position.push(token);
  52876. }
  52877. }
  52878. else if (isIdentToken(token)) {
  52879. switch (token.value) {
  52880. case CIRCLE:
  52881. shape = CSSRadialShape.CIRCLE;
  52882. return false;
  52883. case ELLIPSE:
  52884. shape = CSSRadialShape.ELLIPSE;
  52885. return false;
  52886. case 'at':
  52887. isAtPosition_1 = true;
  52888. return false;
  52889. case CLOSEST_SIDE:
  52890. size = CSSRadialExtent.CLOSEST_SIDE;
  52891. return false;
  52892. case COVER:
  52893. case FARTHEST_SIDE:
  52894. size = CSSRadialExtent.FARTHEST_SIDE;
  52895. return false;
  52896. case CONTAIN:
  52897. case CLOSEST_CORNER:
  52898. size = CSSRadialExtent.CLOSEST_CORNER;
  52899. return false;
  52900. case FARTHEST_CORNER:
  52901. size = CSSRadialExtent.FARTHEST_CORNER;
  52902. return false;
  52903. }
  52904. }
  52905. else if (isLength(token) || isLengthPercentage(token)) {
  52906. if (!Array.isArray(size)) {
  52907. size = [];
  52908. }
  52909. size.push(token);
  52910. return false;
  52911. }
  52912. return acc;
  52913. }, isColorStop);
  52914. }
  52915. if (isColorStop) {
  52916. var colorStop = parseColorStop(arg);
  52917. stops.push(colorStop);
  52918. }
  52919. });
  52920. return { size: size, shape: shape, stops: stops, position: position, type: CSSImageType.RADIAL_GRADIENT };
  52921. };
  52922. var prefixRadialGradient = function (tokens) {
  52923. var shape = CSSRadialShape.CIRCLE;
  52924. var size = CSSRadialExtent.FARTHEST_CORNER;
  52925. var stops = [];
  52926. var position = [];
  52927. parseFunctionArgs(tokens).forEach(function (arg, i) {
  52928. var isColorStop = true;
  52929. if (i === 0) {
  52930. isColorStop = arg.reduce(function (acc, token) {
  52931. if (isIdentToken(token)) {
  52932. switch (token.value) {
  52933. case 'center':
  52934. position.push(FIFTY_PERCENT);
  52935. return false;
  52936. case 'top':
  52937. case 'left':
  52938. position.push(ZERO_LENGTH);
  52939. return false;
  52940. case 'right':
  52941. case 'bottom':
  52942. position.push(HUNDRED_PERCENT);
  52943. return false;
  52944. }
  52945. }
  52946. else if (isLengthPercentage(token) || isLength(token)) {
  52947. position.push(token);
  52948. return false;
  52949. }
  52950. return acc;
  52951. }, isColorStop);
  52952. }
  52953. else if (i === 1) {
  52954. isColorStop = arg.reduce(function (acc, token) {
  52955. if (isIdentToken(token)) {
  52956. switch (token.value) {
  52957. case CIRCLE:
  52958. shape = CSSRadialShape.CIRCLE;
  52959. return false;
  52960. case ELLIPSE:
  52961. shape = CSSRadialShape.ELLIPSE;
  52962. return false;
  52963. case CONTAIN:
  52964. case CLOSEST_SIDE:
  52965. size = CSSRadialExtent.CLOSEST_SIDE;
  52966. return false;
  52967. case FARTHEST_SIDE:
  52968. size = CSSRadialExtent.FARTHEST_SIDE;
  52969. return false;
  52970. case CLOSEST_CORNER:
  52971. size = CSSRadialExtent.CLOSEST_CORNER;
  52972. return false;
  52973. case COVER:
  52974. case FARTHEST_CORNER:
  52975. size = CSSRadialExtent.FARTHEST_CORNER;
  52976. return false;
  52977. }
  52978. }
  52979. else if (isLength(token) || isLengthPercentage(token)) {
  52980. if (!Array.isArray(size)) {
  52981. size = [];
  52982. }
  52983. size.push(token);
  52984. return false;
  52985. }
  52986. return acc;
  52987. }, isColorStop);
  52988. }
  52989. if (isColorStop) {
  52990. var colorStop = parseColorStop(arg);
  52991. stops.push(colorStop);
  52992. }
  52993. });
  52994. return { size: size, shape: shape, stops: stops, position: position, type: CSSImageType.RADIAL_GRADIENT };
  52995. };
  52996. var CSSImageType;
  52997. (function (CSSImageType) {
  52998. CSSImageType[CSSImageType["URL"] = 0] = "URL";
  52999. CSSImageType[CSSImageType["LINEAR_GRADIENT"] = 1] = "LINEAR_GRADIENT";
  53000. CSSImageType[CSSImageType["RADIAL_GRADIENT"] = 2] = "RADIAL_GRADIENT";
  53001. })(CSSImageType || (CSSImageType = {}));
  53002. var isLinearGradient = function (background) {
  53003. return background.type === CSSImageType.LINEAR_GRADIENT;
  53004. };
  53005. var isRadialGradient = function (background) {
  53006. return background.type === CSSImageType.RADIAL_GRADIENT;
  53007. };
  53008. var CSSRadialShape;
  53009. (function (CSSRadialShape) {
  53010. CSSRadialShape[CSSRadialShape["CIRCLE"] = 0] = "CIRCLE";
  53011. CSSRadialShape[CSSRadialShape["ELLIPSE"] = 1] = "ELLIPSE";
  53012. })(CSSRadialShape || (CSSRadialShape = {}));
  53013. var CSSRadialExtent;
  53014. (function (CSSRadialExtent) {
  53015. CSSRadialExtent[CSSRadialExtent["CLOSEST_SIDE"] = 0] = "CLOSEST_SIDE";
  53016. CSSRadialExtent[CSSRadialExtent["FARTHEST_SIDE"] = 1] = "FARTHEST_SIDE";
  53017. CSSRadialExtent[CSSRadialExtent["CLOSEST_CORNER"] = 2] = "CLOSEST_CORNER";
  53018. CSSRadialExtent[CSSRadialExtent["FARTHEST_CORNER"] = 3] = "FARTHEST_CORNER";
  53019. })(CSSRadialExtent || (CSSRadialExtent = {}));
  53020. var image = {
  53021. name: 'image',
  53022. parse: function (value) {
  53023. if (value.type === TokenType.URL_TOKEN) {
  53024. var image_1 = { url: value.value, type: CSSImageType.URL };
  53025. CacheStorage.getInstance().addImage(value.value);
  53026. return image_1;
  53027. }
  53028. if (value.type === TokenType.FUNCTION) {
  53029. var imageFunction = SUPPORTED_IMAGE_FUNCTIONS[value.name];
  53030. if (typeof imageFunction === 'undefined') {
  53031. throw new Error("Attempting to parse an unsupported image function \"" + value.name + "\"");
  53032. }
  53033. return imageFunction(value.values);
  53034. }
  53035. throw new Error("Unsupported image type");
  53036. }
  53037. };
  53038. function isSupportedImage(value) {
  53039. return value.type !== TokenType.FUNCTION || SUPPORTED_IMAGE_FUNCTIONS[value.name];
  53040. }
  53041. var SUPPORTED_IMAGE_FUNCTIONS = {
  53042. 'linear-gradient': linearGradient,
  53043. '-moz-linear-gradient': prefixLinearGradient,
  53044. '-ms-linear-gradient': prefixLinearGradient,
  53045. '-o-linear-gradient': prefixLinearGradient,
  53046. '-webkit-linear-gradient': prefixLinearGradient,
  53047. 'radial-gradient': radialGradient,
  53048. '-moz-radial-gradient': prefixRadialGradient,
  53049. '-ms-radial-gradient': prefixRadialGradient,
  53050. '-o-radial-gradient': prefixRadialGradient,
  53051. '-webkit-radial-gradient': prefixRadialGradient,
  53052. '-webkit-gradient': webkitGradient
  53053. };
  53054. var backgroundImage = {
  53055. name: 'background-image',
  53056. initialValue: 'none',
  53057. type: PropertyDescriptorParsingType.LIST,
  53058. prefix: false,
  53059. parse: function (tokens) {
  53060. if (tokens.length === 0) {
  53061. return [];
  53062. }
  53063. var first = tokens[0];
  53064. if (first.type === TokenType.IDENT_TOKEN && first.value === 'none') {
  53065. return [];
  53066. }
  53067. return tokens.filter(function (value) { return nonFunctionArgSeparator(value) && isSupportedImage(value); }).map(image.parse);
  53068. }
  53069. };
  53070. var backgroundOrigin = {
  53071. name: 'background-origin',
  53072. initialValue: 'border-box',
  53073. prefix: false,
  53074. type: PropertyDescriptorParsingType.LIST,
  53075. parse: function (tokens) {
  53076. return tokens.map(function (token) {
  53077. if (isIdentToken(token)) {
  53078. switch (token.value) {
  53079. case 'padding-box':
  53080. return 1 /* PADDING_BOX */;
  53081. case 'content-box':
  53082. return 2 /* CONTENT_BOX */;
  53083. }
  53084. }
  53085. return 0 /* BORDER_BOX */;
  53086. });
  53087. }
  53088. };
  53089. var backgroundPosition = {
  53090. name: 'background-position',
  53091. initialValue: '0% 0%',
  53092. type: PropertyDescriptorParsingType.LIST,
  53093. prefix: false,
  53094. parse: function (tokens) {
  53095. return parseFunctionArgs(tokens)
  53096. .map(function (values) { return values.filter(isLengthPercentage); })
  53097. .map(parseLengthPercentageTuple);
  53098. }
  53099. };
  53100. var BACKGROUND_REPEAT;
  53101. (function (BACKGROUND_REPEAT) {
  53102. BACKGROUND_REPEAT[BACKGROUND_REPEAT["REPEAT"] = 0] = "REPEAT";
  53103. BACKGROUND_REPEAT[BACKGROUND_REPEAT["NO_REPEAT"] = 1] = "NO_REPEAT";
  53104. BACKGROUND_REPEAT[BACKGROUND_REPEAT["REPEAT_X"] = 2] = "REPEAT_X";
  53105. BACKGROUND_REPEAT[BACKGROUND_REPEAT["REPEAT_Y"] = 3] = "REPEAT_Y";
  53106. })(BACKGROUND_REPEAT || (BACKGROUND_REPEAT = {}));
  53107. var backgroundRepeat = {
  53108. name: 'background-repeat',
  53109. initialValue: 'repeat',
  53110. prefix: false,
  53111. type: PropertyDescriptorParsingType.LIST,
  53112. parse: function (tokens) {
  53113. return parseFunctionArgs(tokens)
  53114. .map(function (values) {
  53115. return values
  53116. .filter(isIdentToken)
  53117. .map(function (token) { return token.value; })
  53118. .join(' ');
  53119. })
  53120. .map(parseBackgroundRepeat);
  53121. }
  53122. };
  53123. var parseBackgroundRepeat = function (value) {
  53124. switch (value) {
  53125. case 'no-repeat':
  53126. return BACKGROUND_REPEAT.NO_REPEAT;
  53127. case 'repeat-x':
  53128. case 'repeat no-repeat':
  53129. return BACKGROUND_REPEAT.REPEAT_X;
  53130. case 'repeat-y':
  53131. case 'no-repeat repeat':
  53132. return BACKGROUND_REPEAT.REPEAT_Y;
  53133. case 'repeat':
  53134. default:
  53135. return BACKGROUND_REPEAT.REPEAT;
  53136. }
  53137. };
  53138. var BACKGROUND_SIZE;
  53139. (function (BACKGROUND_SIZE) {
  53140. BACKGROUND_SIZE["AUTO"] = "auto";
  53141. BACKGROUND_SIZE["CONTAIN"] = "contain";
  53142. BACKGROUND_SIZE["COVER"] = "cover";
  53143. })(BACKGROUND_SIZE || (BACKGROUND_SIZE = {}));
  53144. var backgroundSize = {
  53145. name: 'background-size',
  53146. initialValue: '0',
  53147. prefix: false,
  53148. type: PropertyDescriptorParsingType.LIST,
  53149. parse: function (tokens) {
  53150. return parseFunctionArgs(tokens).map(function (values) { return values.filter(isBackgroundSizeInfoToken); });
  53151. }
  53152. };
  53153. var isBackgroundSizeInfoToken = function (value) {
  53154. return isIdentToken(value) || isLengthPercentage(value);
  53155. };
  53156. var borderColorForSide = function (side) { return ({
  53157. name: "border-" + side + "-color",
  53158. initialValue: 'transparent',
  53159. prefix: false,
  53160. type: PropertyDescriptorParsingType.TYPE_VALUE,
  53161. format: 'color'
  53162. }); };
  53163. var borderTopColor = borderColorForSide('top');
  53164. var borderRightColor = borderColorForSide('right');
  53165. var borderBottomColor = borderColorForSide('bottom');
  53166. var borderLeftColor = borderColorForSide('left');
  53167. var borderRadiusForSide = function (side) { return ({
  53168. name: "border-radius-" + side,
  53169. initialValue: '0 0',
  53170. prefix: false,
  53171. type: PropertyDescriptorParsingType.LIST,
  53172. parse: function (tokens) { return parseLengthPercentageTuple(tokens.filter(isLengthPercentage)); }
  53173. }); };
  53174. var borderTopLeftRadius = borderRadiusForSide('top-left');
  53175. var borderTopRightRadius = borderRadiusForSide('top-right');
  53176. var borderBottomRightRadius = borderRadiusForSide('bottom-right');
  53177. var borderBottomLeftRadius = borderRadiusForSide('bottom-left');
  53178. var BORDER_STYLE;
  53179. (function (BORDER_STYLE) {
  53180. BORDER_STYLE[BORDER_STYLE["NONE"] = 0] = "NONE";
  53181. BORDER_STYLE[BORDER_STYLE["SOLID"] = 1] = "SOLID";
  53182. })(BORDER_STYLE || (BORDER_STYLE = {}));
  53183. var borderStyleForSide = function (side) { return ({
  53184. name: "border-" + side + "-style",
  53185. initialValue: 'solid',
  53186. prefix: false,
  53187. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53188. parse: function (style) {
  53189. switch (style) {
  53190. case 'none':
  53191. return BORDER_STYLE.NONE;
  53192. }
  53193. return BORDER_STYLE.SOLID;
  53194. }
  53195. }); };
  53196. var borderTopStyle = borderStyleForSide('top');
  53197. var borderRightStyle = borderStyleForSide('right');
  53198. var borderBottomStyle = borderStyleForSide('bottom');
  53199. var borderLeftStyle = borderStyleForSide('left');
  53200. var borderWidthForSide = function (side) { return ({
  53201. name: "border-" + side + "-width",
  53202. initialValue: '0',
  53203. type: PropertyDescriptorParsingType.VALUE,
  53204. prefix: false,
  53205. parse: function (token) {
  53206. if (isDimensionToken(token)) {
  53207. return token.number;
  53208. }
  53209. return 0;
  53210. }
  53211. }); };
  53212. var borderTopWidth = borderWidthForSide('top');
  53213. var borderRightWidth = borderWidthForSide('right');
  53214. var borderBottomWidth = borderWidthForSide('bottom');
  53215. var borderLeftWidth = borderWidthForSide('left');
  53216. var color$1 = {
  53217. name: "color",
  53218. initialValue: 'transparent',
  53219. prefix: false,
  53220. type: PropertyDescriptorParsingType.TYPE_VALUE,
  53221. format: 'color'
  53222. };
  53223. var display = {
  53224. name: 'display',
  53225. initialValue: 'inline-block',
  53226. prefix: false,
  53227. type: PropertyDescriptorParsingType.LIST,
  53228. parse: function (tokens) {
  53229. return tokens.filter(isIdentToken).reduce(function (bit, token) {
  53230. return bit | parseDisplayValue(token.value);
  53231. }, 0 /* NONE */);
  53232. }
  53233. };
  53234. var parseDisplayValue = function (display) {
  53235. switch (display) {
  53236. case 'block':
  53237. return 2 /* BLOCK */;
  53238. case 'inline':
  53239. return 4 /* INLINE */;
  53240. case 'run-in':
  53241. return 8 /* RUN_IN */;
  53242. case 'flow':
  53243. return 16 /* FLOW */;
  53244. case 'flow-root':
  53245. return 32 /* FLOW_ROOT */;
  53246. case 'table':
  53247. return 64 /* TABLE */;
  53248. case 'flex':
  53249. case '-webkit-flex':
  53250. return 128 /* FLEX */;
  53251. case 'grid':
  53252. case '-ms-grid':
  53253. return 256 /* GRID */;
  53254. case 'ruby':
  53255. return 512 /* RUBY */;
  53256. case 'subgrid':
  53257. return 1024 /* SUBGRID */;
  53258. case 'list-item':
  53259. return 2048 /* LIST_ITEM */;
  53260. case 'table-row-group':
  53261. return 4096 /* TABLE_ROW_GROUP */;
  53262. case 'table-header-group':
  53263. return 8192 /* TABLE_HEADER_GROUP */;
  53264. case 'table-footer-group':
  53265. return 16384 /* TABLE_FOOTER_GROUP */;
  53266. case 'table-row':
  53267. return 32768 /* TABLE_ROW */;
  53268. case 'table-cell':
  53269. return 65536 /* TABLE_CELL */;
  53270. case 'table-column-group':
  53271. return 131072 /* TABLE_COLUMN_GROUP */;
  53272. case 'table-column':
  53273. return 262144 /* TABLE_COLUMN */;
  53274. case 'table-caption':
  53275. return 524288 /* TABLE_CAPTION */;
  53276. case 'ruby-base':
  53277. return 1048576 /* RUBY_BASE */;
  53278. case 'ruby-text':
  53279. return 2097152 /* RUBY_TEXT */;
  53280. case 'ruby-base-container':
  53281. return 4194304 /* RUBY_BASE_CONTAINER */;
  53282. case 'ruby-text-container':
  53283. return 8388608 /* RUBY_TEXT_CONTAINER */;
  53284. case 'contents':
  53285. return 16777216 /* CONTENTS */;
  53286. case 'inline-block':
  53287. return 33554432 /* INLINE_BLOCK */;
  53288. case 'inline-list-item':
  53289. return 67108864 /* INLINE_LIST_ITEM */;
  53290. case 'inline-table':
  53291. return 134217728 /* INLINE_TABLE */;
  53292. case 'inline-flex':
  53293. return 268435456 /* INLINE_FLEX */;
  53294. case 'inline-grid':
  53295. return 536870912 /* INLINE_GRID */;
  53296. }
  53297. return 0 /* NONE */;
  53298. };
  53299. var FLOAT;
  53300. (function (FLOAT) {
  53301. FLOAT[FLOAT["NONE"] = 0] = "NONE";
  53302. FLOAT[FLOAT["LEFT"] = 1] = "LEFT";
  53303. FLOAT[FLOAT["RIGHT"] = 2] = "RIGHT";
  53304. FLOAT[FLOAT["INLINE_START"] = 3] = "INLINE_START";
  53305. FLOAT[FLOAT["INLINE_END"] = 4] = "INLINE_END";
  53306. })(FLOAT || (FLOAT = {}));
  53307. var float = {
  53308. name: 'float',
  53309. initialValue: 'none',
  53310. prefix: false,
  53311. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53312. parse: function (float) {
  53313. switch (float) {
  53314. case 'left':
  53315. return FLOAT.LEFT;
  53316. case 'right':
  53317. return FLOAT.RIGHT;
  53318. case 'inline-start':
  53319. return FLOAT.INLINE_START;
  53320. case 'inline-end':
  53321. return FLOAT.INLINE_END;
  53322. }
  53323. return FLOAT.NONE;
  53324. }
  53325. };
  53326. var letterSpacing = {
  53327. name: 'letter-spacing',
  53328. initialValue: '0',
  53329. prefix: false,
  53330. type: PropertyDescriptorParsingType.VALUE,
  53331. parse: function (token) {
  53332. if (token.type === TokenType.IDENT_TOKEN && token.value === 'normal') {
  53333. return 0;
  53334. }
  53335. if (token.type === TokenType.NUMBER_TOKEN) {
  53336. return token.number;
  53337. }
  53338. if (token.type === TokenType.DIMENSION_TOKEN) {
  53339. return token.number;
  53340. }
  53341. return 0;
  53342. }
  53343. };
  53344. var LINE_BREAK;
  53345. (function (LINE_BREAK) {
  53346. LINE_BREAK["NORMAL"] = "normal";
  53347. LINE_BREAK["STRICT"] = "strict";
  53348. })(LINE_BREAK || (LINE_BREAK = {}));
  53349. var lineBreak = {
  53350. name: 'line-break',
  53351. initialValue: 'normal',
  53352. prefix: false,
  53353. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53354. parse: function (lineBreak) {
  53355. switch (lineBreak) {
  53356. case 'strict':
  53357. return LINE_BREAK.STRICT;
  53358. case 'normal':
  53359. default:
  53360. return LINE_BREAK.NORMAL;
  53361. }
  53362. }
  53363. };
  53364. var lineHeight = {
  53365. name: 'line-height',
  53366. initialValue: 'normal',
  53367. prefix: false,
  53368. type: PropertyDescriptorParsingType.TOKEN_VALUE
  53369. };
  53370. var computeLineHeight = function (token, fontSize) {
  53371. if (isIdentToken(token) && token.value === 'normal') {
  53372. return 1.2 * fontSize;
  53373. }
  53374. else if (token.type === TokenType.NUMBER_TOKEN) {
  53375. return fontSize * token.number;
  53376. }
  53377. else if (isLengthPercentage(token)) {
  53378. return getAbsoluteValue(token, fontSize);
  53379. }
  53380. return fontSize;
  53381. };
  53382. var listStyleImage = {
  53383. name: 'list-style-image',
  53384. initialValue: 'none',
  53385. type: PropertyDescriptorParsingType.VALUE,
  53386. prefix: false,
  53387. parse: function (token) {
  53388. if (token.type === TokenType.IDENT_TOKEN && token.value === 'none') {
  53389. return null;
  53390. }
  53391. return image.parse(token);
  53392. }
  53393. };
  53394. var LIST_STYLE_POSITION;
  53395. (function (LIST_STYLE_POSITION) {
  53396. LIST_STYLE_POSITION[LIST_STYLE_POSITION["INSIDE"] = 0] = "INSIDE";
  53397. LIST_STYLE_POSITION[LIST_STYLE_POSITION["OUTSIDE"] = 1] = "OUTSIDE";
  53398. })(LIST_STYLE_POSITION || (LIST_STYLE_POSITION = {}));
  53399. var listStylePosition = {
  53400. name: 'list-style-position',
  53401. initialValue: 'outside',
  53402. prefix: false,
  53403. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53404. parse: function (position) {
  53405. switch (position) {
  53406. case 'inside':
  53407. return LIST_STYLE_POSITION.INSIDE;
  53408. case 'outside':
  53409. default:
  53410. return LIST_STYLE_POSITION.OUTSIDE;
  53411. }
  53412. }
  53413. };
  53414. var LIST_STYLE_TYPE;
  53415. (function (LIST_STYLE_TYPE) {
  53416. LIST_STYLE_TYPE[LIST_STYLE_TYPE["NONE"] = -1] = "NONE";
  53417. LIST_STYLE_TYPE[LIST_STYLE_TYPE["DISC"] = 0] = "DISC";
  53418. LIST_STYLE_TYPE[LIST_STYLE_TYPE["CIRCLE"] = 1] = "CIRCLE";
  53419. LIST_STYLE_TYPE[LIST_STYLE_TYPE["SQUARE"] = 2] = "SQUARE";
  53420. LIST_STYLE_TYPE[LIST_STYLE_TYPE["DECIMAL"] = 3] = "DECIMAL";
  53421. LIST_STYLE_TYPE[LIST_STYLE_TYPE["CJK_DECIMAL"] = 4] = "CJK_DECIMAL";
  53422. LIST_STYLE_TYPE[LIST_STYLE_TYPE["DECIMAL_LEADING_ZERO"] = 5] = "DECIMAL_LEADING_ZERO";
  53423. LIST_STYLE_TYPE[LIST_STYLE_TYPE["LOWER_ROMAN"] = 6] = "LOWER_ROMAN";
  53424. LIST_STYLE_TYPE[LIST_STYLE_TYPE["UPPER_ROMAN"] = 7] = "UPPER_ROMAN";
  53425. LIST_STYLE_TYPE[LIST_STYLE_TYPE["LOWER_GREEK"] = 8] = "LOWER_GREEK";
  53426. LIST_STYLE_TYPE[LIST_STYLE_TYPE["LOWER_ALPHA"] = 9] = "LOWER_ALPHA";
  53427. LIST_STYLE_TYPE[LIST_STYLE_TYPE["UPPER_ALPHA"] = 10] = "UPPER_ALPHA";
  53428. LIST_STYLE_TYPE[LIST_STYLE_TYPE["ARABIC_INDIC"] = 11] = "ARABIC_INDIC";
  53429. LIST_STYLE_TYPE[LIST_STYLE_TYPE["ARMENIAN"] = 12] = "ARMENIAN";
  53430. LIST_STYLE_TYPE[LIST_STYLE_TYPE["BENGALI"] = 13] = "BENGALI";
  53431. LIST_STYLE_TYPE[LIST_STYLE_TYPE["CAMBODIAN"] = 14] = "CAMBODIAN";
  53432. LIST_STYLE_TYPE[LIST_STYLE_TYPE["CJK_EARTHLY_BRANCH"] = 15] = "CJK_EARTHLY_BRANCH";
  53433. LIST_STYLE_TYPE[LIST_STYLE_TYPE["CJK_HEAVENLY_STEM"] = 16] = "CJK_HEAVENLY_STEM";
  53434. LIST_STYLE_TYPE[LIST_STYLE_TYPE["CJK_IDEOGRAPHIC"] = 17] = "CJK_IDEOGRAPHIC";
  53435. LIST_STYLE_TYPE[LIST_STYLE_TYPE["DEVANAGARI"] = 18] = "DEVANAGARI";
  53436. LIST_STYLE_TYPE[LIST_STYLE_TYPE["ETHIOPIC_NUMERIC"] = 19] = "ETHIOPIC_NUMERIC";
  53437. LIST_STYLE_TYPE[LIST_STYLE_TYPE["GEORGIAN"] = 20] = "GEORGIAN";
  53438. LIST_STYLE_TYPE[LIST_STYLE_TYPE["GUJARATI"] = 21] = "GUJARATI";
  53439. LIST_STYLE_TYPE[LIST_STYLE_TYPE["GURMUKHI"] = 22] = "GURMUKHI";
  53440. LIST_STYLE_TYPE[LIST_STYLE_TYPE["HEBREW"] = 22] = "HEBREW";
  53441. LIST_STYLE_TYPE[LIST_STYLE_TYPE["HIRAGANA"] = 23] = "HIRAGANA";
  53442. LIST_STYLE_TYPE[LIST_STYLE_TYPE["HIRAGANA_IROHA"] = 24] = "HIRAGANA_IROHA";
  53443. LIST_STYLE_TYPE[LIST_STYLE_TYPE["JAPANESE_FORMAL"] = 25] = "JAPANESE_FORMAL";
  53444. LIST_STYLE_TYPE[LIST_STYLE_TYPE["JAPANESE_INFORMAL"] = 26] = "JAPANESE_INFORMAL";
  53445. LIST_STYLE_TYPE[LIST_STYLE_TYPE["KANNADA"] = 27] = "KANNADA";
  53446. LIST_STYLE_TYPE[LIST_STYLE_TYPE["KATAKANA"] = 28] = "KATAKANA";
  53447. LIST_STYLE_TYPE[LIST_STYLE_TYPE["KATAKANA_IROHA"] = 29] = "KATAKANA_IROHA";
  53448. LIST_STYLE_TYPE[LIST_STYLE_TYPE["KHMER"] = 30] = "KHMER";
  53449. LIST_STYLE_TYPE[LIST_STYLE_TYPE["KOREAN_HANGUL_FORMAL"] = 31] = "KOREAN_HANGUL_FORMAL";
  53450. LIST_STYLE_TYPE[LIST_STYLE_TYPE["KOREAN_HANJA_FORMAL"] = 32] = "KOREAN_HANJA_FORMAL";
  53451. LIST_STYLE_TYPE[LIST_STYLE_TYPE["KOREAN_HANJA_INFORMAL"] = 33] = "KOREAN_HANJA_INFORMAL";
  53452. LIST_STYLE_TYPE[LIST_STYLE_TYPE["LAO"] = 34] = "LAO";
  53453. LIST_STYLE_TYPE[LIST_STYLE_TYPE["LOWER_ARMENIAN"] = 35] = "LOWER_ARMENIAN";
  53454. LIST_STYLE_TYPE[LIST_STYLE_TYPE["MALAYALAM"] = 36] = "MALAYALAM";
  53455. LIST_STYLE_TYPE[LIST_STYLE_TYPE["MONGOLIAN"] = 37] = "MONGOLIAN";
  53456. LIST_STYLE_TYPE[LIST_STYLE_TYPE["MYANMAR"] = 38] = "MYANMAR";
  53457. LIST_STYLE_TYPE[LIST_STYLE_TYPE["ORIYA"] = 39] = "ORIYA";
  53458. LIST_STYLE_TYPE[LIST_STYLE_TYPE["PERSIAN"] = 40] = "PERSIAN";
  53459. LIST_STYLE_TYPE[LIST_STYLE_TYPE["SIMP_CHINESE_FORMAL"] = 41] = "SIMP_CHINESE_FORMAL";
  53460. LIST_STYLE_TYPE[LIST_STYLE_TYPE["SIMP_CHINESE_INFORMAL"] = 42] = "SIMP_CHINESE_INFORMAL";
  53461. LIST_STYLE_TYPE[LIST_STYLE_TYPE["TAMIL"] = 43] = "TAMIL";
  53462. LIST_STYLE_TYPE[LIST_STYLE_TYPE["TELUGU"] = 44] = "TELUGU";
  53463. LIST_STYLE_TYPE[LIST_STYLE_TYPE["THAI"] = 45] = "THAI";
  53464. LIST_STYLE_TYPE[LIST_STYLE_TYPE["TIBETAN"] = 46] = "TIBETAN";
  53465. LIST_STYLE_TYPE[LIST_STYLE_TYPE["TRAD_CHINESE_FORMAL"] = 47] = "TRAD_CHINESE_FORMAL";
  53466. LIST_STYLE_TYPE[LIST_STYLE_TYPE["TRAD_CHINESE_INFORMAL"] = 48] = "TRAD_CHINESE_INFORMAL";
  53467. LIST_STYLE_TYPE[LIST_STYLE_TYPE["UPPER_ARMENIAN"] = 49] = "UPPER_ARMENIAN";
  53468. LIST_STYLE_TYPE[LIST_STYLE_TYPE["DISCLOSURE_OPEN"] = 50] = "DISCLOSURE_OPEN";
  53469. LIST_STYLE_TYPE[LIST_STYLE_TYPE["DISCLOSURE_CLOSED"] = 51] = "DISCLOSURE_CLOSED";
  53470. })(LIST_STYLE_TYPE || (LIST_STYLE_TYPE = {}));
  53471. var listStyleType = {
  53472. name: 'list-style-type',
  53473. initialValue: 'none',
  53474. prefix: false,
  53475. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53476. parse: function (type) {
  53477. switch (type) {
  53478. case 'disc':
  53479. return LIST_STYLE_TYPE.DISC;
  53480. case 'circle':
  53481. return LIST_STYLE_TYPE.CIRCLE;
  53482. case 'square':
  53483. return LIST_STYLE_TYPE.SQUARE;
  53484. case 'decimal':
  53485. return LIST_STYLE_TYPE.DECIMAL;
  53486. case 'cjk-decimal':
  53487. return LIST_STYLE_TYPE.CJK_DECIMAL;
  53488. case 'decimal-leading-zero':
  53489. return LIST_STYLE_TYPE.DECIMAL_LEADING_ZERO;
  53490. case 'lower-roman':
  53491. return LIST_STYLE_TYPE.LOWER_ROMAN;
  53492. case 'upper-roman':
  53493. return LIST_STYLE_TYPE.UPPER_ROMAN;
  53494. case 'lower-greek':
  53495. return LIST_STYLE_TYPE.LOWER_GREEK;
  53496. case 'lower-alpha':
  53497. return LIST_STYLE_TYPE.LOWER_ALPHA;
  53498. case 'upper-alpha':
  53499. return LIST_STYLE_TYPE.UPPER_ALPHA;
  53500. case 'arabic-indic':
  53501. return LIST_STYLE_TYPE.ARABIC_INDIC;
  53502. case 'armenian':
  53503. return LIST_STYLE_TYPE.ARMENIAN;
  53504. case 'bengali':
  53505. return LIST_STYLE_TYPE.BENGALI;
  53506. case 'cambodian':
  53507. return LIST_STYLE_TYPE.CAMBODIAN;
  53508. case 'cjk-earthly-branch':
  53509. return LIST_STYLE_TYPE.CJK_EARTHLY_BRANCH;
  53510. case 'cjk-heavenly-stem':
  53511. return LIST_STYLE_TYPE.CJK_HEAVENLY_STEM;
  53512. case 'cjk-ideographic':
  53513. return LIST_STYLE_TYPE.CJK_IDEOGRAPHIC;
  53514. case 'devanagari':
  53515. return LIST_STYLE_TYPE.DEVANAGARI;
  53516. case 'ethiopic-numeric':
  53517. return LIST_STYLE_TYPE.ETHIOPIC_NUMERIC;
  53518. case 'georgian':
  53519. return LIST_STYLE_TYPE.GEORGIAN;
  53520. case 'gujarati':
  53521. return LIST_STYLE_TYPE.GUJARATI;
  53522. case 'gurmukhi':
  53523. return LIST_STYLE_TYPE.GURMUKHI;
  53524. case 'hebrew':
  53525. return LIST_STYLE_TYPE.HEBREW;
  53526. case 'hiragana':
  53527. return LIST_STYLE_TYPE.HIRAGANA;
  53528. case 'hiragana-iroha':
  53529. return LIST_STYLE_TYPE.HIRAGANA_IROHA;
  53530. case 'japanese-formal':
  53531. return LIST_STYLE_TYPE.JAPANESE_FORMAL;
  53532. case 'japanese-informal':
  53533. return LIST_STYLE_TYPE.JAPANESE_INFORMAL;
  53534. case 'kannada':
  53535. return LIST_STYLE_TYPE.KANNADA;
  53536. case 'katakana':
  53537. return LIST_STYLE_TYPE.KATAKANA;
  53538. case 'katakana-iroha':
  53539. return LIST_STYLE_TYPE.KATAKANA_IROHA;
  53540. case 'khmer':
  53541. return LIST_STYLE_TYPE.KHMER;
  53542. case 'korean-hangul-formal':
  53543. return LIST_STYLE_TYPE.KOREAN_HANGUL_FORMAL;
  53544. case 'korean-hanja-formal':
  53545. return LIST_STYLE_TYPE.KOREAN_HANJA_FORMAL;
  53546. case 'korean-hanja-informal':
  53547. return LIST_STYLE_TYPE.KOREAN_HANJA_INFORMAL;
  53548. case 'lao':
  53549. return LIST_STYLE_TYPE.LAO;
  53550. case 'lower-armenian':
  53551. return LIST_STYLE_TYPE.LOWER_ARMENIAN;
  53552. case 'malayalam':
  53553. return LIST_STYLE_TYPE.MALAYALAM;
  53554. case 'mongolian':
  53555. return LIST_STYLE_TYPE.MONGOLIAN;
  53556. case 'myanmar':
  53557. return LIST_STYLE_TYPE.MYANMAR;
  53558. case 'oriya':
  53559. return LIST_STYLE_TYPE.ORIYA;
  53560. case 'persian':
  53561. return LIST_STYLE_TYPE.PERSIAN;
  53562. case 'simp-chinese-formal':
  53563. return LIST_STYLE_TYPE.SIMP_CHINESE_FORMAL;
  53564. case 'simp-chinese-informal':
  53565. return LIST_STYLE_TYPE.SIMP_CHINESE_INFORMAL;
  53566. case 'tamil':
  53567. return LIST_STYLE_TYPE.TAMIL;
  53568. case 'telugu':
  53569. return LIST_STYLE_TYPE.TELUGU;
  53570. case 'thai':
  53571. return LIST_STYLE_TYPE.THAI;
  53572. case 'tibetan':
  53573. return LIST_STYLE_TYPE.TIBETAN;
  53574. case 'trad-chinese-formal':
  53575. return LIST_STYLE_TYPE.TRAD_CHINESE_FORMAL;
  53576. case 'trad-chinese-informal':
  53577. return LIST_STYLE_TYPE.TRAD_CHINESE_INFORMAL;
  53578. case 'upper-armenian':
  53579. return LIST_STYLE_TYPE.UPPER_ARMENIAN;
  53580. case 'disclosure-open':
  53581. return LIST_STYLE_TYPE.DISCLOSURE_OPEN;
  53582. case 'disclosure-closed':
  53583. return LIST_STYLE_TYPE.DISCLOSURE_CLOSED;
  53584. case 'none':
  53585. default:
  53586. return LIST_STYLE_TYPE.NONE;
  53587. }
  53588. }
  53589. };
  53590. var marginForSide = function (side) { return ({
  53591. name: "margin-" + side,
  53592. initialValue: '0',
  53593. prefix: false,
  53594. type: PropertyDescriptorParsingType.TOKEN_VALUE
  53595. }); };
  53596. var marginTop = marginForSide('top');
  53597. var marginRight = marginForSide('right');
  53598. var marginBottom = marginForSide('bottom');
  53599. var marginLeft = marginForSide('left');
  53600. var OVERFLOW;
  53601. (function (OVERFLOW) {
  53602. OVERFLOW[OVERFLOW["VISIBLE"] = 0] = "VISIBLE";
  53603. OVERFLOW[OVERFLOW["HIDDEN"] = 1] = "HIDDEN";
  53604. OVERFLOW[OVERFLOW["SCROLL"] = 2] = "SCROLL";
  53605. OVERFLOW[OVERFLOW["AUTO"] = 3] = "AUTO";
  53606. })(OVERFLOW || (OVERFLOW = {}));
  53607. var overflow = {
  53608. name: 'overflow',
  53609. initialValue: 'visible',
  53610. prefix: false,
  53611. type: PropertyDescriptorParsingType.LIST,
  53612. parse: function (tokens) {
  53613. return tokens.filter(isIdentToken).map(function (overflow) {
  53614. switch (overflow.value) {
  53615. case 'hidden':
  53616. return OVERFLOW.HIDDEN;
  53617. case 'scroll':
  53618. return OVERFLOW.SCROLL;
  53619. case 'auto':
  53620. return OVERFLOW.AUTO;
  53621. case 'visible':
  53622. default:
  53623. return OVERFLOW.VISIBLE;
  53624. }
  53625. });
  53626. }
  53627. };
  53628. var OVERFLOW_WRAP;
  53629. (function (OVERFLOW_WRAP) {
  53630. OVERFLOW_WRAP["NORMAL"] = "normal";
  53631. OVERFLOW_WRAP["BREAK_WORD"] = "break-word";
  53632. })(OVERFLOW_WRAP || (OVERFLOW_WRAP = {}));
  53633. var overflowWrap = {
  53634. name: 'overflow-wrap',
  53635. initialValue: 'normal',
  53636. prefix: false,
  53637. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53638. parse: function (overflow) {
  53639. switch (overflow) {
  53640. case 'break-word':
  53641. return OVERFLOW_WRAP.BREAK_WORD;
  53642. case 'normal':
  53643. default:
  53644. return OVERFLOW_WRAP.NORMAL;
  53645. }
  53646. }
  53647. };
  53648. var paddingForSide = function (side) { return ({
  53649. name: "padding-" + side,
  53650. initialValue: '0',
  53651. prefix: false,
  53652. type: PropertyDescriptorParsingType.TYPE_VALUE,
  53653. format: 'length-percentage'
  53654. }); };
  53655. var paddingTop = paddingForSide('top');
  53656. var paddingRight = paddingForSide('right');
  53657. var paddingBottom = paddingForSide('bottom');
  53658. var paddingLeft = paddingForSide('left');
  53659. var TEXT_ALIGN;
  53660. (function (TEXT_ALIGN) {
  53661. TEXT_ALIGN[TEXT_ALIGN["LEFT"] = 0] = "LEFT";
  53662. TEXT_ALIGN[TEXT_ALIGN["CENTER"] = 1] = "CENTER";
  53663. TEXT_ALIGN[TEXT_ALIGN["RIGHT"] = 2] = "RIGHT";
  53664. })(TEXT_ALIGN || (TEXT_ALIGN = {}));
  53665. var textAlign = {
  53666. name: 'text-align',
  53667. initialValue: 'left',
  53668. prefix: false,
  53669. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53670. parse: function (textAlign) {
  53671. switch (textAlign) {
  53672. case 'right':
  53673. return TEXT_ALIGN.RIGHT;
  53674. case 'center':
  53675. case 'justify':
  53676. return TEXT_ALIGN.CENTER;
  53677. case 'left':
  53678. default:
  53679. return TEXT_ALIGN.LEFT;
  53680. }
  53681. }
  53682. };
  53683. var POSITION;
  53684. (function (POSITION) {
  53685. POSITION[POSITION["STATIC"] = 0] = "STATIC";
  53686. POSITION[POSITION["RELATIVE"] = 1] = "RELATIVE";
  53687. POSITION[POSITION["ABSOLUTE"] = 2] = "ABSOLUTE";
  53688. POSITION[POSITION["FIXED"] = 3] = "FIXED";
  53689. POSITION[POSITION["STICKY"] = 4] = "STICKY";
  53690. })(POSITION || (POSITION = {}));
  53691. var position = {
  53692. name: 'position',
  53693. initialValue: 'static',
  53694. prefix: false,
  53695. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53696. parse: function (position) {
  53697. switch (position) {
  53698. case 'relative':
  53699. return POSITION.RELATIVE;
  53700. case 'absolute':
  53701. return POSITION.ABSOLUTE;
  53702. case 'fixed':
  53703. return POSITION.FIXED;
  53704. case 'sticky':
  53705. return POSITION.STICKY;
  53706. }
  53707. return POSITION.STATIC;
  53708. }
  53709. };
  53710. var textShadow = {
  53711. name: 'text-shadow',
  53712. initialValue: 'none',
  53713. type: PropertyDescriptorParsingType.LIST,
  53714. prefix: false,
  53715. parse: function (tokens) {
  53716. if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) {
  53717. return [];
  53718. }
  53719. return parseFunctionArgs(tokens).map(function (values) {
  53720. var shadow = {
  53721. color: COLORS.TRANSPARENT,
  53722. offsetX: ZERO_LENGTH,
  53723. offsetY: ZERO_LENGTH,
  53724. blur: ZERO_LENGTH
  53725. };
  53726. var c = 0;
  53727. for (var i = 0; i < values.length; i++) {
  53728. var token = values[i];
  53729. if (isLength(token)) {
  53730. if (c === 0) {
  53731. shadow.offsetX = token;
  53732. }
  53733. else if (c === 1) {
  53734. shadow.offsetY = token;
  53735. }
  53736. else {
  53737. shadow.blur = token;
  53738. }
  53739. c++;
  53740. }
  53741. else {
  53742. shadow.color = color.parse(token);
  53743. }
  53744. }
  53745. return shadow;
  53746. });
  53747. }
  53748. };
  53749. var TEXT_TRANSFORM;
  53750. (function (TEXT_TRANSFORM) {
  53751. TEXT_TRANSFORM[TEXT_TRANSFORM["NONE"] = 0] = "NONE";
  53752. TEXT_TRANSFORM[TEXT_TRANSFORM["LOWERCASE"] = 1] = "LOWERCASE";
  53753. TEXT_TRANSFORM[TEXT_TRANSFORM["UPPERCASE"] = 2] = "UPPERCASE";
  53754. TEXT_TRANSFORM[TEXT_TRANSFORM["CAPITALIZE"] = 3] = "CAPITALIZE";
  53755. })(TEXT_TRANSFORM || (TEXT_TRANSFORM = {}));
  53756. var textTransform = {
  53757. name: 'text-transform',
  53758. initialValue: 'none',
  53759. prefix: false,
  53760. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53761. parse: function (textTransform) {
  53762. switch (textTransform) {
  53763. case 'uppercase':
  53764. return TEXT_TRANSFORM.UPPERCASE;
  53765. case 'lowercase':
  53766. return TEXT_TRANSFORM.LOWERCASE;
  53767. case 'capitalize':
  53768. return TEXT_TRANSFORM.CAPITALIZE;
  53769. }
  53770. return TEXT_TRANSFORM.NONE;
  53771. }
  53772. };
  53773. var transform = {
  53774. name: 'transform',
  53775. initialValue: 'none',
  53776. prefix: true,
  53777. type: PropertyDescriptorParsingType.VALUE,
  53778. parse: function (token) {
  53779. if (token.type === TokenType.IDENT_TOKEN && token.value === 'none') {
  53780. return null;
  53781. }
  53782. if (token.type === TokenType.FUNCTION) {
  53783. var transformFunction = SUPPORTED_TRANSFORM_FUNCTIONS[token.name];
  53784. if (typeof transformFunction === 'undefined') {
  53785. throw new Error("Attempting to parse an unsupported transform function \"" + token.name + "\"");
  53786. }
  53787. return transformFunction(token.values);
  53788. }
  53789. return null;
  53790. }
  53791. };
  53792. var matrix = function (args) {
  53793. var values = args.filter(function (arg) { return arg.type === TokenType.NUMBER_TOKEN; }).map(function (arg) { return arg.number; });
  53794. return values.length === 6 ? values : null;
  53795. };
  53796. // doesn't support 3D transforms at the moment
  53797. var matrix3d = function (args) {
  53798. var values = args.filter(function (arg) { return arg.type === TokenType.NUMBER_TOKEN; }).map(function (arg) { return arg.number; });
  53799. var a1 = values[0], b1 = values[1], _a = values[2], _b = values[3], a2 = values[4], b2 = values[5], _c = values[6], _d = values[7], _e = values[8], _f = values[9], _g = values[10], _h = values[11], a4 = values[12], b4 = values[13], _j = values[14], _k = values[15];
  53800. return values.length === 16 ? [a1, b1, a2, b2, a4, b4] : null;
  53801. };
  53802. var SUPPORTED_TRANSFORM_FUNCTIONS = {
  53803. matrix: matrix,
  53804. matrix3d: matrix3d
  53805. };
  53806. var DEFAULT_VALUE = {
  53807. type: TokenType.PERCENTAGE_TOKEN,
  53808. number: 50,
  53809. flags: FLAG_INTEGER
  53810. };
  53811. var DEFAULT = [DEFAULT_VALUE, DEFAULT_VALUE];
  53812. var transformOrigin = {
  53813. name: 'transform-origin',
  53814. initialValue: '50% 50%',
  53815. prefix: true,
  53816. type: PropertyDescriptorParsingType.LIST,
  53817. parse: function (tokens) {
  53818. var origins = tokens.filter(isLengthPercentage);
  53819. if (origins.length !== 2) {
  53820. return DEFAULT;
  53821. }
  53822. return [origins[0], origins[1]];
  53823. }
  53824. };
  53825. var VISIBILITY;
  53826. (function (VISIBILITY) {
  53827. VISIBILITY[VISIBILITY["VISIBLE"] = 0] = "VISIBLE";
  53828. VISIBILITY[VISIBILITY["HIDDEN"] = 1] = "HIDDEN";
  53829. VISIBILITY[VISIBILITY["COLLAPSE"] = 2] = "COLLAPSE";
  53830. })(VISIBILITY || (VISIBILITY = {}));
  53831. var visibility = {
  53832. name: 'visible',
  53833. initialValue: 'none',
  53834. prefix: false,
  53835. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53836. parse: function (visibility) {
  53837. switch (visibility) {
  53838. case 'hidden':
  53839. return VISIBILITY.HIDDEN;
  53840. case 'collapse':
  53841. return VISIBILITY.COLLAPSE;
  53842. case 'visible':
  53843. default:
  53844. return VISIBILITY.VISIBLE;
  53845. }
  53846. }
  53847. };
  53848. var WORD_BREAK;
  53849. (function (WORD_BREAK) {
  53850. WORD_BREAK["NORMAL"] = "normal";
  53851. WORD_BREAK["BREAK_ALL"] = "break-all";
  53852. WORD_BREAK["KEEP_ALL"] = "keep-all";
  53853. })(WORD_BREAK || (WORD_BREAK = {}));
  53854. var wordBreak = {
  53855. name: 'word-break',
  53856. initialValue: 'normal',
  53857. prefix: false,
  53858. type: PropertyDescriptorParsingType.IDENT_VALUE,
  53859. parse: function (wordBreak) {
  53860. switch (wordBreak) {
  53861. case 'break-all':
  53862. return WORD_BREAK.BREAK_ALL;
  53863. case 'keep-all':
  53864. return WORD_BREAK.KEEP_ALL;
  53865. case 'normal':
  53866. default:
  53867. return WORD_BREAK.NORMAL;
  53868. }
  53869. }
  53870. };
  53871. var zIndex = {
  53872. name: 'z-index',
  53873. initialValue: 'auto',
  53874. prefix: false,
  53875. type: PropertyDescriptorParsingType.VALUE,
  53876. parse: function (token) {
  53877. if (token.type === TokenType.IDENT_TOKEN) {
  53878. return { auto: true, order: 0 };
  53879. }
  53880. if (isNumberToken(token)) {
  53881. return { auto: false, order: token.number };
  53882. }
  53883. throw new Error("Invalid z-index number parsed");
  53884. }
  53885. };
  53886. var opacity = {
  53887. name: 'opacity',
  53888. initialValue: '1',
  53889. type: PropertyDescriptorParsingType.VALUE,
  53890. prefix: false,
  53891. parse: function (token) {
  53892. if (isNumberToken(token)) {
  53893. return token.number;
  53894. }
  53895. return 1;
  53896. }
  53897. };
  53898. var textDecorationColor = {
  53899. name: "text-decoration-color",
  53900. initialValue: 'transparent',
  53901. prefix: false,
  53902. type: PropertyDescriptorParsingType.TYPE_VALUE,
  53903. format: 'color'
  53904. };
  53905. var textDecorationLine = {
  53906. name: 'text-decoration-line',
  53907. initialValue: 'none',
  53908. prefix: false,
  53909. type: PropertyDescriptorParsingType.LIST,
  53910. parse: function (tokens) {
  53911. return tokens
  53912. .filter(isIdentToken)
  53913. .map(function (token) {
  53914. switch (token.value) {
  53915. case 'underline':
  53916. return 1 /* UNDERLINE */;
  53917. case 'overline':
  53918. return 2 /* OVERLINE */;
  53919. case 'line-through':
  53920. return 3 /* LINE_THROUGH */;
  53921. case 'none':
  53922. return 4 /* BLINK */;
  53923. }
  53924. return 0 /* NONE */;
  53925. })
  53926. .filter(function (line) { return line !== 0 /* NONE */; });
  53927. }
  53928. };
  53929. var fontFamily = {
  53930. name: "font-family",
  53931. initialValue: '',
  53932. prefix: false,
  53933. type: PropertyDescriptorParsingType.LIST,
  53934. parse: function (tokens) {
  53935. var accumulator = [];
  53936. var results = [];
  53937. tokens.forEach(function (token) {
  53938. switch (token.type) {
  53939. case TokenType.IDENT_TOKEN:
  53940. case TokenType.STRING_TOKEN:
  53941. accumulator.push(token.value);
  53942. break;
  53943. case TokenType.NUMBER_TOKEN:
  53944. accumulator.push(token.number.toString());
  53945. break;
  53946. case TokenType.COMMA_TOKEN:
  53947. results.push(accumulator.join(' '));
  53948. accumulator.length = 0;
  53949. break;
  53950. }
  53951. });
  53952. if (accumulator.length) {
  53953. results.push(accumulator.join(' '));
  53954. }
  53955. return results.map(function (result) { return (result.indexOf(' ') === -1 ? result : "'" + result + "'"); });
  53956. }
  53957. };
  53958. var fontSize = {
  53959. name: "font-size",
  53960. initialValue: '0',
  53961. prefix: false,
  53962. type: PropertyDescriptorParsingType.TYPE_VALUE,
  53963. format: 'length'
  53964. };
  53965. var fontWeight = {
  53966. name: 'font-weight',
  53967. initialValue: 'normal',
  53968. type: PropertyDescriptorParsingType.VALUE,
  53969. prefix: false,
  53970. parse: function (token) {
  53971. if (isNumberToken(token)) {
  53972. return token.number;
  53973. }
  53974. if (isIdentToken(token)) {
  53975. switch (token.value) {
  53976. case 'bold':
  53977. return 700;
  53978. case 'normal':
  53979. default:
  53980. return 400;
  53981. }
  53982. }
  53983. return 400;
  53984. }
  53985. };
  53986. var fontVariant = {
  53987. name: 'font-variant',
  53988. initialValue: 'none',
  53989. type: PropertyDescriptorParsingType.LIST,
  53990. prefix: false,
  53991. parse: function (tokens) {
  53992. return tokens.filter(isIdentToken).map(function (token) { return token.value; });
  53993. }
  53994. };
  53995. var FONT_STYLE;
  53996. (function (FONT_STYLE) {
  53997. FONT_STYLE["NORMAL"] = "normal";
  53998. FONT_STYLE["ITALIC"] = "italic";
  53999. FONT_STYLE["OBLIQUE"] = "oblique";
  54000. })(FONT_STYLE || (FONT_STYLE = {}));
  54001. var fontStyle = {
  54002. name: 'font-style',
  54003. initialValue: 'normal',
  54004. prefix: false,
  54005. type: PropertyDescriptorParsingType.IDENT_VALUE,
  54006. parse: function (overflow) {
  54007. switch (overflow) {
  54008. case 'oblique':
  54009. return FONT_STYLE.OBLIQUE;
  54010. case 'italic':
  54011. return FONT_STYLE.ITALIC;
  54012. case 'normal':
  54013. default:
  54014. return FONT_STYLE.NORMAL;
  54015. }
  54016. }
  54017. };
  54018. var contains = function (bit, value) { return (bit & value) !== 0; };
  54019. var content = {
  54020. name: 'content',
  54021. initialValue: 'none',
  54022. type: PropertyDescriptorParsingType.LIST,
  54023. prefix: false,
  54024. parse: function (tokens) {
  54025. if (tokens.length === 0) {
  54026. return [];
  54027. }
  54028. var first = tokens[0];
  54029. if (first.type === TokenType.IDENT_TOKEN && first.value === 'none') {
  54030. return [];
  54031. }
  54032. return tokens;
  54033. }
  54034. };
  54035. var counterIncrement = {
  54036. name: 'counter-increment',
  54037. initialValue: 'none',
  54038. prefix: true,
  54039. type: PropertyDescriptorParsingType.LIST,
  54040. parse: function (tokens) {
  54041. if (tokens.length === 0) {
  54042. return null;
  54043. }
  54044. var first = tokens[0];
  54045. if (first.type === TokenType.IDENT_TOKEN && first.value === 'none') {
  54046. return null;
  54047. }
  54048. var increments = [];
  54049. var filtered = tokens.filter(nonWhiteSpace);
  54050. for (var i = 0; i < filtered.length; i++) {
  54051. var counter = filtered[i];
  54052. var next = filtered[i + 1];
  54053. if (counter.type === TokenType.IDENT_TOKEN) {
  54054. var increment = next && isNumberToken(next) ? next.number : 1;
  54055. increments.push({ counter: counter.value, increment: increment });
  54056. }
  54057. }
  54058. return increments;
  54059. }
  54060. };
  54061. var counterReset = {
  54062. name: 'counter-reset',
  54063. initialValue: 'none',
  54064. prefix: true,
  54065. type: PropertyDescriptorParsingType.LIST,
  54066. parse: function (tokens) {
  54067. if (tokens.length === 0) {
  54068. return [];
  54069. }
  54070. var resets = [];
  54071. var filtered = tokens.filter(nonWhiteSpace);
  54072. for (var i = 0; i < filtered.length; i++) {
  54073. var counter = filtered[i];
  54074. var next = filtered[i + 1];
  54075. if (isIdentToken(counter) && counter.value !== 'none') {
  54076. var reset = next && isNumberToken(next) ? next.number : 0;
  54077. resets.push({ counter: counter.value, reset: reset });
  54078. }
  54079. }
  54080. return resets;
  54081. }
  54082. };
  54083. var quotes = {
  54084. name: 'quotes',
  54085. initialValue: 'none',
  54086. prefix: true,
  54087. type: PropertyDescriptorParsingType.LIST,
  54088. parse: function (tokens) {
  54089. if (tokens.length === 0) {
  54090. return null;
  54091. }
  54092. var first = tokens[0];
  54093. if (first.type === TokenType.IDENT_TOKEN && first.value === 'none') {
  54094. return null;
  54095. }
  54096. var quotes = [];
  54097. var filtered = tokens.filter(isStringToken);
  54098. if (filtered.length % 2 !== 0) {
  54099. return null;
  54100. }
  54101. for (var i = 0; i < filtered.length; i += 2) {
  54102. var open_1 = filtered[i].value;
  54103. var close_1 = filtered[i + 1].value;
  54104. quotes.push({ open: open_1, close: close_1 });
  54105. }
  54106. return quotes;
  54107. }
  54108. };
  54109. var getQuote = function (quotes, depth, open) {
  54110. if (!quotes) {
  54111. return '';
  54112. }
  54113. var quote = quotes[Math.min(depth, quotes.length - 1)];
  54114. if (!quote) {
  54115. return '';
  54116. }
  54117. return open ? quote.open : quote.close;
  54118. };
  54119. var boxShadow = {
  54120. name: 'box-shadow',
  54121. initialValue: 'none',
  54122. type: PropertyDescriptorParsingType.LIST,
  54123. prefix: false,
  54124. parse: function (tokens) {
  54125. if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) {
  54126. return [];
  54127. }
  54128. return parseFunctionArgs(tokens).map(function (values) {
  54129. var shadow = {
  54130. color: 0x000000ff,
  54131. offsetX: ZERO_LENGTH,
  54132. offsetY: ZERO_LENGTH,
  54133. blur: ZERO_LENGTH,
  54134. spread: ZERO_LENGTH,
  54135. inset: false
  54136. };
  54137. var c = 0;
  54138. for (var i = 0; i < values.length; i++) {
  54139. var token = values[i];
  54140. if (isIdentWithValue(token, 'inset')) {
  54141. shadow.inset = true;
  54142. }
  54143. else if (isLength(token)) {
  54144. if (c === 0) {
  54145. shadow.offsetX = token;
  54146. }
  54147. else if (c === 1) {
  54148. shadow.offsetY = token;
  54149. }
  54150. else if (c === 2) {
  54151. shadow.blur = token;
  54152. }
  54153. else {
  54154. shadow.spread = token;
  54155. }
  54156. c++;
  54157. }
  54158. else {
  54159. shadow.color = color.parse(token);
  54160. }
  54161. }
  54162. return shadow;
  54163. });
  54164. }
  54165. };
  54166. var CSSParsedDeclaration = /** @class */ (function () {
  54167. function CSSParsedDeclaration(declaration) {
  54168. this.backgroundClip = parse(backgroundClip, declaration.backgroundClip);
  54169. this.backgroundColor = parse(backgroundColor, declaration.backgroundColor);
  54170. this.backgroundImage = parse(backgroundImage, declaration.backgroundImage);
  54171. this.backgroundOrigin = parse(backgroundOrigin, declaration.backgroundOrigin);
  54172. this.backgroundPosition = parse(backgroundPosition, declaration.backgroundPosition);
  54173. this.backgroundRepeat = parse(backgroundRepeat, declaration.backgroundRepeat);
  54174. this.backgroundSize = parse(backgroundSize, declaration.backgroundSize);
  54175. this.borderTopColor = parse(borderTopColor, declaration.borderTopColor);
  54176. this.borderRightColor = parse(borderRightColor, declaration.borderRightColor);
  54177. this.borderBottomColor = parse(borderBottomColor, declaration.borderBottomColor);
  54178. this.borderLeftColor = parse(borderLeftColor, declaration.borderLeftColor);
  54179. this.borderTopLeftRadius = parse(borderTopLeftRadius, declaration.borderTopLeftRadius);
  54180. this.borderTopRightRadius = parse(borderTopRightRadius, declaration.borderTopRightRadius);
  54181. this.borderBottomRightRadius = parse(borderBottomRightRadius, declaration.borderBottomRightRadius);
  54182. this.borderBottomLeftRadius = parse(borderBottomLeftRadius, declaration.borderBottomLeftRadius);
  54183. this.borderTopStyle = parse(borderTopStyle, declaration.borderTopStyle);
  54184. this.borderRightStyle = parse(borderRightStyle, declaration.borderRightStyle);
  54185. this.borderBottomStyle = parse(borderBottomStyle, declaration.borderBottomStyle);
  54186. this.borderLeftStyle = parse(borderLeftStyle, declaration.borderLeftStyle);
  54187. this.borderTopWidth = parse(borderTopWidth, declaration.borderTopWidth);
  54188. this.borderRightWidth = parse(borderRightWidth, declaration.borderRightWidth);
  54189. this.borderBottomWidth = parse(borderBottomWidth, declaration.borderBottomWidth);
  54190. this.borderLeftWidth = parse(borderLeftWidth, declaration.borderLeftWidth);
  54191. this.boxShadow = parse(boxShadow, declaration.boxShadow);
  54192. this.color = parse(color$1, declaration.color);
  54193. this.display = parse(display, declaration.display);
  54194. this.float = parse(float, declaration.cssFloat);
  54195. this.fontFamily = parse(fontFamily, declaration.fontFamily);
  54196. this.fontSize = parse(fontSize, declaration.fontSize);
  54197. this.fontStyle = parse(fontStyle, declaration.fontStyle);
  54198. this.fontVariant = parse(fontVariant, declaration.fontVariant);
  54199. this.fontWeight = parse(fontWeight, declaration.fontWeight);
  54200. this.letterSpacing = parse(letterSpacing, declaration.letterSpacing);
  54201. this.lineBreak = parse(lineBreak, declaration.lineBreak);
  54202. this.lineHeight = parse(lineHeight, declaration.lineHeight);
  54203. this.listStyleImage = parse(listStyleImage, declaration.listStyleImage);
  54204. this.listStylePosition = parse(listStylePosition, declaration.listStylePosition);
  54205. this.listStyleType = parse(listStyleType, declaration.listStyleType);
  54206. this.marginTop = parse(marginTop, declaration.marginTop);
  54207. this.marginRight = parse(marginRight, declaration.marginRight);
  54208. this.marginBottom = parse(marginBottom, declaration.marginBottom);
  54209. this.marginLeft = parse(marginLeft, declaration.marginLeft);
  54210. this.opacity = parse(opacity, declaration.opacity);
  54211. var overflowTuple = parse(overflow, declaration.overflow);
  54212. this.overflowX = overflowTuple[0];
  54213. this.overflowY = overflowTuple[overflowTuple.length > 1 ? 1 : 0];
  54214. this.overflowWrap = parse(overflowWrap, declaration.overflowWrap);
  54215. this.paddingTop = parse(paddingTop, declaration.paddingTop);
  54216. this.paddingRight = parse(paddingRight, declaration.paddingRight);
  54217. this.paddingBottom = parse(paddingBottom, declaration.paddingBottom);
  54218. this.paddingLeft = parse(paddingLeft, declaration.paddingLeft);
  54219. this.position = parse(position, declaration.position);
  54220. this.textAlign = parse(textAlign, declaration.textAlign);
  54221. this.textDecorationColor = parse(textDecorationColor, declaration.textDecorationColor || declaration.color);
  54222. this.textDecorationLine = parse(textDecorationLine, declaration.textDecorationLine);
  54223. this.textShadow = parse(textShadow, declaration.textShadow);
  54224. this.textTransform = parse(textTransform, declaration.textTransform);
  54225. this.transform = parse(transform, declaration.transform);
  54226. this.transformOrigin = parse(transformOrigin, declaration.transformOrigin);
  54227. this.visibility = parse(visibility, declaration.visibility);
  54228. this.wordBreak = parse(wordBreak, declaration.wordBreak);
  54229. this.zIndex = parse(zIndex, declaration.zIndex);
  54230. }
  54231. CSSParsedDeclaration.prototype.isVisible = function () {
  54232. return this.display > 0 && this.opacity > 0 && this.visibility === VISIBILITY.VISIBLE;
  54233. };
  54234. CSSParsedDeclaration.prototype.isTransparent = function () {
  54235. return isTransparent(this.backgroundColor);
  54236. };
  54237. CSSParsedDeclaration.prototype.isTransformed = function () {
  54238. return this.transform !== null;
  54239. };
  54240. CSSParsedDeclaration.prototype.isPositioned = function () {
  54241. return this.position !== POSITION.STATIC;
  54242. };
  54243. CSSParsedDeclaration.prototype.isPositionedWithZIndex = function () {
  54244. return this.isPositioned() && !this.zIndex.auto;
  54245. };
  54246. CSSParsedDeclaration.prototype.isFloating = function () {
  54247. return this.float !== FLOAT.NONE;
  54248. };
  54249. CSSParsedDeclaration.prototype.isInlineLevel = function () {
  54250. return (contains(this.display, 4 /* INLINE */) ||
  54251. contains(this.display, 33554432 /* INLINE_BLOCK */) ||
  54252. contains(this.display, 268435456 /* INLINE_FLEX */) ||
  54253. contains(this.display, 536870912 /* INLINE_GRID */) ||
  54254. contains(this.display, 67108864 /* INLINE_LIST_ITEM */) ||
  54255. contains(this.display, 134217728 /* INLINE_TABLE */));
  54256. };
  54257. return CSSParsedDeclaration;
  54258. }());
  54259. var CSSParsedPseudoDeclaration = /** @class */ (function () {
  54260. function CSSParsedPseudoDeclaration(declaration) {
  54261. this.content = parse(content, declaration.content);
  54262. this.quotes = parse(quotes, declaration.quotes);
  54263. }
  54264. return CSSParsedPseudoDeclaration;
  54265. }());
  54266. var CSSParsedCounterDeclaration = /** @class */ (function () {
  54267. function CSSParsedCounterDeclaration(declaration) {
  54268. this.counterIncrement = parse(counterIncrement, declaration.counterIncrement);
  54269. this.counterReset = parse(counterReset, declaration.counterReset);
  54270. }
  54271. return CSSParsedCounterDeclaration;
  54272. }());
  54273. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  54274. var parse = function (descriptor, style) {
  54275. var tokenizer = new Tokenizer();
  54276. var value = style !== null && typeof style !== 'undefined' ? style.toString() : descriptor.initialValue;
  54277. tokenizer.write(value);
  54278. var parser = new Parser(tokenizer.read());
  54279. switch (descriptor.type) {
  54280. case PropertyDescriptorParsingType.IDENT_VALUE:
  54281. var token = parser.parseComponentValue();
  54282. return descriptor.parse(isIdentToken(token) ? token.value : descriptor.initialValue);
  54283. case PropertyDescriptorParsingType.VALUE:
  54284. return descriptor.parse(parser.parseComponentValue());
  54285. case PropertyDescriptorParsingType.LIST:
  54286. return descriptor.parse(parser.parseComponentValues());
  54287. case PropertyDescriptorParsingType.TOKEN_VALUE:
  54288. return parser.parseComponentValue();
  54289. case PropertyDescriptorParsingType.TYPE_VALUE:
  54290. switch (descriptor.format) {
  54291. case 'angle':
  54292. return angle.parse(parser.parseComponentValue());
  54293. case 'color':
  54294. return color.parse(parser.parseComponentValue());
  54295. case 'image':
  54296. return image.parse(parser.parseComponentValue());
  54297. case 'length':
  54298. var length_1 = parser.parseComponentValue();
  54299. return isLength(length_1) ? length_1 : ZERO_LENGTH;
  54300. case 'length-percentage':
  54301. var value_1 = parser.parseComponentValue();
  54302. return isLengthPercentage(value_1) ? value_1 : ZERO_LENGTH;
  54303. }
  54304. }
  54305. throw new Error("Attempting to parse unsupported css format type " + descriptor.format);
  54306. };
  54307. var ElementContainer = /** @class */ (function () {
  54308. function ElementContainer(element) {
  54309. this.styles = new CSSParsedDeclaration(window.getComputedStyle(element, null));
  54310. this.textNodes = [];
  54311. this.elements = [];
  54312. if (this.styles.transform !== null && isHTMLElementNode(element)) {
  54313. // getBoundingClientRect takes transforms into account
  54314. element.style.transform = 'none';
  54315. }
  54316. this.bounds = parseBounds(element);
  54317. this.flags = 0;
  54318. }
  54319. return ElementContainer;
  54320. }());
  54321. var TextBounds = /** @class */ (function () {
  54322. function TextBounds(text, bounds) {
  54323. this.text = text;
  54324. this.bounds = bounds;
  54325. }
  54326. return TextBounds;
  54327. }());
  54328. var parseTextBounds = function (value, styles, node) {
  54329. var textList = breakText(value, styles);
  54330. var textBounds = [];
  54331. var offset = 0;
  54332. textList.forEach(function (text) {
  54333. if (styles.textDecorationLine.length || text.trim().length > 0) {
  54334. if (FEATURES.SUPPORT_RANGE_BOUNDS) {
  54335. textBounds.push(new TextBounds(text, getRangeBounds(node, offset, text.length)));
  54336. }
  54337. else {
  54338. var replacementNode = node.splitText(text.length);
  54339. textBounds.push(new TextBounds(text, getWrapperBounds(node)));
  54340. node = replacementNode;
  54341. }
  54342. }
  54343. else if (!FEATURES.SUPPORT_RANGE_BOUNDS) {
  54344. node = node.splitText(text.length);
  54345. }
  54346. offset += text.length;
  54347. });
  54348. return textBounds;
  54349. };
  54350. var getWrapperBounds = function (node) {
  54351. var ownerDocument = node.ownerDocument;
  54352. if (ownerDocument) {
  54353. var wrapper = ownerDocument.createElement('html2canvaswrapper');
  54354. wrapper.appendChild(node.cloneNode(true));
  54355. var parentNode = node.parentNode;
  54356. if (parentNode) {
  54357. parentNode.replaceChild(wrapper, node);
  54358. var bounds = parseBounds(wrapper);
  54359. if (wrapper.firstChild) {
  54360. parentNode.replaceChild(wrapper.firstChild, wrapper);
  54361. }
  54362. return bounds;
  54363. }
  54364. }
  54365. return new Bounds(0, 0, 0, 0);
  54366. };
  54367. var getRangeBounds = function (node, offset, length) {
  54368. var ownerDocument = node.ownerDocument;
  54369. if (!ownerDocument) {
  54370. throw new Error('Node has no owner document');
  54371. }
  54372. var range = ownerDocument.createRange();
  54373. range.setStart(node, offset);
  54374. range.setEnd(node, offset + length);
  54375. return Bounds.fromClientRect(range.getBoundingClientRect());
  54376. };
  54377. var breakText = function (value, styles) {
  54378. return styles.letterSpacing !== 0 ? toCodePoints(value).map(function (i) { return fromCodePoint(i); }) : breakWords(value, styles);
  54379. };
  54380. var breakWords = function (str, styles) {
  54381. var breaker = LineBreaker(str, {
  54382. lineBreak: styles.lineBreak,
  54383. wordBreak: styles.overflowWrap === OVERFLOW_WRAP.BREAK_WORD ? 'break-word' : styles.wordBreak
  54384. });
  54385. var words = [];
  54386. var bk;
  54387. while (!(bk = breaker.next()).done) {
  54388. if (bk.value) {
  54389. words.push(bk.value.slice());
  54390. }
  54391. }
  54392. return words;
  54393. };
  54394. var TextContainer = /** @class */ (function () {
  54395. function TextContainer(node, styles) {
  54396. this.text = transform$1(node.data, styles.textTransform);
  54397. this.textBounds = parseTextBounds(this.text, styles, node);
  54398. }
  54399. return TextContainer;
  54400. }());
  54401. var transform$1 = function (text, transform) {
  54402. switch (transform) {
  54403. case TEXT_TRANSFORM.LOWERCASE:
  54404. return text.toLowerCase();
  54405. case TEXT_TRANSFORM.CAPITALIZE:
  54406. return text.replace(CAPITALIZE, capitalize);
  54407. case TEXT_TRANSFORM.UPPERCASE:
  54408. return text.toUpperCase();
  54409. default:
  54410. return text;
  54411. }
  54412. };
  54413. var CAPITALIZE = /(^|\s|:|-|\(|\))([a-z])/g;
  54414. var capitalize = function (m, p1, p2) {
  54415. if (m.length > 0) {
  54416. return p1 + p2.toUpperCase();
  54417. }
  54418. return m;
  54419. };
  54420. var ImageElementContainer = /** @class */ (function (_super) {
  54421. __extends(ImageElementContainer, _super);
  54422. function ImageElementContainer(img) {
  54423. var _this = _super.call(this, img) || this;
  54424. _this.src = img.currentSrc || img.src;
  54425. _this.intrinsicWidth = img.naturalWidth;
  54426. _this.intrinsicHeight = img.naturalHeight;
  54427. CacheStorage.getInstance().addImage(_this.src);
  54428. return _this;
  54429. }
  54430. return ImageElementContainer;
  54431. }(ElementContainer));
  54432. var CanvasElementContainer = /** @class */ (function (_super) {
  54433. __extends(CanvasElementContainer, _super);
  54434. function CanvasElementContainer(canvas) {
  54435. var _this = _super.call(this, canvas) || this;
  54436. _this.canvas = canvas;
  54437. _this.intrinsicWidth = canvas.width;
  54438. _this.intrinsicHeight = canvas.height;
  54439. return _this;
  54440. }
  54441. return CanvasElementContainer;
  54442. }(ElementContainer));
  54443. var SVGElementContainer = /** @class */ (function (_super) {
  54444. __extends(SVGElementContainer, _super);
  54445. function SVGElementContainer(img) {
  54446. var _this = _super.call(this, img) || this;
  54447. var s = new XMLSerializer();
  54448. _this.svg = "data:image/svg+xml," + encodeURIComponent(s.serializeToString(img));
  54449. _this.intrinsicWidth = img.width.baseVal.value;
  54450. _this.intrinsicHeight = img.height.baseVal.value;
  54451. CacheStorage.getInstance().addImage(_this.svg);
  54452. return _this;
  54453. }
  54454. return SVGElementContainer;
  54455. }(ElementContainer));
  54456. var LIElementContainer = /** @class */ (function (_super) {
  54457. __extends(LIElementContainer, _super);
  54458. function LIElementContainer(element) {
  54459. var _this = _super.call(this, element) || this;
  54460. _this.value = element.value;
  54461. return _this;
  54462. }
  54463. return LIElementContainer;
  54464. }(ElementContainer));
  54465. var OLElementContainer = /** @class */ (function (_super) {
  54466. __extends(OLElementContainer, _super);
  54467. function OLElementContainer(element) {
  54468. var _this = _super.call(this, element) || this;
  54469. _this.start = element.start;
  54470. _this.reversed = typeof element.reversed === 'boolean' && element.reversed === true;
  54471. return _this;
  54472. }
  54473. return OLElementContainer;
  54474. }(ElementContainer));
  54475. var CHECKBOX_BORDER_RADIUS = [
  54476. {
  54477. type: TokenType.DIMENSION_TOKEN,
  54478. flags: 0,
  54479. unit: 'px',
  54480. number: 3
  54481. }
  54482. ];
  54483. var RADIO_BORDER_RADIUS = [
  54484. {
  54485. type: TokenType.PERCENTAGE_TOKEN,
  54486. flags: 0,
  54487. number: 50
  54488. }
  54489. ];
  54490. var reformatInputBounds = function (bounds) {
  54491. if (bounds.width > bounds.height) {
  54492. return new Bounds(bounds.left + (bounds.width - bounds.height) / 2, bounds.top, bounds.height, bounds.height);
  54493. }
  54494. else if (bounds.width < bounds.height) {
  54495. return new Bounds(bounds.left, bounds.top + (bounds.height - bounds.width) / 2, bounds.width, bounds.width);
  54496. }
  54497. return bounds;
  54498. };
  54499. var getInputValue = function (node) {
  54500. var value = node.type === PASSWORD ? new Array(node.value.length + 1).join('\u2022') : node.value;
  54501. return value.length === 0 ? node.placeholder || '' : value;
  54502. };
  54503. var CHECKBOX = 'checkbox';
  54504. var RADIO = 'radio';
  54505. var PASSWORD = 'password';
  54506. var INPUT_COLOR = 0x2a2a2aff;
  54507. var InputElementContainer = /** @class */ (function (_super) {
  54508. __extends(InputElementContainer, _super);
  54509. function InputElementContainer(input) {
  54510. var _this = _super.call(this, input) || this;
  54511. _this.type = input.type.toLowerCase();
  54512. _this.checked = input.checked;
  54513. _this.value = getInputValue(input);
  54514. if (_this.type === CHECKBOX || _this.type === RADIO) {
  54515. _this.styles.backgroundColor = 0xdededeff;
  54516. _this.styles.borderTopColor = _this.styles.borderRightColor = _this.styles.borderBottomColor = _this.styles.borderLeftColor = 0xa5a5a5ff;
  54517. _this.styles.borderTopWidth = _this.styles.borderRightWidth = _this.styles.borderBottomWidth = _this.styles.borderLeftWidth = 1;
  54518. _this.styles.borderTopStyle = _this.styles.borderRightStyle = _this.styles.borderBottomStyle = _this.styles.borderLeftStyle =
  54519. BORDER_STYLE.SOLID;
  54520. _this.styles.backgroundClip = [BACKGROUND_CLIP.BORDER_BOX];
  54521. _this.styles.backgroundOrigin = [0 /* BORDER_BOX */];
  54522. _this.bounds = reformatInputBounds(_this.bounds);
  54523. }
  54524. switch (_this.type) {
  54525. case CHECKBOX:
  54526. _this.styles.borderTopRightRadius = _this.styles.borderTopLeftRadius = _this.styles.borderBottomRightRadius = _this.styles.borderBottomLeftRadius = CHECKBOX_BORDER_RADIUS;
  54527. break;
  54528. case RADIO:
  54529. _this.styles.borderTopRightRadius = _this.styles.borderTopLeftRadius = _this.styles.borderBottomRightRadius = _this.styles.borderBottomLeftRadius = RADIO_BORDER_RADIUS;
  54530. break;
  54531. }
  54532. return _this;
  54533. }
  54534. return InputElementContainer;
  54535. }(ElementContainer));
  54536. var SelectElementContainer = /** @class */ (function (_super) {
  54537. __extends(SelectElementContainer, _super);
  54538. function SelectElementContainer(element) {
  54539. var _this = _super.call(this, element) || this;
  54540. var option = element.options[element.selectedIndex || 0];
  54541. _this.value = option ? option.text || '' : '';
  54542. return _this;
  54543. }
  54544. return SelectElementContainer;
  54545. }(ElementContainer));
  54546. var TextareaElementContainer = /** @class */ (function (_super) {
  54547. __extends(TextareaElementContainer, _super);
  54548. function TextareaElementContainer(element) {
  54549. var _this = _super.call(this, element) || this;
  54550. _this.value = element.value;
  54551. return _this;
  54552. }
  54553. return TextareaElementContainer;
  54554. }(ElementContainer));
  54555. var parseColor = function (value) { return color.parse(Parser.create(value).parseComponentValue()); };
  54556. var IFrameElementContainer = /** @class */ (function (_super) {
  54557. __extends(IFrameElementContainer, _super);
  54558. function IFrameElementContainer(iframe) {
  54559. var _this = _super.call(this, iframe) || this;
  54560. _this.src = iframe.src;
  54561. _this.width = parseInt(iframe.width, 10) || 0;
  54562. _this.height = parseInt(iframe.height, 10) || 0;
  54563. _this.backgroundColor = _this.styles.backgroundColor;
  54564. try {
  54565. if (iframe.contentWindow &&
  54566. iframe.contentWindow.document &&
  54567. iframe.contentWindow.document.documentElement) {
  54568. _this.tree = parseTree(iframe.contentWindow.document.documentElement);
  54569. // http://www.w3.org/TR/css3-background/#special-backgrounds
  54570. var documentBackgroundColor = iframe.contentWindow.document.documentElement
  54571. ? parseColor(getComputedStyle(iframe.contentWindow.document.documentElement)
  54572. .backgroundColor)
  54573. : COLORS.TRANSPARENT;
  54574. var bodyBackgroundColor = iframe.contentWindow.document.body
  54575. ? parseColor(getComputedStyle(iframe.contentWindow.document.body).backgroundColor)
  54576. : COLORS.TRANSPARENT;
  54577. _this.backgroundColor = isTransparent(documentBackgroundColor)
  54578. ? isTransparent(bodyBackgroundColor)
  54579. ? _this.styles.backgroundColor
  54580. : bodyBackgroundColor
  54581. : documentBackgroundColor;
  54582. }
  54583. }
  54584. catch (e) { }
  54585. return _this;
  54586. }
  54587. return IFrameElementContainer;
  54588. }(ElementContainer));
  54589. var LIST_OWNERS = ['OL', 'UL', 'MENU'];
  54590. var parseNodeTree = function (node, parent, root) {
  54591. for (var childNode = node.firstChild, nextNode = void 0; childNode; childNode = nextNode) {
  54592. nextNode = childNode.nextSibling;
  54593. if (isTextNode(childNode) && childNode.data.trim().length > 0) {
  54594. parent.textNodes.push(new TextContainer(childNode, parent.styles));
  54595. }
  54596. else if (isElementNode(childNode)) {
  54597. var container = createContainer(childNode);
  54598. if (container.styles.isVisible()) {
  54599. if (createsRealStackingContext(childNode, container, root)) {
  54600. container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */;
  54601. }
  54602. else if (createsStackingContext(container.styles)) {
  54603. container.flags |= 2 /* CREATES_STACKING_CONTEXT */;
  54604. }
  54605. if (LIST_OWNERS.indexOf(childNode.tagName) !== -1) {
  54606. container.flags |= 8 /* IS_LIST_OWNER */;
  54607. }
  54608. parent.elements.push(container);
  54609. if (!isTextareaElement(childNode) && !isSVGElement(childNode) && !isSelectElement(childNode)) {
  54610. parseNodeTree(childNode, container, root);
  54611. }
  54612. }
  54613. }
  54614. }
  54615. };
  54616. var createContainer = function (element) {
  54617. if (isImageElement(element)) {
  54618. return new ImageElementContainer(element);
  54619. }
  54620. if (isCanvasElement(element)) {
  54621. return new CanvasElementContainer(element);
  54622. }
  54623. if (isSVGElement(element)) {
  54624. return new SVGElementContainer(element);
  54625. }
  54626. if (isLIElement(element)) {
  54627. return new LIElementContainer(element);
  54628. }
  54629. if (isOLElement(element)) {
  54630. return new OLElementContainer(element);
  54631. }
  54632. if (isInputElement(element)) {
  54633. return new InputElementContainer(element);
  54634. }
  54635. if (isSelectElement(element)) {
  54636. return new SelectElementContainer(element);
  54637. }
  54638. if (isTextareaElement(element)) {
  54639. return new TextareaElementContainer(element);
  54640. }
  54641. if (isIFrameElement(element)) {
  54642. return new IFrameElementContainer(element);
  54643. }
  54644. return new ElementContainer(element);
  54645. };
  54646. var parseTree = function (element) {
  54647. var container = createContainer(element);
  54648. container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */;
  54649. parseNodeTree(element, container, container);
  54650. return container;
  54651. };
  54652. var createsRealStackingContext = function (node, container, root) {
  54653. return (container.styles.isPositionedWithZIndex() ||
  54654. container.styles.opacity < 1 ||
  54655. container.styles.isTransformed() ||
  54656. (isBodyElement(node) && root.styles.isTransparent()));
  54657. };
  54658. var createsStackingContext = function (styles) { return styles.isPositioned() || styles.isFloating(); };
  54659. var isTextNode = function (node) { return node.nodeType === Node.TEXT_NODE; };
  54660. var isElementNode = function (node) { return node.nodeType === Node.ELEMENT_NODE; };
  54661. var isHTMLElementNode = function (node) {
  54662. return isElementNode(node) && typeof node.style !== 'undefined' && !isSVGElementNode(node);
  54663. };
  54664. var isSVGElementNode = function (element) {
  54665. return typeof element.className === 'object';
  54666. };
  54667. var isLIElement = function (node) { return node.tagName === 'LI'; };
  54668. var isOLElement = function (node) { return node.tagName === 'OL'; };
  54669. var isInputElement = function (node) { return node.tagName === 'INPUT'; };
  54670. var isHTMLElement = function (node) { return node.tagName === 'HTML'; };
  54671. var isSVGElement = function (node) { return node.tagName === 'svg'; };
  54672. var isBodyElement = function (node) { return node.tagName === 'BODY'; };
  54673. var isCanvasElement = function (node) { return node.tagName === 'CANVAS'; };
  54674. var isImageElement = function (node) { return node.tagName === 'IMG'; };
  54675. var isIFrameElement = function (node) { return node.tagName === 'IFRAME'; };
  54676. var isStyleElement = function (node) { return node.tagName === 'STYLE'; };
  54677. var isScriptElement = function (node) { return node.tagName === 'SCRIPT'; };
  54678. var isTextareaElement = function (node) { return node.tagName === 'TEXTAREA'; };
  54679. var isSelectElement = function (node) { return node.tagName === 'SELECT'; };
  54680. var CounterState = /** @class */ (function () {
  54681. function CounterState() {
  54682. this.counters = {};
  54683. }
  54684. CounterState.prototype.getCounterValue = function (name) {
  54685. var counter = this.counters[name];
  54686. if (counter && counter.length) {
  54687. return counter[counter.length - 1];
  54688. }
  54689. return 1;
  54690. };
  54691. CounterState.prototype.getCounterValues = function (name) {
  54692. var counter = this.counters[name];
  54693. return counter ? counter : [];
  54694. };
  54695. CounterState.prototype.pop = function (counters) {
  54696. var _this = this;
  54697. counters.forEach(function (counter) { return _this.counters[counter].pop(); });
  54698. };
  54699. CounterState.prototype.parse = function (style) {
  54700. var _this = this;
  54701. var counterIncrement = style.counterIncrement;
  54702. var counterReset = style.counterReset;
  54703. var canReset = true;
  54704. if (counterIncrement !== null) {
  54705. counterIncrement.forEach(function (entry) {
  54706. var counter = _this.counters[entry.counter];
  54707. if (counter && entry.increment !== 0) {
  54708. canReset = false;
  54709. counter[Math.max(0, counter.length - 1)] += entry.increment;
  54710. }
  54711. });
  54712. }
  54713. var counterNames = [];
  54714. if (canReset) {
  54715. counterReset.forEach(function (entry) {
  54716. var counter = _this.counters[entry.counter];
  54717. counterNames.push(entry.counter);
  54718. if (!counter) {
  54719. counter = _this.counters[entry.counter] = [];
  54720. }
  54721. counter.push(entry.reset);
  54722. });
  54723. }
  54724. return counterNames;
  54725. };
  54726. return CounterState;
  54727. }());
  54728. var ROMAN_UPPER = {
  54729. integers: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
  54730. values: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
  54731. };
  54732. var ARMENIAN = {
  54733. integers: [
  54734. 9000,
  54735. 8000,
  54736. 7000,
  54737. 6000,
  54738. 5000,
  54739. 4000,
  54740. 3000,
  54741. 2000,
  54742. 1000,
  54743. 900,
  54744. 800,
  54745. 700,
  54746. 600,
  54747. 500,
  54748. 400,
  54749. 300,
  54750. 200,
  54751. 100,
  54752. 90,
  54753. 80,
  54754. 70,
  54755. 60,
  54756. 50,
  54757. 40,
  54758. 30,
  54759. 20,
  54760. 10,
  54761. 9,
  54762. 8,
  54763. 7,
  54764. 6,
  54765. 5,
  54766. 4,
  54767. 3,
  54768. 2,
  54769. 1
  54770. ],
  54771. values: [
  54772. 'Ք',
  54773. 'Փ',
  54774. 'Ւ',
  54775. 'Ց',
  54776. 'Ր',
  54777. 'Տ',
  54778. 'Վ',
  54779. 'Ս',
  54780. 'Ռ',
  54781. 'Ջ',
  54782. 'Պ',
  54783. 'Չ',
  54784. 'Ո',
  54785. 'Շ',
  54786. 'Ն',
  54787. 'Յ',
  54788. 'Մ',
  54789. 'Ճ',
  54790. 'Ղ',
  54791. 'Ձ',
  54792. 'Հ',
  54793. 'Կ',
  54794. 'Ծ',
  54795. 'Խ',
  54796. 'Լ',
  54797. 'Ի',
  54798. 'Ժ',
  54799. 'Թ',
  54800. 'Ը',
  54801. 'Է',
  54802. 'Զ',
  54803. 'Ե',
  54804. 'Դ',
  54805. 'Գ',
  54806. 'Բ',
  54807. 'Ա'
  54808. ]
  54809. };
  54810. var HEBREW = {
  54811. integers: [
  54812. 10000,
  54813. 9000,
  54814. 8000,
  54815. 7000,
  54816. 6000,
  54817. 5000,
  54818. 4000,
  54819. 3000,
  54820. 2000,
  54821. 1000,
  54822. 400,
  54823. 300,
  54824. 200,
  54825. 100,
  54826. 90,
  54827. 80,
  54828. 70,
  54829. 60,
  54830. 50,
  54831. 40,
  54832. 30,
  54833. 20,
  54834. 19,
  54835. 18,
  54836. 17,
  54837. 16,
  54838. 15,
  54839. 10,
  54840. 9,
  54841. 8,
  54842. 7,
  54843. 6,
  54844. 5,
  54845. 4,
  54846. 3,
  54847. 2,
  54848. 1
  54849. ],
  54850. values: [
  54851. 'י׳',
  54852. 'ט׳',
  54853. 'ח׳',
  54854. 'ז׳',
  54855. 'ו׳',
  54856. 'ה׳',
  54857. 'ד׳',
  54858. 'ג׳',
  54859. 'ב׳',
  54860. 'א׳',
  54861. 'ת',
  54862. 'ש',
  54863. 'ר',
  54864. 'ק',
  54865. 'צ',
  54866. 'פ',
  54867. 'ע',
  54868. 'ס',
  54869. 'נ',
  54870. 'מ',
  54871. 'ל',
  54872. 'כ',
  54873. 'יט',
  54874. 'יח',
  54875. 'יז',
  54876. 'טז',
  54877. 'טו',
  54878. 'י',
  54879. 'ט',
  54880. 'ח',
  54881. 'ז',
  54882. 'ו',
  54883. 'ה',
  54884. 'ד',
  54885. 'ג',
  54886. 'ב',
  54887. 'א'
  54888. ]
  54889. };
  54890. var GEORGIAN = {
  54891. integers: [
  54892. 10000,
  54893. 9000,
  54894. 8000,
  54895. 7000,
  54896. 6000,
  54897. 5000,
  54898. 4000,
  54899. 3000,
  54900. 2000,
  54901. 1000,
  54902. 900,
  54903. 800,
  54904. 700,
  54905. 600,
  54906. 500,
  54907. 400,
  54908. 300,
  54909. 200,
  54910. 100,
  54911. 90,
  54912. 80,
  54913. 70,
  54914. 60,
  54915. 50,
  54916. 40,
  54917. 30,
  54918. 20,
  54919. 10,
  54920. 9,
  54921. 8,
  54922. 7,
  54923. 6,
  54924. 5,
  54925. 4,
  54926. 3,
  54927. 2,
  54928. 1
  54929. ],
  54930. values: [
  54931. 'ჵ',
  54932. 'ჰ',
  54933. 'ჯ',
  54934. 'ჴ',
  54935. 'ხ',
  54936. 'ჭ',
  54937. 'წ',
  54938. 'ძ',
  54939. 'ც',
  54940. 'ჩ',
  54941. 'შ',
  54942. 'ყ',
  54943. 'ღ',
  54944. 'ქ',
  54945. 'ფ',
  54946. 'ჳ',
  54947. 'ტ',
  54948. 'ს',
  54949. 'რ',
  54950. 'ჟ',
  54951. 'პ',
  54952. 'ო',
  54953. 'ჲ',
  54954. 'ნ',
  54955. 'მ',
  54956. 'ლ',
  54957. 'კ',
  54958. 'ი',
  54959. 'თ',
  54960. 'ჱ',
  54961. 'ზ',
  54962. 'ვ',
  54963. 'ე',
  54964. 'დ',
  54965. 'გ',
  54966. 'ბ',
  54967. 'ა'
  54968. ]
  54969. };
  54970. var createAdditiveCounter = function (value, min, max, symbols, fallback, suffix) {
  54971. if (value < min || value > max) {
  54972. return createCounterText(value, fallback, suffix.length > 0);
  54973. }
  54974. return (symbols.integers.reduce(function (string, integer, index) {
  54975. while (value >= integer) {
  54976. value -= integer;
  54977. string += symbols.values[index];
  54978. }
  54979. return string;
  54980. }, '') + suffix);
  54981. };
  54982. var createCounterStyleWithSymbolResolver = function (value, codePointRangeLength, isNumeric, resolver) {
  54983. var string = '';
  54984. do {
  54985. if (!isNumeric) {
  54986. value--;
  54987. }
  54988. string = resolver(value) + string;
  54989. value /= codePointRangeLength;
  54990. } while (value * codePointRangeLength >= codePointRangeLength);
  54991. return string;
  54992. };
  54993. var createCounterStyleFromRange = function (value, codePointRangeStart, codePointRangeEnd, isNumeric, suffix) {
  54994. var codePointRangeLength = codePointRangeEnd - codePointRangeStart + 1;
  54995. return ((value < 0 ? '-' : '') +
  54996. (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, isNumeric, function (codePoint) {
  54997. return fromCodePoint(Math.floor(codePoint % codePointRangeLength) + codePointRangeStart);
  54998. }) +
  54999. suffix));
  55000. };
  55001. var createCounterStyleFromSymbols = function (value, symbols, suffix) {
  55002. if (suffix === void 0) { suffix = '. '; }
  55003. var codePointRangeLength = symbols.length;
  55004. return (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, false, function (codePoint) { return symbols[Math.floor(codePoint % codePointRangeLength)]; }) + suffix);
  55005. };
  55006. var CJK_ZEROS = 1 << 0;
  55007. var CJK_TEN_COEFFICIENTS = 1 << 1;
  55008. var CJK_TEN_HIGH_COEFFICIENTS = 1 << 2;
  55009. var CJK_HUNDRED_COEFFICIENTS = 1 << 3;
  55010. var createCJKCounter = function (value, numbers, multipliers, negativeSign, suffix, flags) {
  55011. if (value < -9999 || value > 9999) {
  55012. return createCounterText(value, LIST_STYLE_TYPE.CJK_DECIMAL, suffix.length > 0);
  55013. }
  55014. var tmp = Math.abs(value);
  55015. var string = suffix;
  55016. if (tmp === 0) {
  55017. return numbers[0] + string;
  55018. }
  55019. for (var digit = 0; tmp > 0 && digit <= 4; digit++) {
  55020. var coefficient = tmp % 10;
  55021. if (coefficient === 0 && contains(flags, CJK_ZEROS) && string !== '') {
  55022. string = numbers[coefficient] + string;
  55023. }
  55024. else if (coefficient > 1 ||
  55025. (coefficient === 1 && digit === 0) ||
  55026. (coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_COEFFICIENTS)) ||
  55027. (coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_HIGH_COEFFICIENTS) && value > 100) ||
  55028. (coefficient === 1 && digit > 1 && contains(flags, CJK_HUNDRED_COEFFICIENTS))) {
  55029. string = numbers[coefficient] + (digit > 0 ? multipliers[digit - 1] : '') + string;
  55030. }
  55031. else if (coefficient === 1 && digit > 0) {
  55032. string = multipliers[digit - 1] + string;
  55033. }
  55034. tmp = Math.floor(tmp / 10);
  55035. }
  55036. return (value < 0 ? negativeSign : '') + string;
  55037. };
  55038. var CHINESE_INFORMAL_MULTIPLIERS = '十百千萬';
  55039. var CHINESE_FORMAL_MULTIPLIERS = '拾佰仟萬';
  55040. var JAPANESE_NEGATIVE = 'マイナス';
  55041. var KOREAN_NEGATIVE = '마이너스';
  55042. var createCounterText = function (value, type, appendSuffix) {
  55043. var defaultSuffix = appendSuffix ? '. ' : '';
  55044. var cjkSuffix = appendSuffix ? '、' : '';
  55045. var koreanSuffix = appendSuffix ? ', ' : '';
  55046. var spaceSuffix = appendSuffix ? ' ' : '';
  55047. switch (type) {
  55048. case LIST_STYLE_TYPE.DISC:
  55049. return '•' + spaceSuffix;
  55050. case LIST_STYLE_TYPE.CIRCLE:
  55051. return '◦' + spaceSuffix;
  55052. case LIST_STYLE_TYPE.SQUARE:
  55053. return '◾' + spaceSuffix;
  55054. case LIST_STYLE_TYPE.DECIMAL_LEADING_ZERO:
  55055. var string = createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
  55056. return string.length < 4 ? "0" + string : string;
  55057. case LIST_STYLE_TYPE.CJK_DECIMAL:
  55058. return createCounterStyleFromSymbols(value, '〇一二三四五六七八九', cjkSuffix);
  55059. case LIST_STYLE_TYPE.LOWER_ROMAN:
  55060. return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, LIST_STYLE_TYPE.DECIMAL, defaultSuffix).toLowerCase();
  55061. case LIST_STYLE_TYPE.UPPER_ROMAN:
  55062. return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, LIST_STYLE_TYPE.DECIMAL, defaultSuffix);
  55063. case LIST_STYLE_TYPE.LOWER_GREEK:
  55064. return createCounterStyleFromRange(value, 945, 969, false, defaultSuffix);
  55065. case LIST_STYLE_TYPE.LOWER_ALPHA:
  55066. return createCounterStyleFromRange(value, 97, 122, false, defaultSuffix);
  55067. case LIST_STYLE_TYPE.UPPER_ALPHA:
  55068. return createCounterStyleFromRange(value, 65, 90, false, defaultSuffix);
  55069. case LIST_STYLE_TYPE.ARABIC_INDIC:
  55070. return createCounterStyleFromRange(value, 1632, 1641, true, defaultSuffix);
  55071. case LIST_STYLE_TYPE.ARMENIAN:
  55072. case LIST_STYLE_TYPE.UPPER_ARMENIAN:
  55073. return createAdditiveCounter(value, 1, 9999, ARMENIAN, LIST_STYLE_TYPE.DECIMAL, defaultSuffix);
  55074. case LIST_STYLE_TYPE.LOWER_ARMENIAN:
  55075. return createAdditiveCounter(value, 1, 9999, ARMENIAN, LIST_STYLE_TYPE.DECIMAL, defaultSuffix).toLowerCase();
  55076. case LIST_STYLE_TYPE.BENGALI:
  55077. return createCounterStyleFromRange(value, 2534, 2543, true, defaultSuffix);
  55078. case LIST_STYLE_TYPE.CAMBODIAN:
  55079. case LIST_STYLE_TYPE.KHMER:
  55080. return createCounterStyleFromRange(value, 6112, 6121, true, defaultSuffix);
  55081. case LIST_STYLE_TYPE.CJK_EARTHLY_BRANCH:
  55082. return createCounterStyleFromSymbols(value, '子丑寅卯辰巳午未申酉戌亥', cjkSuffix);
  55083. case LIST_STYLE_TYPE.CJK_HEAVENLY_STEM:
  55084. return createCounterStyleFromSymbols(value, '甲乙丙丁戊己庚辛壬癸', cjkSuffix);
  55085. case LIST_STYLE_TYPE.CJK_IDEOGRAPHIC:
  55086. case LIST_STYLE_TYPE.TRAD_CHINESE_INFORMAL:
  55087. return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
  55088. case LIST_STYLE_TYPE.TRAD_CHINESE_FORMAL:
  55089. return createCJKCounter(value, '零壹貳參肆伍陸柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
  55090. case LIST_STYLE_TYPE.SIMP_CHINESE_INFORMAL:
  55091. return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
  55092. case LIST_STYLE_TYPE.SIMP_CHINESE_FORMAL:
  55093. return createCJKCounter(value, '零壹贰叁肆伍陆柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
  55094. case LIST_STYLE_TYPE.JAPANESE_INFORMAL:
  55095. return createCJKCounter(value, '〇一二三四五六七八九', '十百千万', JAPANESE_NEGATIVE, cjkSuffix, 0);
  55096. case LIST_STYLE_TYPE.JAPANESE_FORMAL:
  55097. return createCJKCounter(value, '零壱弐参四伍六七八九', '拾百千万', JAPANESE_NEGATIVE, cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
  55098. case LIST_STYLE_TYPE.KOREAN_HANGUL_FORMAL:
  55099. return createCJKCounter(value, '영일이삼사오육칠팔구', '십백천만', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
  55100. case LIST_STYLE_TYPE.KOREAN_HANJA_INFORMAL:
  55101. return createCJKCounter(value, '零一二三四五六七八九', '十百千萬', KOREAN_NEGATIVE, koreanSuffix, 0);
  55102. case LIST_STYLE_TYPE.KOREAN_HANJA_FORMAL:
  55103. return createCJKCounter(value, '零壹貳參四五六七八九', '拾百千', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
  55104. case LIST_STYLE_TYPE.DEVANAGARI:
  55105. return createCounterStyleFromRange(value, 0x966, 0x96f, true, defaultSuffix);
  55106. case LIST_STYLE_TYPE.GEORGIAN:
  55107. return createAdditiveCounter(value, 1, 19999, GEORGIAN, LIST_STYLE_TYPE.DECIMAL, defaultSuffix);
  55108. case LIST_STYLE_TYPE.GUJARATI:
  55109. return createCounterStyleFromRange(value, 0xae6, 0xaef, true, defaultSuffix);
  55110. case LIST_STYLE_TYPE.GURMUKHI:
  55111. return createCounterStyleFromRange(value, 0xa66, 0xa6f, true, defaultSuffix);
  55112. case LIST_STYLE_TYPE.HEBREW:
  55113. return createAdditiveCounter(value, 1, 10999, HEBREW, LIST_STYLE_TYPE.DECIMAL, defaultSuffix);
  55114. case LIST_STYLE_TYPE.HIRAGANA:
  55115. return createCounterStyleFromSymbols(value, 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん');
  55116. case LIST_STYLE_TYPE.HIRAGANA_IROHA:
  55117. return createCounterStyleFromSymbols(value, 'いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす');
  55118. case LIST_STYLE_TYPE.KANNADA:
  55119. return createCounterStyleFromRange(value, 0xce6, 0xcef, true, defaultSuffix);
  55120. case LIST_STYLE_TYPE.KATAKANA:
  55121. return createCounterStyleFromSymbols(value, 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン', cjkSuffix);
  55122. case LIST_STYLE_TYPE.KATAKANA_IROHA:
  55123. return createCounterStyleFromSymbols(value, 'イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス', cjkSuffix);
  55124. case LIST_STYLE_TYPE.LAO:
  55125. return createCounterStyleFromRange(value, 0xed0, 0xed9, true, defaultSuffix);
  55126. case LIST_STYLE_TYPE.MONGOLIAN:
  55127. return createCounterStyleFromRange(value, 0x1810, 0x1819, true, defaultSuffix);
  55128. case LIST_STYLE_TYPE.MYANMAR:
  55129. return createCounterStyleFromRange(value, 0x1040, 0x1049, true, defaultSuffix);
  55130. case LIST_STYLE_TYPE.ORIYA:
  55131. return createCounterStyleFromRange(value, 0xb66, 0xb6f, true, defaultSuffix);
  55132. case LIST_STYLE_TYPE.PERSIAN:
  55133. return createCounterStyleFromRange(value, 0x6f0, 0x6f9, true, defaultSuffix);
  55134. case LIST_STYLE_TYPE.TAMIL:
  55135. return createCounterStyleFromRange(value, 0xbe6, 0xbef, true, defaultSuffix);
  55136. case LIST_STYLE_TYPE.TELUGU:
  55137. return createCounterStyleFromRange(value, 0xc66, 0xc6f, true, defaultSuffix);
  55138. case LIST_STYLE_TYPE.THAI:
  55139. return createCounterStyleFromRange(value, 0xe50, 0xe59, true, defaultSuffix);
  55140. case LIST_STYLE_TYPE.TIBETAN:
  55141. return createCounterStyleFromRange(value, 0xf20, 0xf29, true, defaultSuffix);
  55142. case LIST_STYLE_TYPE.DECIMAL:
  55143. default:
  55144. return createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
  55145. }
  55146. };
  55147. var IGNORE_ATTRIBUTE = 'data-html2canvas-ignore';
  55148. var DocumentCloner = /** @class */ (function () {
  55149. function DocumentCloner(element, options) {
  55150. this.options = options;
  55151. this.scrolledElements = [];
  55152. this.referenceElement = element;
  55153. this.counters = new CounterState();
  55154. this.quoteDepth = 0;
  55155. if (!element.ownerDocument) {
  55156. throw new Error('Cloned element does not have an owner document');
  55157. }
  55158. this.documentElement = this.cloneNode(element.ownerDocument.documentElement);
  55159. }
  55160. DocumentCloner.prototype.toIFrame = function (ownerDocument, windowSize) {
  55161. var _this = this;
  55162. var iframe = createIFrameContainer(ownerDocument, windowSize);
  55163. if (!iframe.contentWindow) {
  55164. return Promise.reject("Unable to find iframe window");
  55165. }
  55166. var scrollX = ownerDocument.defaultView.pageXOffset;
  55167. var scrollY = ownerDocument.defaultView.pageYOffset;
  55168. var cloneWindow = iframe.contentWindow;
  55169. var documentClone = cloneWindow.document;
  55170. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  55171. if window url is about:blank, we can assign the url to current by writing onto the document
  55172. */
  55173. var iframeLoad = iframeLoader(iframe).then(function () { return __awaiter(_this, void 0, void 0, function () {
  55174. var onclone;
  55175. return __generator(this, function (_a) {
  55176. switch (_a.label) {
  55177. case 0:
  55178. this.scrolledElements.forEach(restoreNodeScroll);
  55179. if (cloneWindow) {
  55180. cloneWindow.scrollTo(windowSize.left, windowSize.top);
  55181. if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent) &&
  55182. (cloneWindow.scrollY !== windowSize.top || cloneWindow.scrollX !== windowSize.left)) {
  55183. documentClone.documentElement.style.top = -windowSize.top + 'px';
  55184. documentClone.documentElement.style.left = -windowSize.left + 'px';
  55185. documentClone.documentElement.style.position = 'absolute';
  55186. }
  55187. }
  55188. onclone = this.options.onclone;
  55189. if (typeof this.clonedReferenceElement === 'undefined') {
  55190. return [2 /*return*/, Promise.reject("Error finding the " + this.referenceElement.nodeName + " in the cloned document")];
  55191. }
  55192. if (!(documentClone.fonts && documentClone.fonts.ready)) return [3 /*break*/, 2];
  55193. return [4 /*yield*/, documentClone.fonts.ready];
  55194. case 1:
  55195. _a.sent();
  55196. _a.label = 2;
  55197. case 2:
  55198. if (typeof onclone === 'function') {
  55199. return [2 /*return*/, Promise.resolve()
  55200. .then(function () { return onclone(documentClone); })
  55201. .then(function () { return iframe; })];
  55202. }
  55203. return [2 /*return*/, iframe];
  55204. }
  55205. });
  55206. }); });
  55207. documentClone.open();
  55208. documentClone.write(serializeDoctype(document.doctype) + "<html></html>");
  55209. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  55210. restoreOwnerScroll(this.referenceElement.ownerDocument, scrollX, scrollY);
  55211. documentClone.replaceChild(documentClone.adoptNode(this.documentElement), documentClone.documentElement);
  55212. documentClone.close();
  55213. return iframeLoad;
  55214. };
  55215. DocumentCloner.prototype.createElementClone = function (node) {
  55216. if (isCanvasElement(node)) {
  55217. return this.createCanvasClone(node);
  55218. }
  55219. /*
  55220. if (isIFrameElement(node)) {
  55221. return this.createIFrameClone(node);
  55222. }
  55223. */
  55224. if (isStyleElement(node)) {
  55225. return this.createStyleClone(node);
  55226. }
  55227. var clone = node.cloneNode(false);
  55228. // @ts-ignore
  55229. if (isImageElement(clone) && clone.loading === 'lazy') {
  55230. // @ts-ignore
  55231. clone.loading = 'eager';
  55232. }
  55233. return clone;
  55234. };
  55235. DocumentCloner.prototype.createStyleClone = function (node) {
  55236. try {
  55237. var sheet = node.sheet;
  55238. if (sheet && sheet.cssRules) {
  55239. var css = [].slice.call(sheet.cssRules, 0).reduce(function (css, rule) {
  55240. if (rule && typeof rule.cssText === 'string') {
  55241. return css + rule.cssText;
  55242. }
  55243. return css;
  55244. }, '');
  55245. var style = node.cloneNode(false);
  55246. style.textContent = css;
  55247. return style;
  55248. }
  55249. }
  55250. catch (e) {
  55251. // accessing node.sheet.cssRules throws a DOMException
  55252. Logger.getInstance(this.options.id).error('Unable to access cssRules property', e);
  55253. if (e.name !== 'SecurityError') {
  55254. throw e;
  55255. }
  55256. }
  55257. return node.cloneNode(false);
  55258. };
  55259. DocumentCloner.prototype.createCanvasClone = function (canvas) {
  55260. if (this.options.inlineImages && canvas.ownerDocument) {
  55261. var img = canvas.ownerDocument.createElement('img');
  55262. try {
  55263. img.src = canvas.toDataURL();
  55264. return img;
  55265. }
  55266. catch (e) {
  55267. Logger.getInstance(this.options.id).info("Unable to clone canvas contents, canvas is tainted");
  55268. }
  55269. }
  55270. var clonedCanvas = canvas.cloneNode(false);
  55271. try {
  55272. clonedCanvas.width = canvas.width;
  55273. clonedCanvas.height = canvas.height;
  55274. var ctx = canvas.getContext('2d');
  55275. var clonedCtx = clonedCanvas.getContext('2d');
  55276. if (clonedCtx) {
  55277. if (ctx) {
  55278. clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  55279. }
  55280. else {
  55281. clonedCtx.drawImage(canvas, 0, 0);
  55282. }
  55283. }
  55284. return clonedCanvas;
  55285. }
  55286. catch (e) { }
  55287. return clonedCanvas;
  55288. };
  55289. /*
  55290. createIFrameClone(iframe: HTMLIFrameElement) {
  55291. const tempIframe = <HTMLIFrameElement>iframe.cloneNode(false);
  55292. const iframeKey = generateIframeKey();
  55293. tempIframe.setAttribute('data-html2canvas-internal-iframe-key', iframeKey);
  55294. const {width, height} = parseBounds(iframe);
  55295. this.resourceLoader.cache[iframeKey] = getIframeDocumentElement(iframe, this.options)
  55296. .then(documentElement => {
  55297. return this.renderer(
  55298. documentElement,
  55299. {
  55300. allowTaint: this.options.allowTaint,
  55301. backgroundColor: '#ffffff',
  55302. canvas: null,
  55303. imageTimeout: this.options.imageTimeout,
  55304. logging: this.options.logging,
  55305. proxy: this.options.proxy,
  55306. removeContainer: this.options.removeContainer,
  55307. scale: this.options.scale,
  55308. foreignObjectRendering: this.options.foreignObjectRendering,
  55309. useCORS: this.options.useCORS,
  55310. target: new CanvasRenderer(),
  55311. width,
  55312. height,
  55313. x: 0,
  55314. y: 0,
  55315. windowWidth: documentElement.ownerDocument.defaultView.innerWidth,
  55316. windowHeight: documentElement.ownerDocument.defaultView.innerHeight,
  55317. scrollX: documentElement.ownerDocument.defaultView.pageXOffset,
  55318. scrollY: documentElement.ownerDocument.defaultView.pageYOffset
  55319. },
  55320. );
  55321. })
  55322. .then(
  55323. (canvas: HTMLCanvasElement) =>
  55324. new Promise((resolve, reject) => {
  55325. const iframeCanvas = document.createElement('img');
  55326. iframeCanvas.onload = () => resolve(canvas);
  55327. iframeCanvas.onerror = (event) => {
  55328. // Empty iframes may result in empty "data:," URLs, which are invalid from the <img>'s point of view
  55329. // and instead of `onload` cause `onerror` and unhandled rejection warnings
  55330. // https://github.com/niklasvh/html2canvas/issues/1502
  55331. iframeCanvas.src == 'data:,' ? resolve(canvas) : reject(event);
  55332. };
  55333. iframeCanvas.src = canvas.toDataURL();
  55334. if (tempIframe.parentNode && iframe.ownerDocument && iframe.ownerDocument.defaultView) {
  55335. tempIframe.parentNode.replaceChild(
  55336. copyCSSStyles(
  55337. iframe.ownerDocument.defaultView.getComputedStyle(iframe),
  55338. iframeCanvas
  55339. ),
  55340. tempIframe
  55341. );
  55342. }
  55343. })
  55344. );
  55345. return tempIframe;
  55346. }
  55347. */
  55348. DocumentCloner.prototype.cloneNode = function (node) {
  55349. if (isTextNode(node)) {
  55350. return document.createTextNode(node.data);
  55351. }
  55352. if (!node.ownerDocument) {
  55353. return node.cloneNode(false);
  55354. }
  55355. var window = node.ownerDocument.defaultView;
  55356. if (window && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {
  55357. var clone = this.createElementClone(node);
  55358. var style = window.getComputedStyle(node);
  55359. var styleBefore = window.getComputedStyle(node, ':before');
  55360. var styleAfter = window.getComputedStyle(node, ':after');
  55361. if (this.referenceElement === node && isHTMLElementNode(clone)) {
  55362. this.clonedReferenceElement = clone;
  55363. }
  55364. if (isBodyElement(clone)) {
  55365. createPseudoHideStyles(clone);
  55366. }
  55367. var counters = this.counters.parse(new CSSParsedCounterDeclaration(style));
  55368. var before = this.resolvePseudoContent(node, clone, styleBefore, PseudoElementType.BEFORE);
  55369. for (var child = node.firstChild; child; child = child.nextSibling) {
  55370. if (!isElementNode(child) ||
  55371. (!isScriptElement(child) &&
  55372. !child.hasAttribute(IGNORE_ATTRIBUTE) &&
  55373. (typeof this.options.ignoreElements !== 'function' || !this.options.ignoreElements(child)))) {
  55374. if (!this.options.copyStyles || !isElementNode(child) || !isStyleElement(child)) {
  55375. clone.appendChild(this.cloneNode(child));
  55376. }
  55377. }
  55378. }
  55379. if (before) {
  55380. clone.insertBefore(before, clone.firstChild);
  55381. }
  55382. var after = this.resolvePseudoContent(node, clone, styleAfter, PseudoElementType.AFTER);
  55383. if (after) {
  55384. clone.appendChild(after);
  55385. }
  55386. this.counters.pop(counters);
  55387. if (style && (this.options.copyStyles || isSVGElementNode(node)) && !isIFrameElement(node)) {
  55388. copyCSSStyles(style, clone);
  55389. }
  55390. //this.inlineAllImages(clone);
  55391. if (node.scrollTop !== 0 || node.scrollLeft !== 0) {
  55392. this.scrolledElements.push([clone, node.scrollLeft, node.scrollTop]);
  55393. }
  55394. if ((isTextareaElement(node) || isSelectElement(node)) &&
  55395. (isTextareaElement(clone) || isSelectElement(clone))) {
  55396. clone.value = node.value;
  55397. }
  55398. return clone;
  55399. }
  55400. return node.cloneNode(false);
  55401. };
  55402. DocumentCloner.prototype.resolvePseudoContent = function (node, clone, style, pseudoElt) {
  55403. var _this = this;
  55404. if (!style) {
  55405. return;
  55406. }
  55407. var value = style.content;
  55408. var document = clone.ownerDocument;
  55409. if (!document || !value || value === 'none' || value === '-moz-alt-content' || style.display === 'none') {
  55410. return;
  55411. }
  55412. this.counters.parse(new CSSParsedCounterDeclaration(style));
  55413. var declaration = new CSSParsedPseudoDeclaration(style);
  55414. var anonymousReplacedElement = document.createElement('html2canvaspseudoelement');
  55415. copyCSSStyles(style, anonymousReplacedElement);
  55416. declaration.content.forEach(function (token) {
  55417. if (token.type === TokenType.STRING_TOKEN) {
  55418. anonymousReplacedElement.appendChild(document.createTextNode(token.value));
  55419. }
  55420. else if (token.type === TokenType.URL_TOKEN) {
  55421. var img = document.createElement('img');
  55422. img.src = token.value;
  55423. img.style.opacity = '1';
  55424. anonymousReplacedElement.appendChild(img);
  55425. }
  55426. else if (token.type === TokenType.FUNCTION) {
  55427. if (token.name === 'attr') {
  55428. var attr = token.values.filter(isIdentToken);
  55429. if (attr.length) {
  55430. anonymousReplacedElement.appendChild(document.createTextNode(node.getAttribute(attr[0].value) || ''));
  55431. }
  55432. }
  55433. else if (token.name === 'counter') {
  55434. var _a = token.values.filter(nonFunctionArgSeparator), counter = _a[0], counterStyle = _a[1];
  55435. if (counter && isIdentToken(counter)) {
  55436. var counterState = _this.counters.getCounterValue(counter.value);
  55437. var counterType = counterStyle && isIdentToken(counterStyle)
  55438. ? listStyleType.parse(counterStyle.value)
  55439. : LIST_STYLE_TYPE.DECIMAL;
  55440. anonymousReplacedElement.appendChild(document.createTextNode(createCounterText(counterState, counterType, false)));
  55441. }
  55442. }
  55443. else if (token.name === 'counters') {
  55444. var _b = token.values.filter(nonFunctionArgSeparator), counter = _b[0], delim = _b[1], counterStyle = _b[2];
  55445. if (counter && isIdentToken(counter)) {
  55446. var counterStates = _this.counters.getCounterValues(counter.value);
  55447. var counterType_1 = counterStyle && isIdentToken(counterStyle)
  55448. ? listStyleType.parse(counterStyle.value)
  55449. : LIST_STYLE_TYPE.DECIMAL;
  55450. var separator = delim && delim.type === TokenType.STRING_TOKEN ? delim.value : '';
  55451. var text = counterStates
  55452. .map(function (value) { return createCounterText(value, counterType_1, false); })
  55453. .join(separator);
  55454. anonymousReplacedElement.appendChild(document.createTextNode(text));
  55455. }
  55456. }
  55457. }
  55458. else if (token.type === TokenType.IDENT_TOKEN) {
  55459. switch (token.value) {
  55460. case 'open-quote':
  55461. anonymousReplacedElement.appendChild(document.createTextNode(getQuote(declaration.quotes, _this.quoteDepth++, true)));
  55462. break;
  55463. case 'close-quote':
  55464. anonymousReplacedElement.appendChild(document.createTextNode(getQuote(declaration.quotes, --_this.quoteDepth, false)));
  55465. break;
  55466. default:
  55467. // safari doesn't parse string tokens correctly because of lack of quotes
  55468. anonymousReplacedElement.appendChild(document.createTextNode(token.value));
  55469. }
  55470. }
  55471. });
  55472. anonymousReplacedElement.className = PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  55473. var newClassName = pseudoElt === PseudoElementType.BEFORE
  55474. ? " " + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE
  55475. : " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  55476. if (isSVGElementNode(clone)) {
  55477. clone.className.baseValue += newClassName;
  55478. }
  55479. else {
  55480. clone.className += newClassName;
  55481. }
  55482. return anonymousReplacedElement;
  55483. };
  55484. DocumentCloner.destroy = function (container) {
  55485. if (container.parentNode) {
  55486. container.parentNode.removeChild(container);
  55487. return true;
  55488. }
  55489. return false;
  55490. };
  55491. return DocumentCloner;
  55492. }());
  55493. var PseudoElementType;
  55494. (function (PseudoElementType) {
  55495. PseudoElementType[PseudoElementType["BEFORE"] = 0] = "BEFORE";
  55496. PseudoElementType[PseudoElementType["AFTER"] = 1] = "AFTER";
  55497. })(PseudoElementType || (PseudoElementType = {}));
  55498. var createIFrameContainer = function (ownerDocument, bounds) {
  55499. var cloneIframeContainer = ownerDocument.createElement('iframe');
  55500. cloneIframeContainer.className = 'html2canvas-container';
  55501. cloneIframeContainer.style.visibility = 'hidden';
  55502. cloneIframeContainer.style.position = 'fixed';
  55503. cloneIframeContainer.style.left = '-10000px';
  55504. cloneIframeContainer.style.top = '0px';
  55505. cloneIframeContainer.style.border = '0';
  55506. cloneIframeContainer.width = bounds.width.toString();
  55507. cloneIframeContainer.height = bounds.height.toString();
  55508. cloneIframeContainer.scrolling = 'no'; // ios won't scroll without it
  55509. cloneIframeContainer.setAttribute(IGNORE_ATTRIBUTE, 'true');
  55510. ownerDocument.body.appendChild(cloneIframeContainer);
  55511. return cloneIframeContainer;
  55512. };
  55513. var iframeLoader = function (iframe) {
  55514. return new Promise(function (resolve, reject) {
  55515. var cloneWindow = iframe.contentWindow;
  55516. if (!cloneWindow) {
  55517. return reject("No window assigned for iframe");
  55518. }
  55519. var documentClone = cloneWindow.document;
  55520. cloneWindow.onload = iframe.onload = documentClone.onreadystatechange = function () {
  55521. cloneWindow.onload = iframe.onload = documentClone.onreadystatechange = null;
  55522. var interval = setInterval(function () {
  55523. if (documentClone.body.childNodes.length > 0 && documentClone.readyState === 'complete') {
  55524. clearInterval(interval);
  55525. resolve(iframe);
  55526. }
  55527. }, 50);
  55528. };
  55529. });
  55530. };
  55531. var copyCSSStyles = function (style, target) {
  55532. // Edge does not provide value for cssText
  55533. for (var i = style.length - 1; i >= 0; i--) {
  55534. var property = style.item(i);
  55535. // Safari shows pseudoelements if content is set
  55536. if (property !== 'content') {
  55537. target.style.setProperty(property, style.getPropertyValue(property));
  55538. }
  55539. }
  55540. return target;
  55541. };
  55542. var serializeDoctype = function (doctype) {
  55543. var str = '';
  55544. if (doctype) {
  55545. str += '<!DOCTYPE ';
  55546. if (doctype.name) {
  55547. str += doctype.name;
  55548. }
  55549. if (doctype.internalSubset) {
  55550. str += doctype.internalSubset;
  55551. }
  55552. if (doctype.publicId) {
  55553. str += "\"" + doctype.publicId + "\"";
  55554. }
  55555. if (doctype.systemId) {
  55556. str += "\"" + doctype.systemId + "\"";
  55557. }
  55558. str += '>';
  55559. }
  55560. return str;
  55561. };
  55562. var restoreOwnerScroll = function (ownerDocument, x, y) {
  55563. if (ownerDocument &&
  55564. ownerDocument.defaultView &&
  55565. (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  55566. ownerDocument.defaultView.scrollTo(x, y);
  55567. }
  55568. };
  55569. var restoreNodeScroll = function (_a) {
  55570. var element = _a[0], x = _a[1], y = _a[2];
  55571. element.scrollLeft = x;
  55572. element.scrollTop = y;
  55573. };
  55574. var PSEUDO_BEFORE = ':before';
  55575. var PSEUDO_AFTER = ':after';
  55576. var PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = '___html2canvas___pseudoelement_before';
  55577. var PSEUDO_HIDE_ELEMENT_CLASS_AFTER = '___html2canvas___pseudoelement_after';
  55578. var PSEUDO_HIDE_ELEMENT_STYLE = "{\n content: \"\" !important;\n display: none !important;\n}";
  55579. var createPseudoHideStyles = function (body) {
  55580. createStyles(body, "." + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + PSEUDO_BEFORE + PSEUDO_HIDE_ELEMENT_STYLE + "\n ." + PSEUDO_HIDE_ELEMENT_CLASS_AFTER + PSEUDO_AFTER + PSEUDO_HIDE_ELEMENT_STYLE);
  55581. };
  55582. var createStyles = function (body, styles) {
  55583. var document = body.ownerDocument;
  55584. if (document) {
  55585. var style = document.createElement('style');
  55586. style.textContent = styles;
  55587. body.appendChild(style);
  55588. }
  55589. };
  55590. var PathType;
  55591. (function (PathType) {
  55592. PathType[PathType["VECTOR"] = 0] = "VECTOR";
  55593. PathType[PathType["BEZIER_CURVE"] = 1] = "BEZIER_CURVE";
  55594. })(PathType || (PathType = {}));
  55595. var equalPath = function (a, b) {
  55596. if (a.length === b.length) {
  55597. return a.some(function (v, i) { return v === b[i]; });
  55598. }
  55599. return false;
  55600. };
  55601. var transformPath = function (path, deltaX, deltaY, deltaW, deltaH) {
  55602. return path.map(function (point, index) {
  55603. switch (index) {
  55604. case 0:
  55605. return point.add(deltaX, deltaY);
  55606. case 1:
  55607. return point.add(deltaX + deltaW, deltaY);
  55608. case 2:
  55609. return point.add(deltaX + deltaW, deltaY + deltaH);
  55610. case 3:
  55611. return point.add(deltaX, deltaY + deltaH);
  55612. }
  55613. return point;
  55614. });
  55615. };
  55616. var Vector = /** @class */ (function () {
  55617. function Vector(x, y) {
  55618. this.type = PathType.VECTOR;
  55619. this.x = x;
  55620. this.y = y;
  55621. }
  55622. Vector.prototype.add = function (deltaX, deltaY) {
  55623. return new Vector(this.x + deltaX, this.y + deltaY);
  55624. };
  55625. return Vector;
  55626. }());
  55627. var lerp = function (a, b, t) {
  55628. return new Vector(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
  55629. };
  55630. var BezierCurve = /** @class */ (function () {
  55631. function BezierCurve(start, startControl, endControl, end) {
  55632. this.type = PathType.BEZIER_CURVE;
  55633. this.start = start;
  55634. this.startControl = startControl;
  55635. this.endControl = endControl;
  55636. this.end = end;
  55637. }
  55638. BezierCurve.prototype.subdivide = function (t, firstHalf) {
  55639. var ab = lerp(this.start, this.startControl, t);
  55640. var bc = lerp(this.startControl, this.endControl, t);
  55641. var cd = lerp(this.endControl, this.end, t);
  55642. var abbc = lerp(ab, bc, t);
  55643. var bccd = lerp(bc, cd, t);
  55644. var dest = lerp(abbc, bccd, t);
  55645. return firstHalf ? new BezierCurve(this.start, ab, abbc, dest) : new BezierCurve(dest, bccd, cd, this.end);
  55646. };
  55647. BezierCurve.prototype.add = function (deltaX, deltaY) {
  55648. return new BezierCurve(this.start.add(deltaX, deltaY), this.startControl.add(deltaX, deltaY), this.endControl.add(deltaX, deltaY), this.end.add(deltaX, deltaY));
  55649. };
  55650. BezierCurve.prototype.reverse = function () {
  55651. return new BezierCurve(this.end, this.endControl, this.startControl, this.start);
  55652. };
  55653. return BezierCurve;
  55654. }());
  55655. var isBezierCurve = function (path) { return path.type === PathType.BEZIER_CURVE; };
  55656. var BoundCurves = /** @class */ (function () {
  55657. function BoundCurves(element) {
  55658. var styles = element.styles;
  55659. var bounds = element.bounds;
  55660. var _a = getAbsoluteValueForTuple(styles.borderTopLeftRadius, bounds.width, bounds.height), tlh = _a[0], tlv = _a[1];
  55661. var _b = getAbsoluteValueForTuple(styles.borderTopRightRadius, bounds.width, bounds.height), trh = _b[0], trv = _b[1];
  55662. var _c = getAbsoluteValueForTuple(styles.borderBottomRightRadius, bounds.width, bounds.height), brh = _c[0], brv = _c[1];
  55663. var _d = getAbsoluteValueForTuple(styles.borderBottomLeftRadius, bounds.width, bounds.height), blh = _d[0], blv = _d[1];
  55664. var factors = [];
  55665. factors.push((tlh + trh) / bounds.width);
  55666. factors.push((blh + brh) / bounds.width);
  55667. factors.push((tlv + blv) / bounds.height);
  55668. factors.push((trv + brv) / bounds.height);
  55669. var maxFactor = Math.max.apply(Math, factors);
  55670. if (maxFactor > 1) {
  55671. tlh /= maxFactor;
  55672. tlv /= maxFactor;
  55673. trh /= maxFactor;
  55674. trv /= maxFactor;
  55675. brh /= maxFactor;
  55676. brv /= maxFactor;
  55677. blh /= maxFactor;
  55678. blv /= maxFactor;
  55679. }
  55680. var topWidth = bounds.width - trh;
  55681. var rightHeight = bounds.height - brv;
  55682. var bottomWidth = bounds.width - brh;
  55683. var leftHeight = bounds.height - blv;
  55684. var borderTopWidth = styles.borderTopWidth;
  55685. var borderRightWidth = styles.borderRightWidth;
  55686. var borderBottomWidth = styles.borderBottomWidth;
  55687. var borderLeftWidth = styles.borderLeftWidth;
  55688. var paddingTop = getAbsoluteValue(styles.paddingTop, element.bounds.width);
  55689. var paddingRight = getAbsoluteValue(styles.paddingRight, element.bounds.width);
  55690. var paddingBottom = getAbsoluteValue(styles.paddingBottom, element.bounds.width);
  55691. var paddingLeft = getAbsoluteValue(styles.paddingLeft, element.bounds.width);
  55692. this.topLeftBorderBox =
  55693. tlh > 0 || tlv > 0
  55694. ? getCurvePoints(bounds.left, bounds.top, tlh, tlv, CORNER.TOP_LEFT)
  55695. : new Vector(bounds.left, bounds.top);
  55696. this.topRightBorderBox =
  55697. trh > 0 || trv > 0
  55698. ? getCurvePoints(bounds.left + topWidth, bounds.top, trh, trv, CORNER.TOP_RIGHT)
  55699. : new Vector(bounds.left + bounds.width, bounds.top);
  55700. this.bottomRightBorderBox =
  55701. brh > 0 || brv > 0
  55702. ? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh, brv, CORNER.BOTTOM_RIGHT)
  55703. : new Vector(bounds.left + bounds.width, bounds.top + bounds.height);
  55704. this.bottomLeftBorderBox =
  55705. blh > 0 || blv > 0
  55706. ? getCurvePoints(bounds.left, bounds.top + leftHeight, blh, blv, CORNER.BOTTOM_LEFT)
  55707. : new Vector(bounds.left, bounds.top + bounds.height);
  55708. this.topLeftPaddingBox =
  55709. tlh > 0 || tlv > 0
  55710. ? getCurvePoints(bounds.left + borderLeftWidth, bounds.top + borderTopWidth, Math.max(0, tlh - borderLeftWidth), Math.max(0, tlv - borderTopWidth), CORNER.TOP_LEFT)
  55711. : new Vector(bounds.left + borderLeftWidth, bounds.top + borderTopWidth);
  55712. this.topRightPaddingBox =
  55713. trh > 0 || trv > 0
  55714. ? getCurvePoints(bounds.left + Math.min(topWidth, bounds.width + borderLeftWidth), bounds.top + borderTopWidth, topWidth > bounds.width + borderLeftWidth ? 0 : trh - borderLeftWidth, trv - borderTopWidth, CORNER.TOP_RIGHT)
  55715. : new Vector(bounds.left + bounds.width - borderRightWidth, bounds.top + borderTopWidth);
  55716. this.bottomRightPaddingBox =
  55717. brh > 0 || brv > 0
  55718. ? getCurvePoints(bounds.left + Math.min(bottomWidth, bounds.width - borderLeftWidth), bounds.top + Math.min(rightHeight, bounds.height + borderTopWidth), Math.max(0, brh - borderRightWidth), brv - borderBottomWidth, CORNER.BOTTOM_RIGHT)
  55719. : new Vector(bounds.left + bounds.width - borderRightWidth, bounds.top + bounds.height - borderBottomWidth);
  55720. this.bottomLeftPaddingBox =
  55721. blh > 0 || blv > 0
  55722. ? getCurvePoints(bounds.left + borderLeftWidth, bounds.top + leftHeight, Math.max(0, blh - borderLeftWidth), blv - borderBottomWidth, CORNER.BOTTOM_LEFT)
  55723. : new Vector(bounds.left + borderLeftWidth, bounds.top + bounds.height - borderBottomWidth);
  55724. this.topLeftContentBox =
  55725. tlh > 0 || tlv > 0
  55726. ? getCurvePoints(bounds.left + borderLeftWidth + paddingLeft, bounds.top + borderTopWidth + paddingTop, Math.max(0, tlh - (borderLeftWidth + paddingLeft)), Math.max(0, tlv - (borderTopWidth + paddingTop)), CORNER.TOP_LEFT)
  55727. : new Vector(bounds.left + borderLeftWidth + paddingLeft, bounds.top + borderTopWidth + paddingTop);
  55728. this.topRightContentBox =
  55729. trh > 0 || trv > 0
  55730. ? getCurvePoints(bounds.left + Math.min(topWidth, bounds.width + borderLeftWidth + paddingLeft), bounds.top + borderTopWidth + paddingTop, topWidth > bounds.width + borderLeftWidth + paddingLeft ? 0 : trh - borderLeftWidth + paddingLeft, trv - (borderTopWidth + paddingTop), CORNER.TOP_RIGHT)
  55731. : new Vector(bounds.left + bounds.width - (borderRightWidth + paddingRight), bounds.top + borderTopWidth + paddingTop);
  55732. this.bottomRightContentBox =
  55733. brh > 0 || brv > 0
  55734. ? getCurvePoints(bounds.left + Math.min(bottomWidth, bounds.width - (borderLeftWidth + paddingLeft)), bounds.top + Math.min(rightHeight, bounds.height + borderTopWidth + paddingTop), Math.max(0, brh - (borderRightWidth + paddingRight)), brv - (borderBottomWidth + paddingBottom), CORNER.BOTTOM_RIGHT)
  55735. : new Vector(bounds.left + bounds.width - (borderRightWidth + paddingRight), bounds.top + bounds.height - (borderBottomWidth + paddingBottom));
  55736. this.bottomLeftContentBox =
  55737. blh > 0 || blv > 0
  55738. ? getCurvePoints(bounds.left + borderLeftWidth + paddingLeft, bounds.top + leftHeight, Math.max(0, blh - (borderLeftWidth + paddingLeft)), blv - (borderBottomWidth + paddingBottom), CORNER.BOTTOM_LEFT)
  55739. : new Vector(bounds.left + borderLeftWidth + paddingLeft, bounds.top + bounds.height - (borderBottomWidth + paddingBottom));
  55740. }
  55741. return BoundCurves;
  55742. }());
  55743. var CORNER;
  55744. (function (CORNER) {
  55745. CORNER[CORNER["TOP_LEFT"] = 0] = "TOP_LEFT";
  55746. CORNER[CORNER["TOP_RIGHT"] = 1] = "TOP_RIGHT";
  55747. CORNER[CORNER["BOTTOM_RIGHT"] = 2] = "BOTTOM_RIGHT";
  55748. CORNER[CORNER["BOTTOM_LEFT"] = 3] = "BOTTOM_LEFT";
  55749. })(CORNER || (CORNER = {}));
  55750. var getCurvePoints = function (x, y, r1, r2, position) {
  55751. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  55752. var ox = r1 * kappa; // control point offset horizontal
  55753. var oy = r2 * kappa; // control point offset vertical
  55754. var xm = x + r1; // x-middle
  55755. var ym = y + r2; // y-middle
  55756. switch (position) {
  55757. case CORNER.TOP_LEFT:
  55758. return new BezierCurve(new Vector(x, ym), new Vector(x, ym - oy), new Vector(xm - ox, y), new Vector(xm, y));
  55759. case CORNER.TOP_RIGHT:
  55760. return new BezierCurve(new Vector(x, y), new Vector(x + ox, y), new Vector(xm, ym - oy), new Vector(xm, ym));
  55761. case CORNER.BOTTOM_RIGHT:
  55762. return new BezierCurve(new Vector(xm, y), new Vector(xm, y + oy), new Vector(x + ox, ym), new Vector(x, ym));
  55763. case CORNER.BOTTOM_LEFT:
  55764. default:
  55765. return new BezierCurve(new Vector(xm, ym), new Vector(xm - ox, ym), new Vector(x, y + oy), new Vector(x, y));
  55766. }
  55767. };
  55768. var calculateBorderBoxPath = function (curves) {
  55769. return [curves.topLeftBorderBox, curves.topRightBorderBox, curves.bottomRightBorderBox, curves.bottomLeftBorderBox];
  55770. };
  55771. var calculateContentBoxPath = function (curves) {
  55772. return [
  55773. curves.topLeftContentBox,
  55774. curves.topRightContentBox,
  55775. curves.bottomRightContentBox,
  55776. curves.bottomLeftContentBox
  55777. ];
  55778. };
  55779. var calculatePaddingBoxPath = function (curves) {
  55780. return [
  55781. curves.topLeftPaddingBox,
  55782. curves.topRightPaddingBox,
  55783. curves.bottomRightPaddingBox,
  55784. curves.bottomLeftPaddingBox
  55785. ];
  55786. };
  55787. var TransformEffect = /** @class */ (function () {
  55788. function TransformEffect(offsetX, offsetY, matrix) {
  55789. this.type = 0 /* TRANSFORM */;
  55790. this.offsetX = offsetX;
  55791. this.offsetY = offsetY;
  55792. this.matrix = matrix;
  55793. this.target = 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */;
  55794. }
  55795. return TransformEffect;
  55796. }());
  55797. var ClipEffect = /** @class */ (function () {
  55798. function ClipEffect(path, target) {
  55799. this.type = 1 /* CLIP */;
  55800. this.target = target;
  55801. this.path = path;
  55802. }
  55803. return ClipEffect;
  55804. }());
  55805. var isTransformEffect = function (effect) {
  55806. return effect.type === 0 /* TRANSFORM */;
  55807. };
  55808. var isClipEffect = function (effect) { return effect.type === 1 /* CLIP */; };
  55809. var StackingContext = /** @class */ (function () {
  55810. function StackingContext(container) {
  55811. this.element = container;
  55812. this.inlineLevel = [];
  55813. this.nonInlineLevel = [];
  55814. this.negativeZIndex = [];
  55815. this.zeroOrAutoZIndexOrTransformedOrOpacity = [];
  55816. this.positiveZIndex = [];
  55817. this.nonPositionedFloats = [];
  55818. this.nonPositionedInlineLevel = [];
  55819. }
  55820. return StackingContext;
  55821. }());
  55822. var ElementPaint = /** @class */ (function () {
  55823. function ElementPaint(element, parentStack) {
  55824. this.container = element;
  55825. this.effects = parentStack.slice(0);
  55826. this.curves = new BoundCurves(element);
  55827. if (element.styles.transform !== null) {
  55828. var offsetX = element.bounds.left + element.styles.transformOrigin[0].number;
  55829. var offsetY = element.bounds.top + element.styles.transformOrigin[1].number;
  55830. var matrix = element.styles.transform;
  55831. this.effects.push(new TransformEffect(offsetX, offsetY, matrix));
  55832. }
  55833. if (element.styles.overflowX !== OVERFLOW.VISIBLE) {
  55834. var borderBox = calculateBorderBoxPath(this.curves);
  55835. var paddingBox = calculatePaddingBoxPath(this.curves);
  55836. if (equalPath(borderBox, paddingBox)) {
  55837. this.effects.push(new ClipEffect(borderBox, 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */));
  55838. }
  55839. else {
  55840. this.effects.push(new ClipEffect(borderBox, 2 /* BACKGROUND_BORDERS */));
  55841. this.effects.push(new ClipEffect(paddingBox, 4 /* CONTENT */));
  55842. }
  55843. }
  55844. }
  55845. ElementPaint.prototype.getParentEffects = function () {
  55846. var effects = this.effects.slice(0);
  55847. if (this.container.styles.overflowX !== OVERFLOW.VISIBLE) {
  55848. var borderBox = calculateBorderBoxPath(this.curves);
  55849. var paddingBox = calculatePaddingBoxPath(this.curves);
  55850. if (!equalPath(borderBox, paddingBox)) {
  55851. effects.push(new ClipEffect(paddingBox, 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */));
  55852. }
  55853. }
  55854. return effects;
  55855. };
  55856. return ElementPaint;
  55857. }());
  55858. var parseStackTree = function (parent, stackingContext, realStackingContext, listItems) {
  55859. parent.container.elements.forEach(function (child) {
  55860. var treatAsRealStackingContext = contains(child.flags, 4 /* CREATES_REAL_STACKING_CONTEXT */);
  55861. var createsStackingContext = contains(child.flags, 2 /* CREATES_STACKING_CONTEXT */);
  55862. var paintContainer = new ElementPaint(child, parent.getParentEffects());
  55863. if (contains(child.styles.display, 2048 /* LIST_ITEM */)) {
  55864. listItems.push(paintContainer);
  55865. }
  55866. var listOwnerItems = contains(child.flags, 8 /* IS_LIST_OWNER */) ? [] : listItems;
  55867. if (treatAsRealStackingContext || createsStackingContext) {
  55868. var parentStack = treatAsRealStackingContext || child.styles.isPositioned() ? realStackingContext : stackingContext;
  55869. var stack = new StackingContext(paintContainer);
  55870. if (child.styles.isPositioned() || child.styles.opacity < 1 || child.styles.isTransformed()) {
  55871. var order_1 = child.styles.zIndex.order;
  55872. if (order_1 < 0) {
  55873. var index_1 = 0;
  55874. parentStack.negativeZIndex.some(function (current, i) {
  55875. if (order_1 > current.element.container.styles.zIndex.order) {
  55876. index_1 = i;
  55877. return false;
  55878. }
  55879. else if (index_1 > 0) {
  55880. return true;
  55881. }
  55882. return false;
  55883. });
  55884. parentStack.negativeZIndex.splice(index_1, 0, stack);
  55885. }
  55886. else if (order_1 > 0) {
  55887. var index_2 = 0;
  55888. parentStack.positiveZIndex.some(function (current, i) {
  55889. if (order_1 >= current.element.container.styles.zIndex.order) {
  55890. index_2 = i + 1;
  55891. return false;
  55892. }
  55893. else if (index_2 > 0) {
  55894. return true;
  55895. }
  55896. return false;
  55897. });
  55898. parentStack.positiveZIndex.splice(index_2, 0, stack);
  55899. }
  55900. else {
  55901. parentStack.zeroOrAutoZIndexOrTransformedOrOpacity.push(stack);
  55902. }
  55903. }
  55904. else {
  55905. if (child.styles.isFloating()) {
  55906. parentStack.nonPositionedFloats.push(stack);
  55907. }
  55908. else {
  55909. parentStack.nonPositionedInlineLevel.push(stack);
  55910. }
  55911. }
  55912. parseStackTree(paintContainer, stack, treatAsRealStackingContext ? stack : realStackingContext, listOwnerItems);
  55913. }
  55914. else {
  55915. if (child.styles.isInlineLevel()) {
  55916. stackingContext.inlineLevel.push(paintContainer);
  55917. }
  55918. else {
  55919. stackingContext.nonInlineLevel.push(paintContainer);
  55920. }
  55921. parseStackTree(paintContainer, stackingContext, realStackingContext, listOwnerItems);
  55922. }
  55923. if (contains(child.flags, 8 /* IS_LIST_OWNER */)) {
  55924. processListItems(child, listOwnerItems);
  55925. }
  55926. });
  55927. };
  55928. var processListItems = function (owner, elements) {
  55929. var numbering = owner instanceof OLElementContainer ? owner.start : 1;
  55930. var reversed = owner instanceof OLElementContainer ? owner.reversed : false;
  55931. for (var i = 0; i < elements.length; i++) {
  55932. var item = elements[i];
  55933. if (item.container instanceof LIElementContainer &&
  55934. typeof item.container.value === 'number' &&
  55935. item.container.value !== 0) {
  55936. numbering = item.container.value;
  55937. }
  55938. item.listValue = createCounterText(numbering, item.container.styles.listStyleType, true);
  55939. numbering += reversed ? -1 : 1;
  55940. }
  55941. };
  55942. var parseStackingContexts = function (container) {
  55943. var paintContainer = new ElementPaint(container, []);
  55944. var root = new StackingContext(paintContainer);
  55945. var listItems = [];
  55946. parseStackTree(paintContainer, root, root, listItems);
  55947. processListItems(paintContainer.container, listItems);
  55948. return root;
  55949. };
  55950. var parsePathForBorder = function (curves, borderSide) {
  55951. switch (borderSide) {
  55952. case 0:
  55953. return createPathFromCurves(curves.topLeftBorderBox, curves.topLeftPaddingBox, curves.topRightBorderBox, curves.topRightPaddingBox);
  55954. case 1:
  55955. return createPathFromCurves(curves.topRightBorderBox, curves.topRightPaddingBox, curves.bottomRightBorderBox, curves.bottomRightPaddingBox);
  55956. case 2:
  55957. return createPathFromCurves(curves.bottomRightBorderBox, curves.bottomRightPaddingBox, curves.bottomLeftBorderBox, curves.bottomLeftPaddingBox);
  55958. case 3:
  55959. default:
  55960. return createPathFromCurves(curves.bottomLeftBorderBox, curves.bottomLeftPaddingBox, curves.topLeftBorderBox, curves.topLeftPaddingBox);
  55961. }
  55962. };
  55963. var createPathFromCurves = function (outer1, inner1, outer2, inner2) {
  55964. var path = [];
  55965. if (isBezierCurve(outer1)) {
  55966. path.push(outer1.subdivide(0.5, false));
  55967. }
  55968. else {
  55969. path.push(outer1);
  55970. }
  55971. if (isBezierCurve(outer2)) {
  55972. path.push(outer2.subdivide(0.5, true));
  55973. }
  55974. else {
  55975. path.push(outer2);
  55976. }
  55977. if (isBezierCurve(inner2)) {
  55978. path.push(inner2.subdivide(0.5, true).reverse());
  55979. }
  55980. else {
  55981. path.push(inner2);
  55982. }
  55983. if (isBezierCurve(inner1)) {
  55984. path.push(inner1.subdivide(0.5, false).reverse());
  55985. }
  55986. else {
  55987. path.push(inner1);
  55988. }
  55989. return path;
  55990. };
  55991. var paddingBox = function (element) {
  55992. var bounds = element.bounds;
  55993. var styles = element.styles;
  55994. return bounds.add(styles.borderLeftWidth, styles.borderTopWidth, -(styles.borderRightWidth + styles.borderLeftWidth), -(styles.borderTopWidth + styles.borderBottomWidth));
  55995. };
  55996. var contentBox = function (element) {
  55997. var styles = element.styles;
  55998. var bounds = element.bounds;
  55999. var paddingLeft = getAbsoluteValue(styles.paddingLeft, bounds.width);
  56000. var paddingRight = getAbsoluteValue(styles.paddingRight, bounds.width);
  56001. var paddingTop = getAbsoluteValue(styles.paddingTop, bounds.width);
  56002. var paddingBottom = getAbsoluteValue(styles.paddingBottom, bounds.width);
  56003. return bounds.add(paddingLeft + styles.borderLeftWidth, paddingTop + styles.borderTopWidth, -(styles.borderRightWidth + styles.borderLeftWidth + paddingLeft + paddingRight), -(styles.borderTopWidth + styles.borderBottomWidth + paddingTop + paddingBottom));
  56004. };
  56005. var calculateBackgroundPositioningArea = function (backgroundOrigin, element) {
  56006. if (backgroundOrigin === 0 /* BORDER_BOX */) {
  56007. return element.bounds;
  56008. }
  56009. if (backgroundOrigin === 2 /* CONTENT_BOX */) {
  56010. return contentBox(element);
  56011. }
  56012. return paddingBox(element);
  56013. };
  56014. var calculateBackgroundPaintingArea = function (backgroundClip, element) {
  56015. if (backgroundClip === BACKGROUND_CLIP.BORDER_BOX) {
  56016. return element.bounds;
  56017. }
  56018. if (backgroundClip === BACKGROUND_CLIP.CONTENT_BOX) {
  56019. return contentBox(element);
  56020. }
  56021. return paddingBox(element);
  56022. };
  56023. var calculateBackgroundRendering = function (container, index, intrinsicSize) {
  56024. var backgroundPositioningArea = calculateBackgroundPositioningArea(getBackgroundValueForIndex(container.styles.backgroundOrigin, index), container);
  56025. var backgroundPaintingArea = calculateBackgroundPaintingArea(getBackgroundValueForIndex(container.styles.backgroundClip, index), container);
  56026. var backgroundImageSize = calculateBackgroundSize(getBackgroundValueForIndex(container.styles.backgroundSize, index), intrinsicSize, backgroundPositioningArea);
  56027. var sizeWidth = backgroundImageSize[0], sizeHeight = backgroundImageSize[1];
  56028. var position = getAbsoluteValueForTuple(getBackgroundValueForIndex(container.styles.backgroundPosition, index), backgroundPositioningArea.width - sizeWidth, backgroundPositioningArea.height - sizeHeight);
  56029. var path = calculateBackgroundRepeatPath(getBackgroundValueForIndex(container.styles.backgroundRepeat, index), position, backgroundImageSize, backgroundPositioningArea, backgroundPaintingArea);
  56030. var offsetX = Math.round(backgroundPositioningArea.left + position[0]);
  56031. var offsetY = Math.round(backgroundPositioningArea.top + position[1]);
  56032. return [path, offsetX, offsetY, sizeWidth, sizeHeight];
  56033. };
  56034. var isAuto = function (token) { return isIdentToken(token) && token.value === BACKGROUND_SIZE.AUTO; };
  56035. var hasIntrinsicValue = function (value) { return typeof value === 'number'; };
  56036. var calculateBackgroundSize = function (size, _a, bounds) {
  56037. var intrinsicWidth = _a[0], intrinsicHeight = _a[1], intrinsicProportion = _a[2];
  56038. var first = size[0], second = size[1];
  56039. if (isLengthPercentage(first) && second && isLengthPercentage(second)) {
  56040. return [getAbsoluteValue(first, bounds.width), getAbsoluteValue(second, bounds.height)];
  56041. }
  56042. var hasIntrinsicProportion = hasIntrinsicValue(intrinsicProportion);
  56043. if (isIdentToken(first) && (first.value === BACKGROUND_SIZE.CONTAIN || first.value === BACKGROUND_SIZE.COVER)) {
  56044. if (hasIntrinsicValue(intrinsicProportion)) {
  56045. var targetRatio = bounds.width / bounds.height;
  56046. return targetRatio < intrinsicProportion !== (first.value === BACKGROUND_SIZE.COVER)
  56047. ? [bounds.width, bounds.width / intrinsicProportion]
  56048. : [bounds.height * intrinsicProportion, bounds.height];
  56049. }
  56050. return [bounds.width, bounds.height];
  56051. }
  56052. var hasIntrinsicWidth = hasIntrinsicValue(intrinsicWidth);
  56053. var hasIntrinsicHeight = hasIntrinsicValue(intrinsicHeight);
  56054. var hasIntrinsicDimensions = hasIntrinsicWidth || hasIntrinsicHeight;
  56055. // If the background-size is auto or auto auto:
  56056. if (isAuto(first) && (!second || isAuto(second))) {
  56057. // If the image has both horizontal and vertical intrinsic dimensions, it's rendered at that size.
  56058. if (hasIntrinsicWidth && hasIntrinsicHeight) {
  56059. return [intrinsicWidth, intrinsicHeight];
  56060. }
  56061. // If the image has no intrinsic dimensions and has no intrinsic proportions,
  56062. // it's rendered at the size of the background positioning area.
  56063. if (!hasIntrinsicProportion && !hasIntrinsicDimensions) {
  56064. return [bounds.width, bounds.height];
  56065. }
  56066. // TODO If the image has no intrinsic dimensions but has intrinsic proportions, it's rendered as if contain had been specified instead.
  56067. // If the image has only one intrinsic dimension and has intrinsic proportions, it's rendered at the size corresponding to that one dimension.
  56068. // The other dimension is computed using the specified dimension and the intrinsic proportions.
  56069. if (hasIntrinsicDimensions && hasIntrinsicProportion) {
  56070. var width_1 = hasIntrinsicWidth
  56071. ? intrinsicWidth
  56072. : intrinsicHeight * intrinsicProportion;
  56073. var height_1 = hasIntrinsicHeight
  56074. ? intrinsicHeight
  56075. : intrinsicWidth / intrinsicProportion;
  56076. return [width_1, height_1];
  56077. }
  56078. // If the image has only one intrinsic dimension but has no intrinsic proportions,
  56079. // it's rendered using the specified dimension and the other dimension of the background positioning area.
  56080. var width_2 = hasIntrinsicWidth ? intrinsicWidth : bounds.width;
  56081. var height_2 = hasIntrinsicHeight ? intrinsicHeight : bounds.height;
  56082. return [width_2, height_2];
  56083. }
  56084. // If the image has intrinsic proportions, it's stretched to the specified dimension.
  56085. // The unspecified dimension is computed using the specified dimension and the intrinsic proportions.
  56086. if (hasIntrinsicProportion) {
  56087. var width_3 = 0;
  56088. var height_3 = 0;
  56089. if (isLengthPercentage(first)) {
  56090. width_3 = getAbsoluteValue(first, bounds.width);
  56091. }
  56092. else if (isLengthPercentage(second)) {
  56093. height_3 = getAbsoluteValue(second, bounds.height);
  56094. }
  56095. if (isAuto(first)) {
  56096. width_3 = height_3 * intrinsicProportion;
  56097. }
  56098. else if (!second || isAuto(second)) {
  56099. height_3 = width_3 / intrinsicProportion;
  56100. }
  56101. return [width_3, height_3];
  56102. }
  56103. // If the image has no intrinsic proportions, it's stretched to the specified dimension.
  56104. // The unspecified dimension is computed using the image's corresponding intrinsic dimension,
  56105. // if there is one. If there is no such intrinsic dimension,
  56106. // it becomes the corresponding dimension of the background positioning area.
  56107. var width = null;
  56108. var height = null;
  56109. if (isLengthPercentage(first)) {
  56110. width = getAbsoluteValue(first, bounds.width);
  56111. }
  56112. else if (second && isLengthPercentage(second)) {
  56113. height = getAbsoluteValue(second, bounds.height);
  56114. }
  56115. if (width !== null && (!second || isAuto(second))) {
  56116. height =
  56117. hasIntrinsicWidth && hasIntrinsicHeight
  56118. ? (width / intrinsicWidth) * intrinsicHeight
  56119. : bounds.height;
  56120. }
  56121. if (height !== null && isAuto(first)) {
  56122. width =
  56123. hasIntrinsicWidth && hasIntrinsicHeight
  56124. ? (height / intrinsicHeight) * intrinsicWidth
  56125. : bounds.width;
  56126. }
  56127. if (width !== null && height !== null) {
  56128. return [width, height];
  56129. }
  56130. throw new Error("Unable to calculate background-size for element");
  56131. };
  56132. var getBackgroundValueForIndex = function (values, index) {
  56133. var value = values[index];
  56134. if (typeof value === 'undefined') {
  56135. return values[0];
  56136. }
  56137. return value;
  56138. };
  56139. var calculateBackgroundRepeatPath = function (repeat, _a, _b, backgroundPositioningArea, backgroundPaintingArea) {
  56140. var x = _a[0], y = _a[1];
  56141. var width = _b[0], height = _b[1];
  56142. switch (repeat) {
  56143. case BACKGROUND_REPEAT.REPEAT_X:
  56144. return [
  56145. new Vector(Math.round(backgroundPositioningArea.left), Math.round(backgroundPositioningArea.top + y)),
  56146. new Vector(Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(backgroundPositioningArea.top + y)),
  56147. new Vector(Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(height + backgroundPositioningArea.top + y)),
  56148. new Vector(Math.round(backgroundPositioningArea.left), Math.round(height + backgroundPositioningArea.top + y))
  56149. ];
  56150. case BACKGROUND_REPEAT.REPEAT_Y:
  56151. return [
  56152. new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top)),
  56153. new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top)),
  56154. new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top)),
  56155. new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top))
  56156. ];
  56157. case BACKGROUND_REPEAT.NO_REPEAT:
  56158. return [
  56159. new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top + y)),
  56160. new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top + y)),
  56161. new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top + y + height)),
  56162. new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top + y + height))
  56163. ];
  56164. default:
  56165. return [
  56166. new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.top)),
  56167. new Vector(Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.top)),
  56168. new Vector(Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top)),
  56169. new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top))
  56170. ];
  56171. }
  56172. };
  56173. var SMALL_IMAGE = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
  56174. var SAMPLE_TEXT = 'Hidden Text';
  56175. var FontMetrics = /** @class */ (function () {
  56176. function FontMetrics(document) {
  56177. this._data = {};
  56178. this._document = document;
  56179. }
  56180. FontMetrics.prototype.parseMetrics = function (fontFamily, fontSize) {
  56181. var container = this._document.createElement('div');
  56182. var img = this._document.createElement('img');
  56183. var span = this._document.createElement('span');
  56184. var body = this._document.body;
  56185. container.style.visibility = 'hidden';
  56186. container.style.fontFamily = fontFamily;
  56187. container.style.fontSize = fontSize;
  56188. container.style.margin = '0';
  56189. container.style.padding = '0';
  56190. body.appendChild(container);
  56191. img.src = SMALL_IMAGE;
  56192. img.width = 1;
  56193. img.height = 1;
  56194. img.style.margin = '0';
  56195. img.style.padding = '0';
  56196. img.style.verticalAlign = 'baseline';
  56197. span.style.fontFamily = fontFamily;
  56198. span.style.fontSize = fontSize;
  56199. span.style.margin = '0';
  56200. span.style.padding = '0';
  56201. span.appendChild(this._document.createTextNode(SAMPLE_TEXT));
  56202. container.appendChild(span);
  56203. container.appendChild(img);
  56204. var baseline = img.offsetTop - span.offsetTop + 2;
  56205. container.removeChild(span);
  56206. container.appendChild(this._document.createTextNode(SAMPLE_TEXT));
  56207. container.style.lineHeight = 'normal';
  56208. img.style.verticalAlign = 'super';
  56209. var middle = img.offsetTop - container.offsetTop + 2;
  56210. body.removeChild(container);
  56211. return { baseline: baseline, middle: middle };
  56212. };
  56213. FontMetrics.prototype.getMetrics = function (fontFamily, fontSize) {
  56214. var key = fontFamily + " " + fontSize;
  56215. if (typeof this._data[key] === 'undefined') {
  56216. this._data[key] = this.parseMetrics(fontFamily, fontSize);
  56217. }
  56218. return this._data[key];
  56219. };
  56220. return FontMetrics;
  56221. }());
  56222. var MASK_OFFSET = 10000;
  56223. var CanvasRenderer = /** @class */ (function () {
  56224. function CanvasRenderer(options) {
  56225. this._activeEffects = [];
  56226. this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
  56227. this.ctx = this.canvas.getContext('2d');
  56228. this.options = options;
  56229. if (!options.canvas) {
  56230. this.canvas.width = Math.floor(options.width * options.scale);
  56231. this.canvas.height = Math.floor(options.height * options.scale);
  56232. this.canvas.style.width = options.width + "px";
  56233. this.canvas.style.height = options.height + "px";
  56234. }
  56235. this.fontMetrics = new FontMetrics(document);
  56236. this.ctx.scale(this.options.scale, this.options.scale);
  56237. this.ctx.translate(-options.x + options.scrollX, -options.y + options.scrollY);
  56238. this.ctx.textBaseline = 'bottom';
  56239. this._activeEffects = [];
  56240. Logger.getInstance(options.id).debug("Canvas renderer initialized (" + options.width + "x" + options.height + " at " + options.x + "," + options.y + ") with scale " + options.scale);
  56241. }
  56242. CanvasRenderer.prototype.applyEffects = function (effects, target) {
  56243. var _this = this;
  56244. while (this._activeEffects.length) {
  56245. this.popEffect();
  56246. }
  56247. effects.filter(function (effect) { return contains(effect.target, target); }).forEach(function (effect) { return _this.applyEffect(effect); });
  56248. };
  56249. CanvasRenderer.prototype.applyEffect = function (effect) {
  56250. this.ctx.save();
  56251. if (isTransformEffect(effect)) {
  56252. this.ctx.translate(effect.offsetX, effect.offsetY);
  56253. this.ctx.transform(effect.matrix[0], effect.matrix[1], effect.matrix[2], effect.matrix[3], effect.matrix[4], effect.matrix[5]);
  56254. this.ctx.translate(-effect.offsetX, -effect.offsetY);
  56255. }
  56256. if (isClipEffect(effect)) {
  56257. this.path(effect.path);
  56258. this.ctx.clip();
  56259. }
  56260. this._activeEffects.push(effect);
  56261. };
  56262. CanvasRenderer.prototype.popEffect = function () {
  56263. this._activeEffects.pop();
  56264. this.ctx.restore();
  56265. };
  56266. CanvasRenderer.prototype.renderStack = function (stack) {
  56267. return __awaiter(this, void 0, void 0, function () {
  56268. var styles;
  56269. return __generator(this, function (_a) {
  56270. switch (_a.label) {
  56271. case 0:
  56272. styles = stack.element.container.styles;
  56273. if (!styles.isVisible()) return [3 /*break*/, 2];
  56274. this.ctx.globalAlpha = styles.opacity;
  56275. return [4 /*yield*/, this.renderStackContent(stack)];
  56276. case 1:
  56277. _a.sent();
  56278. _a.label = 2;
  56279. case 2: return [2 /*return*/];
  56280. }
  56281. });
  56282. });
  56283. };
  56284. CanvasRenderer.prototype.renderNode = function (paint) {
  56285. return __awaiter(this, void 0, void 0, function () {
  56286. return __generator(this, function (_a) {
  56287. switch (_a.label) {
  56288. case 0:
  56289. if (!paint.container.styles.isVisible()) return [3 /*break*/, 3];
  56290. return [4 /*yield*/, this.renderNodeBackgroundAndBorders(paint)];
  56291. case 1:
  56292. _a.sent();
  56293. return [4 /*yield*/, this.renderNodeContent(paint)];
  56294. case 2:
  56295. _a.sent();
  56296. _a.label = 3;
  56297. case 3: return [2 /*return*/];
  56298. }
  56299. });
  56300. });
  56301. };
  56302. CanvasRenderer.prototype.renderTextWithLetterSpacing = function (text, letterSpacing) {
  56303. var _this = this;
  56304. if (letterSpacing === 0) {
  56305. this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
  56306. }
  56307. else {
  56308. var letters = toCodePoints(text.text).map(function (i) { return fromCodePoint(i); });
  56309. letters.reduce(function (left, letter) {
  56310. _this.ctx.fillText(letter, left, text.bounds.top + text.bounds.height);
  56311. return left + _this.ctx.measureText(letter).width;
  56312. }, text.bounds.left);
  56313. }
  56314. };
  56315. CanvasRenderer.prototype.createFontStyle = function (styles) {
  56316. var fontVariant = styles.fontVariant
  56317. .filter(function (variant) { return variant === 'normal' || variant === 'small-caps'; })
  56318. .join('');
  56319. var fontFamily = styles.fontFamily.join(', ');
  56320. var fontSize = isDimensionToken(styles.fontSize)
  56321. ? "" + styles.fontSize.number + styles.fontSize.unit
  56322. : styles.fontSize.number + "px";
  56323. return [
  56324. [styles.fontStyle, fontVariant, styles.fontWeight, fontSize, fontFamily].join(' '),
  56325. fontFamily,
  56326. fontSize
  56327. ];
  56328. };
  56329. CanvasRenderer.prototype.renderTextNode = function (text, styles) {
  56330. return __awaiter(this, void 0, void 0, function () {
  56331. var _a, font, fontFamily, fontSize;
  56332. var _this = this;
  56333. return __generator(this, function (_b) {
  56334. _a = this.createFontStyle(styles), font = _a[0], fontFamily = _a[1], fontSize = _a[2];
  56335. this.ctx.font = font;
  56336. text.textBounds.forEach(function (text) {
  56337. _this.ctx.fillStyle = asString(styles.color);
  56338. _this.renderTextWithLetterSpacing(text, styles.letterSpacing);
  56339. var textShadows = styles.textShadow;
  56340. if (textShadows.length && text.text.trim().length) {
  56341. textShadows
  56342. .slice(0)
  56343. .reverse()
  56344. .forEach(function (textShadow) {
  56345. _this.ctx.shadowColor = asString(textShadow.color);
  56346. _this.ctx.shadowOffsetX = textShadow.offsetX.number * _this.options.scale;
  56347. _this.ctx.shadowOffsetY = textShadow.offsetY.number * _this.options.scale;
  56348. _this.ctx.shadowBlur = textShadow.blur.number;
  56349. _this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
  56350. });
  56351. _this.ctx.shadowColor = '';
  56352. _this.ctx.shadowOffsetX = 0;
  56353. _this.ctx.shadowOffsetY = 0;
  56354. _this.ctx.shadowBlur = 0;
  56355. }
  56356. if (styles.textDecorationLine.length) {
  56357. _this.ctx.fillStyle = asString(styles.textDecorationColor || styles.color);
  56358. styles.textDecorationLine.forEach(function (textDecorationLine) {
  56359. switch (textDecorationLine) {
  56360. case 1 /* UNDERLINE */:
  56361. // Draws a line at the baseline of the font
  56362. // TODO As some browsers display the line as more than 1px if the font-size is big,
  56363. // need to take that into account both in position and size
  56364. var baseline = _this.fontMetrics.getMetrics(fontFamily, fontSize).baseline;
  56365. _this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top + baseline), text.bounds.width, 1);
  56366. break;
  56367. case 2 /* OVERLINE */:
  56368. _this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top), text.bounds.width, 1);
  56369. break;
  56370. case 3 /* LINE_THROUGH */:
  56371. // TODO try and find exact position for line-through
  56372. var middle = _this.fontMetrics.getMetrics(fontFamily, fontSize).middle;
  56373. _this.ctx.fillRect(text.bounds.left, Math.ceil(text.bounds.top + middle), text.bounds.width, 1);
  56374. break;
  56375. }
  56376. });
  56377. }
  56378. });
  56379. return [2 /*return*/];
  56380. });
  56381. });
  56382. };
  56383. CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) {
  56384. if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
  56385. var box = contentBox(container);
  56386. var path = calculatePaddingBoxPath(curves);
  56387. this.path(path);
  56388. this.ctx.save();
  56389. this.ctx.clip();
  56390. this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, box.left, box.top, box.width, box.height);
  56391. this.ctx.restore();
  56392. }
  56393. };
  56394. CanvasRenderer.prototype.renderNodeContent = function (paint) {
  56395. return __awaiter(this, void 0, void 0, function () {
  56396. var container, curves, styles, _i, _a, child, image, e_1, image, e_2, iframeRenderer, canvas, size, bounds, x, textBounds, img, image, url, e_3, bounds;
  56397. return __generator(this, function (_b) {
  56398. switch (_b.label) {
  56399. case 0:
  56400. this.applyEffects(paint.effects, 4 /* CONTENT */);
  56401. container = paint.container;
  56402. curves = paint.curves;
  56403. styles = container.styles;
  56404. _i = 0, _a = container.textNodes;
  56405. _b.label = 1;
  56406. case 1:
  56407. if (!(_i < _a.length)) return [3 /*break*/, 4];
  56408. child = _a[_i];
  56409. return [4 /*yield*/, this.renderTextNode(child, styles)];
  56410. case 2:
  56411. _b.sent();
  56412. _b.label = 3;
  56413. case 3:
  56414. _i++;
  56415. return [3 /*break*/, 1];
  56416. case 4:
  56417. if (!(container instanceof ImageElementContainer)) return [3 /*break*/, 8];
  56418. _b.label = 5;
  56419. case 5:
  56420. _b.trys.push([5, 7, , 8]);
  56421. return [4 /*yield*/, this.options.cache.match(container.src)];
  56422. case 6:
  56423. image = _b.sent();
  56424. this.renderReplacedElement(container, curves, image);
  56425. return [3 /*break*/, 8];
  56426. case 7:
  56427. e_1 = _b.sent();
  56428. Logger.getInstance(this.options.id).error("Error loading image " + container.src);
  56429. return [3 /*break*/, 8];
  56430. case 8:
  56431. if (container instanceof CanvasElementContainer) {
  56432. this.renderReplacedElement(container, curves, container.canvas);
  56433. }
  56434. if (!(container instanceof SVGElementContainer)) return [3 /*break*/, 12];
  56435. _b.label = 9;
  56436. case 9:
  56437. _b.trys.push([9, 11, , 12]);
  56438. return [4 /*yield*/, this.options.cache.match(container.svg)];
  56439. case 10:
  56440. image = _b.sent();
  56441. this.renderReplacedElement(container, curves, image);
  56442. return [3 /*break*/, 12];
  56443. case 11:
  56444. e_2 = _b.sent();
  56445. Logger.getInstance(this.options.id).error("Error loading svg " + container.svg.substring(0, 255));
  56446. return [3 /*break*/, 12];
  56447. case 12:
  56448. if (!(container instanceof IFrameElementContainer && container.tree)) return [3 /*break*/, 14];
  56449. iframeRenderer = new CanvasRenderer({
  56450. id: this.options.id,
  56451. scale: this.options.scale,
  56452. backgroundColor: container.backgroundColor,
  56453. x: 0,
  56454. y: 0,
  56455. scrollX: 0,
  56456. scrollY: 0,
  56457. width: container.width,
  56458. height: container.height,
  56459. cache: this.options.cache,
  56460. windowWidth: container.width,
  56461. windowHeight: container.height
  56462. });
  56463. return [4 /*yield*/, iframeRenderer.render(container.tree)];
  56464. case 13:
  56465. canvas = _b.sent();
  56466. if (container.width && container.height) {
  56467. this.ctx.drawImage(canvas, 0, 0, container.width, container.height, container.bounds.left, container.bounds.top, container.bounds.width, container.bounds.height);
  56468. }
  56469. _b.label = 14;
  56470. case 14:
  56471. if (container instanceof InputElementContainer) {
  56472. size = Math.min(container.bounds.width, container.bounds.height);
  56473. if (container.type === CHECKBOX) {
  56474. if (container.checked) {
  56475. this.ctx.save();
  56476. this.path([
  56477. new Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79),
  56478. new Vector(container.bounds.left + size * 0.16, container.bounds.top + size * 0.5549),
  56479. new Vector(container.bounds.left + size * 0.27347, container.bounds.top + size * 0.44071),
  56480. new Vector(container.bounds.left + size * 0.39694, container.bounds.top + size * 0.5649),
  56481. new Vector(container.bounds.left + size * 0.72983, container.bounds.top + size * 0.23),
  56482. new Vector(container.bounds.left + size * 0.84, container.bounds.top + size * 0.34085),
  56483. new Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79)
  56484. ]);
  56485. this.ctx.fillStyle = asString(INPUT_COLOR);
  56486. this.ctx.fill();
  56487. this.ctx.restore();
  56488. }
  56489. }
  56490. else if (container.type === RADIO) {
  56491. if (container.checked) {
  56492. this.ctx.save();
  56493. this.ctx.beginPath();
  56494. this.ctx.arc(container.bounds.left + size / 2, container.bounds.top + size / 2, size / 4, 0, Math.PI * 2, true);
  56495. this.ctx.fillStyle = asString(INPUT_COLOR);
  56496. this.ctx.fill();
  56497. this.ctx.restore();
  56498. }
  56499. }
  56500. }
  56501. if (isTextInputElement(container) && container.value.length) {
  56502. this.ctx.font = this.createFontStyle(styles)[0];
  56503. this.ctx.fillStyle = asString(styles.color);
  56504. this.ctx.textBaseline = 'middle';
  56505. this.ctx.textAlign = canvasTextAlign(container.styles.textAlign);
  56506. bounds = contentBox(container);
  56507. x = 0;
  56508. switch (container.styles.textAlign) {
  56509. case TEXT_ALIGN.CENTER:
  56510. x += bounds.width / 2;
  56511. break;
  56512. case TEXT_ALIGN.RIGHT:
  56513. x += bounds.width;
  56514. break;
  56515. }
  56516. textBounds = bounds.add(x, 0, 0, -bounds.height / 2 + 1);
  56517. this.ctx.save();
  56518. this.path([
  56519. new Vector(bounds.left, bounds.top),
  56520. new Vector(bounds.left + bounds.width, bounds.top),
  56521. new Vector(bounds.left + bounds.width, bounds.top + bounds.height),
  56522. new Vector(bounds.left, bounds.top + bounds.height)
  56523. ]);
  56524. this.ctx.clip();
  56525. this.renderTextWithLetterSpacing(new TextBounds(container.value, textBounds), styles.letterSpacing);
  56526. this.ctx.restore();
  56527. this.ctx.textBaseline = 'bottom';
  56528. this.ctx.textAlign = 'left';
  56529. }
  56530. if (!contains(container.styles.display, 2048 /* LIST_ITEM */)) return [3 /*break*/, 20];
  56531. if (!(container.styles.listStyleImage !== null)) return [3 /*break*/, 19];
  56532. img = container.styles.listStyleImage;
  56533. if (!(img.type === CSSImageType.URL)) return [3 /*break*/, 18];
  56534. image = void 0;
  56535. url = img.url;
  56536. _b.label = 15;
  56537. case 15:
  56538. _b.trys.push([15, 17, , 18]);
  56539. return [4 /*yield*/, this.options.cache.match(url)];
  56540. case 16:
  56541. image = _b.sent();
  56542. this.ctx.drawImage(image, container.bounds.left - (image.width + 10), container.bounds.top);
  56543. return [3 /*break*/, 18];
  56544. case 17:
  56545. e_3 = _b.sent();
  56546. Logger.getInstance(this.options.id).error("Error loading list-style-image " + url);
  56547. return [3 /*break*/, 18];
  56548. case 18: return [3 /*break*/, 20];
  56549. case 19:
  56550. if (paint.listValue && container.styles.listStyleType !== LIST_STYLE_TYPE.NONE) {
  56551. this.ctx.font = this.createFontStyle(styles)[0];
  56552. this.ctx.fillStyle = asString(styles.color);
  56553. this.ctx.textBaseline = 'middle';
  56554. this.ctx.textAlign = 'right';
  56555. bounds = new Bounds(container.bounds.left, container.bounds.top + getAbsoluteValue(container.styles.paddingTop, container.bounds.width), container.bounds.width, computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 1);
  56556. this.renderTextWithLetterSpacing(new TextBounds(paint.listValue, bounds), styles.letterSpacing);
  56557. this.ctx.textBaseline = 'bottom';
  56558. this.ctx.textAlign = 'left';
  56559. }
  56560. _b.label = 20;
  56561. case 20: return [2 /*return*/];
  56562. }
  56563. });
  56564. });
  56565. };
  56566. CanvasRenderer.prototype.renderStackContent = function (stack) {
  56567. return __awaiter(this, void 0, void 0, function () {
  56568. var _i, _a, child, _b, _c, child, _d, _e, child, _f, _g, child, _h, _j, child, _k, _l, child, _m, _o, child;
  56569. return __generator(this, function (_p) {
  56570. switch (_p.label) {
  56571. case 0:
  56572. // https://www.w3.org/TR/css-position-3/#painting-order
  56573. // 1. the background and borders of the element forming the stacking context.
  56574. return [4 /*yield*/, this.renderNodeBackgroundAndBorders(stack.element)];
  56575. case 1:
  56576. // https://www.w3.org/TR/css-position-3/#painting-order
  56577. // 1. the background and borders of the element forming the stacking context.
  56578. _p.sent();
  56579. _i = 0, _a = stack.negativeZIndex;
  56580. _p.label = 2;
  56581. case 2:
  56582. if (!(_i < _a.length)) return [3 /*break*/, 5];
  56583. child = _a[_i];
  56584. return [4 /*yield*/, this.renderStack(child)];
  56585. case 3:
  56586. _p.sent();
  56587. _p.label = 4;
  56588. case 4:
  56589. _i++;
  56590. return [3 /*break*/, 2];
  56591. case 5:
  56592. // 3. For all its in-flow, non-positioned, block-level descendants in tree order:
  56593. return [4 /*yield*/, this.renderNodeContent(stack.element)];
  56594. case 6:
  56595. // 3. For all its in-flow, non-positioned, block-level descendants in tree order:
  56596. _p.sent();
  56597. _b = 0, _c = stack.nonInlineLevel;
  56598. _p.label = 7;
  56599. case 7:
  56600. if (!(_b < _c.length)) return [3 /*break*/, 10];
  56601. child = _c[_b];
  56602. return [4 /*yield*/, this.renderNode(child)];
  56603. case 8:
  56604. _p.sent();
  56605. _p.label = 9;
  56606. case 9:
  56607. _b++;
  56608. return [3 /*break*/, 7];
  56609. case 10:
  56610. _d = 0, _e = stack.nonPositionedFloats;
  56611. _p.label = 11;
  56612. case 11:
  56613. if (!(_d < _e.length)) return [3 /*break*/, 14];
  56614. child = _e[_d];
  56615. return [4 /*yield*/, this.renderStack(child)];
  56616. case 12:
  56617. _p.sent();
  56618. _p.label = 13;
  56619. case 13:
  56620. _d++;
  56621. return [3 /*break*/, 11];
  56622. case 14:
  56623. _f = 0, _g = stack.nonPositionedInlineLevel;
  56624. _p.label = 15;
  56625. case 15:
  56626. if (!(_f < _g.length)) return [3 /*break*/, 18];
  56627. child = _g[_f];
  56628. return [4 /*yield*/, this.renderStack(child)];
  56629. case 16:
  56630. _p.sent();
  56631. _p.label = 17;
  56632. case 17:
  56633. _f++;
  56634. return [3 /*break*/, 15];
  56635. case 18:
  56636. _h = 0, _j = stack.inlineLevel;
  56637. _p.label = 19;
  56638. case 19:
  56639. if (!(_h < _j.length)) return [3 /*break*/, 22];
  56640. child = _j[_h];
  56641. return [4 /*yield*/, this.renderNode(child)];
  56642. case 20:
  56643. _p.sent();
  56644. _p.label = 21;
  56645. case 21:
  56646. _h++;
  56647. return [3 /*break*/, 19];
  56648. case 22:
  56649. _k = 0, _l = stack.zeroOrAutoZIndexOrTransformedOrOpacity;
  56650. _p.label = 23;
  56651. case 23:
  56652. if (!(_k < _l.length)) return [3 /*break*/, 26];
  56653. child = _l[_k];
  56654. return [4 /*yield*/, this.renderStack(child)];
  56655. case 24:
  56656. _p.sent();
  56657. _p.label = 25;
  56658. case 25:
  56659. _k++;
  56660. return [3 /*break*/, 23];
  56661. case 26:
  56662. _m = 0, _o = stack.positiveZIndex;
  56663. _p.label = 27;
  56664. case 27:
  56665. if (!(_m < _o.length)) return [3 /*break*/, 30];
  56666. child = _o[_m];
  56667. return [4 /*yield*/, this.renderStack(child)];
  56668. case 28:
  56669. _p.sent();
  56670. _p.label = 29;
  56671. case 29:
  56672. _m++;
  56673. return [3 /*break*/, 27];
  56674. case 30: return [2 /*return*/];
  56675. }
  56676. });
  56677. });
  56678. };
  56679. CanvasRenderer.prototype.mask = function (paths) {
  56680. this.ctx.beginPath();
  56681. this.ctx.moveTo(0, 0);
  56682. this.ctx.lineTo(this.canvas.width, 0);
  56683. this.ctx.lineTo(this.canvas.width, this.canvas.height);
  56684. this.ctx.lineTo(0, this.canvas.height);
  56685. this.ctx.lineTo(0, 0);
  56686. this.formatPath(paths.slice(0).reverse());
  56687. this.ctx.closePath();
  56688. };
  56689. CanvasRenderer.prototype.path = function (paths) {
  56690. this.ctx.beginPath();
  56691. this.formatPath(paths);
  56692. this.ctx.closePath();
  56693. };
  56694. CanvasRenderer.prototype.formatPath = function (paths) {
  56695. var _this = this;
  56696. paths.forEach(function (point, index) {
  56697. var start = isBezierCurve(point) ? point.start : point;
  56698. if (index === 0) {
  56699. _this.ctx.moveTo(start.x, start.y);
  56700. }
  56701. else {
  56702. _this.ctx.lineTo(start.x, start.y);
  56703. }
  56704. if (isBezierCurve(point)) {
  56705. _this.ctx.bezierCurveTo(point.startControl.x, point.startControl.y, point.endControl.x, point.endControl.y, point.end.x, point.end.y);
  56706. }
  56707. });
  56708. };
  56709. CanvasRenderer.prototype.renderRepeat = function (path, pattern, offsetX, offsetY) {
  56710. this.path(path);
  56711. this.ctx.fillStyle = pattern;
  56712. this.ctx.translate(offsetX, offsetY);
  56713. this.ctx.fill();
  56714. this.ctx.translate(-offsetX, -offsetY);
  56715. };
  56716. CanvasRenderer.prototype.resizeImage = function (image, width, height) {
  56717. if (image.width === width && image.height === height) {
  56718. return image;
  56719. }
  56720. var canvas = this.canvas.ownerDocument.createElement('canvas');
  56721. canvas.width = width;
  56722. canvas.height = height;
  56723. var ctx = canvas.getContext('2d');
  56724. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, width, height);
  56725. return canvas;
  56726. };
  56727. CanvasRenderer.prototype.renderBackgroundImage = function (container) {
  56728. return __awaiter(this, void 0, void 0, function () {
  56729. var index, _loop_1, this_1, _i, _a, backgroundImage;
  56730. return __generator(this, function (_b) {
  56731. switch (_b.label) {
  56732. case 0:
  56733. index = container.styles.backgroundImage.length - 1;
  56734. _loop_1 = function (backgroundImage) {
  56735. var image, url, e_4, _a, path, x, y, width, height, pattern, _b, path, x, y, width, height, _c, lineLength, x0, x1, y0, y1, canvas, ctx, gradient_1, pattern, _d, path, left, top_1, width, height, position, x, y, _e, rx, ry, radialGradient_1, midX, midY, f, invF;
  56736. return __generator(this, function (_f) {
  56737. switch (_f.label) {
  56738. case 0:
  56739. if (!(backgroundImage.type === CSSImageType.URL)) return [3 /*break*/, 5];
  56740. image = void 0;
  56741. url = backgroundImage.url;
  56742. _f.label = 1;
  56743. case 1:
  56744. _f.trys.push([1, 3, , 4]);
  56745. return [4 /*yield*/, this_1.options.cache.match(url)];
  56746. case 2:
  56747. image = _f.sent();
  56748. return [3 /*break*/, 4];
  56749. case 3:
  56750. e_4 = _f.sent();
  56751. Logger.getInstance(this_1.options.id).error("Error loading background-image " + url);
  56752. return [3 /*break*/, 4];
  56753. case 4:
  56754. if (image) {
  56755. _a = calculateBackgroundRendering(container, index, [
  56756. image.width,
  56757. image.height,
  56758. image.width / image.height
  56759. ]), path = _a[0], x = _a[1], y = _a[2], width = _a[3], height = _a[4];
  56760. pattern = this_1.ctx.createPattern(this_1.resizeImage(image, width, height), 'repeat');
  56761. this_1.renderRepeat(path, pattern, x, y);
  56762. }
  56763. return [3 /*break*/, 6];
  56764. case 5:
  56765. if (isLinearGradient(backgroundImage)) {
  56766. _b = calculateBackgroundRendering(container, index, [null, null, null]), path = _b[0], x = _b[1], y = _b[2], width = _b[3], height = _b[4];
  56767. _c = calculateGradientDirection(backgroundImage.angle, width, height), lineLength = _c[0], x0 = _c[1], x1 = _c[2], y0 = _c[3], y1 = _c[4];
  56768. canvas = document.createElement('canvas');
  56769. canvas.width = width;
  56770. canvas.height = height;
  56771. ctx = canvas.getContext('2d');
  56772. gradient_1 = ctx.createLinearGradient(x0, y0, x1, y1);
  56773. processColorStops(backgroundImage.stops, lineLength).forEach(function (colorStop) {
  56774. return gradient_1.addColorStop(colorStop.stop, asString(colorStop.color));
  56775. });
  56776. ctx.fillStyle = gradient_1;
  56777. ctx.fillRect(0, 0, width, height);
  56778. if (width > 0 && height > 0) {
  56779. pattern = this_1.ctx.createPattern(canvas, 'repeat');
  56780. this_1.renderRepeat(path, pattern, x, y);
  56781. }
  56782. }
  56783. else if (isRadialGradient(backgroundImage)) {
  56784. _d = calculateBackgroundRendering(container, index, [
  56785. null,
  56786. null,
  56787. null
  56788. ]), path = _d[0], left = _d[1], top_1 = _d[2], width = _d[3], height = _d[4];
  56789. position = backgroundImage.position.length === 0 ? [FIFTY_PERCENT] : backgroundImage.position;
  56790. x = getAbsoluteValue(position[0], width);
  56791. y = getAbsoluteValue(position[position.length - 1], height);
  56792. _e = calculateRadius(backgroundImage, x, y, width, height), rx = _e[0], ry = _e[1];
  56793. if (rx > 0 && rx > 0) {
  56794. radialGradient_1 = this_1.ctx.createRadialGradient(left + x, top_1 + y, 0, left + x, top_1 + y, rx);
  56795. processColorStops(backgroundImage.stops, rx * 2).forEach(function (colorStop) {
  56796. return radialGradient_1.addColorStop(colorStop.stop, asString(colorStop.color));
  56797. });
  56798. this_1.path(path);
  56799. this_1.ctx.fillStyle = radialGradient_1;
  56800. if (rx !== ry) {
  56801. midX = container.bounds.left + 0.5 * container.bounds.width;
  56802. midY = container.bounds.top + 0.5 * container.bounds.height;
  56803. f = ry / rx;
  56804. invF = 1 / f;
  56805. this_1.ctx.save();
  56806. this_1.ctx.translate(midX, midY);
  56807. this_1.ctx.transform(1, 0, 0, f, 0, 0);
  56808. this_1.ctx.translate(-midX, -midY);
  56809. this_1.ctx.fillRect(left, invF * (top_1 - midY) + midY, width, height * invF);
  56810. this_1.ctx.restore();
  56811. }
  56812. else {
  56813. this_1.ctx.fill();
  56814. }
  56815. }
  56816. }
  56817. _f.label = 6;
  56818. case 6:
  56819. index--;
  56820. return [2 /*return*/];
  56821. }
  56822. });
  56823. };
  56824. this_1 = this;
  56825. _i = 0, _a = container.styles.backgroundImage.slice(0).reverse();
  56826. _b.label = 1;
  56827. case 1:
  56828. if (!(_i < _a.length)) return [3 /*break*/, 4];
  56829. backgroundImage = _a[_i];
  56830. return [5 /*yield**/, _loop_1(backgroundImage)];
  56831. case 2:
  56832. _b.sent();
  56833. _b.label = 3;
  56834. case 3:
  56835. _i++;
  56836. return [3 /*break*/, 1];
  56837. case 4: return [2 /*return*/];
  56838. }
  56839. });
  56840. });
  56841. };
  56842. CanvasRenderer.prototype.renderBorder = function (color, side, curvePoints) {
  56843. return __awaiter(this, void 0, void 0, function () {
  56844. return __generator(this, function (_a) {
  56845. this.path(parsePathForBorder(curvePoints, side));
  56846. this.ctx.fillStyle = asString(color);
  56847. this.ctx.fill();
  56848. return [2 /*return*/];
  56849. });
  56850. });
  56851. };
  56852. CanvasRenderer.prototype.renderNodeBackgroundAndBorders = function (paint) {
  56853. return __awaiter(this, void 0, void 0, function () {
  56854. var styles, hasBackground, borders, backgroundPaintingArea, side, _i, borders_1, border;
  56855. var _this = this;
  56856. return __generator(this, function (_a) {
  56857. switch (_a.label) {
  56858. case 0:
  56859. this.applyEffects(paint.effects, 2 /* BACKGROUND_BORDERS */);
  56860. styles = paint.container.styles;
  56861. hasBackground = !isTransparent(styles.backgroundColor) || styles.backgroundImage.length;
  56862. borders = [
  56863. { style: styles.borderTopStyle, color: styles.borderTopColor },
  56864. { style: styles.borderRightStyle, color: styles.borderRightColor },
  56865. { style: styles.borderBottomStyle, color: styles.borderBottomColor },
  56866. { style: styles.borderLeftStyle, color: styles.borderLeftColor }
  56867. ];
  56868. backgroundPaintingArea = calculateBackgroundCurvedPaintingArea(getBackgroundValueForIndex(styles.backgroundClip, 0), paint.curves);
  56869. if (!(hasBackground || styles.boxShadow.length)) return [3 /*break*/, 2];
  56870. this.ctx.save();
  56871. this.path(backgroundPaintingArea);
  56872. this.ctx.clip();
  56873. if (!isTransparent(styles.backgroundColor)) {
  56874. this.ctx.fillStyle = asString(styles.backgroundColor);
  56875. this.ctx.fill();
  56876. }
  56877. return [4 /*yield*/, this.renderBackgroundImage(paint.container)];
  56878. case 1:
  56879. _a.sent();
  56880. this.ctx.restore();
  56881. styles.boxShadow
  56882. .slice(0)
  56883. .reverse()
  56884. .forEach(function (shadow) {
  56885. _this.ctx.save();
  56886. var borderBoxArea = calculateBorderBoxPath(paint.curves);
  56887. var maskOffset = shadow.inset ? 0 : MASK_OFFSET;
  56888. var shadowPaintingArea = transformPath(borderBoxArea, -maskOffset + (shadow.inset ? 1 : -1) * shadow.spread.number, (shadow.inset ? 1 : -1) * shadow.spread.number, shadow.spread.number * (shadow.inset ? -2 : 2), shadow.spread.number * (shadow.inset ? -2 : 2));
  56889. if (shadow.inset) {
  56890. _this.path(borderBoxArea);
  56891. _this.ctx.clip();
  56892. _this.mask(shadowPaintingArea);
  56893. }
  56894. else {
  56895. _this.mask(borderBoxArea);
  56896. _this.ctx.clip();
  56897. _this.path(shadowPaintingArea);
  56898. }
  56899. _this.ctx.shadowOffsetX = shadow.offsetX.number + maskOffset;
  56900. _this.ctx.shadowOffsetY = shadow.offsetY.number;
  56901. _this.ctx.shadowColor = asString(shadow.color);
  56902. _this.ctx.shadowBlur = shadow.blur.number;
  56903. _this.ctx.fillStyle = shadow.inset ? asString(shadow.color) : 'rgba(0,0,0,1)';
  56904. _this.ctx.fill();
  56905. _this.ctx.restore();
  56906. });
  56907. _a.label = 2;
  56908. case 2:
  56909. side = 0;
  56910. _i = 0, borders_1 = borders;
  56911. _a.label = 3;
  56912. case 3:
  56913. if (!(_i < borders_1.length)) return [3 /*break*/, 7];
  56914. border = borders_1[_i];
  56915. if (!(border.style !== BORDER_STYLE.NONE && !isTransparent(border.color))) return [3 /*break*/, 5];
  56916. return [4 /*yield*/, this.renderBorder(border.color, side, paint.curves)];
  56917. case 4:
  56918. _a.sent();
  56919. _a.label = 5;
  56920. case 5:
  56921. side++;
  56922. _a.label = 6;
  56923. case 6:
  56924. _i++;
  56925. return [3 /*break*/, 3];
  56926. case 7: return [2 /*return*/];
  56927. }
  56928. });
  56929. });
  56930. };
  56931. CanvasRenderer.prototype.render = function (element) {
  56932. return __awaiter(this, void 0, void 0, function () {
  56933. var stack;
  56934. return __generator(this, function (_a) {
  56935. switch (_a.label) {
  56936. case 0:
  56937. if (this.options.backgroundColor) {
  56938. this.ctx.fillStyle = asString(this.options.backgroundColor);
  56939. this.ctx.fillRect(this.options.x - this.options.scrollX, this.options.y - this.options.scrollY, this.options.width, this.options.height);
  56940. }
  56941. stack = parseStackingContexts(element);
  56942. return [4 /*yield*/, this.renderStack(stack)];
  56943. case 1:
  56944. _a.sent();
  56945. this.applyEffects([], 2 /* BACKGROUND_BORDERS */);
  56946. return [2 /*return*/, this.canvas];
  56947. }
  56948. });
  56949. });
  56950. };
  56951. return CanvasRenderer;
  56952. }());
  56953. var isTextInputElement = function (container) {
  56954. if (container instanceof TextareaElementContainer) {
  56955. return true;
  56956. }
  56957. else if (container instanceof SelectElementContainer) {
  56958. return true;
  56959. }
  56960. else if (container instanceof InputElementContainer && container.type !== RADIO && container.type !== CHECKBOX) {
  56961. return true;
  56962. }
  56963. return false;
  56964. };
  56965. var calculateBackgroundCurvedPaintingArea = function (clip, curves) {
  56966. switch (clip) {
  56967. case BACKGROUND_CLIP.BORDER_BOX:
  56968. return calculateBorderBoxPath(curves);
  56969. case BACKGROUND_CLIP.CONTENT_BOX:
  56970. return calculateContentBoxPath(curves);
  56971. case BACKGROUND_CLIP.PADDING_BOX:
  56972. default:
  56973. return calculatePaddingBoxPath(curves);
  56974. }
  56975. };
  56976. var canvasTextAlign = function (textAlign) {
  56977. switch (textAlign) {
  56978. case TEXT_ALIGN.CENTER:
  56979. return 'center';
  56980. case TEXT_ALIGN.RIGHT:
  56981. return 'right';
  56982. case TEXT_ALIGN.LEFT:
  56983. default:
  56984. return 'left';
  56985. }
  56986. };
  56987. var ForeignObjectRenderer = /** @class */ (function () {
  56988. function ForeignObjectRenderer(options) {
  56989. this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
  56990. this.ctx = this.canvas.getContext('2d');
  56991. this.options = options;
  56992. this.canvas.width = Math.floor(options.width * options.scale);
  56993. this.canvas.height = Math.floor(options.height * options.scale);
  56994. this.canvas.style.width = options.width + "px";
  56995. this.canvas.style.height = options.height + "px";
  56996. this.ctx.scale(this.options.scale, this.options.scale);
  56997. this.ctx.translate(-options.x + options.scrollX, -options.y + options.scrollY);
  56998. Logger.getInstance(options.id).debug("EXPERIMENTAL ForeignObject renderer initialized (" + options.width + "x" + options.height + " at " + options.x + "," + options.y + ") with scale " + options.scale);
  56999. }
  57000. ForeignObjectRenderer.prototype.render = function (element) {
  57001. return __awaiter(this, void 0, void 0, function () {
  57002. var svg, img;
  57003. return __generator(this, function (_a) {
  57004. switch (_a.label) {
  57005. case 0:
  57006. svg = createForeignObjectSVG(Math.max(this.options.windowWidth, this.options.width) * this.options.scale, Math.max(this.options.windowHeight, this.options.height) * this.options.scale, this.options.scrollX * this.options.scale, this.options.scrollY * this.options.scale, element);
  57007. return [4 /*yield*/, loadSerializedSVG$1(svg)];
  57008. case 1:
  57009. img = _a.sent();
  57010. if (this.options.backgroundColor) {
  57011. this.ctx.fillStyle = asString(this.options.backgroundColor);
  57012. this.ctx.fillRect(0, 0, this.options.width * this.options.scale, this.options.height * this.options.scale);
  57013. }
  57014. this.ctx.drawImage(img, -this.options.x * this.options.scale, -this.options.y * this.options.scale);
  57015. return [2 /*return*/, this.canvas];
  57016. }
  57017. });
  57018. });
  57019. };
  57020. return ForeignObjectRenderer;
  57021. }());
  57022. var loadSerializedSVG$1 = function (svg) {
  57023. return new Promise(function (resolve, reject) {
  57024. var img = new Image();
  57025. img.onload = function () {
  57026. resolve(img);
  57027. };
  57028. img.onerror = reject;
  57029. img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg));
  57030. });
  57031. };
  57032. var _this = undefined;
  57033. var parseColor$1 = function (value) { return color.parse(Parser.create(value).parseComponentValue()); };
  57034. var html2canvas = function (element, options) {
  57035. if (options === void 0) { options = {}; }
  57036. return renderElement(element, options);
  57037. };
  57038. if (typeof window !== 'undefined') {
  57039. CacheStorage.setContext(window);
  57040. }
  57041. var renderElement = function (element, opts) { return __awaiter(_this, void 0, void 0, function () {
  57042. var ownerDocument, defaultView, instanceName, _a, width, height, left, top, defaultResourceOptions, resourceOptions, defaultOptions, options, windowBounds, documentCloner, clonedElement, container, documentBackgroundColor, bodyBackgroundColor, bgColor, defaultBackgroundColor, backgroundColor, renderOptions, canvas, renderer, root, renderer;
  57043. return __generator(this, function (_b) {
  57044. switch (_b.label) {
  57045. case 0:
  57046. ownerDocument = element.ownerDocument;
  57047. if (!ownerDocument) {
  57048. throw new Error("Element is not attached to a Document");
  57049. }
  57050. defaultView = ownerDocument.defaultView;
  57051. if (!defaultView) {
  57052. throw new Error("Document is not attached to a Window");
  57053. }
  57054. instanceName = (Math.round(Math.random() * 1000) + Date.now()).toString(16);
  57055. _a = isBodyElement(element) || isHTMLElement(element) ? parseDocumentSize(ownerDocument) : parseBounds(element), width = _a.width, height = _a.height, left = _a.left, top = _a.top;
  57056. defaultResourceOptions = {
  57057. allowTaint: false,
  57058. imageTimeout: 15000,
  57059. proxy: undefined,
  57060. useCORS: false
  57061. };
  57062. resourceOptions = __assign({}, defaultResourceOptions, opts);
  57063. defaultOptions = {
  57064. backgroundColor: '#ffffff',
  57065. cache: opts.cache ? opts.cache : CacheStorage.create(instanceName, resourceOptions),
  57066. logging: true,
  57067. removeContainer: true,
  57068. foreignObjectRendering: false,
  57069. scale: defaultView.devicePixelRatio || 1,
  57070. windowWidth: defaultView.innerWidth,
  57071. windowHeight: defaultView.innerHeight,
  57072. scrollX: defaultView.pageXOffset,
  57073. scrollY: defaultView.pageYOffset,
  57074. x: left,
  57075. y: top,
  57076. width: Math.ceil(width),
  57077. height: Math.ceil(height),
  57078. id: instanceName
  57079. };
  57080. options = __assign({}, defaultOptions, resourceOptions, opts);
  57081. windowBounds = new Bounds(options.scrollX, options.scrollY, options.windowWidth, options.windowHeight);
  57082. Logger.create({ id: instanceName, enabled: options.logging });
  57083. Logger.getInstance(instanceName).debug("Starting document clone");
  57084. documentCloner = new DocumentCloner(element, {
  57085. id: instanceName,
  57086. onclone: options.onclone,
  57087. ignoreElements: options.ignoreElements,
  57088. inlineImages: options.foreignObjectRendering,
  57089. copyStyles: options.foreignObjectRendering
  57090. });
  57091. clonedElement = documentCloner.clonedReferenceElement;
  57092. if (!clonedElement) {
  57093. return [2 /*return*/, Promise.reject("Unable to find element in cloned iframe")];
  57094. }
  57095. return [4 /*yield*/, documentCloner.toIFrame(ownerDocument, windowBounds)];
  57096. case 1:
  57097. container = _b.sent();
  57098. documentBackgroundColor = ownerDocument.documentElement
  57099. ? parseColor$1(getComputedStyle(ownerDocument.documentElement).backgroundColor)
  57100. : COLORS.TRANSPARENT;
  57101. bodyBackgroundColor = ownerDocument.body
  57102. ? parseColor$1(getComputedStyle(ownerDocument.body).backgroundColor)
  57103. : COLORS.TRANSPARENT;
  57104. bgColor = opts.backgroundColor;
  57105. defaultBackgroundColor = typeof bgColor === 'string' ? parseColor$1(bgColor) : bgColor === null ? COLORS.TRANSPARENT : 0xffffffff;
  57106. backgroundColor = element === ownerDocument.documentElement
  57107. ? isTransparent(documentBackgroundColor)
  57108. ? isTransparent(bodyBackgroundColor)
  57109. ? defaultBackgroundColor
  57110. : bodyBackgroundColor
  57111. : documentBackgroundColor
  57112. : defaultBackgroundColor;
  57113. renderOptions = {
  57114. id: instanceName,
  57115. cache: options.cache,
  57116. canvas: options.canvas,
  57117. backgroundColor: backgroundColor,
  57118. scale: options.scale,
  57119. x: options.x,
  57120. y: options.y,
  57121. scrollX: options.scrollX,
  57122. scrollY: options.scrollY,
  57123. width: options.width,
  57124. height: options.height,
  57125. windowWidth: options.windowWidth,
  57126. windowHeight: options.windowHeight
  57127. };
  57128. if (!options.foreignObjectRendering) return [3 /*break*/, 3];
  57129. Logger.getInstance(instanceName).debug("Document cloned, using foreign object rendering");
  57130. renderer = new ForeignObjectRenderer(renderOptions);
  57131. return [4 /*yield*/, renderer.render(clonedElement)];
  57132. case 2:
  57133. canvas = _b.sent();
  57134. return [3 /*break*/, 5];
  57135. case 3:
  57136. Logger.getInstance(instanceName).debug("Document cloned, using computed rendering");
  57137. CacheStorage.attachInstance(options.cache);
  57138. Logger.getInstance(instanceName).debug("Starting DOM parsing");
  57139. root = parseTree(clonedElement);
  57140. CacheStorage.detachInstance();
  57141. if (backgroundColor === root.styles.backgroundColor) {
  57142. root.styles.backgroundColor = COLORS.TRANSPARENT;
  57143. }
  57144. Logger.getInstance(instanceName).debug("Starting renderer");
  57145. renderer = new CanvasRenderer(renderOptions);
  57146. return [4 /*yield*/, renderer.render(root)];
  57147. case 4:
  57148. canvas = _b.sent();
  57149. _b.label = 5;
  57150. case 5:
  57151. if (options.removeContainer === true) {
  57152. if (!DocumentCloner.destroy(container)) {
  57153. Logger.getInstance(instanceName).error("Cannot detach cloned iframe as it is not in the DOM anymore");
  57154. }
  57155. }
  57156. Logger.getInstance(instanceName).debug("Finished rendering");
  57157. Logger.destroy(instanceName);
  57158. CacheStorage.destroy(instanceName);
  57159. return [2 /*return*/, canvas];
  57160. }
  57161. });
  57162. }); };
  57163. return html2canvas;
  57164. }));
  57165. },{}],214:[function(require,module,exports){
  57166. // (c) Dean McNamee <dean@gmail.com>, 2013.
  57167. //
  57168. // https://github.com/deanm/omggif
  57169. //
  57170. // Permission is hereby granted, free of charge, to any person obtaining a copy
  57171. // of this software and associated documentation files (the "Software"), to
  57172. // deal in the Software without restriction, including without limitation the
  57173. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  57174. // sell copies of the Software, and to permit persons to whom the Software is
  57175. // furnished to do so, subject to the following conditions:
  57176. //
  57177. // The above copyright notice and this permission notice shall be included in
  57178. // all copies or substantial portions of the Software.
  57179. //
  57180. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  57181. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  57182. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  57183. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  57184. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  57185. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  57186. // IN THE SOFTWARE.
  57187. //
  57188. // omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
  57189. // including animation and compression. It does not rely on any specific
  57190. // underlying system, so should run in the browser, Node, or Plask.
  57191. function GifWriter(buf, width, height, gopts) {
  57192. var p = 0;
  57193. var gopts = gopts === undefined ? { } : gopts;
  57194. var loop_count = gopts.loop === undefined ? null : gopts.loop;
  57195. var global_palette = gopts.palette === undefined ? null : gopts.palette;
  57196. if (width <= 0 || height <= 0 || width > 65535 || height > 65535)
  57197. throw "Width/Height invalid."
  57198. function check_palette_and_num_colors(palette) {
  57199. var num_colors = palette.length;
  57200. if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1))
  57201. throw "Invalid code/color length, must be power of 2 and 2 .. 256.";
  57202. return num_colors;
  57203. }
  57204. // - Header.
  57205. buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF
  57206. buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a
  57207. // Handling of Global Color Table (palette) and background index.
  57208. var gp_num_colors_pow2 = 0;
  57209. var background = 0;
  57210. if (global_palette !== null) {
  57211. var gp_num_colors = check_palette_and_num_colors(global_palette);
  57212. while (gp_num_colors >>= 1) ++gp_num_colors_pow2;
  57213. gp_num_colors = 1 << gp_num_colors_pow2;
  57214. --gp_num_colors_pow2;
  57215. if (gopts.background !== undefined) {
  57216. background = gopts.background;
  57217. if (background >= gp_num_colors) throw "Background index out of range.";
  57218. // The GIF spec states that a background index of 0 should be ignored, so
  57219. // this is probably a mistake and you really want to set it to another
  57220. // slot in the palette. But actually in the end most browsers, etc end
  57221. // up ignoring this almost completely (including for dispose background).
  57222. if (background === 0)
  57223. throw "Background index explicitly passed as 0.";
  57224. }
  57225. }
  57226. // - Logical Screen Descriptor.
  57227. // NOTE(deanm): w/h apparently ignored by implementations, but set anyway.
  57228. buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff;
  57229. buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff;
  57230. // NOTE: Indicates 0-bpp original color resolution (unused?).
  57231. buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.
  57232. gp_num_colors_pow2; // NOTE: No sort flag (unused?).
  57233. buf[p++] = background; // Background Color Index.
  57234. buf[p++] = 0; // Pixel aspect ratio (unused?).
  57235. // - Global Color Table
  57236. if (global_palette !== null) {
  57237. for (var i = 0, il = global_palette.length; i < il; ++i) {
  57238. var rgb = global_palette[i];
  57239. buf[p++] = rgb >> 16 & 0xff;
  57240. buf[p++] = rgb >> 8 & 0xff;
  57241. buf[p++] = rgb & 0xff;
  57242. }
  57243. }
  57244. if (loop_count !== null) { // Netscape block for looping.
  57245. if (loop_count < 0 || loop_count > 65535)
  57246. throw "Loop count invalid."
  57247. // Extension code, label, and length.
  57248. buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b;
  57249. // NETSCAPE2.0
  57250. buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53;
  57251. buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45;
  57252. buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30;
  57253. // Sub-block
  57254. buf[p++] = 0x03; buf[p++] = 0x01;
  57255. buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff;
  57256. buf[p++] = 0x00; // Terminator.
  57257. }
  57258. var ended = false;
  57259. this.addFrame = function(x, y, w, h, indexed_pixels, opts) {
  57260. if (ended === true) { --p; ended = false; } // Un-end.
  57261. opts = opts === undefined ? { } : opts;
  57262. // TODO(deanm): Bounds check x, y. Do they need to be within the virtual
  57263. // canvas width/height, I imagine?
  57264. if (x < 0 || y < 0 || x > 65535 || y > 65535)
  57265. throw "x/y invalid."
  57266. if (w <= 0 || h <= 0 || w > 65535 || h > 65535)
  57267. throw "Width/Height invalid."
  57268. if (indexed_pixels.length < w * h)
  57269. throw "Not enough pixels for the frame size.";
  57270. var using_local_palette = true;
  57271. var palette = opts.palette;
  57272. if (palette === undefined || palette === null) {
  57273. using_local_palette = false;
  57274. palette = global_palette;
  57275. }
  57276. if (palette === undefined || palette === null)
  57277. throw "Must supply either a local or global palette.";
  57278. var num_colors = check_palette_and_num_colors(palette);
  57279. // Compute the min_code_size (power of 2), destroying num_colors.
  57280. var min_code_size = 0;
  57281. while (num_colors >>= 1) ++min_code_size;
  57282. num_colors = 1 << min_code_size; // Now we can easily get it back.
  57283. var delay = opts.delay === undefined ? 0 : opts.delay;
  57284. // From the spec:
  57285. // 0 - No disposal specified. The decoder is
  57286. // not required to take any action.
  57287. // 1 - Do not dispose. The graphic is to be left
  57288. // in place.
  57289. // 2 - Restore to background color. The area used by the
  57290. // graphic must be restored to the background color.
  57291. // 3 - Restore to previous. The decoder is required to
  57292. // restore the area overwritten by the graphic with
  57293. // what was there prior to rendering the graphic.
  57294. // 4-7 - To be defined.
  57295. // NOTE(deanm): Dispose background doesn't really work, apparently most
  57296. // browsers ignore the background palette index and clear to transparency.
  57297. var disposal = opts.disposal === undefined ? 0 : opts.disposal;
  57298. if (disposal < 0 || disposal > 3) // 4-7 is reserved.
  57299. throw "Disposal out of range.";
  57300. var use_transparency = false;
  57301. var transparent_index = 0;
  57302. if (opts.transparent !== undefined && opts.transparent !== null) {
  57303. use_transparency = true;
  57304. transparent_index = opts.transparent;
  57305. if (transparent_index < 0 || transparent_index >= num_colors)
  57306. throw "Transparent color index.";
  57307. }
  57308. if (disposal !== 0 || use_transparency || delay !== 0) {
  57309. // - Graphics Control Extension
  57310. buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label.
  57311. buf[p++] = 4; // Byte size.
  57312. buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);
  57313. buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff;
  57314. buf[p++] = transparent_index; // Transparent color index.
  57315. buf[p++] = 0; // Block Terminator.
  57316. }
  57317. // - Image Descriptor
  57318. buf[p++] = 0x2c; // Image Seperator.
  57319. buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left.
  57320. buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top.
  57321. buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff;
  57322. buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff;
  57323. // NOTE: No sort flag (unused?).
  57324. // TODO(deanm): Support interlace.
  57325. buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0;
  57326. // - Local Color Table
  57327. if (using_local_palette === true) {
  57328. for (var i = 0, il = palette.length; i < il; ++i) {
  57329. var rgb = palette[i];
  57330. buf[p++] = rgb >> 16 & 0xff;
  57331. buf[p++] = rgb >> 8 & 0xff;
  57332. buf[p++] = rgb & 0xff;
  57333. }
  57334. }
  57335. p = GifWriterOutputLZWCodeStream(
  57336. buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);
  57337. };
  57338. this.end = function() {
  57339. if (ended === false) {
  57340. buf[p++] = 0x3b; // Trailer.
  57341. ended = true;
  57342. }
  57343. return p;
  57344. };
  57345. }
  57346. // Main compression routine, palette indexes -> LZW code stream.
  57347. // |index_stream| must have at least one entry.
  57348. function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {
  57349. buf[p++] = min_code_size;
  57350. var cur_subblock = p++; // Pointing at the length field.
  57351. var clear_code = 1 << min_code_size;
  57352. var code_mask = clear_code - 1;
  57353. var eoi_code = clear_code + 1;
  57354. var next_code = eoi_code + 1;
  57355. var cur_code_size = min_code_size + 1; // Number of bits per code.
  57356. var cur_shift = 0;
  57357. // We have at most 12-bit codes, so we should have to hold a max of 19
  57358. // bits here (and then we would write out).
  57359. var cur = 0;
  57360. function emit_bytes_to_buffer(bit_block_size) {
  57361. while (cur_shift >= bit_block_size) {
  57362. buf[p++] = cur & 0xff;
  57363. cur >>= 8; cur_shift -= 8;
  57364. if (p === cur_subblock + 256) { // Finished a subblock.
  57365. buf[cur_subblock] = 255;
  57366. cur_subblock = p++;
  57367. }
  57368. }
  57369. }
  57370. function emit_code(c) {
  57371. cur |= c << cur_shift;
  57372. cur_shift += cur_code_size;
  57373. emit_bytes_to_buffer(8);
  57374. }
  57375. // I am not an expert on the topic, and I don't want to write a thesis.
  57376. // However, it is good to outline here the basic algorithm and the few data
  57377. // structures and optimizations here that make this implementation fast.
  57378. // The basic idea behind LZW is to build a table of previously seen runs
  57379. // addressed by a short id (herein called output code). All data is
  57380. // referenced by a code, which represents one or more values from the
  57381. // original input stream. All input bytes can be referenced as the same
  57382. // value as an output code. So if you didn't want any compression, you
  57383. // could more or less just output the original bytes as codes (there are
  57384. // some details to this, but it is the idea). In order to achieve
  57385. // compression, values greater then the input range (codes can be up to
  57386. // 12-bit while input only 8-bit) represent a sequence of previously seen
  57387. // inputs. The decompressor is able to build the same mapping while
  57388. // decoding, so there is always a shared common knowledge between the
  57389. // encoding and decoder, which is also important for "timing" aspects like
  57390. // how to handle variable bit width code encoding.
  57391. //
  57392. // One obvious but very important consequence of the table system is there
  57393. // is always a unique id (at most 12-bits) to map the runs. 'A' might be
  57394. // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship
  57395. // can be used for an effecient lookup strategy for the code mapping. We
  57396. // need to know if a run has been seen before, and be able to map that run
  57397. // to the output code. Since we start with known unique ids (input bytes),
  57398. // and then from those build more unique ids (table entries), we can
  57399. // continue this chain (almost like a linked list) to always have small
  57400. // integer values that represent the current byte chains in the encoder.
  57401. // This means instead of tracking the input bytes (AAAABCD) to know our
  57402. // current state, we can track the table entry for AAAABC (it is guaranteed
  57403. // to exist by the nature of the algorithm) and the next character D.
  57404. // Therefor the tuple of (table_entry, byte) is guaranteed to also be
  57405. // unique. This allows us to create a simple lookup key for mapping input
  57406. // sequences to codes (table indices) without having to store or search
  57407. // any of the code sequences. So if 'AAAA' has a table entry of 12, the
  57408. // tuple of ('AAAA', K) for any input byte K will be unique, and can be our
  57409. // key. This leads to a integer value at most 20-bits, which can always
  57410. // fit in an SMI value and be used as a fast sparse array / object key.
  57411. // Output code for the current contents of the index buffer.
  57412. var ib_code = index_stream[0] & code_mask; // Load first input index.
  57413. var code_table = { }; // Key'd on our 20-bit "tuple".
  57414. emit_code(clear_code); // Spec says first code should be a clear code.
  57415. // First index already loaded, process the rest of the stream.
  57416. for (var i = 1, il = index_stream.length; i < il; ++i) {
  57417. var k = index_stream[i] & code_mask;
  57418. var cur_key = ib_code << 8 | k; // (prev, k) unique tuple.
  57419. var cur_code = code_table[cur_key]; // buffer + k.
  57420. // Check if we have to create a new code table entry.
  57421. if (cur_code === undefined) { // We don't have buffer + k.
  57422. // Emit index buffer (without k).
  57423. // This is an inline version of emit_code, because this is the core
  57424. // writing routine of the compressor (and V8 cannot inline emit_code
  57425. // because it is a closure here in a different context). Additionally
  57426. // we can call emit_byte_to_buffer less often, because we can have
  57427. // 30-bits (from our 31-bit signed SMI), and we know our codes will only
  57428. // be 12-bits, so can safely have 18-bits there without overflow.
  57429. // emit_code(ib_code);
  57430. cur |= ib_code << cur_shift;
  57431. cur_shift += cur_code_size;
  57432. while (cur_shift >= 8) {
  57433. buf[p++] = cur & 0xff;
  57434. cur >>= 8; cur_shift -= 8;
  57435. if (p === cur_subblock + 256) { // Finished a subblock.
  57436. buf[cur_subblock] = 255;
  57437. cur_subblock = p++;
  57438. }
  57439. }
  57440. if (next_code === 4096) { // Table full, need a clear.
  57441. emit_code(clear_code);
  57442. next_code = eoi_code + 1;
  57443. cur_code_size = min_code_size + 1;
  57444. code_table = { };
  57445. } else { // Table not full, insert a new entry.
  57446. // Increase our variable bit code sizes if necessary. This is a bit
  57447. // tricky as it is based on "timing" between the encoding and
  57448. // decoder. From the encoders perspective this should happen after
  57449. // we've already emitted the index buffer and are about to create the
  57450. // first table entry that would overflow our current code bit size.
  57451. if (next_code >= (1 << cur_code_size)) ++cur_code_size;
  57452. code_table[cur_key] = next_code++; // Insert into code table.
  57453. }
  57454. ib_code = k; // Index buffer to single input k.
  57455. } else {
  57456. ib_code = cur_code; // Index buffer to sequence in code table.
  57457. }
  57458. }
  57459. emit_code(ib_code); // There will still be something in the index buffer.
  57460. emit_code(eoi_code); // End Of Information.
  57461. // Flush / finalize the sub-blocks stream to the buffer.
  57462. emit_bytes_to_buffer(1);
  57463. // Finish the sub-blocks, writing out any unfinished lengths and
  57464. // terminating with a sub-block of length 0. If we have already started
  57465. // but not yet used a sub-block it can just become the terminator.
  57466. if (cur_subblock + 1 === p) { // Started but unused.
  57467. buf[cur_subblock] = 0;
  57468. } else { // Started and used, write length and additional terminator block.
  57469. buf[cur_subblock] = p - cur_subblock - 1;
  57470. buf[p++] = 0;
  57471. }
  57472. return p;
  57473. }
  57474. function GifReader(buf) {
  57475. var p = 0;
  57476. // - Header (GIF87a or GIF89a).
  57477. if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 ||
  57478. buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) {
  57479. throw "Invalid GIF 87a/89a header.";
  57480. }
  57481. // - Logical Screen Descriptor.
  57482. var width = buf[p++] | buf[p++] << 8;
  57483. var height = buf[p++] | buf[p++] << 8;
  57484. var pf0 = buf[p++]; // <Packed Fields>.
  57485. var global_palette_flag = pf0 >> 7;
  57486. var num_global_colors_pow2 = pf0 & 0x7;
  57487. var num_global_colors = 1 << (num_global_colors_pow2 + 1);
  57488. var background = buf[p++];
  57489. buf[p++]; // Pixel aspect ratio (unused?).
  57490. var global_palette_offset = null;
  57491. if (global_palette_flag) {
  57492. global_palette_offset = p;
  57493. p += num_global_colors * 3; // Seek past palette.
  57494. }
  57495. var no_eof = true;
  57496. var frames = [ ];
  57497. var delay = 0;
  57498. var transparent_index = null;
  57499. var disposal = 0; // 0 - No disposal specified.
  57500. var loop_count = null;
  57501. this.width = width;
  57502. this.height = height;
  57503. while (no_eof && p < buf.length) {
  57504. switch (buf[p++]) {
  57505. case 0x21: // Graphics Control Extension Block
  57506. switch (buf[p++]) {
  57507. case 0xff: // Application specific block
  57508. // Try if it's a Netscape block (with animation loop counter).
  57509. if (buf[p ] !== 0x0b || // 21 FF already read, check block size.
  57510. // NETSCAPE2.0
  57511. buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 &&
  57512. buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 &&
  57513. buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 &&
  57514. buf[p+10] == 0x2e && buf[p+11] == 0x30 &&
  57515. // Sub-block
  57516. buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) {
  57517. p += 14;
  57518. loop_count = buf[p++] | buf[p++] << 8;
  57519. p++; // Skip terminator.
  57520. } else { // We don't know what it is, just try to get past it.
  57521. p += 12;
  57522. while (true) { // Seek through subblocks.
  57523. var block_size = buf[p++];
  57524. if (block_size === 0) break;
  57525. p += block_size;
  57526. }
  57527. }
  57528. break;
  57529. case 0xf9: // Graphics Control Extension
  57530. if (buf[p++] !== 0x4 || buf[p+4] !== 0)
  57531. throw "Invalid graphics extension block.";
  57532. var pf1 = buf[p++];
  57533. delay = buf[p++] | buf[p++] << 8;
  57534. transparent_index = buf[p++];
  57535. if ((pf1 & 1) === 0) transparent_index = null;
  57536. disposal = pf1 >> 2 & 0x7;
  57537. p++; // Skip terminator.
  57538. break;
  57539. case 0xfe: // Comment Extension.
  57540. while (true) { // Seek through subblocks.
  57541. var block_size = buf[p++];
  57542. if (block_size === 0) break;
  57543. // console.log(buf.slice(p, p+block_size).toString('ascii'));
  57544. p += block_size;
  57545. }
  57546. break;
  57547. default:
  57548. throw "Unknown graphic control label: 0x" + buf[p-1].toString(16);
  57549. }
  57550. break;
  57551. case 0x2c: // Image Descriptor.
  57552. var x = buf[p++] | buf[p++] << 8;
  57553. var y = buf[p++] | buf[p++] << 8;
  57554. var w = buf[p++] | buf[p++] << 8;
  57555. var h = buf[p++] | buf[p++] << 8;
  57556. var pf2 = buf[p++];
  57557. var local_palette_flag = pf2 >> 7;
  57558. var interlace_flag = pf2 >> 6 & 1;
  57559. var num_local_colors_pow2 = pf2 & 0x7;
  57560. var num_local_colors = 1 << (num_local_colors_pow2 + 1);
  57561. var palette_offset = global_palette_offset;
  57562. var has_local_palette = false;
  57563. if (local_palette_flag) {
  57564. var has_local_palette = true;
  57565. palette_offset = p; // Override with local palette.
  57566. p += num_local_colors * 3; // Seek past palette.
  57567. }
  57568. var data_offset = p;
  57569. p++; // codesize
  57570. while (true) {
  57571. var block_size = buf[p++];
  57572. if (block_size === 0) break;
  57573. p += block_size;
  57574. }
  57575. frames.push({x: x, y: y, width: w, height: h,
  57576. has_local_palette: has_local_palette,
  57577. palette_offset: palette_offset,
  57578. data_offset: data_offset,
  57579. data_length: p - data_offset,
  57580. transparent_index: transparent_index,
  57581. interlaced: !!interlace_flag,
  57582. delay: delay,
  57583. disposal: disposal});
  57584. break;
  57585. case 0x3b: // Trailer Marker (end of file).
  57586. no_eof = false;
  57587. break;
  57588. default:
  57589. throw "Unknown gif block: 0x" + buf[p-1].toString(16);
  57590. break;
  57591. }
  57592. }
  57593. this.numFrames = function() {
  57594. return frames.length;
  57595. };
  57596. this.loopCount = function() {
  57597. return loop_count;
  57598. };
  57599. this.frameInfo = function(frame_num) {
  57600. if (frame_num < 0 || frame_num >= frames.length)
  57601. throw "Frame index out of range.";
  57602. return frames[frame_num];
  57603. }
  57604. this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {
  57605. var frame = this.frameInfo(frame_num);
  57606. var num_pixels = frame.width * frame.height;
  57607. var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
  57608. GifReaderLZWOutputIndexStream(
  57609. buf, frame.data_offset, index_stream, num_pixels);
  57610. var palette_offset = frame.palette_offset;
  57611. // NOTE(deanm): It seems to be much faster to compare index to 256 than
  57612. // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
  57613. // the profile, not sure if it's related to using a Uint8Array.
  57614. var trans = frame.transparent_index;
  57615. if (trans === null) trans = 256;
  57616. // We are possibly just blitting to a portion of the entire frame.
  57617. // That is a subrect within the framerect, so the additional pixels
  57618. // must be skipped over after we finished a scanline.
  57619. var framewidth = frame.width;
  57620. var framestride = width - framewidth;
  57621. var xleft = framewidth; // Number of subrect pixels left in scanline.
  57622. // Output indicies of the top left and bottom right corners of the subrect.
  57623. var opbeg = ((frame.y * width) + frame.x) * 4;
  57624. var opend = ((frame.y + frame.height) * width + frame.x) * 4;
  57625. var op = opbeg;
  57626. var scanstride = framestride * 4;
  57627. // Use scanstride to skip past the rows when interlacing. This is skipping
  57628. // 7 rows for the first two passes, then 3 then 1.
  57629. if (frame.interlaced === true) {
  57630. scanstride += width * 4 * 7; // Pass 1.
  57631. }
  57632. var interlaceskip = 8; // Tracking the row interval in the current pass.
  57633. for (var i = 0, il = index_stream.length; i < il; ++i) {
  57634. var index = index_stream[i];
  57635. if (xleft === 0) { // Beginning of new scan line
  57636. op += scanstride;
  57637. xleft = framewidth;
  57638. if (op >= opend) { // Catch the wrap to switch passes when interlacing.
  57639. scanstride = framestride * 4 + width * 4 * (interlaceskip-1);
  57640. // interlaceskip / 2 * 4 is interlaceskip << 1.
  57641. op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
  57642. interlaceskip >>= 1;
  57643. }
  57644. }
  57645. if (index === trans) {
  57646. op += 4;
  57647. } else {
  57648. var r = buf[palette_offset + index * 3];
  57649. var g = buf[palette_offset + index * 3 + 1];
  57650. var b = buf[palette_offset + index * 3 + 2];
  57651. pixels[op++] = b;
  57652. pixels[op++] = g;
  57653. pixels[op++] = r;
  57654. pixels[op++] = 255;
  57655. }
  57656. --xleft;
  57657. }
  57658. };
  57659. // I will go to copy and paste hell one day...
  57660. this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {
  57661. var frame = this.frameInfo(frame_num);
  57662. var num_pixels = frame.width * frame.height;
  57663. var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
  57664. GifReaderLZWOutputIndexStream(
  57665. buf, frame.data_offset, index_stream, num_pixels);
  57666. var palette_offset = frame.palette_offset;
  57667. // NOTE(deanm): It seems to be much faster to compare index to 256 than
  57668. // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
  57669. // the profile, not sure if it's related to using a Uint8Array.
  57670. var trans = frame.transparent_index;
  57671. if (trans === null) trans = 256;
  57672. // We are possibly just blitting to a portion of the entire frame.
  57673. // That is a subrect within the framerect, so the additional pixels
  57674. // must be skipped over after we finished a scanline.
  57675. var framewidth = frame.width;
  57676. var framestride = width - framewidth;
  57677. var xleft = framewidth; // Number of subrect pixels left in scanline.
  57678. // Output indicies of the top left and bottom right corners of the subrect.
  57679. var opbeg = ((frame.y * width) + frame.x) * 4;
  57680. var opend = ((frame.y + frame.height) * width + frame.x) * 4;
  57681. var op = opbeg;
  57682. var scanstride = framestride * 4;
  57683. // Use scanstride to skip past the rows when interlacing. This is skipping
  57684. // 7 rows for the first two passes, then 3 then 1.
  57685. if (frame.interlaced === true) {
  57686. scanstride += width * 4 * 7; // Pass 1.
  57687. }
  57688. var interlaceskip = 8; // Tracking the row interval in the current pass.
  57689. for (var i = 0, il = index_stream.length; i < il; ++i) {
  57690. var index = index_stream[i];
  57691. if (xleft === 0) { // Beginning of new scan line
  57692. op += scanstride;
  57693. xleft = framewidth;
  57694. if (op >= opend) { // Catch the wrap to switch passes when interlacing.
  57695. scanstride = framestride * 4 + width * 4 * (interlaceskip-1);
  57696. // interlaceskip / 2 * 4 is interlaceskip << 1.
  57697. op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
  57698. interlaceskip >>= 1;
  57699. }
  57700. }
  57701. if (index === trans) {
  57702. op += 4;
  57703. } else {
  57704. var r = buf[palette_offset + index * 3];
  57705. var g = buf[palette_offset + index * 3 + 1];
  57706. var b = buf[palette_offset + index * 3 + 2];
  57707. pixels[op++] = r;
  57708. pixels[op++] = g;
  57709. pixels[op++] = b;
  57710. pixels[op++] = 255;
  57711. }
  57712. --xleft;
  57713. }
  57714. };
  57715. }
  57716. function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {
  57717. var min_code_size = code_stream[p++];
  57718. var clear_code = 1 << min_code_size;
  57719. var eoi_code = clear_code + 1;
  57720. var next_code = eoi_code + 1;
  57721. var cur_code_size = min_code_size + 1; // Number of bits per code.
  57722. // NOTE: This shares the same name as the encoder, but has a different
  57723. // meaning here. Here this masks each code coming from the code stream.
  57724. var code_mask = (1 << cur_code_size) - 1;
  57725. var cur_shift = 0;
  57726. var cur = 0;
  57727. var op = 0; // Output pointer.
  57728. var subblock_size = code_stream[p++];
  57729. // TODO(deanm): Would using a TypedArray be any faster? At least it would
  57730. // solve the fast mode / backing store uncertainty.
  57731. // var code_table = Array(4096);
  57732. var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.
  57733. var prev_code = null; // Track code-1.
  57734. while (true) {
  57735. // Read up to two bytes, making sure we always 12-bits for max sized code.
  57736. while (cur_shift < 16) {
  57737. if (subblock_size === 0) break; // No more data to be read.
  57738. cur |= code_stream[p++] << cur_shift;
  57739. cur_shift += 8;
  57740. if (subblock_size === 1) { // Never let it get to 0 to hold logic above.
  57741. subblock_size = code_stream[p++]; // Next subblock.
  57742. } else {
  57743. --subblock_size;
  57744. }
  57745. }
  57746. // TODO(deanm): We should never really get here, we should have received
  57747. // and EOI.
  57748. if (cur_shift < cur_code_size)
  57749. break;
  57750. var code = cur & code_mask;
  57751. cur >>= cur_code_size;
  57752. cur_shift -= cur_code_size;
  57753. // TODO(deanm): Maybe should check that the first code was a clear code,
  57754. // at least this is what you're supposed to do. But actually our encoder
  57755. // now doesn't emit a clear code first anyway.
  57756. if (code === clear_code) {
  57757. // We don't actually have to clear the table. This could be a good idea
  57758. // for greater error checking, but we don't really do any anyway. We
  57759. // will just track it with next_code and overwrite old entries.
  57760. next_code = eoi_code + 1;
  57761. cur_code_size = min_code_size + 1;
  57762. code_mask = (1 << cur_code_size) - 1;
  57763. // Don't update prev_code ?
  57764. prev_code = null;
  57765. continue;
  57766. } else if (code === eoi_code) {
  57767. break;
  57768. }
  57769. // We have a similar situation as the decoder, where we want to store
  57770. // variable length entries (code table entries), but we want to do in a
  57771. // faster manner than an array of arrays. The code below stores sort of a
  57772. // linked list within the code table, and then "chases" through it to
  57773. // construct the dictionary entries. When a new entry is created, just the
  57774. // last byte is stored, and the rest (prefix) of the entry is only
  57775. // referenced by its table entry. Then the code chases through the
  57776. // prefixes until it reaches a single byte code. We have to chase twice,
  57777. // first to compute the length, and then to actually copy the data to the
  57778. // output (backwards, since we know the length). The alternative would be
  57779. // storing something in an intermediate stack, but that doesn't make any
  57780. // more sense. I implemented an approach where it also stored the length
  57781. // in the code table, although it's a bit tricky because you run out of
  57782. // bits (12 + 12 + 8), but I didn't measure much improvements (the table
  57783. // entries are generally not the long). Even when I created benchmarks for
  57784. // very long table entries the complexity did not seem worth it.
  57785. // The code table stores the prefix entry in 12 bits and then the suffix
  57786. // byte in 8 bits, so each entry is 20 bits.
  57787. var chase_code = code < next_code ? code : prev_code;
  57788. // Chase what we will output, either {CODE} or {CODE-1}.
  57789. var chase_length = 0;
  57790. var chase = chase_code;
  57791. while (chase > clear_code) {
  57792. chase = code_table[chase] >> 8;
  57793. ++chase_length;
  57794. }
  57795. var k = chase;
  57796. var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
  57797. if (op_end > output_length) {
  57798. console.log("Warning, gif stream longer than expected.");
  57799. return;
  57800. }
  57801. // Already have the first byte from the chase, might as well write it fast.
  57802. output[op++] = k;
  57803. op += chase_length;
  57804. var b = op; // Track pointer, writing backwards.
  57805. if (chase_code !== code) // The case of emitting {CODE-1} + k.
  57806. output[op++] = k;
  57807. chase = chase_code;
  57808. while (chase_length--) {
  57809. chase = code_table[chase];
  57810. output[--b] = chase & 0xff; // Write backwards.
  57811. chase >>= 8; // Pull down to the prefix code.
  57812. }
  57813. if (prev_code !== null && next_code < 4096) {
  57814. code_table[next_code++] = prev_code << 8 | k;
  57815. // TODO(deanm): Figure out this clearing vs code growth logic better. I
  57816. // have an feeling that it should just happen somewhere else, for now it
  57817. // is awkward between when we grow past the max and then hit a clear code.
  57818. // For now just check if we hit the max 12-bits (then a clear code should
  57819. // follow, also of course encoded in 12-bits).
  57820. if (next_code >= code_mask+1 && cur_code_size < 12) {
  57821. ++cur_code_size;
  57822. code_mask = code_mask << 1 | 1;
  57823. }
  57824. }
  57825. prev_code = code;
  57826. }
  57827. if (op !== output_length) {
  57828. console.log("Warning, gif stream shorter than expected.");
  57829. }
  57830. return output;
  57831. }
  57832. try { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) { } // CommonJS.
  57833. },{}],215:[function(require,module,exports){
  57834. // shim for using process in browser
  57835. var process = module.exports = {};
  57836. // cached from whatever global is present so that test runners that stub it
  57837. // don't break things. But we need to wrap it in a try catch in case it is
  57838. // wrapped in strict mode code which doesn't define any globals. It's inside a
  57839. // function because try/catches deoptimize in certain engines.
  57840. var cachedSetTimeout;
  57841. var cachedClearTimeout;
  57842. function defaultSetTimout() {
  57843. throw new Error('setTimeout has not been defined');
  57844. }
  57845. function defaultClearTimeout () {
  57846. throw new Error('clearTimeout has not been defined');
  57847. }
  57848. (function () {
  57849. try {
  57850. if (typeof setTimeout === 'function') {
  57851. cachedSetTimeout = setTimeout;
  57852. } else {
  57853. cachedSetTimeout = defaultSetTimout;
  57854. }
  57855. } catch (e) {
  57856. cachedSetTimeout = defaultSetTimout;
  57857. }
  57858. try {
  57859. if (typeof clearTimeout === 'function') {
  57860. cachedClearTimeout = clearTimeout;
  57861. } else {
  57862. cachedClearTimeout = defaultClearTimeout;
  57863. }
  57864. } catch (e) {
  57865. cachedClearTimeout = defaultClearTimeout;
  57866. }
  57867. } ())
  57868. function runTimeout(fun) {
  57869. if (cachedSetTimeout === setTimeout) {
  57870. //normal enviroments in sane situations
  57871. return setTimeout(fun, 0);
  57872. }
  57873. // if setTimeout wasn't available but was latter defined
  57874. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  57875. cachedSetTimeout = setTimeout;
  57876. return setTimeout(fun, 0);
  57877. }
  57878. try {
  57879. // when when somebody has screwed with setTimeout but no I.E. maddness
  57880. return cachedSetTimeout(fun, 0);
  57881. } catch(e){
  57882. try {
  57883. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  57884. return cachedSetTimeout.call(null, fun, 0);
  57885. } catch(e){
  57886. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  57887. return cachedSetTimeout.call(this, fun, 0);
  57888. }
  57889. }
  57890. }
  57891. function runClearTimeout(marker) {
  57892. if (cachedClearTimeout === clearTimeout) {
  57893. //normal enviroments in sane situations
  57894. return clearTimeout(marker);
  57895. }
  57896. // if clearTimeout wasn't available but was latter defined
  57897. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  57898. cachedClearTimeout = clearTimeout;
  57899. return clearTimeout(marker);
  57900. }
  57901. try {
  57902. // when when somebody has screwed with setTimeout but no I.E. maddness
  57903. return cachedClearTimeout(marker);
  57904. } catch (e){
  57905. try {
  57906. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  57907. return cachedClearTimeout.call(null, marker);
  57908. } catch (e){
  57909. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  57910. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  57911. return cachedClearTimeout.call(this, marker);
  57912. }
  57913. }
  57914. }
  57915. var queue = [];
  57916. var draining = false;
  57917. var currentQueue;
  57918. var queueIndex = -1;
  57919. function cleanUpNextTick() {
  57920. if (!draining || !currentQueue) {
  57921. return;
  57922. }
  57923. draining = false;
  57924. if (currentQueue.length) {
  57925. queue = currentQueue.concat(queue);
  57926. } else {
  57927. queueIndex = -1;
  57928. }
  57929. if (queue.length) {
  57930. drainQueue();
  57931. }
  57932. }
  57933. function drainQueue() {
  57934. if (draining) {
  57935. return;
  57936. }
  57937. var timeout = runTimeout(cleanUpNextTick);
  57938. draining = true;
  57939. var len = queue.length;
  57940. while(len) {
  57941. currentQueue = queue;
  57942. queue = [];
  57943. while (++queueIndex < len) {
  57944. if (currentQueue) {
  57945. currentQueue[queueIndex].run();
  57946. }
  57947. }
  57948. queueIndex = -1;
  57949. len = queue.length;
  57950. }
  57951. currentQueue = null;
  57952. draining = false;
  57953. runClearTimeout(timeout);
  57954. }
  57955. process.nextTick = function (fun) {
  57956. var args = new Array(arguments.length - 1);
  57957. if (arguments.length > 1) {
  57958. for (var i = 1; i < arguments.length; i++) {
  57959. args[i - 1] = arguments[i];
  57960. }
  57961. }
  57962. queue.push(new Item(fun, args));
  57963. if (queue.length === 1 && !draining) {
  57964. runTimeout(drainQueue);
  57965. }
  57966. };
  57967. // v8 likes predictible objects
  57968. function Item(fun, array) {
  57969. this.fun = fun;
  57970. this.array = array;
  57971. }
  57972. Item.prototype.run = function () {
  57973. this.fun.apply(null, this.array);
  57974. };
  57975. process.title = 'browser';
  57976. process.browser = true;
  57977. process.env = {};
  57978. process.argv = [];
  57979. process.version = ''; // empty string to avoid regexp issues
  57980. process.versions = {};
  57981. function noop() {}
  57982. process.on = noop;
  57983. process.addListener = noop;
  57984. process.once = noop;
  57985. process.off = noop;
  57986. process.removeListener = noop;
  57987. process.removeAllListeners = noop;
  57988. process.emit = noop;
  57989. process.prependListener = noop;
  57990. process.prependOnceListener = noop;
  57991. process.listeners = function (name) { return [] }
  57992. process.binding = function (name) {
  57993. throw new Error('process.binding is not supported');
  57994. };
  57995. process.cwd = function () { return '/' };
  57996. process.chdir = function (dir) {
  57997. throw new Error('process.chdir is not supported');
  57998. };
  57999. process.umask = function() { return 0; };
  58000. },{}],216:[function(require,module,exports){
  58001. // minimal library entry point.
  58002. "use strict";
  58003. module.exports = require("./src/index-minimal");
  58004. },{"./src/index-minimal":217}],217:[function(require,module,exports){
  58005. "use strict";
  58006. var protobuf = exports;
  58007. /**
  58008. * Build type, one of `"full"`, `"light"` or `"minimal"`.
  58009. * @name build
  58010. * @type {string}
  58011. * @const
  58012. */
  58013. protobuf.build = "minimal";
  58014. // Serialization
  58015. protobuf.Writer = require("./writer");
  58016. protobuf.BufferWriter = require("./writer_buffer");
  58017. protobuf.Reader = require("./reader");
  58018. protobuf.BufferReader = require("./reader_buffer");
  58019. // Utility
  58020. protobuf.util = require("./util/minimal");
  58021. protobuf.rpc = require("./rpc");
  58022. protobuf.roots = require("./roots");
  58023. protobuf.configure = configure;
  58024. /* istanbul ignore next */
  58025. /**
  58026. * Reconfigures the library according to the environment.
  58027. * @returns {undefined}
  58028. */
  58029. function configure() {
  58030. protobuf.Reader._configure(protobuf.BufferReader);
  58031. protobuf.util._configure();
  58032. }
  58033. // Set up buffer utility according to the environment
  58034. protobuf.Writer._configure(protobuf.BufferWriter);
  58035. configure();
  58036. },{"./reader":218,"./reader_buffer":219,"./roots":220,"./rpc":221,"./util/minimal":224,"./writer":225,"./writer_buffer":226}],218:[function(require,module,exports){
  58037. "use strict";
  58038. module.exports = Reader;
  58039. var util = require("./util/minimal");
  58040. var BufferReader; // cyclic
  58041. var LongBits = util.LongBits,
  58042. utf8 = util.utf8;
  58043. /* istanbul ignore next */
  58044. function indexOutOfRange(reader, writeLength) {
  58045. return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
  58046. }
  58047. /**
  58048. * Constructs a new reader instance using the specified buffer.
  58049. * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
  58050. * @constructor
  58051. * @param {Uint8Array} buffer Buffer to read from
  58052. */
  58053. function Reader(buffer) {
  58054. /**
  58055. * Read buffer.
  58056. * @type {Uint8Array}
  58057. */
  58058. this.buf = buffer;
  58059. /**
  58060. * Read buffer position.
  58061. * @type {number}
  58062. */
  58063. this.pos = 0;
  58064. /**
  58065. * Read buffer length.
  58066. * @type {number}
  58067. */
  58068. this.len = buffer.length;
  58069. }
  58070. var create_array = typeof Uint8Array !== "undefined"
  58071. ? function create_typed_array(buffer) {
  58072. if (buffer instanceof Uint8Array || Array.isArray(buffer))
  58073. return new Reader(buffer);
  58074. throw Error("illegal buffer");
  58075. }
  58076. /* istanbul ignore next */
  58077. : function create_array(buffer) {
  58078. if (Array.isArray(buffer))
  58079. return new Reader(buffer);
  58080. throw Error("illegal buffer");
  58081. };
  58082. /**
  58083. * Creates a new reader using the specified buffer.
  58084. * @function
  58085. * @param {Uint8Array|Buffer} buffer Buffer to read from
  58086. * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
  58087. * @throws {Error} If `buffer` is not a valid buffer
  58088. */
  58089. Reader.create = util.Buffer
  58090. ? function create_buffer_setup(buffer) {
  58091. return (Reader.create = function create_buffer(buffer) {
  58092. return util.Buffer.isBuffer(buffer)
  58093. ? new BufferReader(buffer)
  58094. /* istanbul ignore next */
  58095. : create_array(buffer);
  58096. })(buffer);
  58097. }
  58098. /* istanbul ignore next */
  58099. : create_array;
  58100. Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;
  58101. /**
  58102. * Reads a varint as an unsigned 32 bit value.
  58103. * @function
  58104. * @returns {number} Value read
  58105. */
  58106. Reader.prototype.uint32 = (function read_uint32_setup() {
  58107. var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
  58108. return function read_uint32() {
  58109. value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;
  58110. value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;
  58111. value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;
  58112. value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;
  58113. value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;
  58114. /* istanbul ignore if */
  58115. if ((this.pos += 5) > this.len) {
  58116. this.pos = this.len;
  58117. throw indexOutOfRange(this, 10);
  58118. }
  58119. return value;
  58120. };
  58121. })();
  58122. /**
  58123. * Reads a varint as a signed 32 bit value.
  58124. * @returns {number} Value read
  58125. */
  58126. Reader.prototype.int32 = function read_int32() {
  58127. return this.uint32() | 0;
  58128. };
  58129. /**
  58130. * Reads a zig-zag encoded varint as a signed 32 bit value.
  58131. * @returns {number} Value read
  58132. */
  58133. Reader.prototype.sint32 = function read_sint32() {
  58134. var value = this.uint32();
  58135. return value >>> 1 ^ -(value & 1) | 0;
  58136. };
  58137. /* eslint-disable no-invalid-this */
  58138. function readLongVarint() {
  58139. // tends to deopt with local vars for octet etc.
  58140. var bits = new LongBits(0, 0);
  58141. var i = 0;
  58142. if (this.len - this.pos > 4) { // fast route (lo)
  58143. for (; i < 4; ++i) {
  58144. // 1st..4th
  58145. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
  58146. if (this.buf[this.pos++] < 128)
  58147. return bits;
  58148. }
  58149. // 5th
  58150. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
  58151. bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
  58152. if (this.buf[this.pos++] < 128)
  58153. return bits;
  58154. i = 0;
  58155. } else {
  58156. for (; i < 3; ++i) {
  58157. /* istanbul ignore if */
  58158. if (this.pos >= this.len)
  58159. throw indexOutOfRange(this);
  58160. // 1st..3th
  58161. bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
  58162. if (this.buf[this.pos++] < 128)
  58163. return bits;
  58164. }
  58165. // 4th
  58166. bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
  58167. return bits;
  58168. }
  58169. if (this.len - this.pos > 4) { // fast route (hi)
  58170. for (; i < 5; ++i) {
  58171. // 6th..10th
  58172. bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
  58173. if (this.buf[this.pos++] < 128)
  58174. return bits;
  58175. }
  58176. } else {
  58177. for (; i < 5; ++i) {
  58178. /* istanbul ignore if */
  58179. if (this.pos >= this.len)
  58180. throw indexOutOfRange(this);
  58181. // 6th..10th
  58182. bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
  58183. if (this.buf[this.pos++] < 128)
  58184. return bits;
  58185. }
  58186. }
  58187. /* istanbul ignore next */
  58188. throw Error("invalid varint encoding");
  58189. }
  58190. /* eslint-enable no-invalid-this */
  58191. /**
  58192. * Reads a varint as a signed 64 bit value.
  58193. * @name Reader#int64
  58194. * @function
  58195. * @returns {Long} Value read
  58196. */
  58197. /**
  58198. * Reads a varint as an unsigned 64 bit value.
  58199. * @name Reader#uint64
  58200. * @function
  58201. * @returns {Long} Value read
  58202. */
  58203. /**
  58204. * Reads a zig-zag encoded varint as a signed 64 bit value.
  58205. * @name Reader#sint64
  58206. * @function
  58207. * @returns {Long} Value read
  58208. */
  58209. /**
  58210. * Reads a varint as a boolean.
  58211. * @returns {boolean} Value read
  58212. */
  58213. Reader.prototype.bool = function read_bool() {
  58214. return this.uint32() !== 0;
  58215. };
  58216. function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
  58217. return (buf[end - 4]
  58218. | buf[end - 3] << 8
  58219. | buf[end - 2] << 16
  58220. | buf[end - 1] << 24) >>> 0;
  58221. }
  58222. /**
  58223. * Reads fixed 32 bits as an unsigned 32 bit integer.
  58224. * @returns {number} Value read
  58225. */
  58226. Reader.prototype.fixed32 = function read_fixed32() {
  58227. /* istanbul ignore if */
  58228. if (this.pos + 4 > this.len)
  58229. throw indexOutOfRange(this, 4);
  58230. return readFixed32_end(this.buf, this.pos += 4);
  58231. };
  58232. /**
  58233. * Reads fixed 32 bits as a signed 32 bit integer.
  58234. * @returns {number} Value read
  58235. */
  58236. Reader.prototype.sfixed32 = function read_sfixed32() {
  58237. /* istanbul ignore if */
  58238. if (this.pos + 4 > this.len)
  58239. throw indexOutOfRange(this, 4);
  58240. return readFixed32_end(this.buf, this.pos += 4) | 0;
  58241. };
  58242. /* eslint-disable no-invalid-this */
  58243. function readFixed64(/* this: Reader */) {
  58244. /* istanbul ignore if */
  58245. if (this.pos + 8 > this.len)
  58246. throw indexOutOfRange(this, 8);
  58247. return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
  58248. }
  58249. /* eslint-enable no-invalid-this */
  58250. /**
  58251. * Reads fixed 64 bits.
  58252. * @name Reader#fixed64
  58253. * @function
  58254. * @returns {Long} Value read
  58255. */
  58256. /**
  58257. * Reads zig-zag encoded fixed 64 bits.
  58258. * @name Reader#sfixed64
  58259. * @function
  58260. * @returns {Long} Value read
  58261. */
  58262. /**
  58263. * Reads a float (32 bit) as a number.
  58264. * @function
  58265. * @returns {number} Value read
  58266. */
  58267. Reader.prototype.float = function read_float() {
  58268. /* istanbul ignore if */
  58269. if (this.pos + 4 > this.len)
  58270. throw indexOutOfRange(this, 4);
  58271. var value = util.float.readFloatLE(this.buf, this.pos);
  58272. this.pos += 4;
  58273. return value;
  58274. };
  58275. /**
  58276. * Reads a double (64 bit float) as a number.
  58277. * @function
  58278. * @returns {number} Value read
  58279. */
  58280. Reader.prototype.double = function read_double() {
  58281. /* istanbul ignore if */
  58282. if (this.pos + 8 > this.len)
  58283. throw indexOutOfRange(this, 4);
  58284. var value = util.float.readDoubleLE(this.buf, this.pos);
  58285. this.pos += 8;
  58286. return value;
  58287. };
  58288. /**
  58289. * Reads a sequence of bytes preceeded by its length as a varint.
  58290. * @returns {Uint8Array} Value read
  58291. */
  58292. Reader.prototype.bytes = function read_bytes() {
  58293. var length = this.uint32(),
  58294. start = this.pos,
  58295. end = this.pos + length;
  58296. /* istanbul ignore if */
  58297. if (end > this.len)
  58298. throw indexOutOfRange(this, length);
  58299. this.pos += length;
  58300. if (Array.isArray(this.buf)) // plain array
  58301. return this.buf.slice(start, end);
  58302. return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
  58303. ? new this.buf.constructor(0)
  58304. : this._slice.call(this.buf, start, end);
  58305. };
  58306. /**
  58307. * Reads a string preceeded by its byte length as a varint.
  58308. * @returns {string} Value read
  58309. */
  58310. Reader.prototype.string = function read_string() {
  58311. var bytes = this.bytes();
  58312. return utf8.read(bytes, 0, bytes.length);
  58313. };
  58314. /**
  58315. * Skips the specified number of bytes if specified, otherwise skips a varint.
  58316. * @param {number} [length] Length if known, otherwise a varint is assumed
  58317. * @returns {Reader} `this`
  58318. */
  58319. Reader.prototype.skip = function skip(length) {
  58320. if (typeof length === "number") {
  58321. /* istanbul ignore if */
  58322. if (this.pos + length > this.len)
  58323. throw indexOutOfRange(this, length);
  58324. this.pos += length;
  58325. } else {
  58326. do {
  58327. /* istanbul ignore if */
  58328. if (this.pos >= this.len)
  58329. throw indexOutOfRange(this);
  58330. } while (this.buf[this.pos++] & 128);
  58331. }
  58332. return this;
  58333. };
  58334. /**
  58335. * Skips the next element of the specified wire type.
  58336. * @param {number} wireType Wire type received
  58337. * @returns {Reader} `this`
  58338. */
  58339. Reader.prototype.skipType = function(wireType) {
  58340. switch (wireType) {
  58341. case 0:
  58342. this.skip();
  58343. break;
  58344. case 1:
  58345. this.skip(8);
  58346. break;
  58347. case 2:
  58348. this.skip(this.uint32());
  58349. break;
  58350. case 3:
  58351. while ((wireType = this.uint32() & 7) !== 4) {
  58352. this.skipType(wireType);
  58353. }
  58354. break;
  58355. case 5:
  58356. this.skip(4);
  58357. break;
  58358. /* istanbul ignore next */
  58359. default:
  58360. throw Error("invalid wire type " + wireType + " at offset " + this.pos);
  58361. }
  58362. return this;
  58363. };
  58364. Reader._configure = function(BufferReader_) {
  58365. BufferReader = BufferReader_;
  58366. var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
  58367. util.merge(Reader.prototype, {
  58368. int64: function read_int64() {
  58369. return readLongVarint.call(this)[fn](false);
  58370. },
  58371. uint64: function read_uint64() {
  58372. return readLongVarint.call(this)[fn](true);
  58373. },
  58374. sint64: function read_sint64() {
  58375. return readLongVarint.call(this).zzDecode()[fn](false);
  58376. },
  58377. fixed64: function read_fixed64() {
  58378. return readFixed64.call(this)[fn](true);
  58379. },
  58380. sfixed64: function read_sfixed64() {
  58381. return readFixed64.call(this)[fn](false);
  58382. }
  58383. });
  58384. };
  58385. },{"./util/minimal":224}],219:[function(require,module,exports){
  58386. "use strict";
  58387. module.exports = BufferReader;
  58388. // extends Reader
  58389. var Reader = require("./reader");
  58390. (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
  58391. var util = require("./util/minimal");
  58392. /**
  58393. * Constructs a new buffer reader instance.
  58394. * @classdesc Wire format reader using node buffers.
  58395. * @extends Reader
  58396. * @constructor
  58397. * @param {Buffer} buffer Buffer to read from
  58398. */
  58399. function BufferReader(buffer) {
  58400. Reader.call(this, buffer);
  58401. /**
  58402. * Read buffer.
  58403. * @name BufferReader#buf
  58404. * @type {Buffer}
  58405. */
  58406. }
  58407. /* istanbul ignore else */
  58408. if (util.Buffer)
  58409. BufferReader.prototype._slice = util.Buffer.prototype.slice;
  58410. /**
  58411. * @override
  58412. */
  58413. BufferReader.prototype.string = function read_string_buffer() {
  58414. var len = this.uint32(); // modifies pos
  58415. return this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len));
  58416. };
  58417. /**
  58418. * Reads a sequence of bytes preceeded by its length as a varint.
  58419. * @name BufferReader#bytes
  58420. * @function
  58421. * @returns {Buffer} Value read
  58422. */
  58423. },{"./reader":218,"./util/minimal":224}],220:[function(require,module,exports){
  58424. "use strict";
  58425. module.exports = {};
  58426. /**
  58427. * Named roots.
  58428. * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
  58429. * Can also be used manually to make roots available accross modules.
  58430. * @name roots
  58431. * @type {Object.<string,Root>}
  58432. * @example
  58433. * // pbjs -r myroot -o compiled.js ...
  58434. *
  58435. * // in another module:
  58436. * require("./compiled.js");
  58437. *
  58438. * // in any subsequent module:
  58439. * var root = protobuf.roots["myroot"];
  58440. */
  58441. },{}],221:[function(require,module,exports){
  58442. "use strict";
  58443. /**
  58444. * Streaming RPC helpers.
  58445. * @namespace
  58446. */
  58447. var rpc = exports;
  58448. /**
  58449. * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
  58450. * @typedef RPCImpl
  58451. * @type {function}
  58452. * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
  58453. * @param {Uint8Array} requestData Request data
  58454. * @param {RPCImplCallback} callback Callback function
  58455. * @returns {undefined}
  58456. * @example
  58457. * function rpcImpl(method, requestData, callback) {
  58458. * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
  58459. * throw Error("no such method");
  58460. * asynchronouslyObtainAResponse(requestData, function(err, responseData) {
  58461. * callback(err, responseData);
  58462. * });
  58463. * }
  58464. */
  58465. /**
  58466. * Node-style callback as used by {@link RPCImpl}.
  58467. * @typedef RPCImplCallback
  58468. * @type {function}
  58469. * @param {Error|null} error Error, if any, otherwise `null`
  58470. * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
  58471. * @returns {undefined}
  58472. */
  58473. rpc.Service = require("./rpc/service");
  58474. },{"./rpc/service":222}],222:[function(require,module,exports){
  58475. "use strict";
  58476. module.exports = Service;
  58477. var util = require("../util/minimal");
  58478. // Extends EventEmitter
  58479. (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
  58480. /**
  58481. * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
  58482. *
  58483. * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
  58484. * @typedef rpc.ServiceMethodCallback
  58485. * @template TRes extends Message<TRes>
  58486. * @type {function}
  58487. * @param {Error|null} error Error, if any
  58488. * @param {TRes} [response] Response message
  58489. * @returns {undefined}
  58490. */
  58491. /**
  58492. * A service method part of a {@link rpc.Service} as created by {@link Service.create}.
  58493. * @typedef rpc.ServiceMethod
  58494. * @template TReq extends Message<TReq>
  58495. * @template TRes extends Message<TRes>
  58496. * @type {function}
  58497. * @param {TReq|Properties<TReq>} request Request message or plain object
  58498. * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message
  58499. * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`
  58500. */
  58501. /**
  58502. * Constructs a new RPC service instance.
  58503. * @classdesc An RPC service as returned by {@link Service#create}.
  58504. * @exports rpc.Service
  58505. * @extends util.EventEmitter
  58506. * @constructor
  58507. * @param {RPCImpl} rpcImpl RPC implementation
  58508. * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
  58509. * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
  58510. */
  58511. function Service(rpcImpl, requestDelimited, responseDelimited) {
  58512. if (typeof rpcImpl !== "function")
  58513. throw TypeError("rpcImpl must be a function");
  58514. util.EventEmitter.call(this);
  58515. /**
  58516. * RPC implementation. Becomes `null` once the service is ended.
  58517. * @type {RPCImpl|null}
  58518. */
  58519. this.rpcImpl = rpcImpl;
  58520. /**
  58521. * Whether requests are length-delimited.
  58522. * @type {boolean}
  58523. */
  58524. this.requestDelimited = Boolean(requestDelimited);
  58525. /**
  58526. * Whether responses are length-delimited.
  58527. * @type {boolean}
  58528. */
  58529. this.responseDelimited = Boolean(responseDelimited);
  58530. }
  58531. /**
  58532. * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
  58533. * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
  58534. * @param {Constructor<TReq>} requestCtor Request constructor
  58535. * @param {Constructor<TRes>} responseCtor Response constructor
  58536. * @param {TReq|Properties<TReq>} request Request message or plain object
  58537. * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
  58538. * @returns {undefined}
  58539. * @template TReq extends Message<TReq>
  58540. * @template TRes extends Message<TRes>
  58541. */
  58542. Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
  58543. if (!request)
  58544. throw TypeError("request must be specified");
  58545. var self = this;
  58546. if (!callback)
  58547. return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);
  58548. if (!self.rpcImpl) {
  58549. setTimeout(function() { callback(Error("already ended")); }, 0);
  58550. return undefined;
  58551. }
  58552. try {
  58553. return self.rpcImpl(
  58554. method,
  58555. requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
  58556. function rpcCallback(err, response) {
  58557. if (err) {
  58558. self.emit("error", err, method);
  58559. return callback(err);
  58560. }
  58561. if (response === null) {
  58562. self.end(/* endedByRPC */ true);
  58563. return undefined;
  58564. }
  58565. if (!(response instanceof responseCtor)) {
  58566. try {
  58567. response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
  58568. } catch (err) {
  58569. self.emit("error", err, method);
  58570. return callback(err);
  58571. }
  58572. }
  58573. self.emit("data", response, method);
  58574. return callback(null, response);
  58575. }
  58576. );
  58577. } catch (err) {
  58578. self.emit("error", err, method);
  58579. setTimeout(function() { callback(err); }, 0);
  58580. return undefined;
  58581. }
  58582. };
  58583. /**
  58584. * Ends this service and emits the `end` event.
  58585. * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
  58586. * @returns {rpc.Service} `this`
  58587. */
  58588. Service.prototype.end = function end(endedByRPC) {
  58589. if (this.rpcImpl) {
  58590. if (!endedByRPC) // signal end to rpcImpl
  58591. this.rpcImpl(null, null, null);
  58592. this.rpcImpl = null;
  58593. this.emit("end").off();
  58594. }
  58595. return this;
  58596. };
  58597. },{"../util/minimal":224}],223:[function(require,module,exports){
  58598. "use strict";
  58599. module.exports = LongBits;
  58600. var util = require("../util/minimal");
  58601. /**
  58602. * Constructs new long bits.
  58603. * @classdesc Helper class for working with the low and high bits of a 64 bit value.
  58604. * @memberof util
  58605. * @constructor
  58606. * @param {number} lo Low 32 bits, unsigned
  58607. * @param {number} hi High 32 bits, unsigned
  58608. */
  58609. function LongBits(lo, hi) {
  58610. // note that the casts below are theoretically unnecessary as of today, but older statically
  58611. // generated converter code might still call the ctor with signed 32bits. kept for compat.
  58612. /**
  58613. * Low bits.
  58614. * @type {number}
  58615. */
  58616. this.lo = lo >>> 0;
  58617. /**
  58618. * High bits.
  58619. * @type {number}
  58620. */
  58621. this.hi = hi >>> 0;
  58622. }
  58623. /**
  58624. * Zero bits.
  58625. * @memberof util.LongBits
  58626. * @type {util.LongBits}
  58627. */
  58628. var zero = LongBits.zero = new LongBits(0, 0);
  58629. zero.toNumber = function() { return 0; };
  58630. zero.zzEncode = zero.zzDecode = function() { return this; };
  58631. zero.length = function() { return 1; };
  58632. /**
  58633. * Zero hash.
  58634. * @memberof util.LongBits
  58635. * @type {string}
  58636. */
  58637. var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
  58638. /**
  58639. * Constructs new long bits from the specified number.
  58640. * @param {number} value Value
  58641. * @returns {util.LongBits} Instance
  58642. */
  58643. LongBits.fromNumber = function fromNumber(value) {
  58644. if (value === 0)
  58645. return zero;
  58646. var sign = value < 0;
  58647. if (sign)
  58648. value = -value;
  58649. var lo = value >>> 0,
  58650. hi = (value - lo) / 4294967296 >>> 0;
  58651. if (sign) {
  58652. hi = ~hi >>> 0;
  58653. lo = ~lo >>> 0;
  58654. if (++lo > 4294967295) {
  58655. lo = 0;
  58656. if (++hi > 4294967295)
  58657. hi = 0;
  58658. }
  58659. }
  58660. return new LongBits(lo, hi);
  58661. };
  58662. /**
  58663. * Constructs new long bits from a number, long or string.
  58664. * @param {Long|number|string} value Value
  58665. * @returns {util.LongBits} Instance
  58666. */
  58667. LongBits.from = function from(value) {
  58668. if (typeof value === "number")
  58669. return LongBits.fromNumber(value);
  58670. if (util.isString(value)) {
  58671. /* istanbul ignore else */
  58672. if (util.Long)
  58673. value = util.Long.fromString(value);
  58674. else
  58675. return LongBits.fromNumber(parseInt(value, 10));
  58676. }
  58677. return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
  58678. };
  58679. /**
  58680. * Converts this long bits to a possibly unsafe JavaScript number.
  58681. * @param {boolean} [unsigned=false] Whether unsigned or not
  58682. * @returns {number} Possibly unsafe number
  58683. */
  58684. LongBits.prototype.toNumber = function toNumber(unsigned) {
  58685. if (!unsigned && this.hi >>> 31) {
  58686. var lo = ~this.lo + 1 >>> 0,
  58687. hi = ~this.hi >>> 0;
  58688. if (!lo)
  58689. hi = hi + 1 >>> 0;
  58690. return -(lo + hi * 4294967296);
  58691. }
  58692. return this.lo + this.hi * 4294967296;
  58693. };
  58694. /**
  58695. * Converts this long bits to a long.
  58696. * @param {boolean} [unsigned=false] Whether unsigned or not
  58697. * @returns {Long} Long
  58698. */
  58699. LongBits.prototype.toLong = function toLong(unsigned) {
  58700. return util.Long
  58701. ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
  58702. /* istanbul ignore next */
  58703. : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
  58704. };
  58705. var charCodeAt = String.prototype.charCodeAt;
  58706. /**
  58707. * Constructs new long bits from the specified 8 characters long hash.
  58708. * @param {string} hash Hash
  58709. * @returns {util.LongBits} Bits
  58710. */
  58711. LongBits.fromHash = function fromHash(hash) {
  58712. if (hash === zeroHash)
  58713. return zero;
  58714. return new LongBits(
  58715. ( charCodeAt.call(hash, 0)
  58716. | charCodeAt.call(hash, 1) << 8
  58717. | charCodeAt.call(hash, 2) << 16
  58718. | charCodeAt.call(hash, 3) << 24) >>> 0
  58719. ,
  58720. ( charCodeAt.call(hash, 4)
  58721. | charCodeAt.call(hash, 5) << 8
  58722. | charCodeAt.call(hash, 6) << 16
  58723. | charCodeAt.call(hash, 7) << 24) >>> 0
  58724. );
  58725. };
  58726. /**
  58727. * Converts this long bits to a 8 characters long hash.
  58728. * @returns {string} Hash
  58729. */
  58730. LongBits.prototype.toHash = function toHash() {
  58731. return String.fromCharCode(
  58732. this.lo & 255,
  58733. this.lo >>> 8 & 255,
  58734. this.lo >>> 16 & 255,
  58735. this.lo >>> 24 ,
  58736. this.hi & 255,
  58737. this.hi >>> 8 & 255,
  58738. this.hi >>> 16 & 255,
  58739. this.hi >>> 24
  58740. );
  58741. };
  58742. /**
  58743. * Zig-zag encodes this long bits.
  58744. * @returns {util.LongBits} `this`
  58745. */
  58746. LongBits.prototype.zzEncode = function zzEncode() {
  58747. var mask = this.hi >> 31;
  58748. this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
  58749. this.lo = ( this.lo << 1 ^ mask) >>> 0;
  58750. return this;
  58751. };
  58752. /**
  58753. * Zig-zag decodes this long bits.
  58754. * @returns {util.LongBits} `this`
  58755. */
  58756. LongBits.prototype.zzDecode = function zzDecode() {
  58757. var mask = -(this.lo & 1);
  58758. this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
  58759. this.hi = ( this.hi >>> 1 ^ mask) >>> 0;
  58760. return this;
  58761. };
  58762. /**
  58763. * Calculates the length of this longbits when encoded as a varint.
  58764. * @returns {number} Length
  58765. */
  58766. LongBits.prototype.length = function length() {
  58767. var part0 = this.lo,
  58768. part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
  58769. part2 = this.hi >>> 24;
  58770. return part2 === 0
  58771. ? part1 === 0
  58772. ? part0 < 16384
  58773. ? part0 < 128 ? 1 : 2
  58774. : part0 < 2097152 ? 3 : 4
  58775. : part1 < 16384
  58776. ? part1 < 128 ? 5 : 6
  58777. : part1 < 2097152 ? 7 : 8
  58778. : part2 < 128 ? 9 : 10;
  58779. };
  58780. },{"../util/minimal":224}],224:[function(require,module,exports){
  58781. (function (global){
  58782. "use strict";
  58783. var util = exports;
  58784. // used to return a Promise where callback is omitted
  58785. util.asPromise = require("@protobufjs/aspromise");
  58786. // converts to / from base64 encoded strings
  58787. util.base64 = require("@protobufjs/base64");
  58788. // base class of rpc.Service
  58789. util.EventEmitter = require("@protobufjs/eventemitter");
  58790. // float handling accross browsers
  58791. util.float = require("@protobufjs/float");
  58792. // requires modules optionally and hides the call from bundlers
  58793. util.inquire = require("@protobufjs/inquire");
  58794. // converts to / from utf8 encoded strings
  58795. util.utf8 = require("@protobufjs/utf8");
  58796. // provides a node-like buffer pool in the browser
  58797. util.pool = require("@protobufjs/pool");
  58798. // utility to work with the low and high bits of a 64 bit value
  58799. util.LongBits = require("./longbits");
  58800. // global object reference
  58801. util.global = typeof window !== "undefined" && window
  58802. || typeof global !== "undefined" && global
  58803. || typeof self !== "undefined" && self
  58804. || this; // eslint-disable-line no-invalid-this
  58805. /**
  58806. * An immuable empty array.
  58807. * @memberof util
  58808. * @type {Array.<*>}
  58809. * @const
  58810. */
  58811. util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes
  58812. /**
  58813. * An immutable empty object.
  58814. * @type {Object}
  58815. * @const
  58816. */
  58817. util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes
  58818. /**
  58819. * Whether running within node or not.
  58820. * @memberof util
  58821. * @type {boolean}
  58822. * @const
  58823. */
  58824. util.isNode = Boolean(util.global.process && util.global.process.versions && util.global.process.versions.node);
  58825. /**
  58826. * Tests if the specified value is an integer.
  58827. * @function
  58828. * @param {*} value Value to test
  58829. * @returns {boolean} `true` if the value is an integer
  58830. */
  58831. util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
  58832. return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
  58833. };
  58834. /**
  58835. * Tests if the specified value is a string.
  58836. * @param {*} value Value to test
  58837. * @returns {boolean} `true` if the value is a string
  58838. */
  58839. util.isString = function isString(value) {
  58840. return typeof value === "string" || value instanceof String;
  58841. };
  58842. /**
  58843. * Tests if the specified value is a non-null object.
  58844. * @param {*} value Value to test
  58845. * @returns {boolean} `true` if the value is a non-null object
  58846. */
  58847. util.isObject = function isObject(value) {
  58848. return value && typeof value === "object";
  58849. };
  58850. /**
  58851. * Checks if a property on a message is considered to be present.
  58852. * This is an alias of {@link util.isSet}.
  58853. * @function
  58854. * @param {Object} obj Plain object or message instance
  58855. * @param {string} prop Property name
  58856. * @returns {boolean} `true` if considered to be present, otherwise `false`
  58857. */
  58858. util.isset =
  58859. /**
  58860. * Checks if a property on a message is considered to be present.
  58861. * @param {Object} obj Plain object or message instance
  58862. * @param {string} prop Property name
  58863. * @returns {boolean} `true` if considered to be present, otherwise `false`
  58864. */
  58865. util.isSet = function isSet(obj, prop) {
  58866. var value = obj[prop];
  58867. if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins
  58868. return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
  58869. return false;
  58870. };
  58871. /**
  58872. * Any compatible Buffer instance.
  58873. * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
  58874. * @interface Buffer
  58875. * @extends Uint8Array
  58876. */
  58877. /**
  58878. * Node's Buffer class if available.
  58879. * @type {Constructor<Buffer>}
  58880. */
  58881. util.Buffer = (function() {
  58882. try {
  58883. var Buffer = util.inquire("buffer").Buffer;
  58884. // refuse to use non-node buffers if not explicitly assigned (perf reasons):
  58885. return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
  58886. } catch (e) {
  58887. /* istanbul ignore next */
  58888. return null;
  58889. }
  58890. })();
  58891. // Internal alias of or polyfull for Buffer.from.
  58892. util._Buffer_from = null;
  58893. // Internal alias of or polyfill for Buffer.allocUnsafe.
  58894. util._Buffer_allocUnsafe = null;
  58895. /**
  58896. * Creates a new buffer of whatever type supported by the environment.
  58897. * @param {number|number[]} [sizeOrArray=0] Buffer size or number array
  58898. * @returns {Uint8Array|Buffer} Buffer
  58899. */
  58900. util.newBuffer = function newBuffer(sizeOrArray) {
  58901. /* istanbul ignore next */
  58902. return typeof sizeOrArray === "number"
  58903. ? util.Buffer
  58904. ? util._Buffer_allocUnsafe(sizeOrArray)
  58905. : new util.Array(sizeOrArray)
  58906. : util.Buffer
  58907. ? util._Buffer_from(sizeOrArray)
  58908. : typeof Uint8Array === "undefined"
  58909. ? sizeOrArray
  58910. : new Uint8Array(sizeOrArray);
  58911. };
  58912. /**
  58913. * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
  58914. * @type {Constructor<Uint8Array>}
  58915. */
  58916. util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;
  58917. /**
  58918. * Any compatible Long instance.
  58919. * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
  58920. * @interface Long
  58921. * @property {number} low Low bits
  58922. * @property {number} high High bits
  58923. * @property {boolean} unsigned Whether unsigned or not
  58924. */
  58925. /**
  58926. * Long.js's Long class if available.
  58927. * @type {Constructor<Long>}
  58928. */
  58929. util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long
  58930. || /* istanbul ignore next */ util.global.Long
  58931. || util.inquire("long");
  58932. /**
  58933. * Regular expression used to verify 2 bit (`bool`) map keys.
  58934. * @type {RegExp}
  58935. * @const
  58936. */
  58937. util.key2Re = /^true|false|0|1$/;
  58938. /**
  58939. * Regular expression used to verify 32 bit (`int32` etc.) map keys.
  58940. * @type {RegExp}
  58941. * @const
  58942. */
  58943. util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
  58944. /**
  58945. * Regular expression used to verify 64 bit (`int64` etc.) map keys.
  58946. * @type {RegExp}
  58947. * @const
  58948. */
  58949. util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
  58950. /**
  58951. * Converts a number or long to an 8 characters long hash string.
  58952. * @param {Long|number} value Value to convert
  58953. * @returns {string} Hash
  58954. */
  58955. util.longToHash = function longToHash(value) {
  58956. return value
  58957. ? util.LongBits.from(value).toHash()
  58958. : util.LongBits.zeroHash;
  58959. };
  58960. /**
  58961. * Converts an 8 characters long hash string to a long or number.
  58962. * @param {string} hash Hash
  58963. * @param {boolean} [unsigned=false] Whether unsigned or not
  58964. * @returns {Long|number} Original value
  58965. */
  58966. util.longFromHash = function longFromHash(hash, unsigned) {
  58967. var bits = util.LongBits.fromHash(hash);
  58968. if (util.Long)
  58969. return util.Long.fromBits(bits.lo, bits.hi, unsigned);
  58970. return bits.toNumber(Boolean(unsigned));
  58971. };
  58972. /**
  58973. * Merges the properties of the source object into the destination object.
  58974. * @memberof util
  58975. * @param {Object.<string,*>} dst Destination object
  58976. * @param {Object.<string,*>} src Source object
  58977. * @param {boolean} [ifNotSet=false] Merges only if the key is not already set
  58978. * @returns {Object.<string,*>} Destination object
  58979. */
  58980. function merge(dst, src, ifNotSet) { // used by converters
  58981. for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
  58982. if (dst[keys[i]] === undefined || !ifNotSet)
  58983. dst[keys[i]] = src[keys[i]];
  58984. return dst;
  58985. }
  58986. util.merge = merge;
  58987. /**
  58988. * Converts the first character of a string to lower case.
  58989. * @param {string} str String to convert
  58990. * @returns {string} Converted string
  58991. */
  58992. util.lcFirst = function lcFirst(str) {
  58993. return str.charAt(0).toLowerCase() + str.substring(1);
  58994. };
  58995. /**
  58996. * Creates a custom error constructor.
  58997. * @memberof util
  58998. * @param {string} name Error name
  58999. * @returns {Constructor<Error>} Custom error constructor
  59000. */
  59001. function newError(name) {
  59002. function CustomError(message, properties) {
  59003. if (!(this instanceof CustomError))
  59004. return new CustomError(message, properties);
  59005. // Error.call(this, message);
  59006. // ^ just returns a new error instance because the ctor can be called as a function
  59007. Object.defineProperty(this, "message", { get: function() { return message; } });
  59008. /* istanbul ignore next */
  59009. if (Error.captureStackTrace) // node
  59010. Error.captureStackTrace(this, CustomError);
  59011. else
  59012. Object.defineProperty(this, "stack", { value: (new Error()).stack || "" });
  59013. if (properties)
  59014. merge(this, properties);
  59015. }
  59016. (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;
  59017. Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });
  59018. CustomError.prototype.toString = function toString() {
  59019. return this.name + ": " + this.message;
  59020. };
  59021. return CustomError;
  59022. }
  59023. util.newError = newError;
  59024. /**
  59025. * Constructs a new protocol error.
  59026. * @classdesc Error subclass indicating a protocol specifc error.
  59027. * @memberof util
  59028. * @extends Error
  59029. * @template T extends Message<T>
  59030. * @constructor
  59031. * @param {string} message Error message
  59032. * @param {Object.<string,*>} [properties] Additional properties
  59033. * @example
  59034. * try {
  59035. * MyMessage.decode(someBuffer); // throws if required fields are missing
  59036. * } catch (e) {
  59037. * if (e instanceof ProtocolError && e.instance)
  59038. * console.log("decoded so far: " + JSON.stringify(e.instance));
  59039. * }
  59040. */
  59041. util.ProtocolError = newError("ProtocolError");
  59042. /**
  59043. * So far decoded message instance.
  59044. * @name util.ProtocolError#instance
  59045. * @type {Message<T>}
  59046. */
  59047. /**
  59048. * A OneOf getter as returned by {@link util.oneOfGetter}.
  59049. * @typedef OneOfGetter
  59050. * @type {function}
  59051. * @returns {string|undefined} Set field name, if any
  59052. */
  59053. /**
  59054. * Builds a getter for a oneof's present field name.
  59055. * @param {string[]} fieldNames Field names
  59056. * @returns {OneOfGetter} Unbound getter
  59057. */
  59058. util.oneOfGetter = function getOneOf(fieldNames) {
  59059. var fieldMap = {};
  59060. for (var i = 0; i < fieldNames.length; ++i)
  59061. fieldMap[fieldNames[i]] = 1;
  59062. /**
  59063. * @returns {string|undefined} Set field name, if any
  59064. * @this Object
  59065. * @ignore
  59066. */
  59067. return function() { // eslint-disable-line consistent-return
  59068. for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
  59069. if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
  59070. return keys[i];
  59071. };
  59072. };
  59073. /**
  59074. * A OneOf setter as returned by {@link util.oneOfSetter}.
  59075. * @typedef OneOfSetter
  59076. * @type {function}
  59077. * @param {string|undefined} value Field name
  59078. * @returns {undefined}
  59079. */
  59080. /**
  59081. * Builds a setter for a oneof's present field name.
  59082. * @param {string[]} fieldNames Field names
  59083. * @returns {OneOfSetter} Unbound setter
  59084. */
  59085. util.oneOfSetter = function setOneOf(fieldNames) {
  59086. /**
  59087. * @param {string} name Field name
  59088. * @returns {undefined}
  59089. * @this Object
  59090. * @ignore
  59091. */
  59092. return function(name) {
  59093. for (var i = 0; i < fieldNames.length; ++i)
  59094. if (fieldNames[i] !== name)
  59095. delete this[fieldNames[i]];
  59096. };
  59097. };
  59098. /**
  59099. * Default conversion options used for {@link Message#toJSON} implementations.
  59100. *
  59101. * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
  59102. *
  59103. * - Longs become strings
  59104. * - Enums become string keys
  59105. * - Bytes become base64 encoded strings
  59106. * - (Sub-)Messages become plain objects
  59107. * - Maps become plain objects with all string keys
  59108. * - Repeated fields become arrays
  59109. * - NaN and Infinity for float and double fields become strings
  59110. *
  59111. * @type {IConversionOptions}
  59112. * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
  59113. */
  59114. util.toJSONOptions = {
  59115. longs: String,
  59116. enums: String,
  59117. bytes: String,
  59118. json: true
  59119. };
  59120. // Sets up buffer utility according to the environment (called in index-minimal)
  59121. util._configure = function() {
  59122. var Buffer = util.Buffer;
  59123. /* istanbul ignore if */
  59124. if (!Buffer) {
  59125. util._Buffer_from = util._Buffer_allocUnsafe = null;
  59126. return;
  59127. }
  59128. // because node 4.x buffers are incompatible & immutable
  59129. // see: https://github.com/dcodeIO/protobuf.js/pull/665
  59130. util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
  59131. /* istanbul ignore next */
  59132. function Buffer_from(value, encoding) {
  59133. return new Buffer(value, encoding);
  59134. };
  59135. util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
  59136. /* istanbul ignore next */
  59137. function Buffer_allocUnsafe(size) {
  59138. return new Buffer(size);
  59139. };
  59140. };
  59141. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  59142. },{"./longbits":223,"@protobufjs/aspromise":1,"@protobufjs/base64":2,"@protobufjs/eventemitter":3,"@protobufjs/float":4,"@protobufjs/inquire":5,"@protobufjs/pool":6,"@protobufjs/utf8":7}],225:[function(require,module,exports){
  59143. "use strict";
  59144. module.exports = Writer;
  59145. var util = require("./util/minimal");
  59146. var BufferWriter; // cyclic
  59147. var LongBits = util.LongBits,
  59148. base64 = util.base64,
  59149. utf8 = util.utf8;
  59150. /**
  59151. * Constructs a new writer operation instance.
  59152. * @classdesc Scheduled writer operation.
  59153. * @constructor
  59154. * @param {function(*, Uint8Array, number)} fn Function to call
  59155. * @param {number} len Value byte length
  59156. * @param {*} val Value to write
  59157. * @ignore
  59158. */
  59159. function Op(fn, len, val) {
  59160. /**
  59161. * Function to call.
  59162. * @type {function(Uint8Array, number, *)}
  59163. */
  59164. this.fn = fn;
  59165. /**
  59166. * Value byte length.
  59167. * @type {number}
  59168. */
  59169. this.len = len;
  59170. /**
  59171. * Next operation.
  59172. * @type {Writer.Op|undefined}
  59173. */
  59174. this.next = undefined;
  59175. /**
  59176. * Value to write.
  59177. * @type {*}
  59178. */
  59179. this.val = val; // type varies
  59180. }
  59181. /* istanbul ignore next */
  59182. function noop() {} // eslint-disable-line no-empty-function
  59183. /**
  59184. * Constructs a new writer state instance.
  59185. * @classdesc Copied writer state.
  59186. * @memberof Writer
  59187. * @constructor
  59188. * @param {Writer} writer Writer to copy state from
  59189. * @ignore
  59190. */
  59191. function State(writer) {
  59192. /**
  59193. * Current head.
  59194. * @type {Writer.Op}
  59195. */
  59196. this.head = writer.head;
  59197. /**
  59198. * Current tail.
  59199. * @type {Writer.Op}
  59200. */
  59201. this.tail = writer.tail;
  59202. /**
  59203. * Current buffer length.
  59204. * @type {number}
  59205. */
  59206. this.len = writer.len;
  59207. /**
  59208. * Next state.
  59209. * @type {State|null}
  59210. */
  59211. this.next = writer.states;
  59212. }
  59213. /**
  59214. * Constructs a new writer instance.
  59215. * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
  59216. * @constructor
  59217. */
  59218. function Writer() {
  59219. /**
  59220. * Current length.
  59221. * @type {number}
  59222. */
  59223. this.len = 0;
  59224. /**
  59225. * Operations head.
  59226. * @type {Object}
  59227. */
  59228. this.head = new Op(noop, 0, 0);
  59229. /**
  59230. * Operations tail
  59231. * @type {Object}
  59232. */
  59233. this.tail = this.head;
  59234. /**
  59235. * Linked forked states.
  59236. * @type {Object|null}
  59237. */
  59238. this.states = null;
  59239. // When a value is written, the writer calculates its byte length and puts it into a linked
  59240. // list of operations to perform when finish() is called. This both allows us to allocate
  59241. // buffers of the exact required size and reduces the amount of work we have to do compared
  59242. // to first calculating over objects and then encoding over objects. In our case, the encoding
  59243. // part is just a linked list walk calling operations with already prepared values.
  59244. }
  59245. /**
  59246. * Creates a new writer.
  59247. * @function
  59248. * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
  59249. */
  59250. Writer.create = util.Buffer
  59251. ? function create_buffer_setup() {
  59252. return (Writer.create = function create_buffer() {
  59253. return new BufferWriter();
  59254. })();
  59255. }
  59256. /* istanbul ignore next */
  59257. : function create_array() {
  59258. return new Writer();
  59259. };
  59260. /**
  59261. * Allocates a buffer of the specified size.
  59262. * @param {number} size Buffer size
  59263. * @returns {Uint8Array} Buffer
  59264. */
  59265. Writer.alloc = function alloc(size) {
  59266. return new util.Array(size);
  59267. };
  59268. // Use Uint8Array buffer pool in the browser, just like node does with buffers
  59269. /* istanbul ignore else */
  59270. if (util.Array !== Array)
  59271. Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
  59272. /**
  59273. * Pushes a new operation to the queue.
  59274. * @param {function(Uint8Array, number, *)} fn Function to call
  59275. * @param {number} len Value byte length
  59276. * @param {number} val Value to write
  59277. * @returns {Writer} `this`
  59278. * @private
  59279. */
  59280. Writer.prototype._push = function push(fn, len, val) {
  59281. this.tail = this.tail.next = new Op(fn, len, val);
  59282. this.len += len;
  59283. return this;
  59284. };
  59285. function writeByte(val, buf, pos) {
  59286. buf[pos] = val & 255;
  59287. }
  59288. function writeVarint32(val, buf, pos) {
  59289. while (val > 127) {
  59290. buf[pos++] = val & 127 | 128;
  59291. val >>>= 7;
  59292. }
  59293. buf[pos] = val;
  59294. }
  59295. /**
  59296. * Constructs a new varint writer operation instance.
  59297. * @classdesc Scheduled varint writer operation.
  59298. * @extends Op
  59299. * @constructor
  59300. * @param {number} len Value byte length
  59301. * @param {number} val Value to write
  59302. * @ignore
  59303. */
  59304. function VarintOp(len, val) {
  59305. this.len = len;
  59306. this.next = undefined;
  59307. this.val = val;
  59308. }
  59309. VarintOp.prototype = Object.create(Op.prototype);
  59310. VarintOp.prototype.fn = writeVarint32;
  59311. /**
  59312. * Writes an unsigned 32 bit value as a varint.
  59313. * @param {number} value Value to write
  59314. * @returns {Writer} `this`
  59315. */
  59316. Writer.prototype.uint32 = function write_uint32(value) {
  59317. // here, the call to this.push has been inlined and a varint specific Op subclass is used.
  59318. // uint32 is by far the most frequently used operation and benefits significantly from this.
  59319. this.len += (this.tail = this.tail.next = new VarintOp(
  59320. (value = value >>> 0)
  59321. < 128 ? 1
  59322. : value < 16384 ? 2
  59323. : value < 2097152 ? 3
  59324. : value < 268435456 ? 4
  59325. : 5,
  59326. value)).len;
  59327. return this;
  59328. };
  59329. /**
  59330. * Writes a signed 32 bit value as a varint.
  59331. * @function
  59332. * @param {number} value Value to write
  59333. * @returns {Writer} `this`
  59334. */
  59335. Writer.prototype.int32 = function write_int32(value) {
  59336. return value < 0
  59337. ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
  59338. : this.uint32(value);
  59339. };
  59340. /**
  59341. * Writes a 32 bit value as a varint, zig-zag encoded.
  59342. * @param {number} value Value to write
  59343. * @returns {Writer} `this`
  59344. */
  59345. Writer.prototype.sint32 = function write_sint32(value) {
  59346. return this.uint32((value << 1 ^ value >> 31) >>> 0);
  59347. };
  59348. function writeVarint64(val, buf, pos) {
  59349. while (val.hi) {
  59350. buf[pos++] = val.lo & 127 | 128;
  59351. val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
  59352. val.hi >>>= 7;
  59353. }
  59354. while (val.lo > 127) {
  59355. buf[pos++] = val.lo & 127 | 128;
  59356. val.lo = val.lo >>> 7;
  59357. }
  59358. buf[pos++] = val.lo;
  59359. }
  59360. /**
  59361. * Writes an unsigned 64 bit value as a varint.
  59362. * @param {Long|number|string} value Value to write
  59363. * @returns {Writer} `this`
  59364. * @throws {TypeError} If `value` is a string and no long library is present.
  59365. */
  59366. Writer.prototype.uint64 = function write_uint64(value) {
  59367. var bits = LongBits.from(value);
  59368. return this._push(writeVarint64, bits.length(), bits);
  59369. };
  59370. /**
  59371. * Writes a signed 64 bit value as a varint.
  59372. * @function
  59373. * @param {Long|number|string} value Value to write
  59374. * @returns {Writer} `this`
  59375. * @throws {TypeError} If `value` is a string and no long library is present.
  59376. */
  59377. Writer.prototype.int64 = Writer.prototype.uint64;
  59378. /**
  59379. * Writes a signed 64 bit value as a varint, zig-zag encoded.
  59380. * @param {Long|number|string} value Value to write
  59381. * @returns {Writer} `this`
  59382. * @throws {TypeError} If `value` is a string and no long library is present.
  59383. */
  59384. Writer.prototype.sint64 = function write_sint64(value) {
  59385. var bits = LongBits.from(value).zzEncode();
  59386. return this._push(writeVarint64, bits.length(), bits);
  59387. };
  59388. /**
  59389. * Writes a boolish value as a varint.
  59390. * @param {boolean} value Value to write
  59391. * @returns {Writer} `this`
  59392. */
  59393. Writer.prototype.bool = function write_bool(value) {
  59394. return this._push(writeByte, 1, value ? 1 : 0);
  59395. };
  59396. function writeFixed32(val, buf, pos) {
  59397. buf[pos ] = val & 255;
  59398. buf[pos + 1] = val >>> 8 & 255;
  59399. buf[pos + 2] = val >>> 16 & 255;
  59400. buf[pos + 3] = val >>> 24;
  59401. }
  59402. /**
  59403. * Writes an unsigned 32 bit value as fixed 32 bits.
  59404. * @param {number} value Value to write
  59405. * @returns {Writer} `this`
  59406. */
  59407. Writer.prototype.fixed32 = function write_fixed32(value) {
  59408. return this._push(writeFixed32, 4, value >>> 0);
  59409. };
  59410. /**
  59411. * Writes a signed 32 bit value as fixed 32 bits.
  59412. * @function
  59413. * @param {number} value Value to write
  59414. * @returns {Writer} `this`
  59415. */
  59416. Writer.prototype.sfixed32 = Writer.prototype.fixed32;
  59417. /**
  59418. * Writes an unsigned 64 bit value as fixed 64 bits.
  59419. * @param {Long|number|string} value Value to write
  59420. * @returns {Writer} `this`
  59421. * @throws {TypeError} If `value` is a string and no long library is present.
  59422. */
  59423. Writer.prototype.fixed64 = function write_fixed64(value) {
  59424. var bits = LongBits.from(value);
  59425. return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
  59426. };
  59427. /**
  59428. * Writes a signed 64 bit value as fixed 64 bits.
  59429. * @function
  59430. * @param {Long|number|string} value Value to write
  59431. * @returns {Writer} `this`
  59432. * @throws {TypeError} If `value` is a string and no long library is present.
  59433. */
  59434. Writer.prototype.sfixed64 = Writer.prototype.fixed64;
  59435. /**
  59436. * Writes a float (32 bit).
  59437. * @function
  59438. * @param {number} value Value to write
  59439. * @returns {Writer} `this`
  59440. */
  59441. Writer.prototype.float = function write_float(value) {
  59442. return this._push(util.float.writeFloatLE, 4, value);
  59443. };
  59444. /**
  59445. * Writes a double (64 bit float).
  59446. * @function
  59447. * @param {number} value Value to write
  59448. * @returns {Writer} `this`
  59449. */
  59450. Writer.prototype.double = function write_double(value) {
  59451. return this._push(util.float.writeDoubleLE, 8, value);
  59452. };
  59453. var writeBytes = util.Array.prototype.set
  59454. ? function writeBytes_set(val, buf, pos) {
  59455. buf.set(val, pos); // also works for plain array values
  59456. }
  59457. /* istanbul ignore next */
  59458. : function writeBytes_for(val, buf, pos) {
  59459. for (var i = 0; i < val.length; ++i)
  59460. buf[pos + i] = val[i];
  59461. };
  59462. /**
  59463. * Writes a sequence of bytes.
  59464. * @param {Uint8Array|string} value Buffer or base64 encoded string to write
  59465. * @returns {Writer} `this`
  59466. */
  59467. Writer.prototype.bytes = function write_bytes(value) {
  59468. var len = value.length >>> 0;
  59469. if (!len)
  59470. return this._push(writeByte, 1, 0);
  59471. if (util.isString(value)) {
  59472. var buf = Writer.alloc(len = base64.length(value));
  59473. base64.decode(value, buf, 0);
  59474. value = buf;
  59475. }
  59476. return this.uint32(len)._push(writeBytes, len, value);
  59477. };
  59478. /**
  59479. * Writes a string.
  59480. * @param {string} value Value to write
  59481. * @returns {Writer} `this`
  59482. */
  59483. Writer.prototype.string = function write_string(value) {
  59484. var len = utf8.length(value);
  59485. return len
  59486. ? this.uint32(len)._push(utf8.write, len, value)
  59487. : this._push(writeByte, 1, 0);
  59488. };
  59489. /**
  59490. * Forks this writer's state by pushing it to a stack.
  59491. * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
  59492. * @returns {Writer} `this`
  59493. */
  59494. Writer.prototype.fork = function fork() {
  59495. this.states = new State(this);
  59496. this.head = this.tail = new Op(noop, 0, 0);
  59497. this.len = 0;
  59498. return this;
  59499. };
  59500. /**
  59501. * Resets this instance to the last state.
  59502. * @returns {Writer} `this`
  59503. */
  59504. Writer.prototype.reset = function reset() {
  59505. if (this.states) {
  59506. this.head = this.states.head;
  59507. this.tail = this.states.tail;
  59508. this.len = this.states.len;
  59509. this.states = this.states.next;
  59510. } else {
  59511. this.head = this.tail = new Op(noop, 0, 0);
  59512. this.len = 0;
  59513. }
  59514. return this;
  59515. };
  59516. /**
  59517. * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
  59518. * @returns {Writer} `this`
  59519. */
  59520. Writer.prototype.ldelim = function ldelim() {
  59521. var head = this.head,
  59522. tail = this.tail,
  59523. len = this.len;
  59524. this.reset().uint32(len);
  59525. if (len) {
  59526. this.tail.next = head.next; // skip noop
  59527. this.tail = tail;
  59528. this.len += len;
  59529. }
  59530. return this;
  59531. };
  59532. /**
  59533. * Finishes the write operation.
  59534. * @returns {Uint8Array} Finished buffer
  59535. */
  59536. Writer.prototype.finish = function finish() {
  59537. var head = this.head.next, // skip noop
  59538. buf = this.constructor.alloc(this.len),
  59539. pos = 0;
  59540. while (head) {
  59541. head.fn(head.val, buf, pos);
  59542. pos += head.len;
  59543. head = head.next;
  59544. }
  59545. // this.head = this.tail = null;
  59546. return buf;
  59547. };
  59548. Writer._configure = function(BufferWriter_) {
  59549. BufferWriter = BufferWriter_;
  59550. };
  59551. },{"./util/minimal":224}],226:[function(require,module,exports){
  59552. "use strict";
  59553. module.exports = BufferWriter;
  59554. // extends Writer
  59555. var Writer = require("./writer");
  59556. (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
  59557. var util = require("./util/minimal");
  59558. var Buffer = util.Buffer;
  59559. /**
  59560. * Constructs a new buffer writer instance.
  59561. * @classdesc Wire format writer using node buffers.
  59562. * @extends Writer
  59563. * @constructor
  59564. */
  59565. function BufferWriter() {
  59566. Writer.call(this);
  59567. }
  59568. /**
  59569. * Allocates a buffer of the specified size.
  59570. * @param {number} size Buffer size
  59571. * @returns {Buffer} Buffer
  59572. */
  59573. BufferWriter.alloc = function alloc_buffer(size) {
  59574. return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size);
  59575. };
  59576. var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set"
  59577. ? function writeBytesBuffer_set(val, buf, pos) {
  59578. buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
  59579. // also works for plain array values
  59580. }
  59581. /* istanbul ignore next */
  59582. : function writeBytesBuffer_copy(val, buf, pos) {
  59583. if (val.copy) // Buffer values
  59584. val.copy(buf, pos, 0, val.length);
  59585. else for (var i = 0; i < val.length;) // plain array values
  59586. buf[pos++] = val[i++];
  59587. };
  59588. /**
  59589. * @override
  59590. */
  59591. BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
  59592. if (util.isString(value))
  59593. value = util._Buffer_from(value, "base64");
  59594. var len = value.length >>> 0;
  59595. this.uint32(len);
  59596. if (len)
  59597. this._push(writeBytesBuffer, len, value);
  59598. return this;
  59599. };
  59600. function writeStringBuffer(val, buf, pos) {
  59601. if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
  59602. util.utf8.write(val, buf, pos);
  59603. else
  59604. buf.utf8Write(val, pos);
  59605. }
  59606. /**
  59607. * @override
  59608. */
  59609. BufferWriter.prototype.string = function write_string_buffer(value) {
  59610. var len = Buffer.byteLength(value);
  59611. this.uint32(len);
  59612. if (len)
  59613. this._push(writeStringBuffer, len, value);
  59614. return this;
  59615. };
  59616. /**
  59617. * Finishes the write operation.
  59618. * @name BufferWriter#finish
  59619. * @function
  59620. * @returns {Buffer} Finished buffer
  59621. */
  59622. },{"./util/minimal":224,"./writer":225}],227:[function(require,module,exports){
  59623. (function (global){
  59624. /*! https://mths.be/punycode v1.4.1 by @mathias */
  59625. ;(function(root) {
  59626. /** Detect free variables */
  59627. var freeExports = typeof exports == 'object' && exports &&
  59628. !exports.nodeType && exports;
  59629. var freeModule = typeof module == 'object' && module &&
  59630. !module.nodeType && module;
  59631. var freeGlobal = typeof global == 'object' && global;
  59632. if (
  59633. freeGlobal.global === freeGlobal ||
  59634. freeGlobal.window === freeGlobal ||
  59635. freeGlobal.self === freeGlobal
  59636. ) {
  59637. root = freeGlobal;
  59638. }
  59639. /**
  59640. * The `punycode` object.
  59641. * @name punycode
  59642. * @type Object
  59643. */
  59644. var punycode,
  59645. /** Highest positive signed 32-bit float value */
  59646. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  59647. /** Bootstring parameters */
  59648. base = 36,
  59649. tMin = 1,
  59650. tMax = 26,
  59651. skew = 38,
  59652. damp = 700,
  59653. initialBias = 72,
  59654. initialN = 128, // 0x80
  59655. delimiter = '-', // '\x2D'
  59656. /** Regular expressions */
  59657. regexPunycode = /^xn--/,
  59658. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  59659. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  59660. /** Error messages */
  59661. errors = {
  59662. 'overflow': 'Overflow: input needs wider integers to process',
  59663. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  59664. 'invalid-input': 'Invalid input'
  59665. },
  59666. /** Convenience shortcuts */
  59667. baseMinusTMin = base - tMin,
  59668. floor = Math.floor,
  59669. stringFromCharCode = String.fromCharCode,
  59670. /** Temporary variable */
  59671. key;
  59672. /*--------------------------------------------------------------------------*/
  59673. /**
  59674. * A generic error utility function.
  59675. * @private
  59676. * @param {String} type The error type.
  59677. * @returns {Error} Throws a `RangeError` with the applicable error message.
  59678. */
  59679. function error(type) {
  59680. throw new RangeError(errors[type]);
  59681. }
  59682. /**
  59683. * A generic `Array#map` utility function.
  59684. * @private
  59685. * @param {Array} array The array to iterate over.
  59686. * @param {Function} callback The function that gets called for every array
  59687. * item.
  59688. * @returns {Array} A new array of values returned by the callback function.
  59689. */
  59690. function map(array, fn) {
  59691. var length = array.length;
  59692. var result = [];
  59693. while (length--) {
  59694. result[length] = fn(array[length]);
  59695. }
  59696. return result;
  59697. }
  59698. /**
  59699. * A simple `Array#map`-like wrapper to work with domain name strings or email
  59700. * addresses.
  59701. * @private
  59702. * @param {String} domain The domain name or email address.
  59703. * @param {Function} callback The function that gets called for every
  59704. * character.
  59705. * @returns {Array} A new string of characters returned by the callback
  59706. * function.
  59707. */
  59708. function mapDomain(string, fn) {
  59709. var parts = string.split('@');
  59710. var result = '';
  59711. if (parts.length > 1) {
  59712. // In email addresses, only the domain name should be punycoded. Leave
  59713. // the local part (i.e. everything up to `@`) intact.
  59714. result = parts[0] + '@';
  59715. string = parts[1];
  59716. }
  59717. // Avoid `split(regex)` for IE8 compatibility. See #17.
  59718. string = string.replace(regexSeparators, '\x2E');
  59719. var labels = string.split('.');
  59720. var encoded = map(labels, fn).join('.');
  59721. return result + encoded;
  59722. }
  59723. /**
  59724. * Creates an array containing the numeric code points of each Unicode
  59725. * character in the string. While JavaScript uses UCS-2 internally,
  59726. * this function will convert a pair of surrogate halves (each of which
  59727. * UCS-2 exposes as separate characters) into a single code point,
  59728. * matching UTF-16.
  59729. * @see `punycode.ucs2.encode`
  59730. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  59731. * @memberOf punycode.ucs2
  59732. * @name decode
  59733. * @param {String} string The Unicode input string (UCS-2).
  59734. * @returns {Array} The new array of code points.
  59735. */
  59736. function ucs2decode(string) {
  59737. var output = [],
  59738. counter = 0,
  59739. length = string.length,
  59740. value,
  59741. extra;
  59742. while (counter < length) {
  59743. value = string.charCodeAt(counter++);
  59744. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  59745. // high surrogate, and there is a next character
  59746. extra = string.charCodeAt(counter++);
  59747. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  59748. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  59749. } else {
  59750. // unmatched surrogate; only append this code unit, in case the next
  59751. // code unit is the high surrogate of a surrogate pair
  59752. output.push(value);
  59753. counter--;
  59754. }
  59755. } else {
  59756. output.push(value);
  59757. }
  59758. }
  59759. return output;
  59760. }
  59761. /**
  59762. * Creates a string based on an array of numeric code points.
  59763. * @see `punycode.ucs2.decode`
  59764. * @memberOf punycode.ucs2
  59765. * @name encode
  59766. * @param {Array} codePoints The array of numeric code points.
  59767. * @returns {String} The new Unicode string (UCS-2).
  59768. */
  59769. function ucs2encode(array) {
  59770. return map(array, function(value) {
  59771. var output = '';
  59772. if (value > 0xFFFF) {
  59773. value -= 0x10000;
  59774. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  59775. value = 0xDC00 | value & 0x3FF;
  59776. }
  59777. output += stringFromCharCode(value);
  59778. return output;
  59779. }).join('');
  59780. }
  59781. /**
  59782. * Converts a basic code point into a digit/integer.
  59783. * @see `digitToBasic()`
  59784. * @private
  59785. * @param {Number} codePoint The basic numeric code point value.
  59786. * @returns {Number} The numeric value of a basic code point (for use in
  59787. * representing integers) in the range `0` to `base - 1`, or `base` if
  59788. * the code point does not represent a value.
  59789. */
  59790. function basicToDigit(codePoint) {
  59791. if (codePoint - 48 < 10) {
  59792. return codePoint - 22;
  59793. }
  59794. if (codePoint - 65 < 26) {
  59795. return codePoint - 65;
  59796. }
  59797. if (codePoint - 97 < 26) {
  59798. return codePoint - 97;
  59799. }
  59800. return base;
  59801. }
  59802. /**
  59803. * Converts a digit/integer into a basic code point.
  59804. * @see `basicToDigit()`
  59805. * @private
  59806. * @param {Number} digit The numeric value of a basic code point.
  59807. * @returns {Number} The basic code point whose value (when used for
  59808. * representing integers) is `digit`, which needs to be in the range
  59809. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  59810. * used; else, the lowercase form is used. The behavior is undefined
  59811. * if `flag` is non-zero and `digit` has no uppercase form.
  59812. */
  59813. function digitToBasic(digit, flag) {
  59814. // 0..25 map to ASCII a..z or A..Z
  59815. // 26..35 map to ASCII 0..9
  59816. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  59817. }
  59818. /**
  59819. * Bias adaptation function as per section 3.4 of RFC 3492.
  59820. * https://tools.ietf.org/html/rfc3492#section-3.4
  59821. * @private
  59822. */
  59823. function adapt(delta, numPoints, firstTime) {
  59824. var k = 0;
  59825. delta = firstTime ? floor(delta / damp) : delta >> 1;
  59826. delta += floor(delta / numPoints);
  59827. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  59828. delta = floor(delta / baseMinusTMin);
  59829. }
  59830. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  59831. }
  59832. /**
  59833. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  59834. * symbols.
  59835. * @memberOf punycode
  59836. * @param {String} input The Punycode string of ASCII-only symbols.
  59837. * @returns {String} The resulting string of Unicode symbols.
  59838. */
  59839. function decode(input) {
  59840. // Don't use UCS-2
  59841. var output = [],
  59842. inputLength = input.length,
  59843. out,
  59844. i = 0,
  59845. n = initialN,
  59846. bias = initialBias,
  59847. basic,
  59848. j,
  59849. index,
  59850. oldi,
  59851. w,
  59852. k,
  59853. digit,
  59854. t,
  59855. /** Cached calculation results */
  59856. baseMinusT;
  59857. // Handle the basic code points: let `basic` be the number of input code
  59858. // points before the last delimiter, or `0` if there is none, then copy
  59859. // the first basic code points to the output.
  59860. basic = input.lastIndexOf(delimiter);
  59861. if (basic < 0) {
  59862. basic = 0;
  59863. }
  59864. for (j = 0; j < basic; ++j) {
  59865. // if it's not a basic code point
  59866. if (input.charCodeAt(j) >= 0x80) {
  59867. error('not-basic');
  59868. }
  59869. output.push(input.charCodeAt(j));
  59870. }
  59871. // Main decoding loop: start just after the last delimiter if any basic code
  59872. // points were copied; start at the beginning otherwise.
  59873. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  59874. // `index` is the index of the next character to be consumed.
  59875. // Decode a generalized variable-length integer into `delta`,
  59876. // which gets added to `i`. The overflow checking is easier
  59877. // if we increase `i` as we go, then subtract off its starting
  59878. // value at the end to obtain `delta`.
  59879. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  59880. if (index >= inputLength) {
  59881. error('invalid-input');
  59882. }
  59883. digit = basicToDigit(input.charCodeAt(index++));
  59884. if (digit >= base || digit > floor((maxInt - i) / w)) {
  59885. error('overflow');
  59886. }
  59887. i += digit * w;
  59888. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  59889. if (digit < t) {
  59890. break;
  59891. }
  59892. baseMinusT = base - t;
  59893. if (w > floor(maxInt / baseMinusT)) {
  59894. error('overflow');
  59895. }
  59896. w *= baseMinusT;
  59897. }
  59898. out = output.length + 1;
  59899. bias = adapt(i - oldi, out, oldi == 0);
  59900. // `i` was supposed to wrap around from `out` to `0`,
  59901. // incrementing `n` each time, so we'll fix that now:
  59902. if (floor(i / out) > maxInt - n) {
  59903. error('overflow');
  59904. }
  59905. n += floor(i / out);
  59906. i %= out;
  59907. // Insert `n` at position `i` of the output
  59908. output.splice(i++, 0, n);
  59909. }
  59910. return ucs2encode(output);
  59911. }
  59912. /**
  59913. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  59914. * Punycode string of ASCII-only symbols.
  59915. * @memberOf punycode
  59916. * @param {String} input The string of Unicode symbols.
  59917. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  59918. */
  59919. function encode(input) {
  59920. var n,
  59921. delta,
  59922. handledCPCount,
  59923. basicLength,
  59924. bias,
  59925. j,
  59926. m,
  59927. q,
  59928. k,
  59929. t,
  59930. currentValue,
  59931. output = [],
  59932. /** `inputLength` will hold the number of code points in `input`. */
  59933. inputLength,
  59934. /** Cached calculation results */
  59935. handledCPCountPlusOne,
  59936. baseMinusT,
  59937. qMinusT;
  59938. // Convert the input in UCS-2 to Unicode
  59939. input = ucs2decode(input);
  59940. // Cache the length
  59941. inputLength = input.length;
  59942. // Initialize the state
  59943. n = initialN;
  59944. delta = 0;
  59945. bias = initialBias;
  59946. // Handle the basic code points
  59947. for (j = 0; j < inputLength; ++j) {
  59948. currentValue = input[j];
  59949. if (currentValue < 0x80) {
  59950. output.push(stringFromCharCode(currentValue));
  59951. }
  59952. }
  59953. handledCPCount = basicLength = output.length;
  59954. // `handledCPCount` is the number of code points that have been handled;
  59955. // `basicLength` is the number of basic code points.
  59956. // Finish the basic string - if it is not empty - with a delimiter
  59957. if (basicLength) {
  59958. output.push(delimiter);
  59959. }
  59960. // Main encoding loop:
  59961. while (handledCPCount < inputLength) {
  59962. // All non-basic code points < n have been handled already. Find the next
  59963. // larger one:
  59964. for (m = maxInt, j = 0; j < inputLength; ++j) {
  59965. currentValue = input[j];
  59966. if (currentValue >= n && currentValue < m) {
  59967. m = currentValue;
  59968. }
  59969. }
  59970. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  59971. // but guard against overflow
  59972. handledCPCountPlusOne = handledCPCount + 1;
  59973. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  59974. error('overflow');
  59975. }
  59976. delta += (m - n) * handledCPCountPlusOne;
  59977. n = m;
  59978. for (j = 0; j < inputLength; ++j) {
  59979. currentValue = input[j];
  59980. if (currentValue < n && ++delta > maxInt) {
  59981. error('overflow');
  59982. }
  59983. if (currentValue == n) {
  59984. // Represent delta as a generalized variable-length integer
  59985. for (q = delta, k = base; /* no condition */; k += base) {
  59986. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  59987. if (q < t) {
  59988. break;
  59989. }
  59990. qMinusT = q - t;
  59991. baseMinusT = base - t;
  59992. output.push(
  59993. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  59994. );
  59995. q = floor(qMinusT / baseMinusT);
  59996. }
  59997. output.push(stringFromCharCode(digitToBasic(q, 0)));
  59998. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  59999. delta = 0;
  60000. ++handledCPCount;
  60001. }
  60002. }
  60003. ++delta;
  60004. ++n;
  60005. }
  60006. return output.join('');
  60007. }
  60008. /**
  60009. * Converts a Punycode string representing a domain name or an email address
  60010. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  60011. * it doesn't matter if you call it on a string that has already been
  60012. * converted to Unicode.
  60013. * @memberOf punycode
  60014. * @param {String} input The Punycoded domain name or email address to
  60015. * convert to Unicode.
  60016. * @returns {String} The Unicode representation of the given Punycode
  60017. * string.
  60018. */
  60019. function toUnicode(input) {
  60020. return mapDomain(input, function(string) {
  60021. return regexPunycode.test(string)
  60022. ? decode(string.slice(4).toLowerCase())
  60023. : string;
  60024. });
  60025. }
  60026. /**
  60027. * Converts a Unicode string representing a domain name or an email address to
  60028. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  60029. * i.e. it doesn't matter if you call it with a domain that's already in
  60030. * ASCII.
  60031. * @memberOf punycode
  60032. * @param {String} input The domain name or email address to convert, as a
  60033. * Unicode string.
  60034. * @returns {String} The Punycode representation of the given domain name or
  60035. * email address.
  60036. */
  60037. function toASCII(input) {
  60038. return mapDomain(input, function(string) {
  60039. return regexNonASCII.test(string)
  60040. ? 'xn--' + encode(string)
  60041. : string;
  60042. });
  60043. }
  60044. /*--------------------------------------------------------------------------*/
  60045. /** Define the public API */
  60046. punycode = {
  60047. /**
  60048. * A string representing the current Punycode.js version number.
  60049. * @memberOf punycode
  60050. * @type String
  60051. */
  60052. 'version': '1.4.1',
  60053. /**
  60054. * An object of methods to convert from JavaScript's internal character
  60055. * representation (UCS-2) to Unicode code points, and back.
  60056. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  60057. * @memberOf punycode
  60058. * @type Object
  60059. */
  60060. 'ucs2': {
  60061. 'decode': ucs2decode,
  60062. 'encode': ucs2encode
  60063. },
  60064. 'decode': decode,
  60065. 'encode': encode,
  60066. 'toASCII': toASCII,
  60067. 'toUnicode': toUnicode
  60068. };
  60069. /** Expose `punycode` */
  60070. // Some AMD build optimizers, like r.js, check for specific condition patterns
  60071. // like the following:
  60072. if (
  60073. typeof define == 'function' &&
  60074. typeof define.amd == 'object' &&
  60075. define.amd
  60076. ) {
  60077. define('punycode', function() {
  60078. return punycode;
  60079. });
  60080. } else if (freeExports && freeModule) {
  60081. if (module.exports == freeExports) {
  60082. // in Node.js, io.js, or RingoJS v0.8.0+
  60083. freeModule.exports = punycode;
  60084. } else {
  60085. // in Narwhal or RingoJS v0.7.0-
  60086. for (key in punycode) {
  60087. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  60088. }
  60089. }
  60090. } else {
  60091. // in Rhino or a web browser
  60092. root.punycode = punycode;
  60093. }
  60094. }(this));
  60095. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  60096. },{}],228:[function(require,module,exports){
  60097. // Copyright Joyent, Inc. and other Node contributors.
  60098. //
  60099. // Permission is hereby granted, free of charge, to any person obtaining a
  60100. // copy of this software and associated documentation files (the
  60101. // "Software"), to deal in the Software without restriction, including
  60102. // without limitation the rights to use, copy, modify, merge, publish,
  60103. // distribute, sublicense, and/or sell copies of the Software, and to permit
  60104. // persons to whom the Software is furnished to do so, subject to the
  60105. // following conditions:
  60106. //
  60107. // The above copyright notice and this permission notice shall be included
  60108. // in all copies or substantial portions of the Software.
  60109. //
  60110. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  60111. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  60112. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  60113. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  60114. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  60115. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  60116. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  60117. 'use strict';
  60118. // If obj.hasOwnProperty has been overridden, then calling
  60119. // obj.hasOwnProperty(prop) will break.
  60120. // See: https://github.com/joyent/node/issues/1707
  60121. function hasOwnProperty(obj, prop) {
  60122. return Object.prototype.hasOwnProperty.call(obj, prop);
  60123. }
  60124. module.exports = function(qs, sep, eq, options) {
  60125. sep = sep || '&';
  60126. eq = eq || '=';
  60127. var obj = {};
  60128. if (typeof qs !== 'string' || qs.length === 0) {
  60129. return obj;
  60130. }
  60131. var regexp = /\+/g;
  60132. qs = qs.split(sep);
  60133. var maxKeys = 1000;
  60134. if (options && typeof options.maxKeys === 'number') {
  60135. maxKeys = options.maxKeys;
  60136. }
  60137. var len = qs.length;
  60138. // maxKeys <= 0 means that we should not limit keys count
  60139. if (maxKeys > 0 && len > maxKeys) {
  60140. len = maxKeys;
  60141. }
  60142. for (var i = 0; i < len; ++i) {
  60143. var x = qs[i].replace(regexp, '%20'),
  60144. idx = x.indexOf(eq),
  60145. kstr, vstr, k, v;
  60146. if (idx >= 0) {
  60147. kstr = x.substr(0, idx);
  60148. vstr = x.substr(idx + 1);
  60149. } else {
  60150. kstr = x;
  60151. vstr = '';
  60152. }
  60153. k = decodeURIComponent(kstr);
  60154. v = decodeURIComponent(vstr);
  60155. if (!hasOwnProperty(obj, k)) {
  60156. obj[k] = v;
  60157. } else if (isArray(obj[k])) {
  60158. obj[k].push(v);
  60159. } else {
  60160. obj[k] = [obj[k], v];
  60161. }
  60162. }
  60163. return obj;
  60164. };
  60165. var isArray = Array.isArray || function (xs) {
  60166. return Object.prototype.toString.call(xs) === '[object Array]';
  60167. };
  60168. },{}],229:[function(require,module,exports){
  60169. // Copyright Joyent, Inc. and other Node contributors.
  60170. //
  60171. // Permission is hereby granted, free of charge, to any person obtaining a
  60172. // copy of this software and associated documentation files (the
  60173. // "Software"), to deal in the Software without restriction, including
  60174. // without limitation the rights to use, copy, modify, merge, publish,
  60175. // distribute, sublicense, and/or sell copies of the Software, and to permit
  60176. // persons to whom the Software is furnished to do so, subject to the
  60177. // following conditions:
  60178. //
  60179. // The above copyright notice and this permission notice shall be included
  60180. // in all copies or substantial portions of the Software.
  60181. //
  60182. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  60183. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  60184. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  60185. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  60186. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  60187. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  60188. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  60189. 'use strict';
  60190. var stringifyPrimitive = function(v) {
  60191. switch (typeof v) {
  60192. case 'string':
  60193. return v;
  60194. case 'boolean':
  60195. return v ? 'true' : 'false';
  60196. case 'number':
  60197. return isFinite(v) ? v : '';
  60198. default:
  60199. return '';
  60200. }
  60201. };
  60202. module.exports = function(obj, sep, eq, name) {
  60203. sep = sep || '&';
  60204. eq = eq || '=';
  60205. if (obj === null) {
  60206. obj = undefined;
  60207. }
  60208. if (typeof obj === 'object') {
  60209. return map(objectKeys(obj), function(k) {
  60210. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  60211. if (isArray(obj[k])) {
  60212. return map(obj[k], function(v) {
  60213. return ks + encodeURIComponent(stringifyPrimitive(v));
  60214. }).join(sep);
  60215. } else {
  60216. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  60217. }
  60218. }).join(sep);
  60219. }
  60220. if (!name) return '';
  60221. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  60222. encodeURIComponent(stringifyPrimitive(obj));
  60223. };
  60224. var isArray = Array.isArray || function (xs) {
  60225. return Object.prototype.toString.call(xs) === '[object Array]';
  60226. };
  60227. function map (xs, f) {
  60228. if (xs.map) return xs.map(f);
  60229. var res = [];
  60230. for (var i = 0; i < xs.length; i++) {
  60231. res.push(f(xs[i], i));
  60232. }
  60233. return res;
  60234. }
  60235. var objectKeys = Object.keys || function (obj) {
  60236. var res = [];
  60237. for (var key in obj) {
  60238. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  60239. }
  60240. return res;
  60241. };
  60242. },{}],230:[function(require,module,exports){
  60243. 'use strict';
  60244. exports.decode = exports.parse = require('./decode');
  60245. exports.encode = exports.stringify = require('./encode');
  60246. },{"./decode":228,"./encode":229}],231:[function(require,module,exports){
  60247. // A library of seedable RNGs implemented in Javascript.
  60248. //
  60249. // Usage:
  60250. //
  60251. // var seedrandom = require('seedrandom');
  60252. // var random = seedrandom(1); // or any seed.
  60253. // var x = random(); // 0 <= x < 1. Every bit is random.
  60254. // var x = random.quick(); // 0 <= x < 1. 32 bits of randomness.
  60255. // alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.
  60256. // Period: ~2^116
  60257. // Reported to pass all BigCrush tests.
  60258. var alea = require('./lib/alea');
  60259. // xor128, a pure xor-shift generator by George Marsaglia.
  60260. // Period: 2^128-1.
  60261. // Reported to fail: MatrixRank and LinearComp.
  60262. var xor128 = require('./lib/xor128');
  60263. // xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.
  60264. // Period: 2^192-2^32
  60265. // Reported to fail: CollisionOver, SimpPoker, and LinearComp.
  60266. var xorwow = require('./lib/xorwow');
  60267. // xorshift7, by François Panneton and Pierre L'ecuyer, takes
  60268. // a different approach: it adds robustness by allowing more shifts
  60269. // than Marsaglia's original three. It is a 7-shift generator
  60270. // with 256 bits, that passes BigCrush with no systmatic failures.
  60271. // Period 2^256-1.
  60272. // No systematic BigCrush failures reported.
  60273. var xorshift7 = require('./lib/xorshift7');
  60274. // xor4096, by Richard Brent, is a 4096-bit xor-shift with a
  60275. // very long period that also adds a Weyl generator. It also passes
  60276. // BigCrush with no systematic failures. Its long period may
  60277. // be useful if you have many generators and need to avoid
  60278. // collisions.
  60279. // Period: 2^4128-2^32.
  60280. // No systematic BigCrush failures reported.
  60281. var xor4096 = require('./lib/xor4096');
  60282. // Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random
  60283. // number generator derived from ChaCha, a modern stream cipher.
  60284. // https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
  60285. // Period: ~2^127
  60286. // No systematic BigCrush failures reported.
  60287. var tychei = require('./lib/tychei');
  60288. // The original ARC4-based prng included in this library.
  60289. // Period: ~2^1600
  60290. var sr = require('./seedrandom');
  60291. sr.alea = alea;
  60292. sr.xor128 = xor128;
  60293. sr.xorwow = xorwow;
  60294. sr.xorshift7 = xorshift7;
  60295. sr.xor4096 = xor4096;
  60296. sr.tychei = tychei;
  60297. module.exports = sr;
  60298. },{"./lib/alea":232,"./lib/tychei":233,"./lib/xor128":234,"./lib/xor4096":235,"./lib/xorshift7":236,"./lib/xorwow":237,"./seedrandom":238}],232:[function(require,module,exports){
  60299. // A port of an algorithm by Johannes Baagøe <baagoe@baagoe.com>, 2010
  60300. // http://baagoe.com/en/RandomMusings/javascript/
  60301. // https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
  60302. // Original work is under MIT license -
  60303. // Copyright (C) 2010 by Johannes Baagøe <baagoe@baagoe.org>
  60304. //
  60305. // Permission is hereby granted, free of charge, to any person obtaining a copy
  60306. // of this software and associated documentation files (the "Software"), to deal
  60307. // in the Software without restriction, including without limitation the rights
  60308. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  60309. // copies of the Software, and to permit persons to whom the Software is
  60310. // furnished to do so, subject to the following conditions:
  60311. //
  60312. // The above copyright notice and this permission notice shall be included in
  60313. // all copies or substantial portions of the Software.
  60314. //
  60315. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  60316. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  60317. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  60318. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  60319. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  60320. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  60321. // THE SOFTWARE.
  60322. (function(global, module, define) {
  60323. function Alea(seed) {
  60324. var me = this, mash = Mash();
  60325. me.next = function() {
  60326. var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32
  60327. me.s0 = me.s1;
  60328. me.s1 = me.s2;
  60329. return me.s2 = t - (me.c = t | 0);
  60330. };
  60331. // Apply the seeding algorithm from Baagoe.
  60332. me.c = 1;
  60333. me.s0 = mash(' ');
  60334. me.s1 = mash(' ');
  60335. me.s2 = mash(' ');
  60336. me.s0 -= mash(seed);
  60337. if (me.s0 < 0) { me.s0 += 1; }
  60338. me.s1 -= mash(seed);
  60339. if (me.s1 < 0) { me.s1 += 1; }
  60340. me.s2 -= mash(seed);
  60341. if (me.s2 < 0) { me.s2 += 1; }
  60342. mash = null;
  60343. }
  60344. function copy(f, t) {
  60345. t.c = f.c;
  60346. t.s0 = f.s0;
  60347. t.s1 = f.s1;
  60348. t.s2 = f.s2;
  60349. return t;
  60350. }
  60351. function impl(seed, opts) {
  60352. var xg = new Alea(seed),
  60353. state = opts && opts.state,
  60354. prng = xg.next;
  60355. prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }
  60356. prng.double = function() {
  60357. return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
  60358. };
  60359. prng.quick = prng;
  60360. if (state) {
  60361. if (typeof(state) == 'object') copy(state, xg);
  60362. prng.state = function() { return copy(xg, {}); }
  60363. }
  60364. return prng;
  60365. }
  60366. function Mash() {
  60367. var n = 0xefc8249d;
  60368. var mash = function(data) {
  60369. data = data.toString();
  60370. for (var i = 0; i < data.length; i++) {
  60371. n += data.charCodeAt(i);
  60372. var h = 0.02519603282416938 * n;
  60373. n = h >>> 0;
  60374. h -= n;
  60375. h *= n;
  60376. n = h >>> 0;
  60377. h -= n;
  60378. n += h * 0x100000000; // 2^32
  60379. }
  60380. return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
  60381. };
  60382. return mash;
  60383. }
  60384. if (module && module.exports) {
  60385. module.exports = impl;
  60386. } else if (define && define.amd) {
  60387. define(function() { return impl; });
  60388. } else {
  60389. this.alea = impl;
  60390. }
  60391. })(
  60392. this,
  60393. (typeof module) == 'object' && module, // present in node.js
  60394. (typeof define) == 'function' && define // present with an AMD loader
  60395. );
  60396. },{}],233:[function(require,module,exports){
  60397. // A Javascript implementaion of the "Tyche-i" prng algorithm by
  60398. // Samuel Neves and Filipe Araujo.
  60399. // See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
  60400. (function(global, module, define) {
  60401. function XorGen(seed) {
  60402. var me = this, strseed = '';
  60403. // Set up generator function.
  60404. me.next = function() {
  60405. var b = me.b, c = me.c, d = me.d, a = me.a;
  60406. b = (b << 25) ^ (b >>> 7) ^ c;
  60407. c = (c - d) | 0;
  60408. d = (d << 24) ^ (d >>> 8) ^ a;
  60409. a = (a - b) | 0;
  60410. me.b = b = (b << 20) ^ (b >>> 12) ^ c;
  60411. me.c = c = (c - d) | 0;
  60412. me.d = (d << 16) ^ (c >>> 16) ^ a;
  60413. return me.a = (a - b) | 0;
  60414. };
  60415. /* The following is non-inverted tyche, which has better internal
  60416. * bit diffusion, but which is about 25% slower than tyche-i in JS.
  60417. me.next = function() {
  60418. var a = me.a, b = me.b, c = me.c, d = me.d;
  60419. a = (me.a + me.b | 0) >>> 0;
  60420. d = me.d ^ a; d = d << 16 ^ d >>> 16;
  60421. c = me.c + d | 0;
  60422. b = me.b ^ c; b = b << 12 ^ d >>> 20;
  60423. me.a = a = a + b | 0;
  60424. d = d ^ a; me.d = d = d << 8 ^ d >>> 24;
  60425. me.c = c = c + d | 0;
  60426. b = b ^ c;
  60427. return me.b = (b << 7 ^ b >>> 25);
  60428. }
  60429. */
  60430. me.a = 0;
  60431. me.b = 0;
  60432. me.c = 2654435769 | 0;
  60433. me.d = 1367130551;
  60434. if (seed === Math.floor(seed)) {
  60435. // Integer seed.
  60436. me.a = (seed / 0x100000000) | 0;
  60437. me.b = seed | 0;
  60438. } else {
  60439. // String seed.
  60440. strseed += seed;
  60441. }
  60442. // Mix in string seed, then discard an initial batch of 64 values.
  60443. for (var k = 0; k < strseed.length + 20; k++) {
  60444. me.b ^= strseed.charCodeAt(k) | 0;
  60445. me.next();
  60446. }
  60447. }
  60448. function copy(f, t) {
  60449. t.a = f.a;
  60450. t.b = f.b;
  60451. t.c = f.c;
  60452. t.d = f.d;
  60453. return t;
  60454. };
  60455. function impl(seed, opts) {
  60456. var xg = new XorGen(seed),
  60457. state = opts && opts.state,
  60458. prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  60459. prng.double = function() {
  60460. do {
  60461. var top = xg.next() >>> 11,
  60462. bot = (xg.next() >>> 0) / 0x100000000,
  60463. result = (top + bot) / (1 << 21);
  60464. } while (result === 0);
  60465. return result;
  60466. };
  60467. prng.int32 = xg.next;
  60468. prng.quick = prng;
  60469. if (state) {
  60470. if (typeof(state) == 'object') copy(state, xg);
  60471. prng.state = function() { return copy(xg, {}); }
  60472. }
  60473. return prng;
  60474. }
  60475. if (module && module.exports) {
  60476. module.exports = impl;
  60477. } else if (define && define.amd) {
  60478. define(function() { return impl; });
  60479. } else {
  60480. this.tychei = impl;
  60481. }
  60482. })(
  60483. this,
  60484. (typeof module) == 'object' && module, // present in node.js
  60485. (typeof define) == 'function' && define // present with an AMD loader
  60486. );
  60487. },{}],234:[function(require,module,exports){
  60488. // A Javascript implementaion of the "xor128" prng algorithm by
  60489. // George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
  60490. (function(global, module, define) {
  60491. function XorGen(seed) {
  60492. var me = this, strseed = '';
  60493. me.x = 0;
  60494. me.y = 0;
  60495. me.z = 0;
  60496. me.w = 0;
  60497. // Set up generator function.
  60498. me.next = function() {
  60499. var t = me.x ^ (me.x << 11);
  60500. me.x = me.y;
  60501. me.y = me.z;
  60502. me.z = me.w;
  60503. return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);
  60504. };
  60505. if (seed === (seed | 0)) {
  60506. // Integer seed.
  60507. me.x = seed;
  60508. } else {
  60509. // String seed.
  60510. strseed += seed;
  60511. }
  60512. // Mix in string seed, then discard an initial batch of 64 values.
  60513. for (var k = 0; k < strseed.length + 64; k++) {
  60514. me.x ^= strseed.charCodeAt(k) | 0;
  60515. me.next();
  60516. }
  60517. }
  60518. function copy(f, t) {
  60519. t.x = f.x;
  60520. t.y = f.y;
  60521. t.z = f.z;
  60522. t.w = f.w;
  60523. return t;
  60524. }
  60525. function impl(seed, opts) {
  60526. var xg = new XorGen(seed),
  60527. state = opts && opts.state,
  60528. prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  60529. prng.double = function() {
  60530. do {
  60531. var top = xg.next() >>> 11,
  60532. bot = (xg.next() >>> 0) / 0x100000000,
  60533. result = (top + bot) / (1 << 21);
  60534. } while (result === 0);
  60535. return result;
  60536. };
  60537. prng.int32 = xg.next;
  60538. prng.quick = prng;
  60539. if (state) {
  60540. if (typeof(state) == 'object') copy(state, xg);
  60541. prng.state = function() { return copy(xg, {}); }
  60542. }
  60543. return prng;
  60544. }
  60545. if (module && module.exports) {
  60546. module.exports = impl;
  60547. } else if (define && define.amd) {
  60548. define(function() { return impl; });
  60549. } else {
  60550. this.xor128 = impl;
  60551. }
  60552. })(
  60553. this,
  60554. (typeof module) == 'object' && module, // present in node.js
  60555. (typeof define) == 'function' && define // present with an AMD loader
  60556. );
  60557. },{}],235:[function(require,module,exports){
  60558. // A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.
  60559. //
  60560. // This fast non-cryptographic random number generator is designed for
  60561. // use in Monte-Carlo algorithms. It combines a long-period xorshift
  60562. // generator with a Weyl generator, and it passes all common batteries
  60563. // of stasticial tests for randomness while consuming only a few nanoseconds
  60564. // for each prng generated. For background on the generator, see Brent's
  60565. // paper: "Some long-period random number generators using shifts and xors."
  60566. // http://arxiv.org/pdf/1004.3115v1.pdf
  60567. //
  60568. // Usage:
  60569. //
  60570. // var xor4096 = require('xor4096');
  60571. // random = xor4096(1); // Seed with int32 or string.
  60572. // assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.
  60573. // assert.equal(random.int32(), 1806534897); // signed int32, 32 bits.
  60574. //
  60575. // For nonzero numeric keys, this impelementation provides a sequence
  60576. // identical to that by Brent's xorgens 3 implementaion in C. This
  60577. // implementation also provides for initalizing the generator with
  60578. // string seeds, or for saving and restoring the state of the generator.
  60579. //
  60580. // On Chrome, this prng benchmarks about 2.1 times slower than
  60581. // Javascript's built-in Math.random().
  60582. (function(global, module, define) {
  60583. function XorGen(seed) {
  60584. var me = this;
  60585. // Set up generator function.
  60586. me.next = function() {
  60587. var w = me.w,
  60588. X = me.X, i = me.i, t, v;
  60589. // Update Weyl generator.
  60590. me.w = w = (w + 0x61c88647) | 0;
  60591. // Update xor generator.
  60592. v = X[(i + 34) & 127];
  60593. t = X[i = ((i + 1) & 127)];
  60594. v ^= v << 13;
  60595. t ^= t << 17;
  60596. v ^= v >>> 15;
  60597. t ^= t >>> 12;
  60598. // Update Xor generator array state.
  60599. v = X[i] = v ^ t;
  60600. me.i = i;
  60601. // Result is the combination.
  60602. return (v + (w ^ (w >>> 16))) | 0;
  60603. };
  60604. function init(me, seed) {
  60605. var t, v, i, j, w, X = [], limit = 128;
  60606. if (seed === (seed | 0)) {
  60607. // Numeric seeds initialize v, which is used to generates X.
  60608. v = seed;
  60609. seed = null;
  60610. } else {
  60611. // String seeds are mixed into v and X one character at a time.
  60612. seed = seed + '\0';
  60613. v = 0;
  60614. limit = Math.max(limit, seed.length);
  60615. }
  60616. // Initialize circular array and weyl value.
  60617. for (i = 0, j = -32; j < limit; ++j) {
  60618. // Put the unicode characters into the array, and shuffle them.
  60619. if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);
  60620. // After 32 shuffles, take v as the starting w value.
  60621. if (j === 0) w = v;
  60622. v ^= v << 10;
  60623. v ^= v >>> 15;
  60624. v ^= v << 4;
  60625. v ^= v >>> 13;
  60626. if (j >= 0) {
  60627. w = (w + 0x61c88647) | 0; // Weyl.
  60628. t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.
  60629. i = (0 == t) ? i + 1 : 0; // Count zeroes.
  60630. }
  60631. }
  60632. // We have detected all zeroes; make the key nonzero.
  60633. if (i >= 128) {
  60634. X[(seed && seed.length || 0) & 127] = -1;
  60635. }
  60636. // Run the generator 512 times to further mix the state before using it.
  60637. // Factoring this as a function slows the main generator, so it is just
  60638. // unrolled here. The weyl generator is not advanced while warming up.
  60639. i = 127;
  60640. for (j = 4 * 128; j > 0; --j) {
  60641. v = X[(i + 34) & 127];
  60642. t = X[i = ((i + 1) & 127)];
  60643. v ^= v << 13;
  60644. t ^= t << 17;
  60645. v ^= v >>> 15;
  60646. t ^= t >>> 12;
  60647. X[i] = v ^ t;
  60648. }
  60649. // Storing state as object members is faster than using closure variables.
  60650. me.w = w;
  60651. me.X = X;
  60652. me.i = i;
  60653. }
  60654. init(me, seed);
  60655. }
  60656. function copy(f, t) {
  60657. t.i = f.i;
  60658. t.w = f.w;
  60659. t.X = f.X.slice();
  60660. return t;
  60661. };
  60662. function impl(seed, opts) {
  60663. if (seed == null) seed = +(new Date);
  60664. var xg = new XorGen(seed),
  60665. state = opts && opts.state,
  60666. prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  60667. prng.double = function() {
  60668. do {
  60669. var top = xg.next() >>> 11,
  60670. bot = (xg.next() >>> 0) / 0x100000000,
  60671. result = (top + bot) / (1 << 21);
  60672. } while (result === 0);
  60673. return result;
  60674. };
  60675. prng.int32 = xg.next;
  60676. prng.quick = prng;
  60677. if (state) {
  60678. if (state.X) copy(state, xg);
  60679. prng.state = function() { return copy(xg, {}); }
  60680. }
  60681. return prng;
  60682. }
  60683. if (module && module.exports) {
  60684. module.exports = impl;
  60685. } else if (define && define.amd) {
  60686. define(function() { return impl; });
  60687. } else {
  60688. this.xor4096 = impl;
  60689. }
  60690. })(
  60691. this, // window object or global
  60692. (typeof module) == 'object' && module, // present in node.js
  60693. (typeof define) == 'function' && define // present with an AMD loader
  60694. );
  60695. },{}],236:[function(require,module,exports){
  60696. // A Javascript implementaion of the "xorshift7" algorithm by
  60697. // François Panneton and Pierre L'ecuyer:
  60698. // "On the Xorgshift Random Number Generators"
  60699. // http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf
  60700. (function(global, module, define) {
  60701. function XorGen(seed) {
  60702. var me = this;
  60703. // Set up generator function.
  60704. me.next = function() {
  60705. // Update xor generator.
  60706. var X = me.x, i = me.i, t, v, w;
  60707. t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);
  60708. t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);
  60709. t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);
  60710. t = X[(i + 4) & 7]; v ^= t ^ (t << 7);
  60711. t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);
  60712. X[i] = v;
  60713. me.i = (i + 1) & 7;
  60714. return v;
  60715. };
  60716. function init(me, seed) {
  60717. var j, w, X = [];
  60718. if (seed === (seed | 0)) {
  60719. // Seed state array using a 32-bit integer.
  60720. w = X[0] = seed;
  60721. } else {
  60722. // Seed state using a string.
  60723. seed = '' + seed;
  60724. for (j = 0; j < seed.length; ++j) {
  60725. X[j & 7] = (X[j & 7] << 15) ^
  60726. (seed.charCodeAt(j) + X[(j + 1) & 7] << 13);
  60727. }
  60728. }
  60729. // Enforce an array length of 8, not all zeroes.
  60730. while (X.length < 8) X.push(0);
  60731. for (j = 0; j < 8 && X[j] === 0; ++j);
  60732. if (j == 8) w = X[7] = -1; else w = X[j];
  60733. me.x = X;
  60734. me.i = 0;
  60735. // Discard an initial 256 values.
  60736. for (j = 256; j > 0; --j) {
  60737. me.next();
  60738. }
  60739. }
  60740. init(me, seed);
  60741. }
  60742. function copy(f, t) {
  60743. t.x = f.x.slice();
  60744. t.i = f.i;
  60745. return t;
  60746. }
  60747. function impl(seed, opts) {
  60748. if (seed == null) seed = +(new Date);
  60749. var xg = new XorGen(seed),
  60750. state = opts && opts.state,
  60751. prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  60752. prng.double = function() {
  60753. do {
  60754. var top = xg.next() >>> 11,
  60755. bot = (xg.next() >>> 0) / 0x100000000,
  60756. result = (top + bot) / (1 << 21);
  60757. } while (result === 0);
  60758. return result;
  60759. };
  60760. prng.int32 = xg.next;
  60761. prng.quick = prng;
  60762. if (state) {
  60763. if (state.x) copy(state, xg);
  60764. prng.state = function() { return copy(xg, {}); }
  60765. }
  60766. return prng;
  60767. }
  60768. if (module && module.exports) {
  60769. module.exports = impl;
  60770. } else if (define && define.amd) {
  60771. define(function() { return impl; });
  60772. } else {
  60773. this.xorshift7 = impl;
  60774. }
  60775. })(
  60776. this,
  60777. (typeof module) == 'object' && module, // present in node.js
  60778. (typeof define) == 'function' && define // present with an AMD loader
  60779. );
  60780. },{}],237:[function(require,module,exports){
  60781. // A Javascript implementaion of the "xorwow" prng algorithm by
  60782. // George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
  60783. (function(global, module, define) {
  60784. function XorGen(seed) {
  60785. var me = this, strseed = '';
  60786. // Set up generator function.
  60787. me.next = function() {
  60788. var t = (me.x ^ (me.x >>> 2));
  60789. me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;
  60790. return (me.d = (me.d + 362437 | 0)) +
  60791. (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;
  60792. };
  60793. me.x = 0;
  60794. me.y = 0;
  60795. me.z = 0;
  60796. me.w = 0;
  60797. me.v = 0;
  60798. if (seed === (seed | 0)) {
  60799. // Integer seed.
  60800. me.x = seed;
  60801. } else {
  60802. // String seed.
  60803. strseed += seed;
  60804. }
  60805. // Mix in string seed, then discard an initial batch of 64 values.
  60806. for (var k = 0; k < strseed.length + 64; k++) {
  60807. me.x ^= strseed.charCodeAt(k) | 0;
  60808. if (k == strseed.length) {
  60809. me.d = me.x << 10 ^ me.x >>> 4;
  60810. }
  60811. me.next();
  60812. }
  60813. }
  60814. function copy(f, t) {
  60815. t.x = f.x;
  60816. t.y = f.y;
  60817. t.z = f.z;
  60818. t.w = f.w;
  60819. t.v = f.v;
  60820. t.d = f.d;
  60821. return t;
  60822. }
  60823. function impl(seed, opts) {
  60824. var xg = new XorGen(seed),
  60825. state = opts && opts.state,
  60826. prng = function() { return (xg.next() >>> 0) / 0x100000000; };
  60827. prng.double = function() {
  60828. do {
  60829. var top = xg.next() >>> 11,
  60830. bot = (xg.next() >>> 0) / 0x100000000,
  60831. result = (top + bot) / (1 << 21);
  60832. } while (result === 0);
  60833. return result;
  60834. };
  60835. prng.int32 = xg.next;
  60836. prng.quick = prng;
  60837. if (state) {
  60838. if (typeof(state) == 'object') copy(state, xg);
  60839. prng.state = function() { return copy(xg, {}); }
  60840. }
  60841. return prng;
  60842. }
  60843. if (module && module.exports) {
  60844. module.exports = impl;
  60845. } else if (define && define.amd) {
  60846. define(function() { return impl; });
  60847. } else {
  60848. this.xorwow = impl;
  60849. }
  60850. })(
  60851. this,
  60852. (typeof module) == 'object' && module, // present in node.js
  60853. (typeof define) == 'function' && define // present with an AMD loader
  60854. );
  60855. },{}],238:[function(require,module,exports){
  60856. /*
  60857. Copyright 2014 David Bau.
  60858. Permission is hereby granted, free of charge, to any person obtaining
  60859. a copy of this software and associated documentation files (the
  60860. "Software"), to deal in the Software without restriction, including
  60861. without limitation the rights to use, copy, modify, merge, publish,
  60862. distribute, sublicense, and/or sell copies of the Software, and to
  60863. permit persons to whom the Software is furnished to do so, subject to
  60864. the following conditions:
  60865. The above copyright notice and this permission notice shall be
  60866. included in all copies or substantial portions of the Software.
  60867. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  60868. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  60869. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  60870. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  60871. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  60872. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  60873. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  60874. */
  60875. (function (pool, math) {
  60876. //
  60877. // The following constants are related to IEEE 754 limits.
  60878. //
  60879. var global = this,
  60880. width = 256, // each RC4 output is 0 <= x < 256
  60881. chunks = 6, // at least six RC4 outputs for each double
  60882. digits = 52, // there are 52 significant digits in a double
  60883. rngname = 'random', // rngname: name for Math.random and Math.seedrandom
  60884. startdenom = math.pow(width, chunks),
  60885. significance = math.pow(2, digits),
  60886. overflow = significance * 2,
  60887. mask = width - 1,
  60888. nodecrypto; // node.js crypto module, initialized at the bottom.
  60889. //
  60890. // seedrandom()
  60891. // This is the seedrandom function described above.
  60892. //
  60893. function seedrandom(seed, options, callback) {
  60894. var key = [];
  60895. options = (options == true) ? { entropy: true } : (options || {});
  60896. // Flatten the seed string or build one from local entropy if needed.
  60897. var shortseed = mixkey(flatten(
  60898. options.entropy ? [seed, tostring(pool)] :
  60899. (seed == null) ? autoseed() : seed, 3), key);
  60900. // Use the seed to initialize an ARC4 generator.
  60901. var arc4 = new ARC4(key);
  60902. // This function returns a random double in [0, 1) that contains
  60903. // randomness in every bit of the mantissa of the IEEE 754 value.
  60904. var prng = function() {
  60905. var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
  60906. d = startdenom, // and denominator d = 2 ^ 48.
  60907. x = 0; // and no 'extra last byte'.
  60908. while (n < significance) { // Fill up all significant digits by
  60909. n = (n + x) * width; // shifting numerator and
  60910. d *= width; // denominator and generating a
  60911. x = arc4.g(1); // new least-significant-byte.
  60912. }
  60913. while (n >= overflow) { // To avoid rounding up, before adding
  60914. n /= 2; // last byte, shift everything
  60915. d /= 2; // right using integer math until
  60916. x >>>= 1; // we have exactly the desired bits.
  60917. }
  60918. return (n + x) / d; // Form the number within [0, 1).
  60919. };
  60920. prng.int32 = function() { return arc4.g(4) | 0; }
  60921. prng.quick = function() { return arc4.g(4) / 0x100000000; }
  60922. prng.double = prng;
  60923. // Mix the randomness into accumulated entropy.
  60924. mixkey(tostring(arc4.S), pool);
  60925. // Calling convention: what to return as a function of prng, seed, is_math.
  60926. return (options.pass || callback ||
  60927. function(prng, seed, is_math_call, state) {
  60928. if (state) {
  60929. // Load the arc4 state from the given state if it has an S array.
  60930. if (state.S) { copy(state, arc4); }
  60931. // Only provide the .state method if requested via options.state.
  60932. prng.state = function() { return copy(arc4, {}); }
  60933. }
  60934. // If called as a method of Math (Math.seedrandom()), mutate
  60935. // Math.random because that is how seedrandom.js has worked since v1.0.
  60936. if (is_math_call) { math[rngname] = prng; return seed; }
  60937. // Otherwise, it is a newer calling convention, so return the
  60938. // prng directly.
  60939. else return prng;
  60940. })(
  60941. prng,
  60942. shortseed,
  60943. 'global' in options ? options.global : (this == math),
  60944. options.state);
  60945. }
  60946. math['seed' + rngname] = seedrandom;
  60947. //
  60948. // ARC4
  60949. //
  60950. // An ARC4 implementation. The constructor takes a key in the form of
  60951. // an array of at most (width) integers that should be 0 <= x < (width).
  60952. //
  60953. // The g(count) method returns a pseudorandom integer that concatenates
  60954. // the next (count) outputs from ARC4. Its return value is a number x
  60955. // that is in the range 0 <= x < (width ^ count).
  60956. //
  60957. function ARC4(key) {
  60958. var t, keylen = key.length,
  60959. me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
  60960. // The empty key [] is treated as [0].
  60961. if (!keylen) { key = [keylen++]; }
  60962. // Set up S using the standard key scheduling algorithm.
  60963. while (i < width) {
  60964. s[i] = i++;
  60965. }
  60966. for (i = 0; i < width; i++) {
  60967. s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
  60968. s[j] = t;
  60969. }
  60970. // The "g" method returns the next (count) outputs as one number.
  60971. (me.g = function(count) {
  60972. // Using instance members instead of closure state nearly doubles speed.
  60973. var t, r = 0,
  60974. i = me.i, j = me.j, s = me.S;
  60975. while (count--) {
  60976. t = s[i = mask & (i + 1)];
  60977. r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
  60978. }
  60979. me.i = i; me.j = j;
  60980. return r;
  60981. // For robust unpredictability, the function call below automatically
  60982. // discards an initial batch of values. This is called RC4-drop[256].
  60983. // See http://google.com/search?q=rsa+fluhrer+response&btnI
  60984. })(width);
  60985. }
  60986. //
  60987. // copy()
  60988. // Copies internal state of ARC4 to or from a plain object.
  60989. //
  60990. function copy(f, t) {
  60991. t.i = f.i;
  60992. t.j = f.j;
  60993. t.S = f.S.slice();
  60994. return t;
  60995. };
  60996. //
  60997. // flatten()
  60998. // Converts an object tree to nested arrays of strings.
  60999. //
  61000. function flatten(obj, depth) {
  61001. var result = [], typ = (typeof obj), prop;
  61002. if (depth && typ == 'object') {
  61003. for (prop in obj) {
  61004. try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
  61005. }
  61006. }
  61007. return (result.length ? result : typ == 'string' ? obj : obj + '\0');
  61008. }
  61009. //
  61010. // mixkey()
  61011. // Mixes a string seed into a key that is an array of integers, and
  61012. // returns a shortened string seed that is equivalent to the result key.
  61013. //
  61014. function mixkey(seed, key) {
  61015. var stringseed = seed + '', smear, j = 0;
  61016. while (j < stringseed.length) {
  61017. key[mask & j] =
  61018. mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
  61019. }
  61020. return tostring(key);
  61021. }
  61022. //
  61023. // autoseed()
  61024. // Returns an object for autoseeding, using window.crypto and Node crypto
  61025. // module if available.
  61026. //
  61027. function autoseed() {
  61028. try {
  61029. var out;
  61030. if (nodecrypto && (out = nodecrypto.randomBytes)) {
  61031. // The use of 'out' to remember randomBytes makes tight minified code.
  61032. out = out(width);
  61033. } else {
  61034. out = new Uint8Array(width);
  61035. (global.crypto || global.msCrypto).getRandomValues(out);
  61036. }
  61037. return tostring(out);
  61038. } catch (e) {
  61039. var browser = global.navigator,
  61040. plugins = browser && browser.plugins;
  61041. return [+new Date, global, plugins, global.screen, tostring(pool)];
  61042. }
  61043. }
  61044. //
  61045. // tostring()
  61046. // Converts an array of charcodes to a string
  61047. //
  61048. function tostring(a) {
  61049. return String.fromCharCode.apply(0, a);
  61050. }
  61051. //
  61052. // When seedrandom.js is loaded, we immediately mix a few bits
  61053. // from the built-in RNG into the entropy pool. Because we do
  61054. // not want to interfere with deterministic PRNG state later,
  61055. // seedrandom will not call math.random on its own again after
  61056. // initialization.
  61057. //
  61058. mixkey(math.random(), pool);
  61059. //
  61060. // Nodejs and AMD support: export the implementation as a module using
  61061. // either convention.
  61062. //
  61063. if ((typeof module) == 'object' && module.exports) {
  61064. module.exports = seedrandom;
  61065. // When in node.js, try using crypto package for autoseeding.
  61066. try {
  61067. nodecrypto = require('crypto');
  61068. } catch (ex) {}
  61069. } else if ((typeof define) == 'function' && define.amd) {
  61070. define(function() { return seedrandom; });
  61071. }
  61072. // End anonymous scope, and pass initial values.
  61073. })(
  61074. [], // pool: entropy pool starts empty
  61075. Math // math: package containing random, pow, and seedrandom
  61076. );
  61077. },{"crypto":208}],239:[function(require,module,exports){
  61078. // Copyright Joyent, Inc. and other Node contributors.
  61079. //
  61080. // Permission is hereby granted, free of charge, to any person obtaining a
  61081. // copy of this software and associated documentation files (the
  61082. // "Software"), to deal in the Software without restriction, including
  61083. // without limitation the rights to use, copy, modify, merge, publish,
  61084. // distribute, sublicense, and/or sell copies of the Software, and to permit
  61085. // persons to whom the Software is furnished to do so, subject to the
  61086. // following conditions:
  61087. //
  61088. // The above copyright notice and this permission notice shall be included
  61089. // in all copies or substantial portions of the Software.
  61090. //
  61091. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  61092. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  61093. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  61094. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  61095. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  61096. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  61097. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  61098. 'use strict';
  61099. var punycode = require('punycode');
  61100. var util = require('./util');
  61101. exports.parse = urlParse;
  61102. exports.resolve = urlResolve;
  61103. exports.resolveObject = urlResolveObject;
  61104. exports.format = urlFormat;
  61105. exports.Url = Url;
  61106. function Url() {
  61107. this.protocol = null;
  61108. this.slashes = null;
  61109. this.auth = null;
  61110. this.host = null;
  61111. this.port = null;
  61112. this.hostname = null;
  61113. this.hash = null;
  61114. this.search = null;
  61115. this.query = null;
  61116. this.pathname = null;
  61117. this.path = null;
  61118. this.href = null;
  61119. }
  61120. // Reference: RFC 3986, RFC 1808, RFC 2396
  61121. // define these here so at least they only have to be
  61122. // compiled once on the first module load.
  61123. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  61124. portPattern = /:[0-9]*$/,
  61125. // Special case for a simple path URL
  61126. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  61127. // RFC 2396: characters reserved for delimiting URLs.
  61128. // We actually just auto-escape these.
  61129. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  61130. // RFC 2396: characters not allowed for various reasons.
  61131. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  61132. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  61133. autoEscape = ['\''].concat(unwise),
  61134. // Characters that are never ever allowed in a hostname.
  61135. // Note that any invalid chars are also handled, but these
  61136. // are the ones that are *expected* to be seen, so we fast-path
  61137. // them.
  61138. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  61139. hostEndingChars = ['/', '?', '#'],
  61140. hostnameMaxLen = 255,
  61141. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  61142. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  61143. // protocols that can allow "unsafe" and "unwise" chars.
  61144. unsafeProtocol = {
  61145. 'javascript': true,
  61146. 'javascript:': true
  61147. },
  61148. // protocols that never have a hostname.
  61149. hostlessProtocol = {
  61150. 'javascript': true,
  61151. 'javascript:': true
  61152. },
  61153. // protocols that always contain a // bit.
  61154. slashedProtocol = {
  61155. 'http': true,
  61156. 'https': true,
  61157. 'ftp': true,
  61158. 'gopher': true,
  61159. 'file': true,
  61160. 'http:': true,
  61161. 'https:': true,
  61162. 'ftp:': true,
  61163. 'gopher:': true,
  61164. 'file:': true
  61165. },
  61166. querystring = require('querystring');
  61167. function urlParse(url, parseQueryString, slashesDenoteHost) {
  61168. if (url && util.isObject(url) && url instanceof Url) return url;
  61169. var u = new Url;
  61170. u.parse(url, parseQueryString, slashesDenoteHost);
  61171. return u;
  61172. }
  61173. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  61174. if (!util.isString(url)) {
  61175. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  61176. }
  61177. // Copy chrome, IE, opera backslash-handling behavior.
  61178. // Back slashes before the query string get converted to forward slashes
  61179. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  61180. var queryIndex = url.indexOf('?'),
  61181. splitter =
  61182. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  61183. uSplit = url.split(splitter),
  61184. slashRegex = /\\/g;
  61185. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  61186. url = uSplit.join(splitter);
  61187. var rest = url;
  61188. // trim before proceeding.
  61189. // This is to support parse stuff like " http://foo.com \n"
  61190. rest = rest.trim();
  61191. if (!slashesDenoteHost && url.split('#').length === 1) {
  61192. // Try fast path regexp
  61193. var simplePath = simplePathPattern.exec(rest);
  61194. if (simplePath) {
  61195. this.path = rest;
  61196. this.href = rest;
  61197. this.pathname = simplePath[1];
  61198. if (simplePath[2]) {
  61199. this.search = simplePath[2];
  61200. if (parseQueryString) {
  61201. this.query = querystring.parse(this.search.substr(1));
  61202. } else {
  61203. this.query = this.search.substr(1);
  61204. }
  61205. } else if (parseQueryString) {
  61206. this.search = '';
  61207. this.query = {};
  61208. }
  61209. return this;
  61210. }
  61211. }
  61212. var proto = protocolPattern.exec(rest);
  61213. if (proto) {
  61214. proto = proto[0];
  61215. var lowerProto = proto.toLowerCase();
  61216. this.protocol = lowerProto;
  61217. rest = rest.substr(proto.length);
  61218. }
  61219. // figure out if it's got a host
  61220. // user@server is *always* interpreted as a hostname, and url
  61221. // resolution will treat //foo/bar as host=foo,path=bar because that's
  61222. // how the browser resolves relative URLs.
  61223. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  61224. var slashes = rest.substr(0, 2) === '//';
  61225. if (slashes && !(proto && hostlessProtocol[proto])) {
  61226. rest = rest.substr(2);
  61227. this.slashes = true;
  61228. }
  61229. }
  61230. if (!hostlessProtocol[proto] &&
  61231. (slashes || (proto && !slashedProtocol[proto]))) {
  61232. // there's a hostname.
  61233. // the first instance of /, ?, ;, or # ends the host.
  61234. //
  61235. // If there is an @ in the hostname, then non-host chars *are* allowed
  61236. // to the left of the last @ sign, unless some host-ending character
  61237. // comes *before* the @-sign.
  61238. // URLs are obnoxious.
  61239. //
  61240. // ex:
  61241. // http://a@b@c/ => user:a@b host:c
  61242. // http://a@b?@c => user:a host:c path:/?@c
  61243. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  61244. // Review our test case against browsers more comprehensively.
  61245. // find the first instance of any hostEndingChars
  61246. var hostEnd = -1;
  61247. for (var i = 0; i < hostEndingChars.length; i++) {
  61248. var hec = rest.indexOf(hostEndingChars[i]);
  61249. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  61250. hostEnd = hec;
  61251. }
  61252. // at this point, either we have an explicit point where the
  61253. // auth portion cannot go past, or the last @ char is the decider.
  61254. var auth, atSign;
  61255. if (hostEnd === -1) {
  61256. // atSign can be anywhere.
  61257. atSign = rest.lastIndexOf('@');
  61258. } else {
  61259. // atSign must be in auth portion.
  61260. // http://a@b/c@d => host:b auth:a path:/c@d
  61261. atSign = rest.lastIndexOf('@', hostEnd);
  61262. }
  61263. // Now we have a portion which is definitely the auth.
  61264. // Pull that off.
  61265. if (atSign !== -1) {
  61266. auth = rest.slice(0, atSign);
  61267. rest = rest.slice(atSign + 1);
  61268. this.auth = decodeURIComponent(auth);
  61269. }
  61270. // the host is the remaining to the left of the first non-host char
  61271. hostEnd = -1;
  61272. for (var i = 0; i < nonHostChars.length; i++) {
  61273. var hec = rest.indexOf(nonHostChars[i]);
  61274. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  61275. hostEnd = hec;
  61276. }
  61277. // if we still have not hit it, then the entire thing is a host.
  61278. if (hostEnd === -1)
  61279. hostEnd = rest.length;
  61280. this.host = rest.slice(0, hostEnd);
  61281. rest = rest.slice(hostEnd);
  61282. // pull out port.
  61283. this.parseHost();
  61284. // we've indicated that there is a hostname,
  61285. // so even if it's empty, it has to be present.
  61286. this.hostname = this.hostname || '';
  61287. // if hostname begins with [ and ends with ]
  61288. // assume that it's an IPv6 address.
  61289. var ipv6Hostname = this.hostname[0] === '[' &&
  61290. this.hostname[this.hostname.length - 1] === ']';
  61291. // validate a little.
  61292. if (!ipv6Hostname) {
  61293. var hostparts = this.hostname.split(/\./);
  61294. for (var i = 0, l = hostparts.length; i < l; i++) {
  61295. var part = hostparts[i];
  61296. if (!part) continue;
  61297. if (!part.match(hostnamePartPattern)) {
  61298. var newpart = '';
  61299. for (var j = 0, k = part.length; j < k; j++) {
  61300. if (part.charCodeAt(j) > 127) {
  61301. // we replace non-ASCII char with a temporary placeholder
  61302. // we need this to make sure size of hostname is not
  61303. // broken by replacing non-ASCII by nothing
  61304. newpart += 'x';
  61305. } else {
  61306. newpart += part[j];
  61307. }
  61308. }
  61309. // we test again with ASCII char only
  61310. if (!newpart.match(hostnamePartPattern)) {
  61311. var validParts = hostparts.slice(0, i);
  61312. var notHost = hostparts.slice(i + 1);
  61313. var bit = part.match(hostnamePartStart);
  61314. if (bit) {
  61315. validParts.push(bit[1]);
  61316. notHost.unshift(bit[2]);
  61317. }
  61318. if (notHost.length) {
  61319. rest = '/' + notHost.join('.') + rest;
  61320. }
  61321. this.hostname = validParts.join('.');
  61322. break;
  61323. }
  61324. }
  61325. }
  61326. }
  61327. if (this.hostname.length > hostnameMaxLen) {
  61328. this.hostname = '';
  61329. } else {
  61330. // hostnames are always lower case.
  61331. this.hostname = this.hostname.toLowerCase();
  61332. }
  61333. if (!ipv6Hostname) {
  61334. // IDNA Support: Returns a punycoded representation of "domain".
  61335. // It only converts parts of the domain name that
  61336. // have non-ASCII characters, i.e. it doesn't matter if
  61337. // you call it with a domain that already is ASCII-only.
  61338. this.hostname = punycode.toASCII(this.hostname);
  61339. }
  61340. var p = this.port ? ':' + this.port : '';
  61341. var h = this.hostname || '';
  61342. this.host = h + p;
  61343. this.href += this.host;
  61344. // strip [ and ] from the hostname
  61345. // the host field still retains them, though
  61346. if (ipv6Hostname) {
  61347. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  61348. if (rest[0] !== '/') {
  61349. rest = '/' + rest;
  61350. }
  61351. }
  61352. }
  61353. // now rest is set to the post-host stuff.
  61354. // chop off any delim chars.
  61355. if (!unsafeProtocol[lowerProto]) {
  61356. // First, make 100% sure that any "autoEscape" chars get
  61357. // escaped, even if encodeURIComponent doesn't think they
  61358. // need to be.
  61359. for (var i = 0, l = autoEscape.length; i < l; i++) {
  61360. var ae = autoEscape[i];
  61361. if (rest.indexOf(ae) === -1)
  61362. continue;
  61363. var esc = encodeURIComponent(ae);
  61364. if (esc === ae) {
  61365. esc = escape(ae);
  61366. }
  61367. rest = rest.split(ae).join(esc);
  61368. }
  61369. }
  61370. // chop off from the tail first.
  61371. var hash = rest.indexOf('#');
  61372. if (hash !== -1) {
  61373. // got a fragment string.
  61374. this.hash = rest.substr(hash);
  61375. rest = rest.slice(0, hash);
  61376. }
  61377. var qm = rest.indexOf('?');
  61378. if (qm !== -1) {
  61379. this.search = rest.substr(qm);
  61380. this.query = rest.substr(qm + 1);
  61381. if (parseQueryString) {
  61382. this.query = querystring.parse(this.query);
  61383. }
  61384. rest = rest.slice(0, qm);
  61385. } else if (parseQueryString) {
  61386. // no query string, but parseQueryString still requested
  61387. this.search = '';
  61388. this.query = {};
  61389. }
  61390. if (rest) this.pathname = rest;
  61391. if (slashedProtocol[lowerProto] &&
  61392. this.hostname && !this.pathname) {
  61393. this.pathname = '/';
  61394. }
  61395. //to support http.request
  61396. if (this.pathname || this.search) {
  61397. var p = this.pathname || '';
  61398. var s = this.search || '';
  61399. this.path = p + s;
  61400. }
  61401. // finally, reconstruct the href based on what has been validated.
  61402. this.href = this.format();
  61403. return this;
  61404. };
  61405. // format a parsed object into a url string
  61406. function urlFormat(obj) {
  61407. // ensure it's an object, and not a string url.
  61408. // If it's an obj, this is a no-op.
  61409. // this way, you can call url_format() on strings
  61410. // to clean up potentially wonky urls.
  61411. if (util.isString(obj)) obj = urlParse(obj);
  61412. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  61413. return obj.format();
  61414. }
  61415. Url.prototype.format = function() {
  61416. var auth = this.auth || '';
  61417. if (auth) {
  61418. auth = encodeURIComponent(auth);
  61419. auth = auth.replace(/%3A/i, ':');
  61420. auth += '@';
  61421. }
  61422. var protocol = this.protocol || '',
  61423. pathname = this.pathname || '',
  61424. hash = this.hash || '',
  61425. host = false,
  61426. query = '';
  61427. if (this.host) {
  61428. host = auth + this.host;
  61429. } else if (this.hostname) {
  61430. host = auth + (this.hostname.indexOf(':') === -1 ?
  61431. this.hostname :
  61432. '[' + this.hostname + ']');
  61433. if (this.port) {
  61434. host += ':' + this.port;
  61435. }
  61436. }
  61437. if (this.query &&
  61438. util.isObject(this.query) &&
  61439. Object.keys(this.query).length) {
  61440. query = querystring.stringify(this.query);
  61441. }
  61442. var search = this.search || (query && ('?' + query)) || '';
  61443. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  61444. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  61445. // unless they had them to begin with.
  61446. if (this.slashes ||
  61447. (!protocol || slashedProtocol[protocol]) && host !== false) {
  61448. host = '//' + (host || '');
  61449. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  61450. } else if (!host) {
  61451. host = '';
  61452. }
  61453. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  61454. if (search && search.charAt(0) !== '?') search = '?' + search;
  61455. pathname = pathname.replace(/[?#]/g, function(match) {
  61456. return encodeURIComponent(match);
  61457. });
  61458. search = search.replace('#', '%23');
  61459. return protocol + host + pathname + search + hash;
  61460. };
  61461. function urlResolve(source, relative) {
  61462. return urlParse(source, false, true).resolve(relative);
  61463. }
  61464. Url.prototype.resolve = function(relative) {
  61465. return this.resolveObject(urlParse(relative, false, true)).format();
  61466. };
  61467. function urlResolveObject(source, relative) {
  61468. if (!source) return relative;
  61469. return urlParse(source, false, true).resolveObject(relative);
  61470. }
  61471. Url.prototype.resolveObject = function(relative) {
  61472. if (util.isString(relative)) {
  61473. var rel = new Url();
  61474. rel.parse(relative, false, true);
  61475. relative = rel;
  61476. }
  61477. var result = new Url();
  61478. var tkeys = Object.keys(this);
  61479. for (var tk = 0; tk < tkeys.length; tk++) {
  61480. var tkey = tkeys[tk];
  61481. result[tkey] = this[tkey];
  61482. }
  61483. // hash is always overridden, no matter what.
  61484. // even href="" will remove it.
  61485. result.hash = relative.hash;
  61486. // if the relative url is empty, then there's nothing left to do here.
  61487. if (relative.href === '') {
  61488. result.href = result.format();
  61489. return result;
  61490. }
  61491. // hrefs like //foo/bar always cut to the protocol.
  61492. if (relative.slashes && !relative.protocol) {
  61493. // take everything except the protocol from relative
  61494. var rkeys = Object.keys(relative);
  61495. for (var rk = 0; rk < rkeys.length; rk++) {
  61496. var rkey = rkeys[rk];
  61497. if (rkey !== 'protocol')
  61498. result[rkey] = relative[rkey];
  61499. }
  61500. //urlParse appends trailing / to urls like http://www.example.com
  61501. if (slashedProtocol[result.protocol] &&
  61502. result.hostname && !result.pathname) {
  61503. result.path = result.pathname = '/';
  61504. }
  61505. result.href = result.format();
  61506. return result;
  61507. }
  61508. if (relative.protocol && relative.protocol !== result.protocol) {
  61509. // if it's a known url protocol, then changing
  61510. // the protocol does weird things
  61511. // first, if it's not file:, then we MUST have a host,
  61512. // and if there was a path
  61513. // to begin with, then we MUST have a path.
  61514. // if it is file:, then the host is dropped,
  61515. // because that's known to be hostless.
  61516. // anything else is assumed to be absolute.
  61517. if (!slashedProtocol[relative.protocol]) {
  61518. var keys = Object.keys(relative);
  61519. for (var v = 0; v < keys.length; v++) {
  61520. var k = keys[v];
  61521. result[k] = relative[k];
  61522. }
  61523. result.href = result.format();
  61524. return result;
  61525. }
  61526. result.protocol = relative.protocol;
  61527. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  61528. var relPath = (relative.pathname || '').split('/');
  61529. while (relPath.length && !(relative.host = relPath.shift()));
  61530. if (!relative.host) relative.host = '';
  61531. if (!relative.hostname) relative.hostname = '';
  61532. if (relPath[0] !== '') relPath.unshift('');
  61533. if (relPath.length < 2) relPath.unshift('');
  61534. result.pathname = relPath.join('/');
  61535. } else {
  61536. result.pathname = relative.pathname;
  61537. }
  61538. result.search = relative.search;
  61539. result.query = relative.query;
  61540. result.host = relative.host || '';
  61541. result.auth = relative.auth;
  61542. result.hostname = relative.hostname || relative.host;
  61543. result.port = relative.port;
  61544. // to support http.request
  61545. if (result.pathname || result.search) {
  61546. var p = result.pathname || '';
  61547. var s = result.search || '';
  61548. result.path = p + s;
  61549. }
  61550. result.slashes = result.slashes || relative.slashes;
  61551. result.href = result.format();
  61552. return result;
  61553. }
  61554. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  61555. isRelAbs = (
  61556. relative.host ||
  61557. relative.pathname && relative.pathname.charAt(0) === '/'
  61558. ),
  61559. mustEndAbs = (isRelAbs || isSourceAbs ||
  61560. (result.host && relative.pathname)),
  61561. removeAllDots = mustEndAbs,
  61562. srcPath = result.pathname && result.pathname.split('/') || [],
  61563. relPath = relative.pathname && relative.pathname.split('/') || [],
  61564. psychotic = result.protocol && !slashedProtocol[result.protocol];
  61565. // if the url is a non-slashed url, then relative
  61566. // links like ../.. should be able
  61567. // to crawl up to the hostname, as well. This is strange.
  61568. // result.protocol has already been set by now.
  61569. // Later on, put the first path part into the host field.
  61570. if (psychotic) {
  61571. result.hostname = '';
  61572. result.port = null;
  61573. if (result.host) {
  61574. if (srcPath[0] === '') srcPath[0] = result.host;
  61575. else srcPath.unshift(result.host);
  61576. }
  61577. result.host = '';
  61578. if (relative.protocol) {
  61579. relative.hostname = null;
  61580. relative.port = null;
  61581. if (relative.host) {
  61582. if (relPath[0] === '') relPath[0] = relative.host;
  61583. else relPath.unshift(relative.host);
  61584. }
  61585. relative.host = null;
  61586. }
  61587. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  61588. }
  61589. if (isRelAbs) {
  61590. // it's absolute.
  61591. result.host = (relative.host || relative.host === '') ?
  61592. relative.host : result.host;
  61593. result.hostname = (relative.hostname || relative.hostname === '') ?
  61594. relative.hostname : result.hostname;
  61595. result.search = relative.search;
  61596. result.query = relative.query;
  61597. srcPath = relPath;
  61598. // fall through to the dot-handling below.
  61599. } else if (relPath.length) {
  61600. // it's relative
  61601. // throw away the existing file, and take the new path instead.
  61602. if (!srcPath) srcPath = [];
  61603. srcPath.pop();
  61604. srcPath = srcPath.concat(relPath);
  61605. result.search = relative.search;
  61606. result.query = relative.query;
  61607. } else if (!util.isNullOrUndefined(relative.search)) {
  61608. // just pull out the search.
  61609. // like href='?foo'.
  61610. // Put this after the other two cases because it simplifies the booleans
  61611. if (psychotic) {
  61612. result.hostname = result.host = srcPath.shift();
  61613. //occationaly the auth can get stuck only in host
  61614. //this especially happens in cases like
  61615. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  61616. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  61617. result.host.split('@') : false;
  61618. if (authInHost) {
  61619. result.auth = authInHost.shift();
  61620. result.host = result.hostname = authInHost.shift();
  61621. }
  61622. }
  61623. result.search = relative.search;
  61624. result.query = relative.query;
  61625. //to support http.request
  61626. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  61627. result.path = (result.pathname ? result.pathname : '') +
  61628. (result.search ? result.search : '');
  61629. }
  61630. result.href = result.format();
  61631. return result;
  61632. }
  61633. if (!srcPath.length) {
  61634. // no path at all. easy.
  61635. // we've already handled the other stuff above.
  61636. result.pathname = null;
  61637. //to support http.request
  61638. if (result.search) {
  61639. result.path = '/' + result.search;
  61640. } else {
  61641. result.path = null;
  61642. }
  61643. result.href = result.format();
  61644. return result;
  61645. }
  61646. // if a url ENDs in . or .., then it must get a trailing slash.
  61647. // however, if it ends in anything else non-slashy,
  61648. // then it must NOT get a trailing slash.
  61649. var last = srcPath.slice(-1)[0];
  61650. var hasTrailingSlash = (
  61651. (result.host || relative.host || srcPath.length > 1) &&
  61652. (last === '.' || last === '..') || last === '');
  61653. // strip single dots, resolve double dots to parent dir
  61654. // if the path tries to go above the root, `up` ends up > 0
  61655. var up = 0;
  61656. for (var i = srcPath.length; i >= 0; i--) {
  61657. last = srcPath[i];
  61658. if (last === '.') {
  61659. srcPath.splice(i, 1);
  61660. } else if (last === '..') {
  61661. srcPath.splice(i, 1);
  61662. up++;
  61663. } else if (up) {
  61664. srcPath.splice(i, 1);
  61665. up--;
  61666. }
  61667. }
  61668. // if the path is allowed to go above the root, restore leading ..s
  61669. if (!mustEndAbs && !removeAllDots) {
  61670. for (; up--; up) {
  61671. srcPath.unshift('..');
  61672. }
  61673. }
  61674. if (mustEndAbs && srcPath[0] !== '' &&
  61675. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  61676. srcPath.unshift('');
  61677. }
  61678. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  61679. srcPath.push('');
  61680. }
  61681. var isAbsolute = srcPath[0] === '' ||
  61682. (srcPath[0] && srcPath[0].charAt(0) === '/');
  61683. // put the host back
  61684. if (psychotic) {
  61685. result.hostname = result.host = isAbsolute ? '' :
  61686. srcPath.length ? srcPath.shift() : '';
  61687. //occationaly the auth can get stuck only in host
  61688. //this especially happens in cases like
  61689. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  61690. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  61691. result.host.split('@') : false;
  61692. if (authInHost) {
  61693. result.auth = authInHost.shift();
  61694. result.host = result.hostname = authInHost.shift();
  61695. }
  61696. }
  61697. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  61698. if (mustEndAbs && !isAbsolute) {
  61699. srcPath.unshift('');
  61700. }
  61701. if (!srcPath.length) {
  61702. result.pathname = null;
  61703. result.path = null;
  61704. } else {
  61705. result.pathname = srcPath.join('/');
  61706. }
  61707. //to support request.http
  61708. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  61709. result.path = (result.pathname ? result.pathname : '') +
  61710. (result.search ? result.search : '');
  61711. }
  61712. result.auth = relative.auth || result.auth;
  61713. result.slashes = result.slashes || relative.slashes;
  61714. result.href = result.format();
  61715. return result;
  61716. };
  61717. Url.prototype.parseHost = function() {
  61718. var host = this.host;
  61719. var port = portPattern.exec(host);
  61720. if (port) {
  61721. port = port[0];
  61722. if (port !== ':') {
  61723. this.port = port.substr(1);
  61724. }
  61725. host = host.substr(0, host.length - port.length);
  61726. }
  61727. if (host) this.hostname = host;
  61728. };
  61729. },{"./util":240,"punycode":227,"querystring":230}],240:[function(require,module,exports){
  61730. 'use strict';
  61731. module.exports = {
  61732. isString: function(arg) {
  61733. return typeof(arg) === 'string';
  61734. },
  61735. isObject: function(arg) {
  61736. return typeof(arg) === 'object' && arg !== null;
  61737. },
  61738. isNull: function(arg) {
  61739. return arg === null;
  61740. },
  61741. isNullOrUndefined: function(arg) {
  61742. return arg == null;
  61743. }
  61744. };
  61745. },{}],241:[function(require,module,exports){
  61746. 'use strict';
  61747. Object.defineProperty(exports, "__esModule", {
  61748. value: true
  61749. });
  61750. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  61751. var _config = require('./../config.js');
  61752. var _config2 = _interopRequireDefault(_config);
  61753. var _tfjs = require('@tensorflow/tfjs');
  61754. var tf = _interopRequireWildcard(_tfjs);
  61755. var _knnClassifier = require('@tensorflow-models/knn-classifier');
  61756. var knnClassifier = _interopRequireWildcard(_knnClassifier);
  61757. var _mobilenet = require('@tensorflow-models/mobilenet');
  61758. var mobilenet = _interopRequireWildcard(_mobilenet);
  61759. var _html2canvas = require('html2canvas');
  61760. var _html2canvas2 = _interopRequireDefault(_html2canvas);
  61761. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  61762. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  61763. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  61764. // Copyright 2017 Google Inc.
  61765. //
  61766. // Licensed under the Apache License, Version 2.0 (the "License");
  61767. // you may not use this file except in compliance with the License.
  61768. // You may obtain a copy of the License at
  61769. //
  61770. // http://www.apache.org/licenses/LICENSE-2.0
  61771. //
  61772. // Unless required by applicable law or agreed to in writing, software
  61773. // distributed under the License is distributed on an "AS IS" BASIS,
  61774. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  61775. // See the License for the specific language governing permissions and
  61776. // limitations under the License.
  61777. /* eslint-disable camelcase, max-lines, */
  61778. var IMAGE_SIZE = 227;
  61779. var INPUT_SIZE = 1000;
  61780. var TOPK = 10;
  61781. var CLASS_COUNT = 3;
  61782. var MEASURE_TIMING_EVERY_NUM_FRAMES = 20;
  61783. var image_format = 'jpeg';
  61784. var image_quality = 90;
  61785. function passThrough() {
  61786. return 0;
  61787. }
  61788. var WebcamClassifier = function () {
  61789. function WebcamClassifier() {
  61790. _classCallCheck(this, WebcamClassifier);
  61791. this.loaded = false;
  61792. this.video = document.createElement('video');
  61793. this.video.setAttribute('autoplay', '');
  61794. this.video.setAttribute('playsinline', '');
  61795. this.video.style.display = 'none';
  61796. // this.video = document.getElementById('output')
  61797. // this.video.addEventListener('loadedmetadata', this.videoLoaded.bind(this));
  61798. this.wasStop = false;
  61799. this.wasStart = false;
  61800. this.blankCanvas = document.createElement('canvas');
  61801. this.blankCanvas.width = 400;
  61802. this.blankCanvas.height = 436;
  61803. this.timer = null;
  61804. this.active = false;
  61805. this.wasActive = false;
  61806. this.stream = null;
  61807. this.latestCanvas = document.createElement('canvas');
  61808. this.latestCanvas.width = 98;
  61809. this.latestCanvas.height = 98;
  61810. this.latestContext = this.latestCanvas.getContext('2d');
  61811. this.thumbCanvas = document.createElement('canvas');
  61812. this.thumbCanvas.width = Math.floor(this.latestCanvas.width / 3) + 1;
  61813. this.thumbCanvas.height = Math.floor(this.latestCanvas.height / 3) + 1;
  61814. this.thumbContext = this.thumbCanvas.getContext('2d');
  61815. this.imgSrc = [];
  61816. this.thumbVideoX = 0;
  61817. this.classNames = _config2.default.classNames;
  61818. this.images = {};
  61819. for (var index = 0; index < this.classNames.length; index += 1) {
  61820. this.images[this.classNames[index]] = {
  61821. index: index,
  61822. down: false,
  61823. imagesCount: 0,
  61824. images: [],
  61825. latestImages: [],
  61826. latestThumbs: []
  61827. };
  61828. }
  61829. this.isDown = false;
  61830. this.current = null;
  61831. this.currentClass = null;
  61832. this.measureTimingCounter = 0;
  61833. this.lastFrameTimeMs = 1000;
  61834. this.classIndices = {};
  61835. this.currentSavedClassIndex = 0;
  61836. this.mappedButtonIndexes = [];
  61837. this.init();
  61838. }
  61839. _createClass(WebcamClassifier, [{
  61840. key: 'startWebcam',
  61841. value: function startWebcam() {
  61842. var _this = this;
  61843. if (this.wasStart) {
  61844. this.startTimer();
  61845. return;
  61846. }
  61847. var video = true;
  61848. if (_config2.default.browserUtils.isMobile) {
  61849. video = { facingMode: _config2.default.isBackFacingCam ? 'environment' : 'user' };
  61850. }
  61851. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  61852. navigator.mediaDevices.getUserMedia({
  61853. video: video
  61854. // audio: (GLOBALS.browserUtils.isChrome && !GLOBALS.browserUtils.isMobile)
  61855. }).then(function (stream) {
  61856. _config2.default.isCamGranted = true;
  61857. // if ((GLOBALS.browserUtils.isChrome && !GLOBALS.browserUtils.isMobile)) {
  61858. // GLOBALS.audioContext.createMediaStreamSource(stream);
  61859. // GLOBALS.stream = stream;
  61860. // }
  61861. // console.log("GLOBALS.stream " + GLOBALS.stream)
  61862. // this.activateWebcamButton.style.display = 'none';
  61863. _this.active = true;
  61864. _this.stream = stream;
  61865. _this.video.muted = true;
  61866. _this.video.srcObject = stream;
  61867. _this.video.width = 300;
  61868. _this.video.height = 436;
  61869. // this.videoLoaded();
  61870. _this.video.addEventListener('loadedmetadata', _this.videoLoaded.bind(_this));
  61871. var event = new CustomEvent('webcam-status', { detail: { granted: true } });
  61872. _this.startTimer();
  61873. _this.wasStart = true;
  61874. }).catch(function (error) {
  61875. var event = new CustomEvent('webcam-status', {
  61876. detail: {
  61877. granted: false,
  61878. error: error
  61879. }
  61880. });
  61881. // this.activateWebcamButton.style.display = 'block';
  61882. window.dispatchEvent(event);
  61883. gtag('event', 'webcam_denied');
  61884. });
  61885. }
  61886. document.querySelector(".cam--stop").classList.add("show");
  61887. document.querySelector(".cam--start").style = "display:none";
  61888. }
  61889. }, {
  61890. key: 'stopWebcam',
  61891. value: function stopWebcam() {
  61892. // this.stopTimer();
  61893. if (this.stream) {
  61894. if (this.stream.getTracks()) {
  61895. this.stream.getTracks().forEach(function (track) {
  61896. track.stop();
  61897. });
  61898. }
  61899. if ("srcObject" in this.video) {
  61900. this.video.srcObject = null;
  61901. } else {
  61902. // using URL.createObjectURL() as fallback for old browsers
  61903. this.video.src = null;
  61904. }
  61905. }
  61906. this.stream = null;
  61907. _config2.default.stream = null;
  61908. this.wasStop = true;
  61909. this.wasStart = false;
  61910. // this.video.removeEventListener('loadedmetadata', this.videoLoaded.bind(this));
  61911. document.querySelector(".cam--stop").classList.remove("show");
  61912. document.querySelector(".cam--start").style = "display:flex";
  61913. }
  61914. }, {
  61915. key: 'init',
  61916. value: async function init() {
  61917. this.useFloatTextures = !_config2.default.browserUtils.isMobile && !_config2.default.browserUtils.isSafari;
  61918. tf.ENV.set('WEBGL_DOWNLOAD_FLOAT_ENABLED', false);
  61919. this.classifier = knnClassifier.create();
  61920. // Load mobilenet.
  61921. this.mobilenetModule = await mobilenet.load();
  61922. }
  61923. /**
  61924. * There is an issue with mobilenetModule/knnClassifier where
  61925. * it returns -1 if you don't start with an index of zero
  61926. *
  61927. * In these train/predict methods, we remap the index of 0-2.
  61928. * This way you can train the third model and have it retain
  61929. * the index of 2.
  61930. *
  61931. * We have these super verbosely named functions
  61932. * so it's clear what's happening
  61933. */
  61934. }, {
  61935. key: 'predict',
  61936. value: async function predict(image) {
  61937. var imgFromPixels = tf.fromPixels(image);
  61938. var logits = this.mobilenetModule.infer(imgFromPixels, 'conv_preds');
  61939. var response = await this.classifier.predictClass(logits);
  61940. var newOutput = {
  61941. classIndex: this.mappedButtonIndexes[response.classIndex],
  61942. confidences: {
  61943. 0: 0,
  61944. 1: 0,
  61945. 2: 0
  61946. }
  61947. };
  61948. this.mappedButtonIndexes.forEach(function (index, count) {
  61949. newOutput.confidences[index] = response.confidences[count];
  61950. });
  61951. return newOutput;
  61952. }
  61953. }, {
  61954. key: 'train',
  61955. value: async function train(image, index) {
  61956. if (this.mappedButtonIndexes.indexOf(index) === -1) {
  61957. this.mappedButtonIndexes.push(index);
  61958. }
  61959. var newMappedIndex = this.mappedButtonIndexes.indexOf(index);
  61960. var img = tf.fromPixels(image);
  61961. if (this.mobilenetModule && this.mobilenetModule.infer) {
  61962. var logits = this.mobilenetModule.infer(img, 'conv_preds');
  61963. this.classifier.addExample(logits, newMappedIndex);
  61964. }
  61965. // const logits = this.mobilenetModule.infer(img, 'conv_preds');
  61966. // this.classifier.addExample(logits, newMappedIndex);
  61967. }
  61968. }, {
  61969. key: 'clear',
  61970. value: function clear(index) {
  61971. var newMappedIndex = this.mappedButtonIndexes.indexOf(index);
  61972. this.classifier.clearClass(newMappedIndex);
  61973. }
  61974. }, {
  61975. key: 'deleteClassData',
  61976. value: function deleteClassData(index) {
  61977. _config2.default.clearing = true;
  61978. this.clear(index);
  61979. this.images[this.classNames[index]].imagesCount = 0;
  61980. this.images[this.classNames[index]].latestThumbs = [];
  61981. this.images[this.classNames[index]].latestImages = [];
  61982. _config2.default.soundOutput.pauseCurrentSound();
  61983. setTimeout(function () {
  61984. _config2.default.clearing = false;
  61985. }, 300);
  61986. }
  61987. }, {
  61988. key: 'ready',
  61989. value: function ready() {
  61990. this.startWebcam();
  61991. }
  61992. }, {
  61993. key: 'videoLoaded',
  61994. value: function videoLoaded() {
  61995. var flip = _config2.default.isBackFacingCam ? 1 : -1;
  61996. var videoRatio = this.video.videoWidth / this.video.videoHeight;
  61997. var parent = this.video.parentNode;
  61998. // console.log(this.video.parentNode)
  61999. var parentWidth = parent.offsetWidth;
  62000. var parentHeight = parent.offsetHeight;
  62001. var videoWidth = parentHeight * videoRatio;
  62002. this.video.style.width = videoWidth + 'px';
  62003. this.video.style.height = parentHeight + 'px';
  62004. this.video.style.transform = 'scaleX(' + flip + ') translate(' + 50 * flip * -1 + '%, -50%)';
  62005. // If video is taller:
  62006. if (videoRatio < 1) {
  62007. this.video.style.transform = 'scale(' + flip * 2 + ', 2) translate(' + flip * 20 * -1 + '%, -30%)';
  62008. }
  62009. }
  62010. }, {
  62011. key: 'blur',
  62012. value: function blur() {
  62013. if (this.timer) {
  62014. // this.stopTimer();
  62015. }
  62016. }
  62017. }, {
  62018. key: 'focus',
  62019. value: function focus() {
  62020. if (this.wasActive) {
  62021. this.startTimer();
  62022. }
  62023. }
  62024. }, {
  62025. key: 'buttonDown',
  62026. value: function buttonDown(id, canvas, learningClass) {
  62027. this.current = this.images[id];
  62028. this.current.down = true;
  62029. this.isDown = true;
  62030. this.training = this.current.index;
  62031. this.videoRatio = this.video.videoWidth / this.video.videoHeight;
  62032. this.currentClass = learningClass;
  62033. this.canvasWidth = canvas.width;
  62034. this.canvasHeight = canvas.height;
  62035. this.videoWidth = this.canvasHeight * this.videoRatio;
  62036. this.thumbVideoHeight = this.canvasHeight / 3;
  62037. this.thumbVideoWidth = this.canvasWidth / 3;
  62038. this.thumbVideoWidthReal = this.thumbVideoHeight * this.videoRatio;
  62039. this.thumbVideoX = -(this.thumbVideoWidthReal - this.thumbVideoWidth) / 2;
  62040. this.currentContext = this.currentClass.canvas.getContext('2d');
  62041. }
  62042. }, {
  62043. key: 'buttonUp',
  62044. value: function buttonUp(id) {
  62045. this.images[id].down = false;
  62046. this.isDown = false;
  62047. this.training = -1;
  62048. this.current = null;
  62049. this.currentContext = null;
  62050. this.currentClass = null;
  62051. }
  62052. }, {
  62053. key: 'startTimer',
  62054. value: function startTimer() {
  62055. if (this.timer) {
  62056. this.stopTimer();
  62057. }
  62058. this.video.play();
  62059. this.wasActive = true;
  62060. this.timer = requestAnimationFrame(this.animate.bind(this));
  62061. }
  62062. }, {
  62063. key: 'stopTimer',
  62064. value: function stopTimer() {
  62065. this.active = false;
  62066. this.wasActive = true;
  62067. // this.video.pause();
  62068. cancelAnimationFrame(this.timer);
  62069. if (_config2.default.soundOutput && _config2.default.soundOutput.muteSounds) {
  62070. _config2.default.soundOutput.muteSounds();
  62071. }
  62072. }
  62073. }, {
  62074. key: 'animate',
  62075. value: async function animate() {
  62076. var _this2 = this;
  62077. // Get image data from video element
  62078. var image = this.video;
  62079. var exampleCount = Object.keys(this.classifier.getClassExampleCount()).length;
  62080. if (this.isDown) {
  62081. this.current.imagesCount += 1;
  62082. this.currentClass.setSamples(this.current.imagesCount);
  62083. if (this.current.latestThumbs.length > 8) {
  62084. this.current.latestThumbs.shift();
  62085. }
  62086. if (this.current.latestImages.length > 8) {
  62087. this.current.latestImages.shift();
  62088. }
  62089. // 将canvas 显示到另一画布上
  62090. // 弹框
  62091. var canvas = document.getElementById('output');
  62092. var img = new Image();
  62093. img.src = canvas.toDataURL("image/png");
  62094. if (this.imgSrc[this.training] && this.imgSrc[this.training].length > 0) {
  62095. this.imgSrc[this.training].push(img.src);
  62096. } else {
  62097. this.imgSrc[this.training] = [img.src];
  62098. }
  62099. this.thumbContext.drawImage(canvas, this.thumbVideoX, 0, this.thumbVideoWidthReal, this.thumbVideoHeight);
  62100. var data = this.thumbContext.getImageData(0, 0, this.canvasWidth, this.canvasHeight);
  62101. this.current.latestThumbs.push(data);
  62102. var cols = 0;
  62103. var rows = 0;
  62104. for (var index = 0; index < this.current.latestThumbs.length; index += 1) {
  62105. this.currentContext.putImageData(this.current.latestThumbs[index], (2 - cols) * this.thumbCanvas.width, rows * this.thumbVideoHeight, 0, 0, this.thumbCanvas.width, this.thumbCanvas.height);
  62106. if (cols === 2) {
  62107. rows += 1;
  62108. cols = 0;
  62109. } else {
  62110. cols += 1;
  62111. }
  62112. }
  62113. // Train class if one of the buttons is held down
  62114. // Add current image to classifier
  62115. if (this.training !== -1) {
  62116. this.train(image, this.training);
  62117. }
  62118. } else if (exampleCount > 0) {
  62119. // If any examples have been added, run predict
  62120. var measureTimer = false;
  62121. var start = performance.now();
  62122. measureTimer = this.measureTimingCounter === 0;
  62123. if (exampleCount > 0) {
  62124. var res = await this.predict(image);
  62125. var computeConfidences = function computeConfidences() {
  62126. _config2.default.learningSection.setConfidences(res.confidences);
  62127. _this2.measureTimingCounter = (_this2.measureTimingCounter + 1) % MEASURE_TIMING_EVERY_NUM_FRAMES;
  62128. };
  62129. if (!_config2.default.browserUtils.isSafari || measureTimer || !_config2.default.browserUtils.isMobile) {
  62130. this.lastFrameTimeMs = performance.now() - start;
  62131. computeConfidences();
  62132. } else {
  62133. setTimeout(computeConfidences, this.lastFrameTimeMs);
  62134. }
  62135. } else if (image.dispose) {
  62136. image.dispose();
  62137. }
  62138. }
  62139. this.timer = requestAnimationFrame(this.animate.bind(this));
  62140. }
  62141. }]);
  62142. return WebcamClassifier;
  62143. }();
  62144. /* eslint-disable keyword-spacing */
  62145. /* eslint-enable camelcase, max-lines, keyword-spacing */
  62146. exports.default = WebcamClassifier;
  62147. },{"./../config.js":242,"@tensorflow-models/knn-classifier":8,"@tensorflow-models/mobilenet":11,"@tensorflow/tfjs":205,"html2canvas":213}],242:[function(require,module,exports){
  62148. 'use strict';
  62149. Object.defineProperty(exports, "__esModule", {
  62150. value: true
  62151. });
  62152. // Copyright 2017 Google Inc.
  62153. //
  62154. // Licensed under the Apache License, Version 2.0 (the "License");
  62155. // you may not use this file except in compliance with the License.
  62156. // You may obtain a copy of the License at
  62157. //
  62158. // http://www.apache.org/licenses/LICENSE-2.0
  62159. //
  62160. // Unless required by applicable law or agreed to in writing, software
  62161. // distributed under the License is distributed on an "AS IS" BASIS,
  62162. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62163. // See the License for the specific language governing permissions and
  62164. // limitations under the License.
  62165. var AudioContext = window.AudioContext || window.webkitAudioContext;
  62166. var GLOBALS = {
  62167. button: {
  62168. padding: 0,
  62169. frontHeight: 40,
  62170. states: {
  62171. normal: {
  62172. x: 8,
  62173. y: 8
  62174. },
  62175. pressed: {
  62176. x: 4,
  62177. y: 4
  62178. }
  62179. }
  62180. },
  62181. classNames: ['green', 'purple', 'orange', 'red'],
  62182. colors: {
  62183. 'green': '#2baa5e',
  62184. 'purple': '#c95ac5',
  62185. 'orange': '#dd4d31',
  62186. 'red': '#e8453c'
  62187. },
  62188. rgbaColors: {
  62189. 'green': 'rgba(43, 170, 94, 0.25)',
  62190. 'purple': 'rgba(201, 90, 197, 0.25)',
  62191. 'orange': 'rgba(221, 77, 49, 0.25)',
  62192. 'red': 'rgba(232, 69, 60, 0.25)'
  62193. },
  62194. classId: null,
  62195. predicting: false,
  62196. micThreshold: 25,
  62197. classesTrained: {
  62198. 'green': false,
  62199. 'purple': false,
  62200. 'orange': false
  62201. },
  62202. numClasses: 3,
  62203. audioContext: new AudioContext(),
  62204. isBackFacingCam: false,
  62205. base_url: '//api.cocorobo.cn/',
  62206. // base_url: '//staging.cocorobo.cn/api/', // staging
  62207. USER: {
  62208. api_key: null,
  62209. evnets: null
  62210. },
  62211. port: '',
  62212. iframe: true,
  62213. lang: 'en',
  62214. languare: {
  62215. en: {
  62216. start: "Start",
  62217. input: 'Input',
  62218. learning: "Learning",
  62219. reset: "Reset",
  62220. CloudOutputL: "Cloud",
  62221. SoundOutput: "Sound",
  62222. SpeechOutput: "Speech",
  62223. stop: "Stop",
  62224. epxamples: "Examples",
  62225. green: 'Train Character One',
  62226. purple: 'Train Character Two',
  62227. orange: 'Train Character Three',
  62228. output: 'Output',
  62229. ModuleOutput: "Module",
  62230. training: "Training",
  62231. triggered_green: "You've triggered Character One!",
  62232. triggered_purple: "You've triggered Character Two!",
  62233. triggered_orange: "You've triggered Character Three!",
  62234. no_triggered: "Nothing is triggered",
  62235. select_cloud: "Select your Cloud Event",
  62236. confidence: "Confidence",
  62237. cloud_title: "STATUS:",
  62238. cloud_content: "Nothing is triggered",
  62239. cloud_green: "Character One",
  62240. cloud_purple: "Character Two",
  62241. cloud_orange: "Character Three",
  62242. selectCloud: "- Choose an event here -",
  62243. content: "Play",
  62244. speech_content: "Say"
  62245. },
  62246. hans: {
  62247. start: "开始",
  62248. input: '输入',
  62249. learning: "学习",
  62250. reset: "重置",
  62251. CloudOutputL: "云端",
  62252. SoundOutput: "声音",
  62253. SpeechOutput: "说话",
  62254. stop: "停止",
  62255. epxamples: "训练图像",
  62256. green: '训练人物一',
  62257. purple: '训练人物二',
  62258. orange: '训练人物三',
  62259. output: '输出',
  62260. ModuleOutput: "模块",
  62261. training: "训练中",
  62262. triggered_green: "识别到了人物一!",
  62263. triggered_purple: "识别到了人物二!",
  62264. triggered_orange: "识别到了人物三!",
  62265. no_triggered: "没有识别到任何东西",
  62266. select_cloud: "选择发送云端事件",
  62267. confidence: "置信度",
  62268. cloud_title: "状态:",
  62269. cloud_content: "什么都没有触发",
  62270. cloud_green: "人物一",
  62271. cloud_purple: "人物二",
  62272. cloud_orange: "人物三",
  62273. selectCloud: "- 请在这里选择一个事件 -",
  62274. content: "播放",
  62275. speech_content: "说"
  62276. },
  62277. hant: {
  62278. start: "開始",
  62279. input: '輸入',
  62280. learning: "學習",
  62281. reset: "重置",
  62282. CloudOutputL: "雲端",
  62283. SoundOutput: "聲音",
  62284. SpeechOutput: "說話",
  62285. stop: "停止",
  62286. epxamples: "訓練圖像",
  62287. green: '訓練人物一',
  62288. purple: '訓練人物二',
  62289. orange: '訓練人物三',
  62290. output: '輸出',
  62291. ModuleOutput: "模塊",
  62292. training: "訓練中",
  62293. triggered_green: "識別到了人物一!",
  62294. triggered_purple: "識別到了人物二!",
  62295. triggered_orange: "識別到了人物三!",
  62296. no_triggered: "沒有識別到任何東西",
  62297. select_cloud: "選擇發送雲端事件",
  62298. confidence: "置信度",
  62299. cloud_title: "狀態:",
  62300. cloud_content: "什麼都沒有觸發",
  62301. cloud_green: "人物一",
  62302. cloud_purple: "人物二",
  62303. cloud_orange: "人物三",
  62304. selectCloud: "- 請在這裏選擇一個事件 -",
  62305. content: "播放",
  62306. speech_content: "說"
  62307. }
  62308. }
  62309. };
  62310. exports.default = GLOBALS;
  62311. },{}],243:[function(require,module,exports){
  62312. "use strict";
  62313. Object.defineProperty(exports, "__esModule", {
  62314. value: true
  62315. });
  62316. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // Copyright 2017 Google Inc.
  62317. //
  62318. // Licensed under the Apache License, Version 2.0 (the "License");
  62319. // you may not use this file except in compliance with the License.
  62320. // You may obtain a copy of the License at
  62321. //
  62322. // http://www.apache.org/licenses/LICENSE-2.0
  62323. //
  62324. // Unless required by applicable law or agreed to in writing, software
  62325. // distributed under the License is distributed on an "AS IS" BASIS,
  62326. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62327. // See the License for the specific language governing permissions and
  62328. // limitations under the License.
  62329. // import Wizard from './ui/modules/Wizard.js';
  62330. // import RecordOpener from './ui/components/RecordOpener.js';
  62331. var _gsap = require("gsap");
  62332. var _gsap2 = _interopRequireDefault(_gsap);
  62333. var _config = require("./config.js");
  62334. var _config2 = _interopRequireDefault(_config);
  62335. var _Button = require("./ui/components/Button.js");
  62336. var _Button2 = _interopRequireDefault(_Button);
  62337. var _IntroSection = require("./ui/modules/IntroSection.js");
  62338. var _IntroSection2 = _interopRequireDefault(_IntroSection);
  62339. var _InputSection = require("./ui/modules/InputSection.js");
  62340. var _InputSection2 = _interopRequireDefault(_InputSection);
  62341. var _LearningSection = require("./ui/modules/LearningSection.js");
  62342. var _LearningSection2 = _interopRequireDefault(_LearningSection);
  62343. var _OutputSection = require("./ui/modules/OutputSection.js");
  62344. var _OutputSection2 = _interopRequireDefault(_OutputSection);
  62345. var _Recording = require("./ui/modules/Recording");
  62346. var _Recording2 = _interopRequireDefault(_Recording);
  62347. var _LaunchScreen = require("./ui/modules/wizard/LaunchScreen.js");
  62348. var _LaunchScreen2 = _interopRequireDefault(_LaunchScreen);
  62349. var _QuickLaunch = require("./ui/modules/wizard/QuickLaunch.js");
  62350. var _QuickLaunch2 = _interopRequireDefault(_QuickLaunch);
  62351. var _BrowserUtils = require("./ui/components/BrowserUtils");
  62352. var _BrowserUtils2 = _interopRequireDefault(_BrowserUtils);
  62353. var _Iframe = require("./ui/modules/Iframe.js");
  62354. var _Iframe2 = _interopRequireDefault(_Iframe);
  62355. var _tfjs = require("@tensorflow/tfjs");
  62356. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  62357. function init() {
  62358. // Shim for forEach for IE/Edge
  62359. if (typeof NodeList.prototype.forEach !== "function") {
  62360. NodeList.prototype.forEach = Array.prototype.forEach;
  62361. }
  62362. _config2.default.browserUtils = new _BrowserUtils2.default();
  62363. // GLOBALS.launchScreen = new LaunchScreen();
  62364. _config2.default.quicklaunch = new _QuickLaunch2.default();
  62365. // GLOBALS.iframePage = new Iframe(document.querySelector("#login_modal"))
  62366. _config2.default.learningSection = new _LearningSection2.default(document.querySelector("#learning-section"));
  62367. _config2.default.inputSection = new _InputSection2.default(document.querySelector("#input-section"));
  62368. _config2.default.outputSection = new _OutputSection2.default(document.querySelector("#output-section"));
  62369. // GLOBALS.recordOpener = new RecordOpener(document.querySelector('#record-open-section'));
  62370. _config2.default.inputSection.ready();
  62371. _config2.default.learningSection.ready();
  62372. // GLOBALS.wizard = new Wizard();
  62373. _config2.default.recordSection = new _Recording2.default(document.querySelector('#recording'));
  62374. if (localStorage.getItem("isBackFacingCam") && localStorage.getItem("isBackFacingCam") === "true") {
  62375. _config2.default.isBackFacingCam = true;
  62376. }
  62377. // Camera status messages per browser
  62378. // if (GLOBALS.browserUtils.isChrome && !GLOBALS.browserUtils.isEdge) {
  62379. // document.querySelector('.input__media__activate').innerHTML = 'To teach your machine, <span class="input__media__activate--desktop"> you need to click up here to turn on your camera and then <a href="#">refresh the page</a>.</span><span class="input__media__activate--mobile"> you need to <a href="#">refresh the page</a> and allow camera access.</span></p>';
  62380. // if (!GLOBALS.browserUtils.isCompatable) {
  62381. // document.querySelector('.wizard__browser-warning').innerHTML = 'Something went wrong and we could not load the site, please try restarting your browser.';
  62382. // }
  62383. // }else if (GLOBALS.browserUtils.isSafari) {
  62384. // document.querySelector('.input__media__activate').innerHTML = 'To teach your machine, you need to turn on your camera. To do this click "Safari" in the menu bar, navigate to "Settings for This Website", in the "Camera" drop down menu choose "Allow" and then <a href="#">refresh the page</a>.';
  62385. // }else if (GLOBALS.browserUtils.isFirefox) {
  62386. // document.querySelector('.input__media__activate').innerHTML = 'To teach your machine, you need to turn on your camera. To do this you need to click this icon <img class="camera-icon" src="assets/ff-camera-icon.png"> to grant access and <a href="#">refresh the page</a>.';
  62387. // }
  62388. _config2.default.quicklaunch.start();
  62389. }
  62390. window.addEventListener("load", init);
  62391. // language('zh-hans');
  62392. // GLOBALS.lang = "hans"
  62393. window.addEventListener("message", function (e) {
  62394. var data = e.data;
  62395. console.log('data', data);
  62396. if ((typeof data === "undefined" ? "undefined" : _typeof(data)) === "object" && data.id === "loginVerify" && data.status === "logged") {
  62397. _config2.default.USER.api_key = data.data.apiKey;
  62398. _config2.default.outputSection.outputs.CloudOutput.getCoCloudEvent();
  62399. _config2.default.lang = data.url.indexOf('zh') > -1 ? data.url.slice(3) : data.url;
  62400. _config2.default.port = data.boards;
  62401. // GLOBALS.iframePage.destory();
  62402. language(data.url);
  62403. if (document.getElementById('port_connect') && data.boards) {
  62404. document.getElementById('portNumber').innerHTML = data.boards;
  62405. document.getElementsByClassName('send_button')[0].classList.add('send_button_color');
  62406. document.getElementsByClassName('send_button')[0].style.display = "block";
  62407. document.getElementsByClassName('send_button')[1].classList.add('send_button_color');
  62408. document.getElementsByClassName('send_button')[1].style.display = "none";
  62409. }
  62410. }
  62411. if (typeof data === "string" && data === "startCam") {
  62412. // GLOBALS.camInput.start();
  62413. setTimeout(function () {
  62414. _config2.default.camInput.webcam_on.click();
  62415. }, 100);
  62416. } else if (typeof data === "string" && data === "stopCam") {
  62417. _config2.default.camInput.webcam_off.click();
  62418. }
  62419. });
  62420. // setTimeout(() => { GLOBALS.camInput.webcam_on.click() }, 1000);
  62421. function language(url) {
  62422. var lang = {
  62423. en: {
  62424. start: "Start",
  62425. input: 'Input',
  62426. learning: "Learning",
  62427. reset: "Big",
  62428. CloudOutputL: "Cloud",
  62429. SoundOutput: "Sound",
  62430. SpeechOutput: "Speech",
  62431. stop: "Stop",
  62432. epxamples: "Examples",
  62433. green: 'Train Character One',
  62434. purple: 'Train Character Two',
  62435. orange: 'Train Character Three',
  62436. outputs: 'Output',
  62437. ModuleOutput: "Module",
  62438. training: "Training",
  62439. triggered_green: "You've triggered Character One!",
  62440. triggered_purple: "You've triggered Character Two!",
  62441. triggered_orange: "You've triggered Character Three!",
  62442. no_triggered: "Nothing is triggered",
  62443. select_cloud: "Select your Cloud Event",
  62444. confidence: "Confidence",
  62445. posenet: "Posenet Result",
  62446. custom_data: "Custom send values",
  62447. cloud_title: "STATUS:",
  62448. cloud_content: "Nothing is triggered",
  62449. cloud_green: "Character One",
  62450. cloud_purple: "Character Two",
  62451. cloud_orange: "Character Three",
  62452. selectCloud: "- Choose an event here -",
  62453. content: "Play"
  62454. },
  62455. hans: {
  62456. start: "开始",
  62457. input: '输入',
  62458. learning: "学习",
  62459. reset: "放大",
  62460. CloudOutputL: "云端",
  62461. SoundOutput: "声音",
  62462. SpeechOutput: "说话",
  62463. stop: "停止",
  62464. epxamples: "训练图像",
  62465. green: '训练人物一',
  62466. purple: '训练人物二',
  62467. orange: '训练人物三',
  62468. outputs: '输出',
  62469. ModuleOutput: "模块",
  62470. training: "训练中",
  62471. triggered_green: "识别到了人物一!",
  62472. triggered_purple: "识别到了人物二!",
  62473. triggered_orange: "识别到了人物三!",
  62474. no_triggered: "没有识别到任何东西",
  62475. select_cloud: "选择发送云端事件",
  62476. confidence: "置信度",
  62477. posenet: "姿态识别结果",
  62478. custom_data: "自定义发送值",
  62479. cloud_title: "状态:",
  62480. cloud_content: "什么都没有触发",
  62481. cloud_green: "人物一",
  62482. cloud_purple: "人物二",
  62483. cloud_orange: "人物三",
  62484. selectCloud: "- 请在这里选择一个事件 -",
  62485. content: "播放"
  62486. },
  62487. hant: {
  62488. start: "開始",
  62489. input: '輸入',
  62490. learning: "學習",
  62491. reset: "放大",
  62492. CloudOutputL: "雲端",
  62493. SoundOutput: "聲音",
  62494. SpeechOutput: "說話",
  62495. stop: "停止",
  62496. epxamples: "訓練圖像",
  62497. green: '訓練人物一',
  62498. purple: '訓練人物二',
  62499. orange: '訓練人物三',
  62500. outputs: '輸出',
  62501. ModuleOutput: "模塊",
  62502. training: "訓練中",
  62503. triggered_green: "識別到了人物一!",
  62504. triggered_purple: "識別到了人物二!",
  62505. triggered_orange: "識別到了人物三!",
  62506. no_triggered: "沒有識別到任何東西",
  62507. select_cloud: "選擇發送雲端事件",
  62508. confidence: "置信度",
  62509. posenet: "姿態識別結果",
  62510. custom_data: "自定義發送值",
  62511. cloud_title: "狀態:",
  62512. cloud_content: "什麼都沒有觸發",
  62513. cloud_green: "人物一",
  62514. cloud_purple: "人物二",
  62515. cloud_orange: "人物三",
  62516. selectCloud: "- 請在這裏選擇一個事件 -",
  62517. content: "播放"
  62518. }
  62519. };
  62520. setTimeout(function () {
  62521. var language = lang.en;
  62522. if (url === 'zh-hans') {
  62523. language = lang.hans;
  62524. } else if (url === 'zh-hant') {
  62525. language = lang.hant;
  62526. } else {
  62527. language = lang.en;
  62528. }
  62529. document.getElementById('input').innerText = language.input;
  62530. document.getElementById('start').innerText = language.start;
  62531. document.getElementById('stop').innerText = language.stop;
  62532. document.getElementById('CloudOutput').innerText = language.CloudOutputL;
  62533. document.getElementById('SoundOutput').innerText = language.SoundOutput;
  62534. document.getElementById('SpeechOutput').innerText = language.SpeechOutput;
  62535. document.getElementById('learning').innerText = language.learning;
  62536. document.getElementById('posenet').innerText = language.posenet;
  62537. document.getElementById('train_green').innerText = language.green;
  62538. document.getElementById('train_purple').innerText = language.purple;
  62539. document.getElementById('train_orange').innerText = language.orange;
  62540. document.getElementById('outputs').innerText = language.outputs;
  62541. // document.getElementById('ModuleOutput').innerText = language.ModuleOutput;
  62542. document.getElementById('cloud_title').innerText = language.cloud_title;
  62543. document.getElementById('cloud__viewer_title').innerText = language.select_cloud;
  62544. document.getElementById('cloud_content').innerText = language.no_triggered;
  62545. document.getElementById('cloud_green').childNodes[1].innerText = language.cloud_green;
  62546. document.getElementById('cloud_purple').childNodes[1].innerText = language.cloud_purple;
  62547. document.getElementById('cloud_orange').childNodes[1].innerText = language.cloud_orange;
  62548. var reset = document.getElementsByClassName('reset_lang');
  62549. for (var i = 0; i < reset.length; i++) {
  62550. reset[i].innerText = language.reset;
  62551. }
  62552. var confidence = document.getElementsByClassName('confidence__status_value');
  62553. for (var _i = 0; _i < confidence.length; _i++) {
  62554. confidence[_i].innerText = language.confidence;
  62555. }
  62556. var examples = document.getElementsByClassName('examples_lang');
  62557. for (var _i2 = 0; _i2 < examples.length; _i2++) {
  62558. examples[_i2].innerText = language.epxamples;
  62559. }
  62560. var custom_data = document.getElementsByClassName('custom_data');
  62561. for (var _i3 = 0; _i3 < custom_data.length; _i3++) {
  62562. custom_data[_i3].setAttribute("placeholder", language.custom_data);
  62563. }
  62564. }, 1000);
  62565. }
  62566. exports.default = _config2.default;
  62567. },{"./config.js":242,"./ui/components/BrowserUtils":251,"./ui/components/Button.js":252,"./ui/modules/Iframe.js":258,"./ui/modules/InputSection.js":259,"./ui/modules/IntroSection.js":260,"./ui/modules/LearningSection.js":262,"./ui/modules/OutputSection.js":263,"./ui/modules/Recording":264,"./ui/modules/wizard/LaunchScreen.js":269,"./ui/modules/wizard/QuickLaunch.js":270,"@tensorflow/tfjs":205,"gsap":212}],244:[function(require,module,exports){
  62568. 'use strict';
  62569. Object.defineProperty(exports, "__esModule", {
  62570. value: true
  62571. });
  62572. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // Copyright 2017 Google Inc.
  62573. //
  62574. // Licensed under the Apache License, Version 2.0 (the "License");
  62575. // you may not use this file except in compliance with the License.
  62576. // You may obtain a copy of the License at
  62577. //
  62578. // http://www.apache.org/licenses/LICENSE-2.0
  62579. //
  62580. // Unless required by applicable law or agreed to in writing, software
  62581. // distributed under the License is distributed on an "AS IS" BASIS,
  62582. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62583. // See the License for the specific language governing permissions and
  62584. // limitations under the License.
  62585. // import 'gifler';
  62586. var _gsap = require('gsap');
  62587. var _gsap2 = _interopRequireDefault(_gsap);
  62588. var _gifCanvas = require('./../ui/components/gifCanvas.js');
  62589. var _gifCanvas2 = _interopRequireDefault(_gifCanvas);
  62590. var _config = require('./../config.js');
  62591. var _config2 = _interopRequireDefault(_config);
  62592. var _tfjs = require('@tensorflow/tfjs');
  62593. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  62594. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  62595. var CloudOutput = function () {
  62596. function CloudOutput() {
  62597. var _this = this;
  62598. _classCallCheck(this, CloudOutput);
  62599. var lang = _config2.default.lang;
  62600. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  62601. this.id = 'CloudOutput';
  62602. this.element = document.createElement('div');
  62603. this.element.classList.add('output__container');
  62604. this.element.classList.add('cloud_output__container');
  62605. this.classNames = _config2.default.classNames;
  62606. this.colors = _config2.default.colors;
  62607. this.cloudEvent = null;
  62608. this.defaultKeys = ["detectA", "detectB", "detectC"];
  62609. this.defaultValues = ["no", "no", "no"];
  62610. this.defaultTexts = [];
  62611. this.texts = [];
  62612. this.currentIndex = null;
  62613. this.currentClass = null;
  62614. this.resultOffset = 0;
  62615. this.numResults = 10;
  62616. this.defaultTexts.push(language.cloud_green);
  62617. this.defaultTexts.push(language.cloud_purple);
  62618. this.defaultTexts.push(language.cloud_orange);
  62619. this.edit = document.createElement('div');
  62620. this.edit.classList.add('cloud__edit');
  62621. this.editBar = document.createElement('div');
  62622. this.editBar.classList.add('cloud__edit-bar');
  62623. this.borders = [];
  62624. // 并排排列三个结果显示框
  62625. for (var index = 0; index < 3; index += 1) {
  62626. var id = this.classNames[index];
  62627. var text = this.defaultTexts[index];
  62628. this.texts[index] = this.defaultTexts[index];
  62629. var inputClass = document.createElement('div');
  62630. inputClass.classList.add('cloud__thumb');
  62631. inputClass.id = "cloud_" + id;
  62632. inputClass.index = index;
  62633. // inputClass.image = this.defaultclouds[index].cloud;
  62634. var border = document.createElement('div');
  62635. border.classList.add('cloud__thumb-border');
  62636. border.classList.add('cloud__thumb-border--' + id);
  62637. inputClass.appendChild(border);
  62638. var inputContent = document.createElement('div');
  62639. inputContent.classList.add('cloud__horizon_wrapper');
  62640. inputContent.textContent = text;
  62641. inputClass.appendChild(inputContent);
  62642. this.editBar.appendChild(inputClass);
  62643. this.borders.push(border);
  62644. }
  62645. // top-viewer
  62646. this.editViewer = document.createElement('div');
  62647. this.editViewer.classList.add('cloud__edit-viewer');
  62648. this.viewerTitle = document.createElement('div');
  62649. this.viewerTitle.id = "cloud__viewer_title";
  62650. this.viewerTitle.classList.add('cloud__viewer_title');
  62651. this.viewerTitle.textContent = language.select_cloud;
  62652. this.editViewer.appendChild(this.viewerTitle);
  62653. this.viewerSelection = document.createElement('div');
  62654. this.viewerSelection.style = "margin-bottom:12px";
  62655. this.viewerEvent = document.createElement('select');
  62656. this.viewerEvent.style = "padding-left: 15px";
  62657. this.viewerEvent.id = "selectCloud";
  62658. this.viewerEvent.add(new Option(language.selectCloud, ""));
  62659. this.viewerSelection.appendChild(this.viewerEvent);
  62660. this.viewerButton = document.createElement('img');
  62661. this.viewerButton.classList.add('cloud_icons');
  62662. // this.viewerButton.textContent = "autorenew";
  62663. this.viewerButton.src = "./media/refresh_tm.png";
  62664. this.viewerButton.addEventListener('click', function () {
  62665. _this.getCoCloudEvent();
  62666. });
  62667. this.viewerSelection.appendChild(this.viewerButton);
  62668. this.editViewer.appendChild(this.viewerSelection);
  62669. this.viewerOutput = document.createElement('div');
  62670. this.viewerOutput.id = "cloud_output";
  62671. this.viewerOutput.classList.add("cloud_output");
  62672. this.viewerOutput_title = document.createElement('div');
  62673. this.viewerOutput_title.id = "cloud_title";
  62674. this.viewerOutput_title.classList.add("cloud_output_title");
  62675. this.viewerOutput_title.textContent = language.cloud_title;
  62676. this.viewerOutput_content = document.createElement('div');
  62677. this.viewerOutput_content.id = "cloud_content";
  62678. this.viewerOutput_content.classList.add("cloud_output_content");
  62679. this.viewerOutput_content.textContent = language.no_triggered;
  62680. this.viewerOutput_footer = document.createElement('div');
  62681. this.viewerOutput_footer.id = "cloud_footer";
  62682. this.viewerOutput_footer.classList.add("cloud_output_footer");
  62683. this.viewerOutput_footer.textContent = "";
  62684. this.viewerOutput.appendChild(this.viewerOutput_title);
  62685. this.viewerOutput.appendChild(this.viewerOutput_content);
  62686. this.viewerOutput.appendChild(this.viewerOutput_footer);
  62687. this.editViewer.appendChild(this.viewerOutput);
  62688. this.edit.appendChild(this.editViewer);
  62689. //-- horizion
  62690. this.edit.appendChild(this.editBar);
  62691. this.element.appendChild(this.edit);
  62692. }
  62693. _createClass(CloudOutput, [{
  62694. key: 'trigger',
  62695. value: function trigger(index) {
  62696. var _this2 = this;
  62697. var lang = _config2.default.lang;
  62698. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  62699. if (!_config2.default.clearing) {
  62700. if (this.currentBorder && this.currentClassName) {
  62701. this.currentBorder.classList.remove('cloud__thumb-border--' + this.currentClassName + '-selected');
  62702. }
  62703. var border = this.borders[index];
  62704. var id = this.classNames[index];
  62705. this.currentBorder = border;
  62706. this.currentClassName = id;
  62707. this.currentBorder.classList.add('cloud__thumb-border--' + this.currentClassName + '-selected');
  62708. var textResult = this.texts[index];
  62709. var data = {
  62710. "detectA": "no",
  62711. "detectB": "no",
  62712. "detectC": "no"
  62713. };
  62714. var inputValue = document.getElementsByClassName('custom_data');
  62715. data[this.defaultKeys[index]] = inputValue[index].value || this.defaultTexts[index];
  62716. var output = document.getElementsByClassName('cloud__horizon_wrapper');
  62717. for (var i = 0; i < output.length; i++) {
  62718. var text = inputValue[i] && inputValue[i].value || this.defaultTexts[i];
  62719. if (document.getElementsByClassName('cloud__horizon_wrapper')[i + 3]) {
  62720. document.getElementsByClassName('cloud__horizon_wrapper')[i + 3].innerHTML = text;
  62721. }
  62722. }
  62723. this.edit.appendChild(document.getElementById('coordinate_points'));
  62724. //remove select class mode
  62725. this.classNames.map(function (item) {
  62726. _this2.viewerOutput.classList.remove('cloud_output--' + item);
  62727. });
  62728. this.classNames.map(function (item) {
  62729. if (item != "red") {
  62730. var _card = document.querySelector('#cloud_' + item);
  62731. _card.classList.remove('cloud__thumb--' + item);
  62732. }
  62733. });
  62734. this.viewerOutput_content.classList.remove("cloud_output_trigger");
  62735. this.viewerOutput_content.textContent = language.no_triggered;
  62736. this.viewerOutput_footer.classList.remove("cloud_output_trigger");
  62737. this.viewerOutput_footer.textContent = "";
  62738. //---
  62739. var card = document.querySelector('#cloud_' + this.currentClassName);
  62740. card.classList.add('cloud__thumb--' + this.currentClassName);
  62741. this.viewerOutput.classList.add('cloud_output--' + this.currentClassName);
  62742. this.viewerOutput_content.classList.add("cloud_output_trigger");
  62743. var type = this.currentClassName === "green" ? language.triggered_green : this.currentClassName === "purple" ? language.triggered_purple : language.triggered_orange;
  62744. this.viewerOutput_content.textContent = type;
  62745. // this.viewerOutput_content.textContent = `You've triggered ${this.currentClassName}!`
  62746. this.viewerOutput_footer.classList.add("cloud_output_trigger");
  62747. if (this.currentIndex != index) this.AjaxCloudEvent(data);
  62748. this.currentIndex = index;
  62749. }
  62750. if (_config2.default.clearing) {
  62751. var _card2 = document.querySelector('#cloud_' + this.currentClassName);
  62752. _card2.classList.remove('cloud__thumb--' + this.currentClassName);
  62753. this.classNames.map(function (item) {
  62754. console.log(item);
  62755. _this2.viewerOutput.classList.remove('cloud_output--' + item);
  62756. });
  62757. this.viewerOutput_content.classList.remove("cloud_output_trigger");
  62758. this.viewerOutput_content.textContent = language.no_triggered;
  62759. this.viewerOutput_footer.classList.remove("cloud_output_trigger");
  62760. this.viewerOutput_footer.textContent = "";
  62761. }
  62762. }
  62763. }, {
  62764. key: 'stop',
  62765. value: function stop() {
  62766. this.element.style.display = 'none';
  62767. // this.loadMore.removeEventListener('click', this.loadMoreResults.bind(this));
  62768. }
  62769. }, {
  62770. key: 'start',
  62771. value: function start() {
  62772. this.element.style.display = 'block';
  62773. // this.loadMore.addEventListener('click', this.loadMoreResults.bind(this));
  62774. }
  62775. }, {
  62776. key: 'clear',
  62777. value: function clear() {
  62778. var _this3 = this;
  62779. var lang = _config2.default.lang;
  62780. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  62781. this.classNames.map(function (item) {
  62782. _this3.viewerOutput.classList.remove('cloud_output--' + item);
  62783. });
  62784. this.classNames.forEach(function (item) {
  62785. if (item != "red") {
  62786. var card = document.querySelector('#cloud_' + item);
  62787. card.classList.remove('cloud__thumb--' + item);
  62788. }
  62789. });
  62790. this.viewerOutput_content.classList.remove("cloud_output_trigger");
  62791. this.viewerOutput_content.textContent = language.no_triggered;
  62792. this.viewerOutput_footer.classList.remove("cloud_output_trigger");
  62793. this.viewerOutput_footer.textContent = "";
  62794. }
  62795. }, {
  62796. key: 'showAnimation',
  62797. value: function showAnimation(index) {
  62798. if (this.gifCanvas) {
  62799. _config2.default.isRecording = true;
  62800. // this.gifCanvas.setSource(url);
  62801. }
  62802. }
  62803. }, {
  62804. key: 'stopAnimation',
  62805. value: function stopAnimation() {
  62806. if (this.gifCanvas) {
  62807. _config2.default.isRecording = false;
  62808. this.gifCanvas.clear();
  62809. }
  62810. }
  62811. }, {
  62812. key: 'getCoCloudEvent',
  62813. value: function getCoCloudEvent() {
  62814. var ajax = new XMLHttpRequest();
  62815. var that = this;
  62816. ajax.onreadystatechange = function () {
  62817. if (this.status === 200 && this.readyState === 4) {
  62818. _config2.default.USER.events = ajax.response;
  62819. that.updateCoEvent();
  62820. }
  62821. };
  62822. var url = _config2.default.base_url + 'iot/data/apikey/' + _config2.default.USER.api_key + '/event/';
  62823. ajax.open('get', url, true);
  62824. ajax.withCredentials = true;
  62825. ajax.send(null);
  62826. }
  62827. }, {
  62828. key: 'updateCoEvent',
  62829. value: function updateCoEvent() {
  62830. var lang = _config2.default.lang;
  62831. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  62832. var select = document.querySelector("#selectCloud");
  62833. select.innerHTML = "";
  62834. var option0 = document.createElement('option');
  62835. option0.textContent = language.selectCloud;
  62836. option0.value = "";
  62837. select.appendChild(option0);
  62838. // select.empty();
  62839. var events = JSON.parse(_config2.default.USER.events);
  62840. var temp = events.map(function (event) {
  62841. var option = document.createElement('option');
  62842. option.textContent = event.name;
  62843. option.value = event.eventAPIKey;
  62844. select.appendChild(option);
  62845. // select.append(option)
  62846. });
  62847. }
  62848. }, {
  62849. key: 'AjaxCloudEvent',
  62850. value: function AjaxCloudEvent(data) {
  62851. var that = this;
  62852. // var request = new XMLHttpRequest();
  62853. // request.onreadystatechange = function() {
  62854. // if (this.status === 200 && this.readyState === 4) {
  62855. // console.log("You have send data to CocoCloud");
  62856. // that.viewerOutput_footer.textContent = "Event data updated."
  62857. // }
  62858. // };
  62859. // var url = `${GLOBALS.base_url}iot/data/eventAPIKey/${this.viewerEvent.value}`;
  62860. // request.setRequestHeader("Content-type", "application/json");
  62861. // request.open('post', url, true);
  62862. // request.send(data);
  62863. $.ajax(_config2.default.base_url + 'iot/data/eventAPIKey/' + this.viewerEvent.value, {
  62864. type: "POST",
  62865. xhrFields: {
  62866. withCredentials: true
  62867. },
  62868. data: data,
  62869. success: function success() {
  62870. that.viewerOutput_footer.textContent = "Event data updated.";
  62871. },
  62872. error: function error() {
  62873. that.viewerOutput_footer.textContent = "Event data updated fail.";
  62874. }
  62875. });
  62876. }
  62877. }]);
  62878. return CloudOutput;
  62879. }();
  62880. exports.default = CloudOutput;
  62881. },{"./../config.js":242,"./../ui/components/gifCanvas.js":257,"@tensorflow/tfjs":205,"gsap":212}],245:[function(require,module,exports){
  62882. 'use strict';
  62883. Object.defineProperty(exports, "__esModule", {
  62884. value: true
  62885. });
  62886. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  62887. var _gsap = require('gsap');
  62888. var _gsap2 = _interopRequireDefault(_gsap);
  62889. require('gifler');
  62890. var _GifCanvas = require('./../ui/components/GifCanvas.js');
  62891. var _GifCanvas2 = _interopRequireDefault(_GifCanvas);
  62892. var _config = require('./../config.js');
  62893. var _config2 = _interopRequireDefault(_config);
  62894. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  62895. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  62896. // Copyright 2017 Google Inc.
  62897. //
  62898. // Licensed under the Apache License, Version 2.0 (the "License");
  62899. // you may not use this file except in compliance with the License.
  62900. // You may obtain a copy of the License at
  62901. //
  62902. // http://www.apache.org/licenses/LICENSE-2.0
  62903. //
  62904. // Unless required by applicable law or agreed to in writing, software
  62905. // distributed under the License is distributed on an "AS IS" BASIS,
  62906. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62907. // See the License for the specific language governing permissions and
  62908. // limitations under the License.
  62909. var GIFOutput = function () {
  62910. function GIFOutput() {
  62911. _classCallCheck(this, GIFOutput);
  62912. this.id = 'GIFOutput';
  62913. this.element = document.createElement('div');
  62914. this.element.classList.add('output__container');
  62915. this.classNames = _config2.default.classNames;
  62916. this.colors = _config2.default.colors;
  62917. this.defaultGifs = [];
  62918. this.gifs = [];
  62919. this.currentIndex = null;
  62920. this.currentClass = null;
  62921. this.resultOffset = 0;
  62922. this.numResults = 10;
  62923. this.useCanvas = !_config2.default.browserUtils.isMobile && _config2.default.browserUtils.isChrome;
  62924. if (this.useCanvas) {
  62925. this.gifCanvas = new _GifCanvas2.default();
  62926. }
  62927. this.defaultGifs.push({
  62928. still: 'https://media1.giphy.com/media/vFKqnCdLPNOKc/giphy-downsized_s.gif',
  62929. gif: 'https://media1.giphy.com/media/vFKqnCdLPNOKc/200w.gif'
  62930. });
  62931. this.defaultGifs.push({
  62932. still: 'https://media3.giphy.com/media/14ivBLRRRmyQw0/giphy-downsized_s.gif',
  62933. gif: 'https://media3.giphy.com/media/14ivBLRRRmyQw0/200w.gif'
  62934. });
  62935. this.defaultGifs.push({
  62936. still: 'https://media0.giphy.com/media/I3BLTIP5Gv6h2/giphy-downsized_s.gif',
  62937. gif: 'https://media0.giphy.com/media/I3BLTIP5Gv6h2/200w.gif'
  62938. });
  62939. this.edit = document.createElement('div');
  62940. this.edit.classList.add('gif__edit');
  62941. this.editBar = document.createElement('div');
  62942. this.editBar.classList.add('gif__edit-bar');
  62943. this.borders = [];
  62944. for (var index = 0; index < 3; index += 1) {
  62945. var id = this.classNames[index];
  62946. var image = this.defaultGifs[index].still;
  62947. this.gifs[index] = this.defaultGifs[index];
  62948. var button = document.createElement('div');
  62949. button.classList.add('gif__thumb');
  62950. button.id = id;
  62951. button.index = index;
  62952. button.image = this.defaultGifs[index].gif;
  62953. var border = document.createElement('div');
  62954. border.classList.add('gif__thumb-border');
  62955. border.classList.add('gif__thumb-border--' + id);
  62956. button.appendChild(border);
  62957. var imageWrapper = document.createElement('div');
  62958. imageWrapper.classList.add('gif__thumb-image-wrapper');
  62959. imageWrapper.style.backgroundImage = 'url(' + image + ')';
  62960. button.appendChild(imageWrapper);
  62961. this.editBar.appendChild(button);
  62962. button.imageWrapper = imageWrapper;
  62963. button.addEventListener('mouseenter', this.editThumbOver.bind(this));
  62964. button.addEventListener('mouseleave', this.editThumbOut.bind(this));
  62965. button.addEventListener('click', this.editThumbClick.bind(this));
  62966. this.borders.push(border);
  62967. }
  62968. this.editViewer = document.createElement('div');
  62969. this.editViewer.classList.add('gif__edit-viewer');
  62970. if (this.gifCanvas) {
  62971. this.editViewer.appendChild(this.gifCanvas.getElement());
  62972. this.gifCanvas.getElement().classList.add('gif__canvas');
  62973. }
  62974. this.edit.appendChild(this.editViewer);
  62975. this.edit.appendChild(this.editBar);
  62976. this.search = document.createElement('div');
  62977. this.search.classList.add('gif__search');
  62978. this.search.style.display = 'none';
  62979. this.searchBar = document.createElement('div');
  62980. this.searchBar.classList.add('gif__search-bar');
  62981. this.searchInput = document.createElement('input');
  62982. this.searchInput.setAttribute('placeholder', 'Search Giphy');
  62983. this.searchInput.classList.add('gif__search-input');
  62984. this.searchBar.appendChild(this.searchInput);
  62985. this.searchBackButton = document.createElement('div');
  62986. this.searchBackButton.classList.add('gif__search-back-button');
  62987. this.searchBar.appendChild(this.searchBackButton);
  62988. this.search.appendChild(this.searchBar);
  62989. this.searchScroll = document.createElement('div');
  62990. this.searchScroll.classList.add('gif__search-scroll');
  62991. this.search.appendChild(this.searchScroll);
  62992. this.searchScrollContent = document.createElement('div');
  62993. this.searchScrollContent.classList.add('gif__search-scroll-content');
  62994. var sponsorMessage = document.createElement('div');
  62995. sponsorMessage.classList.add('gif__search-sponsor');
  62996. this.searchScrollContent.appendChild(sponsorMessage);
  62997. this.searchResults = document.createElement('div');
  62998. this.searchResults.classList.add('gif__search-results');
  62999. this.leftColumn = document.createElement('div');
  63000. this.leftColumn.classList.add('gif__search-column');
  63001. this.searchResults.appendChild(this.leftColumn);
  63002. this.rightColumn = document.createElement('div');
  63003. this.rightColumn.classList.add('gif__search-column');
  63004. this.searchResults.appendChild(this.rightColumn);
  63005. this.searchScrollContent.appendChild(this.searchResults);
  63006. this.loadMore = document.createElement('div');
  63007. this.loadMore.classList.add('gif__load-more');
  63008. this.loadMore.textContent = 'Load more';
  63009. this.searchScrollContent.appendChild(this.loadMore);
  63010. this.searchScroll.appendChild(this.searchScrollContent);
  63011. this.edit.appendChild(this.search);
  63012. this.element.appendChild(this.edit);
  63013. }
  63014. _createClass(GIFOutput, [{
  63015. key: 'editThumbOver',
  63016. value: function editThumbOver(event) {
  63017. var image = event.target.image;
  63018. this.editViewer.style.backgroundImage = 'url(' + image + ')';
  63019. this.showAnimation(image);
  63020. }
  63021. }, {
  63022. key: 'editThumbOut',
  63023. value: function editThumbOut(event) {
  63024. this.editViewer.style.backgroundImage = 'none';
  63025. this.stopAnimation();
  63026. }
  63027. }, {
  63028. key: 'editThumbClick',
  63029. value: function editThumbClick(event) {
  63030. this.showSearch(event);
  63031. }
  63032. }, {
  63033. key: 'loadMoreResults',
  63034. value: function loadMoreResults() {
  63035. this.searchGiphy();
  63036. }
  63037. }, {
  63038. key: 'selectImage',
  63039. value: function selectImage(event) {
  63040. var index = this.currentClass.index;
  63041. this.gifs[index] = {
  63042. gif: event.currentTarget.large,
  63043. still: event.currentTarget.still
  63044. };
  63045. this.currentClass.image = this.gifs[index].gif;
  63046. this.currentClass.imageWrapper.style.backgroundImage = 'url(' + this.gifs[index].still + ')';
  63047. this.hideSearch();
  63048. }
  63049. }, {
  63050. key: 'displaySearchResults',
  63051. value: function displaySearchResults(json) {
  63052. this.leftColumn.innerHTML = '';
  63053. this.rightColumn.innerHTML = '';
  63054. var column = this.leftColumn;
  63055. for (var index = 0; index < json.data.length; index += 1) {
  63056. var small = json.data[index].images.fixed_width_small.url;
  63057. // let large = json.data[index].images.downsized.url;
  63058. var large = json.data[index].images.fixed_width.url;
  63059. var still = json.data[index].images.downsized_still.url;
  63060. var image = new Image();
  63061. image.large = large;
  63062. image.still = still;
  63063. image.src = small;
  63064. if (index % 2 === 0) {
  63065. column = this.leftColumn;
  63066. } else {
  63067. column = this.rightColumn;
  63068. }
  63069. image.addEventListener('click', this.selectImage.bind(this));
  63070. column.appendChild(image);
  63071. }
  63072. this.loadMore.style.opacity = 1;
  63073. }
  63074. }, {
  63075. key: 'searchGiphy',
  63076. value: function searchGiphy() {
  63077. var that = this;
  63078. var request = new XMLHttpRequest();
  63079. request.onreadystatechange = function () {
  63080. if (this.status === 200 && this.readyState === 4) {
  63081. var json = JSON.parse(request.responseText);
  63082. that.displaySearchResults(json);
  63083. }
  63084. };
  63085. var url = 'https://api.giphy.com/v1/gifs/search?q=' + encodeURIComponent(this.phrase) + '&api_key=l4FGxiI99hPQ0k6nS&limit=' + this.numResults + '&offset=' + this.resultOffset;
  63086. request.open('get', url, true);
  63087. request.send();
  63088. this.resultOffset += this.numResults;
  63089. }
  63090. }, {
  63091. key: 'searchKeyUp',
  63092. value: function searchKeyUp(event) {
  63093. var value = this.searchInput.value;
  63094. if (value.length > 0) {
  63095. this.phrase = value;
  63096. this.resultOffset = 0;
  63097. this.searchGiphy();
  63098. }
  63099. }
  63100. }, {
  63101. key: 'showSearch',
  63102. value: function showSearch(event) {
  63103. var id = event.currentTarget.getAttribute('id');
  63104. this.currentClass = event.currentTarget;
  63105. this.loadMore.style.opacity = 0;
  63106. this.leftColumn.innerHTML = '';
  63107. this.rightColumn.innerHTML = '';
  63108. this.search.style.display = 'block';
  63109. this.searchInput.className = 'gif__search-input';
  63110. this.searchInput.classList.add('gif__search-input--' + id);
  63111. this.searchBackButton.className = 'gif__search-back-button';
  63112. this.searchBackButton.classList.add('gif__search-back-button--' + id);
  63113. this.searchInput.focus();
  63114. this.searchInput.value = '';
  63115. }
  63116. }, {
  63117. key: 'hideSearch',
  63118. value: function hideSearch() {
  63119. this.search.style.display = 'none';
  63120. }
  63121. }, {
  63122. key: 'trigger',
  63123. value: function trigger(index) {
  63124. if (!_config2.default.clearing) {
  63125. this.currentIndex = index;
  63126. if (this.currentBorder && this.currentClassName) {
  63127. this.currentBorder.classList.remove('gif__thumb-border--' + this.currentClassName + '-selected');
  63128. }
  63129. var border = this.borders[index];
  63130. var id = this.classNames[index];
  63131. this.currentBorder = border;
  63132. this.currentClassName = id;
  63133. this.currentBorder.classList.add('gif__thumb-border--' + this.currentClassName + '-selected');
  63134. var image = this.gifs[this.currentIndex].gif;
  63135. this.editViewer.style.backgroundImage = 'url(' + image + ')';
  63136. this.showAnimation(image);
  63137. }
  63138. if (_config2.default.clearing) {
  63139. this.currentBorder.classList.remove('gif__thumb-border--' + this.currentClassName + '-selected');
  63140. }
  63141. }
  63142. }, {
  63143. key: 'stop',
  63144. value: function stop() {
  63145. this.element.style.display = 'none';
  63146. this.searchInput.removeEventListener('keyup', this.searchKeyUp.bind(this));
  63147. this.searchBackButton.removeEventListener('click', this.hideSearch.bind(this));
  63148. this.loadMore.removeEventListener('click', this.loadMoreResults.bind(this));
  63149. }
  63150. }, {
  63151. key: 'start',
  63152. value: function start() {
  63153. this.element.style.display = 'block';
  63154. this.searchInput.addEventListener('keyup', this.searchKeyUp.bind(this));
  63155. this.searchBackButton.addEventListener('click', this.hideSearch.bind(this));
  63156. this.loadMore.addEventListener('click', this.loadMoreResults.bind(this));
  63157. }
  63158. }, {
  63159. key: 'showAnimation',
  63160. value: function showAnimation(url) {
  63161. if (this.gifCanvas) {
  63162. _config2.default.isRecording = true;
  63163. this.gifCanvas.setSource(url);
  63164. }
  63165. }
  63166. }, {
  63167. key: 'clear',
  63168. value: function clear() {}
  63169. }, {
  63170. key: 'stopAnimation',
  63171. value: function stopAnimation() {
  63172. if (this.gifCanvas) {
  63173. _config2.default.isRecording = false;
  63174. this.gifCanvas.clear();
  63175. }
  63176. }
  63177. }]);
  63178. return GIFOutput;
  63179. }();
  63180. exports.default = GIFOutput;
  63181. },{"./../config.js":242,"./../ui/components/GifCanvas.js":254,"gifler":209,"gsap":212}],246:[function(require,module,exports){
  63182. 'use strict';
  63183. Object.defineProperty(exports, "__esModule", {
  63184. value: true
  63185. });
  63186. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // Copyright 2017 Google Inc.
  63187. //
  63188. // Licensed under the Apache License, Version 2.0 (the "License");
  63189. // you may not use this file except in compliance with the License.
  63190. // You may obtain a copy of the License at
  63191. //
  63192. // http://www.apache.org/licenses/LICENSE-2.0
  63193. //
  63194. // Unless required by applicable law or agreed to in writing, software
  63195. // distributed under the License is distributed on an "AS IS" BASIS,
  63196. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  63197. // See the License for the specific language governing permissions and
  63198. // limitations under the License.
  63199. // import 'gifler';
  63200. var _gsap = require('gsap');
  63201. var _gsap2 = _interopRequireDefault(_gsap);
  63202. var _gifCanvas = require('./../ui/components/gifCanvas.js');
  63203. var _gifCanvas2 = _interopRequireDefault(_gifCanvas);
  63204. var _config = require('./../config.js');
  63205. var _config2 = _interopRequireDefault(_config);
  63206. var _tfjs = require('@tensorflow/tfjs');
  63207. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  63208. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  63209. var ModuleOutput = function () {
  63210. function ModuleOutput() {
  63211. var _this = this;
  63212. _classCallCheck(this, ModuleOutput);
  63213. setTimeout(function () {
  63214. var lang = _config2.default.lang;
  63215. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  63216. _this.id = 'ModuleOutput';
  63217. _this.element = document.createElement('div');
  63218. _this.element.classList.add('output__container');
  63219. _this.element.classList.add('cloud_output__container');
  63220. _this.classNames = _config2.default.classNames;
  63221. _this.colors = _config2.default.colors;
  63222. _this.cloudEvent = null;
  63223. _this.defaultKeys = ["detectA", "detectB", "detectC"];
  63224. _this.defaultValues = ["no", "no", "no"];
  63225. _this.defaultTexts = [];
  63226. _this.texts = [];
  63227. _this.currentIndex = null;
  63228. _this.currentClass = null;
  63229. _this.resultOffset = 0;
  63230. _this.numResults = 10;
  63231. _this.defaultTexts.push(language.cloud_green);
  63232. _this.defaultTexts.push(language.cloud_purple);
  63233. _this.defaultTexts.push(language.cloud_orange);
  63234. _this.edit = document.createElement('div');
  63235. _this.edit.classList.add('module__edit');
  63236. _this.editBar = document.createElement('div');
  63237. _this.editBar.classList.add('cloud__edit-bar');
  63238. _this.borders = [];
  63239. // 并排排列三个结果显示框
  63240. for (var index = 0; index < 3; index += 1) {
  63241. var id = _this.classNames[index];
  63242. var text = _this.defaultTexts[index];
  63243. _this.texts[index] = _this.defaultTexts[index];
  63244. var inputClass = document.createElement('div');
  63245. inputClass.classList.add('cloud__thumb');
  63246. inputClass.id = "module_" + id;
  63247. inputClass.index = index;
  63248. // inputClass.image = this.defaultclouds[index].cloud;
  63249. var border = document.createElement('div');
  63250. border.classList.add('cloud__thumb-border');
  63251. border.classList.add('cloud__thumb-border--' + id);
  63252. inputClass.appendChild(border);
  63253. var inputContent = document.createElement('div');
  63254. inputContent.classList.add('cloud__horizon_wrapper');
  63255. inputContent.textContent = text;
  63256. inputClass.appendChild(inputContent);
  63257. _this.editBar.appendChild(inputClass);
  63258. _this.borders.push(border);
  63259. }
  63260. // top-viewer
  63261. _this.editViewer = document.createElement('div');
  63262. _this.editViewer.classList.add('cloud__edit-viewer');
  63263. _this.viewerTitle = document.createElement('div');
  63264. _this.viewerTitle.classList.add('cloud__viewer_title');
  63265. _this.viewerTitle.textContent = lang == 'en' ? 'Send Module' : lang == 'hant' ? "發送到模塊" : "发送到模块";
  63266. _this.editViewer.appendChild(_this.viewerTitle);
  63267. _this.viewerSelection = document.createElement('div');
  63268. _this.viewerSelection.id = "port_connect";
  63269. _this.viewerSelection.style = "height:40px;text-align:left;line-height:40px;";
  63270. var port = lang == 'en' ? 'Port' : lang == 'hant' ? "端口" : "端口";
  63271. var connects = lang == 'en' ? 'Connect' : lang == 'hant' ? "連接" : "连接";
  63272. var disconnects = lang == 'en' ? 'Disconnect' : lang == 'hant' ? "斷開" : "断开";
  63273. _this.viewerSelection.innerHTML = '<span>' + port + ':</span><span id="portNumber">' + (_config2.default.port ? _config2.default.port : "") + '</span><button class="send_button ' + (_config2.default.port && 'send_button_color') + '" style="display:block">' + connects + '</button><button class="send_button ' + (_config2.default.port && 'send_button_color') + '" style="display:none">' + disconnects + '</button>';
  63274. _this.viewerSelection.addEventListener('click', function (e) {
  63275. var send = document.getElementsByClassName('send_button');
  63276. if (e.target.tagName == "BUTTON") {
  63277. if (send[0].style.display == 'block' && _config2.default.port) {
  63278. send[0].style.display = "none";
  63279. send[1].style.display = "block";
  63280. window.parent.postMessage("open", "*");
  63281. } else if (send[1].style.display == 'block' && _config2.default.port) {
  63282. send[0].style.display = "block";
  63283. send[1].style.display = "none";
  63284. window.parent.postMessage("close", "*");
  63285. }
  63286. }
  63287. });
  63288. // this.viewerSelection.appendChild(this.modulePortNumber)
  63289. _this.editViewer.appendChild(_this.viewerSelection);
  63290. _this.viewerOutput = document.createElement('div');
  63291. _this.viewerOutput.id = "cloud_output";
  63292. _this.viewerOutput.classList.add("cloud_output");
  63293. _this.viewerOutput_title = document.createElement('div');
  63294. _this.viewerOutput_title.id = "cloud_title";
  63295. _this.viewerOutput_title.classList.add("cloud_output_title");
  63296. _this.viewerOutput_title.textContent = language.cloud_title;
  63297. _this.viewerOutput_content = document.createElement('div');
  63298. _this.viewerOutput_content.id = "cloud_content";
  63299. _this.viewerOutput_content.classList.add("cloud_output_content");
  63300. _this.viewerOutput_content.textContent = language.no_triggered;
  63301. _this.viewerOutput_footer = document.createElement('div');
  63302. _this.viewerOutput_footer.id = "cloud_footer";
  63303. _this.viewerOutput_footer.classList.add("cloud_output_footer");
  63304. _this.viewerOutput_footer.textContent = "";
  63305. _this.viewerOutput.appendChild(_this.viewerOutput_title);
  63306. _this.viewerOutput.appendChild(_this.viewerOutput_content);
  63307. _this.viewerOutput.appendChild(_this.viewerOutput_footer);
  63308. _this.editViewer.appendChild(_this.viewerOutput);
  63309. _this.edit.appendChild(_this.editViewer);
  63310. //-- horizion
  63311. _this.edit.appendChild(_this.editBar);
  63312. _this.element.appendChild(_this.edit);
  63313. }, 1500);
  63314. }
  63315. _createClass(ModuleOutput, [{
  63316. key: 'trigger',
  63317. value: function trigger(index) {
  63318. var _this2 = this;
  63319. var lang = _config2.default.lang;
  63320. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  63321. if (!_config2.default.clearing) {
  63322. if (this.currentBorder && this.currentClassName) {
  63323. this.currentBorder.classList.remove('cloud__thumb-border--' + this.currentClassName + '-selected');
  63324. }
  63325. var border = this.borders[index];
  63326. var id = this.classNames[index];
  63327. this.currentBorder = border;
  63328. this.currentClassName = id;
  63329. this.currentBorder.classList.add('cloud__thumb-border--' + this.currentClassName + '-selected');
  63330. var textResult = this.texts[index];
  63331. var data = {
  63332. "detectA": "no",
  63333. "detectB": "no",
  63334. "detectC": "no"
  63335. };
  63336. var inputValue = document.getElementsByClassName('custom_data');
  63337. data[this.defaultKeys[index]] = inputValue[index].value || this.defaultTexts[index];
  63338. var output = document.getElementsByClassName('cloud__horizon_wrapper');
  63339. for (var i = 0; i < output.length; i++) {
  63340. var text = inputValue[i] && inputValue[i].value || this.defaultTexts[i];
  63341. if (document.getElementsByClassName('cloud__horizon_wrapper')[i + 3]) {
  63342. document.getElementsByClassName('cloud__horizon_wrapper')[i + 3].innerHTML = text;
  63343. }
  63344. }
  63345. this.edit.appendChild(document.getElementById('coordinate_points'));
  63346. //remove select class mode
  63347. this.classNames.map(function (item) {
  63348. _this2.viewerOutput.classList.remove('cloud_output--' + item);
  63349. });
  63350. this.classNames.map(function (item) {
  63351. if (item != "red") {
  63352. var _card = document.querySelector('#module_' + item);
  63353. _card.classList.remove('cloud__thumb--' + item);
  63354. }
  63355. });
  63356. this.viewerOutput_content.classList.remove("cloud_output_trigger");
  63357. this.viewerOutput_content.textContent = language.no_triggered;
  63358. this.viewerOutput_footer.classList.remove("cloud_output_trigger");
  63359. this.viewerOutput_footer.textContent = "";
  63360. //---
  63361. var card = document.querySelector('#module_' + this.currentClassName);
  63362. card.classList.add('cloud__thumb--' + this.currentClassName);
  63363. this.viewerOutput.classList.add('cloud_output--' + this.currentClassName);
  63364. this.viewerOutput_content.classList.add("cloud_output_trigger");
  63365. var type = this.currentClassName === "green" ? language.triggered_green : this.currentClassName === "purple" ? language.triggered_purple : language.triggered_orange;
  63366. this.viewerOutput_content.textContent = type;
  63367. this.viewerOutput_footer.classList.add("cloud_output_trigger");
  63368. if (this.currentIndex != index) this.sendModuleEvent(data);
  63369. this.currentIndex = index;
  63370. }
  63371. if (_config2.default.clearing) {
  63372. var _card2 = document.querySelector('#module_' + this.currentClassName);
  63373. _card2.classList.remove('cloud__thumb--' + this.currentClassName);
  63374. this.classNames.map(function (item) {
  63375. _this2.viewerOutput.classList.remove('cloud_output--' + item);
  63376. });
  63377. this.viewerOutput_content.classList.remove("cloud_output_trigger");
  63378. this.viewerOutput_content.textContent = language.no_triggered;
  63379. this.viewerOutput_footer.classList.remove("cloud_output_trigger");
  63380. this.viewerOutput_footer.textContent = "";
  63381. }
  63382. }
  63383. }, {
  63384. key: 'stop',
  63385. value: function stop() {
  63386. this.element.style.display = 'none';
  63387. // this.loadMore.removeEventListener('click', this.loadMoreResults.bind(this));
  63388. }
  63389. }, {
  63390. key: 'start',
  63391. value: function start() {
  63392. this.element.style.display = 'block';
  63393. // this.loadMore.addEventListener('click', this.loadMoreResults.bind(this));
  63394. }
  63395. }, {
  63396. key: 'clear',
  63397. value: function clear() {
  63398. var _this3 = this;
  63399. var lang = _config2.default.lang;
  63400. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  63401. this.classNames.map(function (item) {
  63402. _this3.viewerOutput.classList.remove('cloud_output--' + item);
  63403. });
  63404. this.classNames.forEach(function (item) {
  63405. if (item != "red") {
  63406. var card = document.querySelector('#module_' + item);
  63407. card.classList.remove('cloud__thumb--' + item);
  63408. }
  63409. });
  63410. this.viewerOutput_content.classList.remove("cloud_output_trigger");
  63411. this.viewerOutput_content.textContent = language.no_triggered;
  63412. this.viewerOutput_footer.classList.remove("cloud_output_trigger");
  63413. this.viewerOutput_footer.textContent = "";
  63414. }
  63415. }, {
  63416. key: 'showAnimation',
  63417. value: function showAnimation(index) {
  63418. if (this.gifCanvas) {
  63419. _config2.default.isRecording = true;
  63420. // this.gifCanvas.setSource(url);
  63421. }
  63422. }
  63423. }, {
  63424. key: 'stopAnimation',
  63425. value: function stopAnimation() {
  63426. if (this.gifCanvas) {
  63427. _config2.default.isRecording = false;
  63428. this.gifCanvas.clear();
  63429. }
  63430. }
  63431. }, {
  63432. key: 'updateCoEvent',
  63433. value: function updateCoEvent() {
  63434. var lang = _config2.default.lang;
  63435. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  63436. var select = document.querySelector("#selectCloud");
  63437. select.innerHTML = "";
  63438. var option0 = document.createElement('option');
  63439. option0.textContent = language.selectCloud;
  63440. option0.value = "";
  63441. select.appendChild(option0);
  63442. // select.empty();
  63443. var events = JSON.parse(_config2.default.USER.events);
  63444. var temp = events.map(function (event) {
  63445. var option = document.createElement('option');
  63446. option.textContent = event.name;
  63447. option.value = event.eventAPIKey;
  63448. select.appendChild(option);
  63449. // select.append(option)
  63450. });
  63451. }
  63452. }, {
  63453. key: 'sendModuleEvent',
  63454. value: function sendModuleEvent(data) {
  63455. var that = this;
  63456. // var request = new XMLHttpRequest();
  63457. // request.onreadystatechange = function() {
  63458. // if (this.status === 200 && this.readyState === 4) {
  63459. // console.log("You have send data to CocoCloud");
  63460. // that.viewerOutput_footer.textContent = "Event data updated."
  63461. // }
  63462. // };
  63463. // var url = `${GLOBALS.base_url}iot/data/eventAPIKey/${this.viewerEvent.value}`;
  63464. // request.setRequestHeader("Content-type", "application/json");
  63465. // request.open('post', url, true);
  63466. // request.send(data);
  63467. var datas = {
  63468. posenet: window.dataPosenet,
  63469. data: data
  63470. };
  63471. window.parent.postMessage(datas, "*");
  63472. }
  63473. }]);
  63474. return ModuleOutput;
  63475. }();
  63476. exports.default = ModuleOutput;
  63477. },{"./../config.js":242,"./../ui/components/gifCanvas.js":257,"@tensorflow/tfjs":205,"gsap":212}],247:[function(require,module,exports){
  63478. 'use strict';
  63479. Object.defineProperty(exports, "__esModule", {
  63480. value: true
  63481. });
  63482. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // Copyright 2017 Google Inc.
  63483. //
  63484. // Licensed under the Apache License, Version 2.0 (the "License");
  63485. // you may not use this file except in compliance with the License.
  63486. // You may obtain a copy of the License at
  63487. //
  63488. // http://www.apache.org/licenses/LICENSE-2.0
  63489. //
  63490. // Unless required by applicable law or agreed to in writing, software
  63491. // distributed under the License is distributed on an "AS IS" BASIS,
  63492. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  63493. // See the License for the specific language governing permissions and
  63494. // limitations under the License.
  63495. var _SoundSearch = require('./sound/SoundSearch.js');
  63496. var _SoundSearch2 = _interopRequireDefault(_SoundSearch);
  63497. var _config = require('./../config.js');
  63498. var _config2 = _interopRequireDefault(_config);
  63499. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  63500. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  63501. var SoundOutput = function () {
  63502. function SoundOutput() {
  63503. var _this = this;
  63504. _classCallCheck(this, SoundOutput);
  63505. setTimeout(function () {
  63506. var lang = _config2.default.lang;
  63507. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  63508. _this.id = 'SoundOutput';
  63509. _this.loaded = false;
  63510. _this.canTrigger = true;
  63511. _this.basePath = 'assets/outputs/sound/sounds/';
  63512. _this.assets = [];
  63513. _this.assets.push('applause.mp3');
  63514. _this.assets.push('bass.mp3');
  63515. _this.assets.push('birds.mp3');
  63516. _this.assets.push('cow.mp3');
  63517. _this.assets.push('drum_joke.mp3');
  63518. _this.assets.push('drum_roll.mp3');
  63519. _this.assets.push('drums_1.mp3');
  63520. _this.assets.push('drums_2.mp3');
  63521. _this.assets.push('fanfare.mp3');
  63522. _this.assets.push('flute_1.mp3');
  63523. _this.assets.push('flute_2.mp3');
  63524. _this.assets.push('flute_3.mp3');
  63525. _this.assets.push('guitar_1.mp3');
  63526. _this.assets.push('guitar_2.mp3');
  63527. _this.assets.push('harp.mp3');
  63528. _this.assets.push('jingle.mp3');
  63529. _this.assets.push('orchestra.mp3');
  63530. _this.assets.push('organ.mp3');
  63531. _this.assets.push('trombone.mp3');
  63532. _this.assets.push('trumpet_1.mp3');
  63533. _this.assets.push('trumpet_2.mp3');
  63534. _this.assets.push('trumpet_3.mp3');
  63535. _this.assets.push('tuba.mp3');
  63536. _this.numAssets = _this.assets.length;
  63537. window.addEventListener('mobileLaunch', _this.touchAudio.bind(_this));
  63538. _this.defaultAssets = [];
  63539. _this.defaultAssets[0] = 'birds.mp3';
  63540. _this.defaultAssets[1] = 'guitar_1.mp3';
  63541. _this.defaultAssets[2] = 'trombone.mp3';
  63542. _this.numLoaded = 0;
  63543. _this.sounds = {};
  63544. _this.currentSound = null;
  63545. _this.currentIcon = null;
  63546. _this.element = document.createElement('div');
  63547. _this.element.classList.add('output__container');
  63548. _this.element.classList.add('output__container--sound');
  63549. _this.classNames = _config2.default.classNames;
  63550. _this.colors = _config2.default.colors;
  63551. _this.numClasses = _config2.default.numClasses;
  63552. _this.loadingScreen = document.createElement('div');
  63553. _this.loadingScreen.classList.add('output__loading-screen');
  63554. _this.loadingScreen.classList.add('output__loading-screen--sound');
  63555. var loadingTitle = document.createElement('div');
  63556. loadingTitle.textContent = 'Loading';
  63557. loadingTitle.classList.add('output__loading-title');
  63558. _this.loadingScreen.appendChild(loadingTitle);
  63559. _this.element.appendChild(_this.loadingScreen);
  63560. _this.offScreen = document.createElement('div');
  63561. _this.offScreen.classList.add('output__sound');
  63562. var options = {};
  63563. options.playCallback = _this.searchResultPlayClick.bind(_this);
  63564. options.selectCallback = _this.searchResultClick.bind(_this);
  63565. options.assets = _this.assets;
  63566. _this.search = new _SoundSearch2.default(options);
  63567. _this.offScreen.appendChild(_this.search.element);
  63568. _this.inputClasses = [];
  63569. _this.lastSound;
  63570. for (var index = 0; index < _this.assets.length; index += 1) {
  63571. var sound = _this.assets[index];
  63572. var audio = new Audio();
  63573. audio.muted = true;
  63574. audio.loop = true;
  63575. audio.addEventListener('canplaythrough', _this.assetLoaded.bind(_this));
  63576. audio.src = _this.basePath + sound;
  63577. _this.sounds[sound] = audio;
  63578. }
  63579. for (var _index = 0; _index < _this.numClasses; _index += 1) {
  63580. var id = _this.classNames[_index];
  63581. var inputClass = document.createElement('div');
  63582. var _sound = _this.defaultAssets[_index];
  63583. inputClass.classList.add('output__sound-class');
  63584. inputClass.classList.add('output__sound-class--' + id);
  63585. var speakerIcon = document.createElement('div');
  63586. speakerIcon.classList.add('output__sound-speaker');
  63587. speakerIcon.classList.add('output__sound-speaker--' + id);
  63588. inputClass.sound = _sound;
  63589. inputClass.icon = speakerIcon;
  63590. var loader = function (el) {
  63591. var ajax = new XMLHttpRequest();
  63592. ajax.open('GET', 'assets/outputs/speaker-icon.svg', true);
  63593. ajax.onload = function (event) {
  63594. el.innerHTML = ajax.responseText;
  63595. };
  63596. ajax.send();
  63597. }(speakerIcon);
  63598. var editIcon = document.createElement('div');
  63599. editIcon.classList.add('output__sound-edit');
  63600. editIcon.classList.add('output__sound-edit--' + id);
  63601. editIcon.setAttribute("data-attr", language.content);
  63602. var input = document.createElement('input');
  63603. input.classId = id;
  63604. input.classList.add('output__sound-input');
  63605. input.classList.add('output__sound-input--' + id);
  63606. input.setAttribute('readonly', 'readonly');
  63607. input.value = _sound;
  63608. inputClass.appendChild(speakerIcon);
  63609. inputClass.appendChild(editIcon);
  63610. inputClass.appendChild(input);
  63611. var deleteIcon = document.createElement('div');
  63612. deleteIcon.classList.add('output__sound-delete');
  63613. inputClass.appendChild(deleteIcon);
  63614. deleteIcon.addEventListener('click', _this.clearInput.bind(_this));
  63615. input.addEventListener('click', _this.editInput.bind(_this));
  63616. document.addEventListener('visibilitychange', _this.handleVisibilityChange.bind(_this), false);
  63617. // speakerIcon.addEventListener('click', this.testSound.bind(this));
  63618. // this.inputClasses[index] = speakerIcon;
  63619. inputClass.input = input;
  63620. _this.inputClasses[_index] = inputClass;
  63621. _this.offScreen.appendChild(inputClass);
  63622. }
  63623. _this.element.appendChild(_this.offScreen);
  63624. _this.speakers = [];
  63625. _this.buildCanvas();
  63626. }, 1500);
  63627. }
  63628. _createClass(SoundOutput, [{
  63629. key: 'handleVisibilityChange',
  63630. value: function handleVisibilityChange() {
  63631. if (_config2.default.outputSection.currentOutput && _config2.default.outputSection.currentOutput.id === 'SoundOutput') {
  63632. if (this.currentSound === null) {
  63633. this.currentSound;
  63634. } else if (document.hidden) {
  63635. this.currentSound.pause();
  63636. } else {
  63637. this.currentSound.play();
  63638. }
  63639. }
  63640. }
  63641. }, {
  63642. key: 'playCurrentSound',
  63643. value: function playCurrentSound() {
  63644. if (this.currentSound) {
  63645. this.currentSound.play();
  63646. }
  63647. }
  63648. }, {
  63649. key: 'pauseCurrentSound',
  63650. value: function pauseCurrentSound() {
  63651. if (this.currentSound) {
  63652. this.currentSound.pause();
  63653. }
  63654. }
  63655. }, {
  63656. key: 'clearInput',
  63657. value: function clearInput(event) {
  63658. if (this.currentSound === this.sounds[event.target.parentNode.sound]) {
  63659. this.currentSound.muted = true;
  63660. this.currentSound = null;
  63661. if (this.currentIcon) {
  63662. this.currentIcon.classList.remove('output__sound-speaker--active');
  63663. this.currentIcon = null;
  63664. }
  63665. }
  63666. event.target.parentNode.sound = null;
  63667. event.target.parentNode.input.value = 'Nothing';
  63668. event.target.parentNode.input.classList.add('output__sound-input--nothing');
  63669. if (this.currentBorder && this.currentClassName) {
  63670. this.currentBorder.classList.remove('output__sound-input--' + this.currentClassName + '-selected');
  63671. }
  63672. }
  63673. }, {
  63674. key: 'searchResultPlayClick',
  63675. value: function searchResultPlayClick(event) {
  63676. event.stopPropagation();
  63677. var sound = event.target.parentNode.value;
  63678. this.lastSound = sound;
  63679. this.playSound(sound);
  63680. }
  63681. }, {
  63682. key: 'searchResultClick',
  63683. value: function searchResultClick(event) {
  63684. var value = event.target.value;
  63685. this.activeInput.value = value;
  63686. this.activeInput.parentNode.sound = value;
  63687. this.activeInput.parentNode.input.classList.remove('output__sound-input--nothing');
  63688. if (this.currentSound) {
  63689. this.currentSound.muted = true;
  63690. this.currentSound = null;
  63691. }
  63692. this.search.hide();
  63693. }
  63694. }, {
  63695. key: 'editInput',
  63696. value: function editInput(event) {
  63697. this.activeInput = event.target;
  63698. var classId = this.activeInput.classId;
  63699. if (this.currentSound) {
  63700. this.currentSound.muted = true;
  63701. this.currentSound = null;
  63702. if (this.currentIcon) {
  63703. this.currentIcon.classList.remove('output__sound-speaker--active');
  63704. this.currentIcon = null;
  63705. }
  63706. }
  63707. this.search.show(classId);
  63708. }
  63709. }, {
  63710. key: 'filterResults',
  63711. value: function filterResults() {
  63712. var phrase = this.searchInput.value;
  63713. }
  63714. }, {
  63715. key: 'soundEnded',
  63716. value: function soundEnded(event) {
  63717. if (this.activeSpeaker) {
  63718. this.currentSound.muted = true;
  63719. this.activeSpeaker.classList.remove('output__sound-speaker--active');
  63720. }
  63721. this.canTrigger = true;
  63722. if (this.currentSound === event.target) {
  63723. this.currentSound.muted = true;
  63724. this.currentSound = null;
  63725. if (this.currentIcon) {
  63726. this.currentIcon.classList.remove('output__sound-speaker--active');
  63727. this.currentIcon = null;
  63728. }
  63729. }
  63730. }
  63731. }, {
  63732. key: 'playSound',
  63733. value: function playSound(sound) {
  63734. this.muteSounds();
  63735. if (!this.search.visible) {
  63736. if (this.currentSound === sound) {
  63737. this.currentSound = null;
  63738. } else if (this.sounds[sound]) {
  63739. this.currentSound = this.sounds[sound];
  63740. this.currentSound.muted = false;
  63741. this.currentSound.currentTime = 0;
  63742. this.currentSound.play();
  63743. this.lastSound = this.currentSound;
  63744. }
  63745. }
  63746. }
  63747. }, {
  63748. key: 'muteSounds',
  63749. value: function muteSounds() {
  63750. if (this.currentSound) {
  63751. this.currentSound.muted = true;
  63752. }
  63753. }
  63754. }, {
  63755. key: 'assetLoaded',
  63756. value: function assetLoaded(event) {
  63757. this.numLoaded += 1;
  63758. if (this.numLoaded === this.numAssets) {
  63759. this.loaded = true;
  63760. for (var index = 0; index < this.numAssets; index += 1) {
  63761. var id = this.assets[index];
  63762. }
  63763. this.showScreen();
  63764. }
  63765. }
  63766. }, {
  63767. key: 'showScreen',
  63768. value: function showScreen() {
  63769. this.loadingScreen.style.display = 'none';
  63770. this.offScreen.style.display = 'block';
  63771. }
  63772. }, {
  63773. key: 'trigger',
  63774. value: function trigger(index) {
  63775. if (!_config2.default.clearing) {
  63776. if (this.currentIndex !== index) {
  63777. this.currentIndex = index;
  63778. var sound = this.inputClasses[this.currentIndex].sound;
  63779. if (sound) {
  63780. this.playSound(sound);
  63781. } else {
  63782. this.muteSounds();
  63783. }
  63784. if (this.currentIcon) {
  63785. this.currentIcon.classList.remove('output__sound-speaker--active');
  63786. }
  63787. if (this.currentBorder && this.currentClassName) {
  63788. this.currentBorder.classList.remove('output__sound-input--' + this.currentClassName + '-selected');
  63789. }
  63790. var border = this.inputClasses[index].input;
  63791. var id = this.classNames[index];
  63792. this.currentClassName = id;
  63793. this.currentBorder = border;
  63794. this.currentBorder.classList.add('output__sound-input--' + this.currentClassName + '-selected');
  63795. this.currentIcon = this.inputClasses[this.currentIndex];
  63796. this.currentIcon.classList.add('output__sound-speaker--active');
  63797. if (this.canvas) {
  63798. sound === null ? sound = '(nothing)' : sound;
  63799. this.updateCanvas(this.currentIndex, sound);
  63800. }
  63801. }
  63802. }
  63803. if (_config2.default.clearing) {
  63804. if (this.currentIcon) {
  63805. this.currentIcon.classList.remove('output__sound-speaker--active');
  63806. }
  63807. if (this.currentBorder && this.currentClassName) {
  63808. this.currentBorder.classList.remove('output__sound-input--' + this.currentClassName + '-selected');
  63809. }
  63810. for (var _index2 = 0; _index2 < this.numAssets; _index2 += 1) {
  63811. var _id = this.assets[_index2];
  63812. this.sounds[_id].pause();
  63813. }
  63814. }
  63815. }
  63816. }, {
  63817. key: 'stop',
  63818. value: function stop() {
  63819. for (var index = 0; index < this.numAssets; index += 1) {
  63820. var id = this.assets[index];
  63821. this.sounds[id].pause();
  63822. }
  63823. this.element.style.display = 'none';
  63824. }
  63825. }, {
  63826. key: 'start',
  63827. value: function start() {
  63828. this.element.style.display = 'block';
  63829. this.handleVisibilityChange();
  63830. }
  63831. }, {
  63832. key: 'clear',
  63833. value: function clear() {}
  63834. }, {
  63835. key: 'buildCanvas',
  63836. value: function buildCanvas() {
  63837. var _this2 = this;
  63838. this.canvas = document.createElement('canvas');
  63839. this.canvas.style.display = 'none';
  63840. this.context = this.canvas.getContext('2d');
  63841. this.canvas.width = 340;
  63842. this.canvas.height = 260;
  63843. this.offScreen.appendChild(this.canvas);
  63844. var img = new Image();
  63845. img.onload = function () {
  63846. _this2.canvasImage = img;
  63847. };
  63848. img.src = 'assets/outputs/speaker-icon.svg';
  63849. }
  63850. }, {
  63851. key: 'updateCanvas',
  63852. value: function updateCanvas(colorId, sound) {
  63853. if (sound === 'null') {
  63854. this.sound = ' ';
  63855. }
  63856. var color = '#2baa5e';
  63857. switch (colorId) {
  63858. case 0:
  63859. color = '#2baa5e';
  63860. break;
  63861. case 1:
  63862. color = '#c95ac5';
  63863. break;
  63864. default:
  63865. case 2:
  63866. color = '#dd4d31';
  63867. break;
  63868. }
  63869. if (this.canvasImage) {
  63870. this.context.globalCompositeOperation = 'source-over';
  63871. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  63872. this.context.fillStyle = 'rgb(255, 255, 255)';
  63873. this.context.fillRect(0, 0, 300, 300);
  63874. this.context.drawImage(this.canvasImage, 105, 52, 95, 95);
  63875. this.context.font = '25px Poppins';
  63876. this.context.fillStyle = '#000';
  63877. this.context.fillText(sound, this.canvas.width / 2 - this.context.measureText(sound).width / 2 - 20, 207);
  63878. this.context.globalCompositeOperation = 'screen';
  63879. this.context.fillStyle = color;
  63880. this.context.fillRect(0, 0, 300, 300);
  63881. }
  63882. }
  63883. }, {
  63884. key: 'touchAudio',
  63885. value: function touchAudio() {
  63886. for (var key in this.sounds) {
  63887. /* eslint-disable */
  63888. if (this.sounds.hasOwnProperty(key)) {
  63889. this.sounds[key].play();
  63890. this.sounds[key].pause();
  63891. }
  63892. /* eslint-enable */
  63893. }
  63894. }
  63895. }]);
  63896. return SoundOutput;
  63897. }();
  63898. exports.default = SoundOutput;
  63899. },{"./../config.js":242,"./sound/SoundSearch.js":249}],248:[function(require,module,exports){
  63900. 'use strict';
  63901. Object.defineProperty(exports, "__esModule", {
  63902. value: true
  63903. });
  63904. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // Copyright 2017 Google Inc.
  63905. //
  63906. // Licensed under the Apache License, Version 2.0 (the "License");
  63907. // you may not use this file except in compliance with the License.
  63908. // You may obtain a copy of the License at
  63909. //
  63910. // http://www.apache.org/licenses/LICENSE-2.0
  63911. //
  63912. // Unless required by applicable law or agreed to in writing, software
  63913. // distributed under the License is distributed on an "AS IS" BASIS,
  63914. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  63915. // See the License for the specific language governing permissions and
  63916. // limitations under the License.
  63917. var _TextToSpeech = require('./speech/TextToSpeech.js');
  63918. var _TextToSpeech2 = _interopRequireDefault(_TextToSpeech);
  63919. var _config = require('./../config.js');
  63920. var _config2 = _interopRequireDefault(_config);
  63921. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  63922. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  63923. var SpeechOutput = function () {
  63924. function SpeechOutput() {
  63925. var _this = this;
  63926. _classCallCheck(this, SpeechOutput);
  63927. setTimeout(function () {
  63928. var lang = _config2.default.lang;
  63929. var language = lang === "en" ? _config2.default.languare.en : lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  63930. _this.id = 'SpeechOutput';
  63931. _this.canTrigger = true;
  63932. _this.currentSound = null;
  63933. _this.currentIcon = null;
  63934. _this.currentIndex = null;
  63935. _this.textToSpeech = new _TextToSpeech2.default();
  63936. _this.element = document.createElement('div');
  63937. _this.element.classList.add('output__container');
  63938. _this.element.classList.add('output__container--speech');
  63939. _this.defaultMessages = ['Hello', 'Awesome', 'Yes'];
  63940. _this.classNames = _config2.default.classNames;
  63941. _this.colors = _config2.default.colors;
  63942. _this.numClasses = _config2.default.numClasses;
  63943. _this.offScreen = document.createElement('div');
  63944. _this.offScreen.classList.add('output__speech');
  63945. var options = {};
  63946. _this.inputClasses = [];
  63947. for (var index = 0; index < _this.numClasses; index += 1) {
  63948. var id = _this.classNames[index];
  63949. var inputClass = document.createElement('div');
  63950. var message = _this.defaultMessages[index];
  63951. inputClass.defaultMessage = message;
  63952. inputClass.message = message;
  63953. inputClass.classList.add('output__speech-class');
  63954. inputClass.classList.add('output__speech-class--' + id);
  63955. var speakerIcon = document.createElement('div');
  63956. speakerIcon.classList.add('output__speech-speaker');
  63957. speakerIcon.classList.add('output__speech-speaker--' + id);
  63958. var loader = function (el) {
  63959. var ajax = new XMLHttpRequest();
  63960. ajax.open('GET', 'assets/outputs/speaker-icon.svg', true);
  63961. ajax.onload = function (event) {
  63962. el.innerHTML = ajax.responseText;
  63963. };
  63964. ajax.send();
  63965. }(speakerIcon);
  63966. var editIcon = document.createElement('div');
  63967. editIcon.classList.add('output__speech-edit');
  63968. editIcon.classList.add('output__speech-edit--' + id);
  63969. editIcon.setAttribute("data-attr", language.speech_content);
  63970. var input = document.createElement('input');
  63971. input.classId = id;
  63972. input.classList.add('output__speech-input');
  63973. input.classList.add('output__speech-input--' + id);
  63974. input.setAttribute('maxlength', 25);
  63975. input.value = _this.defaultMessages[index];
  63976. inputClass.appendChild(speakerIcon);
  63977. inputClass.appendChild(editIcon);
  63978. inputClass.appendChild(input);
  63979. var deleteIcon = document.createElement('div');
  63980. deleteIcon.classList.add('output__speech-delete');
  63981. inputClass.appendChild(deleteIcon);
  63982. inputClass.input = input;
  63983. inputClass.icon = speakerIcon;
  63984. deleteIcon.addEventListener('click', _this.clearInput.bind(_this));
  63985. input.addEventListener('blur', _this.inputBlur.bind(_this));
  63986. input.addEventListener('keyup', _this.keyUp.bind(_this));
  63987. input.addEventListener('click', _this.editInput.bind(_this));
  63988. // speakerIcon.addEventListener('click', this.playSound.bind(this));
  63989. _this.inputClasses[index] = inputClass;
  63990. _this.element.appendChild(inputClass);
  63991. }
  63992. _this.buildCanvas();
  63993. }, 1500);
  63994. }
  63995. _createClass(SpeechOutput, [{
  63996. key: 'clearInput',
  63997. value: function clearInput(event) {
  63998. event.target.parentNode.message = null;
  63999. event.target.parentNode.input.value = 'Nothing';
  64000. event.target.parentNode.input.classList.add('output__speech-input--nothing');
  64001. }
  64002. }, {
  64003. key: 'keyUp',
  64004. value: function keyUp(event) {
  64005. var message = event.target.value;
  64006. event.target.parentNode.message = message;
  64007. event.target.classList.remove('output__speech-input--nothing');
  64008. }
  64009. }, {
  64010. key: 'inputBlur',
  64011. value: function inputBlur(event) {
  64012. var message = event.target.value;
  64013. event.target.classList.remove('output__speech-input--nothing');
  64014. message = event.target.value;
  64015. event.target.parentNode.message = message;
  64016. }
  64017. }, {
  64018. key: 'editInput',
  64019. value: function editInput(event) {
  64020. event.target.parentNode.input.value = '';
  64021. this.activeInput = event.target;
  64022. var classId = this.activeInput.classId;
  64023. }
  64024. }, {
  64025. key: 'filterResults',
  64026. value: function filterResults() {
  64027. var phrase = this.searchInput.value;
  64028. if (phrase.length === 0) {
  64029. phrase = 'Hello';
  64030. }
  64031. this.ttsItem.children[1].value = '"' + phrase + '"';
  64032. this.ttsItem.value = '"' + phrase + '"';
  64033. }
  64034. }, {
  64035. key: 'soundEnded',
  64036. value: function soundEnded(event) {
  64037. if (this.activeSpeaker) {
  64038. this.activeSpeaker.classList.remove('output__speech-speaker--active');
  64039. }
  64040. this.canTrigger = true;
  64041. if (this.currentSound === event.target) {
  64042. this.currentSound.pause();
  64043. this.currentSound = null;
  64044. if (this.currentIcon) {
  64045. this.currentIcon.classList.remove('output__speech-speaker--active');
  64046. this.currentIcon = null;
  64047. }
  64048. }
  64049. }
  64050. }, {
  64051. key: 'ttsEnded',
  64052. value: function ttsEnded() {
  64053. if (this.activeSpeaker) {
  64054. this.activeSpeaker.classList.remove('output__speech-speaker--active');
  64055. }
  64056. this.canTrigger = true;
  64057. this.currentTTS = null;
  64058. this.currentIcon.classList.remove('output__speech-speaker--active');
  64059. }
  64060. }, {
  64061. key: 'playSound',
  64062. value: function playSound(event) {
  64063. var icon = event.target;
  64064. var sound = icon.parentNode.message;
  64065. if (this.currentIcon) {
  64066. this.currentIcon.classList.remove('output__speech-speaker--active');
  64067. }
  64068. if (this.currentTTS) {
  64069. this.textToSpeech.stop();
  64070. }
  64071. icon.classList.add('output__speech-speaker--active');
  64072. this.textToSpeech.say(sound, this.ttsEnded.bind(this));
  64073. this.currentTTS = true;
  64074. this.currentIcon = icon;
  64075. }
  64076. }, {
  64077. key: 'trigger',
  64078. value: function trigger(index) {
  64079. var overrideAndPlay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  64080. if (!_config2.default.clearing) {
  64081. if (this.currentIndex !== index || overrideAndPlay) {
  64082. this.canTrigger = false;
  64083. this.currentIndex = index;
  64084. if (this.currentIcon) {
  64085. this.currentIcon.classList.remove('output__speech-speaker--active');
  64086. }
  64087. if (this.currentBorder && this.currentClassName) {
  64088. this.currentBorder.classList.remove('output__speech-input--' + this.currentClassName + '-selected');
  64089. }
  64090. var border = this.inputClasses[index].input;
  64091. var id = this.classNames[index];
  64092. this.currentClassName = id;
  64093. this.currentBorder = border;
  64094. this.currentBorder.classList.add('output__speech-input--' + this.currentClassName + '-selected');
  64095. if (this.currentTTS) {
  64096. this.textToSpeech.stop();
  64097. }
  64098. var icon = this.inputClasses[index].icon;
  64099. var sound = this.inputClasses[index].message;
  64100. if (sound) {
  64101. this.currentIcon = icon;
  64102. this.currentIcon.classList.add('output__speech-speaker--active');
  64103. this.textToSpeech.say(sound, this.ttsEnded.bind(this));
  64104. this.currentTTS = true;
  64105. } else {
  64106. this.canTrigger = true;
  64107. }
  64108. if (this.canvas) {
  64109. sound === null ? sound = '(nothing)' : sound;
  64110. this.updateCanvas(this.currentIndex, sound);
  64111. }
  64112. }
  64113. }
  64114. if (_config2.default.clearing) {
  64115. if (this.currentBorder && this.currentClassName) {
  64116. this.currentBorder.classList.remove('output__speech-input--' + this.currentClassName + '-selected');
  64117. }
  64118. if (this.currentIcon) {
  64119. this.currentIcon.classList.remove('output__speech-speaker--active');
  64120. }
  64121. if (this.currentTTS) {
  64122. this.textToSpeech.stop();
  64123. }
  64124. }
  64125. }
  64126. }, {
  64127. key: 'stop',
  64128. value: function stop() {
  64129. if (this.currentTTS) {
  64130. this.textToSpeech.stop();
  64131. }
  64132. this.element.style.display = 'none';
  64133. }
  64134. }, {
  64135. key: 'start',
  64136. value: function start() {
  64137. this.element.style.display = 'block';
  64138. if (typeof this.currentIndex === 'number') {
  64139. this.trigger(this.currentIndex, true);
  64140. }
  64141. }
  64142. }, {
  64143. key: 'clear',
  64144. value: function clear() {}
  64145. }, {
  64146. key: 'buildCanvas',
  64147. value: function buildCanvas() {
  64148. var _this2 = this;
  64149. this.canvas = document.createElement('canvas');
  64150. this.canvas.style.display = 'none';
  64151. this.context = this.canvas.getContext('2d');
  64152. this.canvas.width = 340;
  64153. this.canvas.height = 260;
  64154. this.element.appendChild(this.canvas);
  64155. var img = new Image();
  64156. img.onload = function () {
  64157. _this2.canvasImage = img;
  64158. };
  64159. img.src = 'assets/outputs/speaker-icon.svg';
  64160. }
  64161. }, {
  64162. key: 'updateCanvas',
  64163. value: function updateCanvas(colorId, sound) {
  64164. if (sound === 'null') {
  64165. this.sound = ' ';
  64166. }
  64167. var color = '#2baa5e';
  64168. switch (colorId) {
  64169. case 0:
  64170. color = '#2baa5e';
  64171. break;
  64172. case 1:
  64173. color = '#c95ac5';
  64174. break;
  64175. default:
  64176. case 2:
  64177. color = '#dd4d31';
  64178. break;
  64179. }
  64180. if (this.canvasImage) {
  64181. this.context.globalCompositeOperation = 'source-over';
  64182. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  64183. this.context.fillStyle = 'rgb(255, 255, 255)';
  64184. this.context.fillRect(0, 0, 300, 300);
  64185. this.context.drawImage(this.canvasImage, 105, 52, 95, 95);
  64186. this.context.font = '25px Poppins';
  64187. this.context.fillStyle = '#000';
  64188. this.context.fillText(sound, this.canvas.width / 2 - 21, 207);
  64189. this.context.textAlign = 'center';
  64190. this.context.globalCompositeOperation = 'screen';
  64191. this.context.fillStyle = color;
  64192. this.context.fillRect(0, 0, 300, 300);
  64193. }
  64194. }
  64195. }]);
  64196. return SpeechOutput;
  64197. }();
  64198. exports.default = SpeechOutput;
  64199. },{"./../config.js":242,"./speech/TextToSpeech.js":250}],249:[function(require,module,exports){
  64200. 'use strict';
  64201. Object.defineProperty(exports, "__esModule", {
  64202. value: true
  64203. });
  64204. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  64205. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  64206. // Copyright 2017 Google Inc.
  64207. //
  64208. // Licensed under the Apache License, Version 2.0 (the "License");
  64209. // you may not use this file except in compliance with the License.
  64210. // You may obtain a copy of the License at
  64211. //
  64212. // http://www.apache.org/licenses/LICENSE-2.0
  64213. //
  64214. // Unless required by applicable law or agreed to in writing, software
  64215. // distributed under the License is distributed on an "AS IS" BASIS,
  64216. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  64217. // See the License for the specific language governing permissions and
  64218. // limitations under the License.
  64219. var SoundSearch = function () {
  64220. function SoundSearch(options) {
  64221. _classCallCheck(this, SoundSearch);
  64222. this.playCallback = options.playCallback;
  64223. this.selectCallback = options.selectCallback;
  64224. this.assets = options.assets;
  64225. this.element = document.createElement('div');
  64226. this.element.classList.add('output__sound-search');
  64227. this.searchBar = document.createElement('div');
  64228. this.searchBar.classList.add('output__sound-search-bar');
  64229. this.element.appendChild(this.searchBar);
  64230. this.searchInput = document.createElement('input');
  64231. this.searchInput.classList.add('output__sound-search-input');
  64232. this.searchBar.appendChild(this.searchInput);
  64233. this.backButton = document.createElement('div');
  64234. this.backButton.addEventListener('click', this.hide.bind(this));
  64235. this.backButton.classList.add('output__sound-back');
  64236. var loader = function (el) {
  64237. var ajax = new XMLHttpRequest();
  64238. ajax.open('GET', 'assets/outputs/back-icon.svg', true);
  64239. ajax.onload = function (event) {
  64240. el.innerHTML = ajax.responseText;
  64241. };
  64242. ajax.send();
  64243. }(this.backButton);
  64244. this.searchBar.appendChild(this.backButton);
  64245. this.searchResults = document.createElement('div');
  64246. this.searchResults.classList.add('output__sound-search-results');
  64247. this.allResults = [];
  64248. for (var index = 0; index < this.assets.length; index += 1) {
  64249. var item = document.createElement('div');
  64250. item.classList.add('output__sound-search-result');
  64251. var icon = document.createElement('div');
  64252. icon.classList.add('output__sound-search-result-icon');
  64253. var label = document.createElement('input');
  64254. label.setAttribute('readonly', 'readonly');
  64255. label.classList.add('output__sound-search-result-input');
  64256. // icon.classList.add('output__sound-search-result-play');
  64257. var _loader = function (el) {
  64258. var ajax = new XMLHttpRequest();
  64259. ajax.open('GET', 'assets/outputs/play-icon.svg', true);
  64260. ajax.onload = function (event) {
  64261. el.innerHTML = ajax.responseText;
  64262. };
  64263. ajax.send();
  64264. }(icon);
  64265. item.value = this.assets[index];
  64266. label.value = item.value;
  64267. icon.addEventListener('click', this.playCallback);
  64268. this.allResults.push(item);
  64269. item.appendChild(icon);
  64270. item.appendChild(label);
  64271. item.addEventListener('click', this.selectCallback);
  64272. this.searchResults.appendChild(item);
  64273. }
  64274. this.element.appendChild(this.searchResults);
  64275. this.searchInput.addEventListener('keyup', this.filterResults.bind(this));
  64276. }
  64277. _createClass(SoundSearch, [{
  64278. key: 'hide',
  64279. value: function hide() {
  64280. this.element.style.display = 'none';
  64281. this.searchResults.className = 'output__sound-search-results';
  64282. this.searchInput.className = 'output__sound-search-input';
  64283. this.backButton.className = 'output__sound-back';
  64284. this.allResults.forEach(function (item) {
  64285. var icon = item.children[0];
  64286. icon.className = 'output__sound-search-result-icon';
  64287. });
  64288. this.visible = false;
  64289. }
  64290. }, {
  64291. key: 'show',
  64292. value: function show(classId) {
  64293. this.element.style.display = 'block';
  64294. this.searchResults.classList.add('output__sound-search-results--' + classId);
  64295. this.searchInput.classList.add('output__sound-search-input--' + classId);
  64296. this.backButton.classList.add('output__sound-back--' + classId);
  64297. this.allResults.forEach(function (item) {
  64298. var icon = item.children[0];
  64299. icon.classList.add('output__sound-search-result-icon--' + classId);
  64300. });
  64301. this.searchInput.focus();
  64302. this.visible = true;
  64303. }
  64304. }, {
  64305. key: 'filterResults',
  64306. value: function filterResults() {
  64307. var phrase = this.searchInput.value;
  64308. var showAll = false;
  64309. if (phrase.length === 0) {
  64310. showAll = true;
  64311. }
  64312. this.allResults.forEach(function (item) {
  64313. if (showAll) {
  64314. item.style.display = 'block';
  64315. } else if (item.value.toLowerCase().indexOf(phrase.toLowerCase()) > -1) {
  64316. item.style.display = 'block';
  64317. } else {
  64318. item.style.display = 'none';
  64319. }
  64320. });
  64321. }
  64322. }]);
  64323. return SoundSearch;
  64324. }();
  64325. exports.default = SoundSearch;
  64326. },{}],250:[function(require,module,exports){
  64327. 'use strict';
  64328. Object.defineProperty(exports, "__esModule", {
  64329. value: true
  64330. });
  64331. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  64332. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  64333. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  64334. // Copyright 2017 Google Inc.
  64335. //
  64336. // Licensed under the Apache License, Version 2.0 (the "License");
  64337. // you may not use this file except in compliance with the License.
  64338. // You may obtain a copy of the License at
  64339. //
  64340. // http://www.apache.org/licenses/LICENSE-2.0
  64341. //
  64342. // Unless required by applicable law or agreed to in writing, software
  64343. // distributed under the License is distributed on an "AS IS" BASIS,
  64344. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  64345. // See the License for the specific language governing permissions and
  64346. // limitations under the License.
  64347. var TextToSpeech = function () {
  64348. function TextToSpeech() {
  64349. _classCallCheck(this, TextToSpeech);
  64350. this.voices = [];
  64351. this.voice = null;
  64352. this.message = null;
  64353. if ((typeof speechSynthesis === 'undefined' ? 'undefined' : _typeof(speechSynthesis)) === 'object' && typeof speechSynthesis.onvoiceschanged === 'function') {
  64354. speechSynthesis.onvoiceschanged = this.setVoice;
  64355. }
  64356. }
  64357. _createClass(TextToSpeech, [{
  64358. key: 'setVoice',
  64359. value: function setVoice() {
  64360. this.voices = window.speechSynthesis.getVoices();
  64361. this.voice = this.voices.filter(function (voice) {
  64362. return voice.name === 'Google US English Female';
  64363. })[0];
  64364. }
  64365. }, {
  64366. key: 'stop',
  64367. value: function stop() {
  64368. window.speechSynthesis.cancel();
  64369. }
  64370. }, {
  64371. key: 'say',
  64372. value: function say(text, callback) {
  64373. this.message = new SpeechSynthesisUtterance();
  64374. this.message.text = text;
  64375. this.message.voice = this.voice;
  64376. this.message.rate = 0.9;
  64377. this.message.lang = 'en-US';
  64378. this.message.addEventListener('end', callback);
  64379. window.speechSynthesis.speak(this.message);
  64380. }
  64381. }]);
  64382. return TextToSpeech;
  64383. }();
  64384. exports.default = TextToSpeech;
  64385. },{}],251:[function(require,module,exports){
  64386. 'use strict';
  64387. Object.defineProperty(exports, "__esModule", {
  64388. value: true
  64389. });
  64390. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  64391. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  64392. // Copyright 2017 Google Inc.
  64393. //
  64394. // Licensed under the Apache License, Version 2.0 (the "License");
  64395. // you may not use this file except in compliance with the License.
  64396. // You may obtain a copy of the License at
  64397. //
  64398. // http://www.apache.org/licenses/LICENSE-2.0
  64399. //
  64400. // Unless required by applicable law or agreed to in writing, software
  64401. // distributed under the License is distributed on an "AS IS" BASIS,
  64402. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  64403. // See the License for the specific language governing permissions and
  64404. // limitations under the License.
  64405. var BrowserUtils = function () {
  64406. function BrowserUtils() {
  64407. _classCallCheck(this, BrowserUtils);
  64408. /* eslint-disable */
  64409. this.isAndroid = navigator.userAgent.toLowerCase().indexOf('android') > -1;
  64410. this.isSafari = navigator.userAgent.indexOf('Safari') > -1;
  64411. this.isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
  64412. this.isIE = navigator.userAgent.indexOf('MSIE') > -1;
  64413. this.isEdge = navigator.userAgent.indexOf('Edge') > -1;
  64414. this.isMobile = false;
  64415. this.isChrome = /chrome/i.test(navigator.userAgent);
  64416. this.isCompatible;
  64417. if (this.isChrome) {
  64418. this.isSafari = false;
  64419. }
  64420. if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) {
  64421. this.isMobile = true;
  64422. }
  64423. if (this.isMobile) {
  64424. var androidVersion = this.getAndroidVersion();
  64425. if (androidVersion) {
  64426. this.isSafari = false;
  64427. }
  64428. if (androidVersion && androidVersion >= 7) {
  64429. this.isCompatible = true;
  64430. }
  64431. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia && this.isSafari) {
  64432. this.isCompatible = true;
  64433. }
  64434. } else {
  64435. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia && !this.isEdge && !this.isIE) {
  64436. this.isCompatible = true;
  64437. }
  64438. }
  64439. if (this.isCompatible) {
  64440. this.isCompatible = this.webglSupport();
  64441. }
  64442. }
  64443. _createClass(BrowserUtils, [{
  64444. key: 'webglSupport',
  64445. value: function webglSupport() {
  64446. var canvas;
  64447. var ctx;
  64448. var exts;
  64449. var support = false;
  64450. try {
  64451. canvas = document.createElement('canvas');
  64452. ctx = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  64453. exts = ctx.getSupportedExtensions();
  64454. } catch (e) {
  64455. return support;
  64456. }
  64457. if (ctx !== undefined) {
  64458. support = true;
  64459. }
  64460. for (var i = -1, len = exts.length; ++i < len;) {
  64461. support = true;
  64462. }
  64463. canvas = undefined;
  64464. console.log(support);
  64465. return support;
  64466. }
  64467. }, {
  64468. key: 'getAndroidVersion',
  64469. value: function getAndroidVersion() {
  64470. var ua = navigator.userAgent.toLowerCase();
  64471. var match = ua.match(/android\s([0-9\.]*)/);
  64472. return match ? parseInt(match[1], 10) : false;
  64473. }
  64474. /* eslint-enable */
  64475. }]);
  64476. return BrowserUtils;
  64477. }();
  64478. exports.default = BrowserUtils;
  64479. },{}],252:[function(require,module,exports){
  64480. 'use strict';
  64481. Object.defineProperty(exports, "__esModule", {
  64482. value: true
  64483. });
  64484. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // Copyright 2017 Google Inc.
  64485. //
  64486. // Licensed under the Apache License, Version 2.0 (the "License");
  64487. // you may not use this file except in compliance with the License.
  64488. // You may obtain a copy of the License at
  64489. //
  64490. // http://www.apache.org/licenses/LICENSE-2.0
  64491. //
  64492. // Unless required by applicable law or agreed to in writing, software
  64493. // distributed under the License is distributed on an "AS IS" BASIS,
  64494. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  64495. // See the License for the specific language governing permissions and
  64496. // limitations under the License.
  64497. var _gsap = require('gsap');
  64498. var _gsap2 = _interopRequireDefault(_gsap);
  64499. var _config = require('./../../config.js');
  64500. var _config2 = _interopRequireDefault(_config);
  64501. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  64502. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  64503. var Button = function () {
  64504. function Button(element) {
  64505. var _this = this;
  64506. _classCallCheck(this, Button);
  64507. this.initialElement = element.innerHTML;
  64508. this.element = element;
  64509. element.addEventListener('mousedown', this.mousedown.bind(this));
  64510. element.addEventListener('mouseup', this.mouseup.bind(this));
  64511. element.addEventListener('touchstart', this.mousedown.bind(this));
  64512. element.addEventListener('touchend', this.mouseup.bind(this));
  64513. element.addEventListener('click', this.click.bind(this));
  64514. window.addEventListener('resize', function () {
  64515. clearTimeout(_this.sizeTimeout);
  64516. _this.sizeTimeout = setTimeout(function () {
  64517. _this.size();
  64518. }, 300);
  64519. });
  64520. this.size();
  64521. this.selected = false;
  64522. }
  64523. _createClass(Button, [{
  64524. key: 'click',
  64525. value: function click(event) {
  64526. event.preventDefault();
  64527. }
  64528. }, {
  64529. key: 'select',
  64530. value: function select() {
  64531. this.element.classList.add('button__toggle--selected');
  64532. this.selected = true;
  64533. this.down();
  64534. }
  64535. }, {
  64536. key: 'deselect',
  64537. value: function deselect() {
  64538. this.element.classList.remove('button__toggle--selected');
  64539. this.selected = false;
  64540. this.up();
  64541. }
  64542. }, {
  64543. key: 'mousedown',
  64544. value: function mousedown(event) {
  64545. event.preventDefault();
  64546. this.down();
  64547. }
  64548. }, {
  64549. key: 'mouseup',
  64550. value: function mouseup(event) {
  64551. if (this.selected) {
  64552. return;
  64553. }
  64554. event.preventDefault();
  64555. this.up();
  64556. }
  64557. }, {
  64558. key: 'down',
  64559. value: function down() {
  64560. _gsap2.default.to(this.content, 0.12, {
  64561. x: -(this.depthX - this.depthXPressed),
  64562. y: this.depthY - this.depthYPressed
  64563. });
  64564. }
  64565. }, {
  64566. key: 'up',
  64567. value: function up() {
  64568. _gsap2.default.to(this.content, 0.12, {
  64569. x: 0,
  64570. y: 0
  64571. });
  64572. }
  64573. }, {
  64574. key: 'html',
  64575. value: function html() {
  64576. return this.el;
  64577. }
  64578. }, {
  64579. key: 'setText',
  64580. value: function setText(text) {
  64581. this.label.children[0].innerHTML = text;
  64582. }
  64583. }, {
  64584. key: 'size',
  64585. value: function size() {
  64586. var element = this.element;
  64587. element.innerHTML = this.initialElement;
  64588. element.style.height = 'auto';
  64589. element.style.width = 'auto';
  64590. var textWidth = element.offsetWidth;
  64591. var textHeight = element.offsetHeight;
  64592. var depthX = _config2.default.button.states.normal.x;
  64593. var depthY = _config2.default.button.states.normal.y;
  64594. var depthXPressed = _config2.default.button.states.pressed.x;
  64595. var depthYPressed = _config2.default.button.states.pressed.y;
  64596. if (element.classList.contains('button__toggle')) {
  64597. textWidth += 3.5;
  64598. this.isToggle = true;
  64599. }
  64600. if (element.classList.contains('button--large')) {
  64601. textHeight += 20;
  64602. textWidth += 20;
  64603. }
  64604. var frontWidth = textWidth + _config2.default.button.padding;
  64605. var frontHeight = textHeight < _config2.default.button.frontHeight ? _config2.default.button.frontHeight : textHeight;
  64606. if (element.classList.contains('button--small')) {
  64607. textWidth = 36;
  64608. textHeight = 30;
  64609. frontWidth = textWidth;
  64610. frontHeight = textHeight;
  64611. }
  64612. frontWidth = textWidth - _config2.default.button.states.normal.x;
  64613. var buttonWidth = frontWidth + _config2.default.button.states.normal.x;
  64614. var buttonHeight = frontHeight + _config2.default.button.states.normal.y;
  64615. var colorClass = 'grey';
  64616. element.classList.forEach(function (className) {
  64617. if (className.indexOf('button--color-') > -1) {
  64618. var index = className.indexOf('button--color-') + 'button--color-'.length;
  64619. colorClass = className.slice(index);
  64620. }
  64621. });
  64622. var buttonContent = element.children[0];
  64623. buttonContent.classList.remove('button__content');
  64624. var htmlContent = element.innerHTML;
  64625. element.innerHTML = '';
  64626. element.style.width = buttonWidth + 'px';
  64627. element.style.height = buttonHeight + 'px';
  64628. var mask = document.createElement('div');
  64629. mask.classList.add('button__mask');
  64630. var content = document.createElement('div');
  64631. content.classList.add('button__inner');
  64632. var label = document.createElement('div');
  64633. label.classList.add('button__label');
  64634. label.innerHTML = htmlContent;
  64635. label.style.width = frontWidth + 'px';
  64636. label.style.height = frontHeight + 'px';
  64637. // label.style.lineHeight = frontHeight + 'px';
  64638. label.style.left = depthX + 'px';
  64639. content.appendChild(label);
  64640. label.style.top = '10px';
  64641. this.label = label;
  64642. var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  64643. svg.setAttribute('width', buttonWidth);
  64644. svg.setAttribute('height', buttonHeight);
  64645. this.svg = svg;
  64646. var frontFace = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  64647. frontFace.classList.add('front-face');
  64648. frontFace.classList.add('front-face--' + colorClass);
  64649. frontFace.setAttribute('d', 'M' + depthX + ' 0 ' + (frontWidth + depthX) + ' 0 ' + (frontWidth + depthX) + ' ' + frontHeight + ' ' + depthX + ' ' + frontHeight + 'z');
  64650. svg.appendChild(frontFace);
  64651. this.frontFace = frontFace;
  64652. var bottomFace = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  64653. bottomFace.classList.add('bottom-face');
  64654. bottomFace.classList.add('bottom-face--' + colorClass);
  64655. bottomFace.setAttribute('d', 'M' + depthX + ' ' + frontHeight + ' ' + (frontWidth + depthX) + ' ' + frontHeight + ' ' + frontWidth + ' ' + (frontHeight + depthY) + ' 0 ' + (frontHeight + depthY) + 'z');
  64656. svg.appendChild(bottomFace);
  64657. this.bottomFace = bottomFace;
  64658. var leftFace = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  64659. leftFace.classList.add('left-face');
  64660. leftFace.classList.add('left-face--' + colorClass);
  64661. leftFace.setAttribute('d', 'M0 ' + depthY + ' ' + depthX + ' 0 ' + depthX + ' ' + frontHeight + ' 0 ' + (frontHeight + depthY) + 'z');
  64662. svg.appendChild(leftFace);
  64663. this.leftFace = leftFace;
  64664. content.appendChild(svg);
  64665. mask.appendChild(content);
  64666. element.appendChild(mask);
  64667. // Editable for reszing
  64668. this.label = label;
  64669. this.svg = svg;
  64670. this.frontFace = frontFace;
  64671. this.bottomFace = bottomFace;
  64672. this.leftFace = leftFace;
  64673. this.parentWidth = element.parentNode.offsetWidth;
  64674. this.buttonWidth = buttonWidth;
  64675. this.buttonHeight = buttonHeight;
  64676. this.textWidth = textWidth;
  64677. this.textHeight = textHeight;
  64678. this.frontWidth = frontWidth;
  64679. this.frontHeight = frontHeight;
  64680. this.depthX = depthX;
  64681. this.depthY = depthY;
  64682. this.depthXPressed = depthXPressed;
  64683. this.depthYPressed = depthYPressed;
  64684. this.buttonWidth = buttonWidth;
  64685. this.buttonHeight = buttonHeight;
  64686. this.content = content;
  64687. this.depthX = depthX;
  64688. this.depthY = depthY;
  64689. this.depthXPressed = depthXPressed;
  64690. this.depthYPressed = depthYPressed;
  64691. this.element = element;
  64692. this.selected = false;
  64693. }
  64694. }]);
  64695. return Button;
  64696. }();
  64697. exports.default = Button;
  64698. },{"./../../config.js":242,"gsap":212}],253:[function(require,module,exports){
  64699. 'use strict';
  64700. Object.defineProperty(exports, "__esModule", {
  64701. value: true
  64702. });
  64703. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  64704. var _config = require('./../../config.js');
  64705. var _config2 = _interopRequireDefault(_config);
  64706. var _WebcamClassifier = require('./../../ai/WebcamClassifier.js');
  64707. var _WebcamClassifier2 = _interopRequireDefault(_WebcamClassifier);
  64708. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  64709. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  64710. // Copyright 2017 Google Inc.
  64711. //
  64712. // Licensed under the Apache License, Version 2.0 (the "License");
  64713. // you may not use this file except in compliance with the License.
  64714. // You may obtain a copy of the License at
  64715. //
  64716. // http://www.apache.org/licenses/LICENSE-2.0
  64717. //
  64718. // Unless required by applicable law or agreed to in writing, software
  64719. // distributed under the License is distributed on an "AS IS" BASIS,
  64720. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  64721. // See the License for the specific language governing permissions and
  64722. // limitations under the License.
  64723. var CamInput = function () {
  64724. function CamInput() {
  64725. var _this = this;
  64726. _classCallCheck(this, CamInput);
  64727. this.element = document.createElement('div');
  64728. this.element.classList.add('input__camera');
  64729. this.webcamClassifier = new _WebcamClassifier2.default();
  64730. this.element.appendChild(this.webcamClassifier.video);
  64731. this.element.appendChild(document.getElementById('output'));
  64732. // this.webcamClassifier.video.setAttribute('muted', 'true');
  64733. // this.webcamClassifier.video.classList.add('input__camera-video');
  64734. // this.webcamClassifier.video.addEventListener(
  64735. // 'loadeddata', this.videoLoaded.bind(this));
  64736. // this.webcamClassifier.video.addEventListener(
  64737. // 'loadeddata', this.webcamClassifier.videoLoaded.bind(this));
  64738. window.addEventListener('resize', this.size.bind(this));
  64739. _config2.default.webcamClassifier = this.webcamClassifier;
  64740. // this.stop();
  64741. this.restartCam = document.querySelector(".cam--start");
  64742. this.restartCam.addEventListener('click', function () {
  64743. document.querySelector(".webcam--on").click();
  64744. _this.start();
  64745. _this.restartCam.style = "display:none";
  64746. _this.stopCam.classList.add("show");
  64747. // this.webcamClassifier.startWebcam();
  64748. _config2.default.learningSection.enable();
  64749. _config2.default.learningSection.undim();
  64750. _config2.default.outputSection.undim();
  64751. _config2.default.outputSection.enable();
  64752. });
  64753. this.stopCam = document.querySelector(".cam--stop");
  64754. this.stopCam.addEventListener('click', function () {
  64755. _this.stop();
  64756. _this.restartCam.style = "display:flex";
  64757. _this.stopCam.classList.remove("show");
  64758. // this.webcamClassifier.stopWebcam();
  64759. // document.querySelector(".webcam--off").click()
  64760. _config2.default.learningSection.disable();
  64761. _config2.default.learningSection.dim();
  64762. _config2.default.outputSection.dim();
  64763. _config2.default.outputSection.disable();
  64764. _config2.default.outputSection.clear();
  64765. _config2.default.learningSection.learningClasses.forEach(function (learningClass) {
  64766. if (learningClass.exampleCounter > 0) learningClass.resetLink.click();
  64767. });
  64768. if (_config2.default.outputSection.currentOutput.clear) _config2.default.outputSection.currentOutput.clear();
  64769. });
  64770. this.webcam_on = document.querySelector(".webcam--on");
  64771. this.webcam_on.addEventListener("click", function () {
  64772. _this.restartCam.click();
  64773. // this.webcamClassifier.startWebcam();
  64774. });
  64775. this.webcam_off = document.querySelector(".webcam--off");
  64776. this.webcam_off.addEventListener("click", function () {
  64777. _this.stopCam.click();
  64778. _this.webcamClassifier.stopWebcam();
  64779. });
  64780. this.webcam_off.click();
  64781. }
  64782. _createClass(CamInput, [{
  64783. key: 'videoLoaded',
  64784. value: function videoLoaded() {
  64785. this.videoWidth = this.webcamClassifier.video.videoWidth;
  64786. this.videoHeight = this.webcamClassifier.video.videoHeight;
  64787. this.videoRatio = this.videoWidth / this.videoHeight;
  64788. this.size();
  64789. }
  64790. }, {
  64791. key: 'start',
  64792. value: function start() {
  64793. this.show();
  64794. if (this.started) {
  64795. return;
  64796. }
  64797. this.started = true;
  64798. // this.webcamClassifier.stopTimer();
  64799. this.webcamClassifier.ready();
  64800. }
  64801. }, {
  64802. key: 'stop',
  64803. value: function stop() {
  64804. this.started = false;
  64805. this.webcamClassifier.stopTimer();
  64806. this.hide();
  64807. }
  64808. }, {
  64809. key: 'hide',
  64810. value: function hide() {
  64811. this.element.style.display = 'none';
  64812. }
  64813. }, {
  64814. key: 'show',
  64815. value: function show() {
  64816. this.element.style.display = 'block';
  64817. this.size();
  64818. }
  64819. }, {
  64820. key: 'renderExamples',
  64821. value: function renderExamples(canvas) {
  64822. // console.log('render', canvas);
  64823. }
  64824. }, {
  64825. key: 'resetClass',
  64826. value: function resetClass(id) {
  64827. this.webcamClassifier.deleteClassData(id);
  64828. }
  64829. }, {
  64830. key: 'size',
  64831. value: function size() {
  64832. this.width = this.element.offsetWidth;
  64833. this.height = this.width;
  64834. this.webcamClassifier.video.width = 300;
  64835. this.webcamClassifier.video.height = 436;
  64836. /*
  64837. if (this.videoRatio > 1) {
  64838. this.webcamClassifier.video.width = this.height * this.videoRatio;
  64839. this.webcamClassifier.video.height = this.height;
  64840. }else {
  64841. this.webcamClassifier.video.width = this.width;
  64842. this.webcamClassifier.video.height = this.width / this.videoRatio;
  64843. }*/
  64844. }
  64845. }]);
  64846. return CamInput;
  64847. }();
  64848. exports.default = CamInput;
  64849. },{"./../../ai/WebcamClassifier.js":241,"./../../config.js":242}],254:[function(require,module,exports){
  64850. 'use strict';
  64851. Object.defineProperty(exports, "__esModule", {
  64852. value: true
  64853. });
  64854. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  64855. var _index = require('../../index');
  64856. var _index2 = _interopRequireDefault(_index);
  64857. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  64858. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  64859. // Copyright 2017 Google Inc.
  64860. //
  64861. // Licensed under the Apache License, Version 2.0 (the "License");
  64862. // you may not use this file except in compliance with the License.
  64863. // You may obtain a copy of the License at
  64864. //
  64865. // http://www.apache.org/licenses/LICENSE-2.0
  64866. //
  64867. // Unless required by applicable law or agreed to in writing, software
  64868. // distributed under the License is distributed on an "AS IS" BASIS,
  64869. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  64870. // See the License for the specific language governing permissions and
  64871. // limitations under the License.
  64872. var GifCanvas = function () {
  64873. function GifCanvas() {
  64874. _classCallCheck(this, GifCanvas);
  64875. this.element = document.createElement('div');
  64876. this.canvas = document.createElement('canvas');
  64877. this.context = this.canvas.getContext('2d');
  64878. this.element.style.display = 'none';
  64879. this.canvas.width = 340;
  64880. this.canvas.height = 260;
  64881. this.canvas.classList.add('gifler-canvas');
  64882. this.canvas.name = 'gif';
  64883. this.element.appendChild(this.canvas);
  64884. this.gifs = {};
  64885. }
  64886. _createClass(GifCanvas, [{
  64887. key: 'setSource',
  64888. value: function setSource(source) {
  64889. if (_index2.default.isRecording) {
  64890. // Downsize the recorder gif
  64891. var smallerSource = source.replace('200w.gif', '200_d.gif');
  64892. if (smallerSource !== this.source) {
  64893. this.clear();
  64894. this.source = smallerSource;
  64895. this.getGifler(smallerSource);
  64896. }
  64897. }
  64898. }
  64899. }, {
  64900. key: 'getGifler',
  64901. value: function getGifler(source) {
  64902. var _this = this;
  64903. return new Promise(function (resolve) {
  64904. if (!_this.gifs[source]) {
  64905. /* eslint-disable */
  64906. window.gifler(source).frames('canvas.gifler-canvas', _this.draw.bind(_this)).then(function (response) {
  64907. _this.gifs[source] = response;
  64908. _this.gifs[source].start();
  64909. resolve(_this.gifs[source]);
  64910. });
  64911. /* eslint-enable */
  64912. }
  64913. if (_this.gifs[source]) {
  64914. _this.gifs[source].start();
  64915. resolve(_this.gifs[source]);
  64916. }
  64917. });
  64918. }
  64919. }, {
  64920. key: 'draw',
  64921. value: function draw(ctx, frame) {
  64922. if (_index2.default.isRecording) {
  64923. var hRatio = this.canvas.width / frame.width;
  64924. var vRatio = this.canvas.height / frame.height;
  64925. var ratio = Math.min(hRatio, vRatio);
  64926. var centerShiftX = (this.canvas.width - frame.width * ratio) / 2;
  64927. var centerShiftY = (this.canvas.height - frame.height * ratio) / 2;
  64928. ctx.drawImage(frame.buffer, 0, 0, frame.width, frame.height, centerShiftX, centerShiftY, frame.width * ratio, frame.height * ratio);
  64929. } else {
  64930. this.clear();
  64931. }
  64932. }
  64933. }, {
  64934. key: 'clear',
  64935. value: function clear() {
  64936. var _this2 = this;
  64937. this.source = null;
  64938. Object.keys(this.gifs).forEach(function (key) {
  64939. var gif = _this2.gifs[key];
  64940. gif.reset();
  64941. gif.stop();
  64942. });
  64943. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  64944. }
  64945. }, {
  64946. key: 'getElement',
  64947. value: function getElement() {
  64948. return this.element;
  64949. }
  64950. }]);
  64951. return GifCanvas;
  64952. }();
  64953. exports.default = GifCanvas;
  64954. },{"../../index":243}],255:[function(require,module,exports){
  64955. 'use strict';
  64956. Object.defineProperty(exports, "__esModule", {
  64957. value: true
  64958. });
  64959. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  64960. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  64961. // Copyright 2017 Google Inc.
  64962. //
  64963. // Licensed under the Apache License, Version 2.0 (the "License");
  64964. // you may not use this file except in compliance with the License.
  64965. // You may obtain a copy of the License at
  64966. //
  64967. // http://www.apache.org/licenses/LICENSE-2.0
  64968. //
  64969. // Unless required by applicable law or agreed to in writing, software
  64970. // distributed under the License is distributed on an "AS IS" BASIS,
  64971. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  64972. // See the License for the specific language governing permissions and
  64973. // limitations under the License.
  64974. var HighlightArrow = function () {
  64975. function HighlightArrow(type) {
  64976. _classCallCheck(this, HighlightArrow);
  64977. this.element = new Image();
  64978. this.element.classList.add('wizard__arrow');
  64979. this.element.width = 200;
  64980. this.element.src = 'assets/arrows/arrow-' + type + '.svg';
  64981. }
  64982. _createClass(HighlightArrow, [{
  64983. key: 'hide',
  64984. value: function hide() {
  64985. this.element.style.display = 'none';
  64986. }
  64987. }, {
  64988. key: 'show',
  64989. value: function show() {
  64990. this.element.style.display = 'block';
  64991. }
  64992. }]);
  64993. return HighlightArrow;
  64994. }();
  64995. exports.default = HighlightArrow;
  64996. },{}],256:[function(require,module,exports){
  64997. 'use strict';
  64998. Object.defineProperty(exports, "__esModule", {
  64999. value: true
  65000. });
  65001. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  65002. var _config = require('./../../config.js');
  65003. var _config2 = _interopRequireDefault(_config);
  65004. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  65005. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  65006. // Copyright 2017 Google Inc.
  65007. //
  65008. // Licensed under the Apache License, Version 2.0 (the "License");
  65009. // you may not use this file except in compliance with the License.
  65010. // You may obtain a copy of the License at
  65011. //
  65012. // http://www.apache.org/licenses/LICENSE-2.0
  65013. //
  65014. // Unless required by applicable law or agreed to in writing, software
  65015. // distributed under the License is distributed on an "AS IS" BASIS,
  65016. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  65017. // See the License for the specific language governing permissions and
  65018. // limitations under the License.
  65019. var Selector = function () {
  65020. function Selector(element) {
  65021. _classCallCheck(this, Selector);
  65022. this.element = element;
  65023. var wrapper = element.parentNode;
  65024. this.element.addEventListener('change', this.change.bind(this));
  65025. this.titleWrapper = document.createElement('div');
  65026. this.titleWrapper.classList.add('output__selector-title-wrapper');
  65027. this.title = document.createElement('span');
  65028. this.title.classList.add('output__selector-title');
  65029. this.titleWrapper.appendChild(this.title);
  65030. wrapper.appendChild(this.titleWrapper);
  65031. this.change();
  65032. }
  65033. _createClass(Selector, [{
  65034. key: 'change',
  65035. value: function change() {
  65036. var value = this.element.value;
  65037. var text = this.element.options[this.element.selectedIndex].textContent;
  65038. this.title.textContent = text;
  65039. }
  65040. }]);
  65041. return Selector;
  65042. }();
  65043. exports.default = Selector;
  65044. },{"./../../config.js":242}],257:[function(require,module,exports){
  65045. 'use strict';
  65046. Object.defineProperty(exports, "__esModule", {
  65047. value: true
  65048. });
  65049. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  65050. var _index = require('../../index');
  65051. var _index2 = _interopRequireDefault(_index);
  65052. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  65053. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  65054. // Copyright 2017 Google Inc.
  65055. //
  65056. // Licensed under the Apache License, Version 2.0 (the "License");
  65057. // you may not use this file except in compliance with the License.
  65058. // You may obtain a copy of the License at
  65059. //
  65060. // http://www.apache.org/licenses/LICENSE-2.0
  65061. //
  65062. // Unless required by applicable law or agreed to in writing, software
  65063. // distributed under the License is distributed on an "AS IS" BASIS,
  65064. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  65065. // See the License for the specific language governing permissions and
  65066. // limitations under the License.
  65067. var GifCanvas = function () {
  65068. function GifCanvas() {
  65069. _classCallCheck(this, GifCanvas);
  65070. this.element = document.createElement('div');
  65071. this.canvas = document.createElement('canvas');
  65072. this.context = this.canvas.getContext('2d');
  65073. this.element.style.display = 'none';
  65074. this.canvas.width = 340;
  65075. this.canvas.height = 260;
  65076. this.canvas.classList.add('gifler-canvas');
  65077. this.canvas.name = 'gif';
  65078. this.element.appendChild(this.canvas);
  65079. this.gifs = {};
  65080. }
  65081. _createClass(GifCanvas, [{
  65082. key: 'setSource',
  65083. value: function setSource(source) {
  65084. if (_index2.default.isRecording) {
  65085. // Downsize the recorder gif
  65086. var smallerSource = source.replace('200w.gif', '200_d.gif');
  65087. if (smallerSource !== this.source) {
  65088. this.clear();
  65089. this.source = smallerSource;
  65090. this.getGifler(smallerSource);
  65091. }
  65092. }
  65093. }
  65094. }, {
  65095. key: 'getGifler',
  65096. value: function getGifler(source) {
  65097. var _this = this;
  65098. return new Promise(function (resolve) {
  65099. if (!_this.gifs[source]) {
  65100. /* eslint-disable */
  65101. window.gifler(source).frames('canvas.gifler-canvas', _this.draw.bind(_this)).then(function (response) {
  65102. _this.gifs[source] = response;
  65103. _this.gifs[source].start();
  65104. resolve(_this.gifs[source]);
  65105. });
  65106. /* eslint-enable */
  65107. }
  65108. if (_this.gifs[source]) {
  65109. _this.gifs[source].start();
  65110. resolve(_this.gifs[source]);
  65111. }
  65112. });
  65113. }
  65114. }, {
  65115. key: 'draw',
  65116. value: function draw(ctx, frame) {
  65117. if (_index2.default.isRecording) {
  65118. var hRatio = this.canvas.width / frame.width;
  65119. var vRatio = this.canvas.height / frame.height;
  65120. var ratio = Math.min(hRatio, vRatio);
  65121. var centerShiftX = (this.canvas.width - frame.width * ratio) / 2;
  65122. var centerShiftY = (this.canvas.height - frame.height * ratio) / 2;
  65123. ctx.drawImage(frame.buffer, 0, 0, frame.width, frame.height, centerShiftX, centerShiftY, frame.width * ratio, frame.height * ratio);
  65124. } else {
  65125. this.clear();
  65126. }
  65127. }
  65128. }, {
  65129. key: 'clear',
  65130. value: function clear() {
  65131. var _this2 = this;
  65132. this.source = null;
  65133. Object.keys(this.gifs).forEach(function (key) {
  65134. var gif = _this2.gifs[key];
  65135. gif.reset();
  65136. gif.stop();
  65137. });
  65138. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  65139. }
  65140. }, {
  65141. key: 'getElement',
  65142. value: function getElement() {
  65143. return this.element;
  65144. }
  65145. }]);
  65146. return GifCanvas;
  65147. }();
  65148. exports.default = GifCanvas;
  65149. },{"../../index":243}],258:[function(require,module,exports){
  65150. 'use strict';
  65151. Object.defineProperty(exports, "__esModule", {
  65152. value: true
  65153. });
  65154. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  65155. var _config = require('./../../config.js');
  65156. var _config2 = _interopRequireDefault(_config);
  65157. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  65158. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  65159. //class construct for login iframe
  65160. var Iframe = function () {
  65161. function Iframe(element) {
  65162. _classCallCheck(this, Iframe);
  65163. this.parentElement = element;
  65164. this.parentElement.classList.add('iframe_class');
  65165. this.iframe = document.createElement('iframe');
  65166. this.iframe.src = "//cocorobo.cn/login/";
  65167. this.iframe.scrolling = "no";
  65168. this.iframe.classList.add('iframe_class');
  65169. this.parentElement.append(this.iframe);
  65170. }
  65171. _createClass(Iframe, [{
  65172. key: 'destory',
  65173. value: function destory() {
  65174. this.parentElement.innerHTML = "";
  65175. _config2.default.iframe = false;
  65176. }
  65177. }]);
  65178. return Iframe;
  65179. }();
  65180. exports.default = Iframe;
  65181. },{"./../../config.js":242}],259:[function(require,module,exports){
  65182. 'use strict';
  65183. Object.defineProperty(exports, "__esModule", {
  65184. value: true
  65185. });
  65186. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  65187. var _gsap = require('gsap');
  65188. var _gsap2 = _interopRequireDefault(_gsap);
  65189. var _config = require('./../../config.js');
  65190. var _config2 = _interopRequireDefault(_config);
  65191. var _Button = require('./../components/Button.js');
  65192. var _Button2 = _interopRequireDefault(_Button);
  65193. var _CamInput = require('./../components/CamInput.js');
  65194. var _CamInput2 = _interopRequireDefault(_CamInput);
  65195. var _HighlightArrow = require('./../components/HighlightArrow.js');
  65196. var _HighlightArrow2 = _interopRequireDefault(_HighlightArrow);
  65197. var _WizardGIFExample = require('./WizardGIFExample.js');
  65198. var _WizardGIFExample2 = _interopRequireDefault(_WizardGIFExample);
  65199. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  65200. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  65201. // Copyright 2017 Google Inc.
  65202. //
  65203. // Licensed under the Apache License, Version 2.0 (the "License");
  65204. // you may not use this file except in compliance with the License.
  65205. // You may obtain a copy of the License at
  65206. //
  65207. // http://www.apache.org/licenses/LICENSE-2.0
  65208. //
  65209. // Unless required by applicable law or agreed to in writing, software
  65210. // distributed under the License is distributed on an "AS IS" BASIS,
  65211. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  65212. // See the License for the specific language governing permissions and
  65213. // limitations under the License.
  65214. var InputSection = function () {
  65215. function InputSection(element) {
  65216. _classCallCheck(this, InputSection);
  65217. this.element = element;
  65218. // this.camInputToggle = new Button(element.querySelector('#cam-input-toggle'));
  65219. // this.micInputToggle = new Button(element.querySelector('#mic-input-toggle'));
  65220. // this.camInputToggle.deselect();
  65221. // this.micInputToggle.deselect();
  65222. // this.camInputToggle.element.addEventListener('click', this.selectCamInput.bind(this));
  65223. // this.micInputToggle.element.addEventListener('click', this.selectMicInput.bind(this));
  65224. // this.camInputToggle.element.addEventListener('touchend', this.selectCamInput.bind(this));
  65225. // this.micInputToggle.element.addEventListener('touchend', this.selectMicInput.bind(this));
  65226. this.mediaFlipButton = element.querySelector('.input__media__flip');
  65227. this.mediaFlipButton.addEventListener('click', this.flipCamera.bind(this));
  65228. this.inputContainer = element.querySelector('.input__media');
  65229. this.currentInput = null;
  65230. // if (!GLOBALS.browserUtils.isMobile) {
  65231. // this.createMicInput();
  65232. // this.createCamInput();
  65233. // this.selectCamInput();
  65234. // this.camInputToggle.select();
  65235. // }
  65236. this.arrow = new _HighlightArrow2.default(1);
  65237. if (_config2.default.browserUtils.isMobile) {
  65238. _gsap2.default.set(this.arrow.element, {
  65239. rotation: -120,
  65240. scaleX: -0.5,
  65241. x: -20,
  65242. y: -60
  65243. });
  65244. } else {
  65245. _gsap2.default.set(this.arrow.element, {
  65246. rotation: -120,
  65247. scaleX: -0.8,
  65248. x: -20,
  65249. y: -120
  65250. });
  65251. }
  65252. this.element.appendChild(this.arrow.element);
  65253. this.gifs = [];
  65254. var gif1 = new _WizardGIFExample2.default('assets/wizard/1.gif');
  65255. if (_config2.default.browserUtils.isMobile) {
  65256. _gsap2.default.set(gif1.element, {
  65257. rotation: -5,
  65258. scale: 0.65,
  65259. x: 40,
  65260. y: 275
  65261. });
  65262. } else {
  65263. _gsap2.default.set(gif1.element, {
  65264. rotation: -5,
  65265. scale: 0.65,
  65266. x: 70,
  65267. y: -25
  65268. });
  65269. }
  65270. this.element.appendChild(gif1.element);
  65271. this.gifs.push(gif1);
  65272. var gif2 = new _WizardGIFExample2.default('assets/wizard/2.gif');
  65273. if (_config2.default.browserUtils.isMobile) {
  65274. _gsap2.default.set(gif2.element, {
  65275. rotation: -5,
  65276. scale: 0.65,
  65277. x: 40,
  65278. y: 275
  65279. });
  65280. } else {
  65281. _gsap2.default.set(gif2.element, {
  65282. rotation: -5,
  65283. scale: 0.65,
  65284. x: 70,
  65285. y: -25
  65286. });
  65287. }
  65288. this.element.appendChild(gif2.element);
  65289. this.gifs.push(gif2);
  65290. var gif3 = new _WizardGIFExample2.default('assets/wizard/3.gif');
  65291. if (_config2.default.browserUtils.isMobile) {
  65292. _gsap2.default.set(gif3.element, {
  65293. rotation: -5,
  65294. scale: 0.65,
  65295. x: 40,
  65296. y: 275
  65297. });
  65298. } else {
  65299. _gsap2.default.set(gif3.element, {
  65300. rotation: -5,
  65301. scale: 0.65,
  65302. x: 70,
  65303. y: -25
  65304. });
  65305. }
  65306. this.element.appendChild(gif3.element);
  65307. this.gifs.push(gif3);
  65308. var gif4 = new _WizardGIFExample2.default('assets/wizard/4.gif');
  65309. if (_config2.default.browserUtils.isMobile) {
  65310. _gsap2.default.set(gif4.element, {
  65311. rotation: -5,
  65312. scale: 0.65,
  65313. x: 40,
  65314. y: 275
  65315. });
  65316. } else {
  65317. _gsap2.default.set(gif4.element, {
  65318. rotation: -5,
  65319. scale: 0.65,
  65320. x: 70,
  65321. y: -25
  65322. });
  65323. }
  65324. this.element.appendChild(gif4.element);
  65325. this.gifs.push(gif4);
  65326. }
  65327. _createClass(InputSection, [{
  65328. key: 'showGif',
  65329. value: function showGif(index) {
  65330. this.gifs[index].show();
  65331. }
  65332. }, {
  65333. key: 'hideGif',
  65334. value: function hideGif(index) {
  65335. this.gifs[index].hide();
  65336. }
  65337. }, {
  65338. key: 'ready',
  65339. value: function ready() {
  65340. if (!_config2.default.browserUtils.isMobile) {
  65341. this.createCamInput();
  65342. this.selectCamInput();
  65343. }
  65344. }
  65345. }, {
  65346. key: 'highlight',
  65347. value: function highlight() {
  65348. this.arrow.show();
  65349. _gsap2.default.from(this.arrow.element, 0.3, { opacity: 0 });
  65350. }
  65351. }, {
  65352. key: 'dehighlight',
  65353. value: function dehighlight() {
  65354. _gsap2.default.killTweensOf(this.arrow.element);
  65355. this.arrow.hide();
  65356. }
  65357. }, {
  65358. key: 'enable',
  65359. value: function enable(highlight) {
  65360. this.element.classList.remove('section--disabled');
  65361. if (highlight) {
  65362. this.highlight();
  65363. } else {
  65364. this.dehighlight();
  65365. }
  65366. }
  65367. }, {
  65368. key: 'disable',
  65369. value: function disable() {
  65370. this.element.classList.add('section--disabled');
  65371. this.dehighlight();
  65372. }
  65373. }, {
  65374. key: 'dim',
  65375. value: function dim() {
  65376. this.element.classList.add('dimmed');
  65377. }
  65378. }, {
  65379. key: 'undim',
  65380. value: function undim() {
  65381. this.element.classList.remove('dimmed');
  65382. }
  65383. }, {
  65384. key: 'createCamInput',
  65385. value: function createCamInput() {
  65386. if (!this.camInput) {
  65387. this.camInput = new _CamInput2.default();
  65388. this.inputContainer.appendChild(this.camInput.element);
  65389. _config2.default.camInput = this.camInput;
  65390. // GLOBALS.camInput.start();
  65391. }
  65392. }
  65393. }, {
  65394. key: 'selectCamInput',
  65395. value: function selectCamInput() {
  65396. this.createCamInput();
  65397. this.currentInput = this.camInput;
  65398. }
  65399. }, {
  65400. key: 'resetClass',
  65401. value: function resetClass(id) {
  65402. this.camInput.resetClass(id);
  65403. }
  65404. }, {
  65405. key: 'flipCamera',
  65406. value: function flipCamera(event) {
  65407. event.preventDefault();
  65408. if (!_config2.default.browserUtils.isAndroid) {
  65409. _config2.default.isBackFacingCam = !_config2.default.isBackFacingCam;
  65410. _config2.default.webcamClassifier.loaded = false;
  65411. _config2.default.webcamClassifier.ready();
  65412. }
  65413. if (_config2.default.browserUtils.isAndroid) {
  65414. /*eslint-disable */
  65415. if (confirm('Switching camera will clear your trained classes and reload the page.')) {
  65416. /* eslint-enable */
  65417. _config2.default.isBackFacingCam = !_config2.default.isBackFacingCam;
  65418. localStorage.setItem('isBackFacingCam', _config2.default.isBackFacingCam.toString());
  65419. location.reload();
  65420. }
  65421. }
  65422. }
  65423. }]);
  65424. return InputSection;
  65425. }();
  65426. exports.default = InputSection;
  65427. },{"./../../config.js":242,"./../components/Button.js":252,"./../components/CamInput.js":253,"./../components/HighlightArrow.js":255,"./WizardGIFExample.js":268,"gsap":212}],260:[function(require,module,exports){
  65428. 'use strict';
  65429. Object.defineProperty(exports, "__esModule", {
  65430. value: true
  65431. });
  65432. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  65433. var _gsap = require('gsap');
  65434. var _gsap2 = _interopRequireDefault(_gsap);
  65435. var _config = require('./../../config.js');
  65436. var _config2 = _interopRequireDefault(_config);
  65437. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  65438. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  65439. // Copyright 2017 Google Inc.
  65440. //
  65441. // Licensed under the Apache License, Version 2.0 (the "License");
  65442. // you may not use this file except in compliance with the License.
  65443. // You may obtain a copy of the License at
  65444. //
  65445. // http://www.apache.org/licenses/LICENSE-2.0
  65446. //
  65447. // Unless required by applicable law or agreed to in writing, software
  65448. // distributed under the License is distributed on an "AS IS" BASIS,
  65449. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  65450. // See the License for the specific language governing permissions and
  65451. // limitations under the License.
  65452. var IntroSection = function () {
  65453. function IntroSection(element) {
  65454. _classCallCheck(this, IntroSection);
  65455. this.videoPlayButton = element.querySelector('#video-play-link');
  65456. this.videoPlayButton.addEventListener('click', this.openVideoPlayer.bind(this));
  65457. this.closeVideoLink = element.querySelector('#video-close-link');
  65458. this.closeVideoLink.addEventListener('click', this.closeVideoPlayer.bind(this));
  65459. this.videoContainer = element.querySelector('.intro__video');
  65460. _gsap2.default.set(this.videoContainer, {
  65461. transformOrigin: 'top center',
  65462. opacity: 0
  65463. });
  65464. this.player = null;
  65465. this.open = false;
  65466. }
  65467. _createClass(IntroSection, [{
  65468. key: 'startVideo',
  65469. value: function startVideo() {
  65470. this.player.playVideo();
  65471. }
  65472. }, {
  65473. key: 'openVideoPlayer',
  65474. value: function openVideoPlayer() {
  65475. if (this.open) {
  65476. return;
  65477. }
  65478. if (_config2.default.YOUTUBE_API_READY) {
  65479. if (this.player) {
  65480. this.player.seekTo(0);
  65481. } else {
  65482. this.player = new window.YT.Player('intro-video-player', {
  65483. height: '100%',
  65484. width: '100%',
  65485. videoId: 'a1Y73sPHKxw',
  65486. playerVars: {
  65487. autoplay: 0,
  65488. fs: 1,
  65489. loop: 0,
  65490. controls: 1,
  65491. modestbranding: 1,
  65492. rel: 0,
  65493. showinfo: 0
  65494. }
  65495. });
  65496. }
  65497. }
  65498. var videoRatio = 1.7777777778;
  65499. this.open = true;
  65500. this.videoContainer.style.height = 'auto';
  65501. var width = this.videoContainer.offsetWidth;
  65502. var height = width / videoRatio;
  65503. this.videoContainer.style.height = 0 + 'px';
  65504. var that = this;
  65505. _gsap2.default.to(this.videoPlayButton, 0.5, {
  65506. opacity: 0,
  65507. ease: _gsap2.default.Expo.easeOut
  65508. });
  65509. _gsap2.default.to(this.videoContainer, 1, {
  65510. opacity: 1,
  65511. height: height,
  65512. transformOrigin: 'top center',
  65513. ease: _gsap2.default.Expo.easeOut,
  65514. onComplete: that.startVideo.bind(that)
  65515. });
  65516. }
  65517. }, {
  65518. key: 'closeVideoPlayer',
  65519. value: function closeVideoPlayer() {
  65520. this.open = false;
  65521. if (this.player) {
  65522. this.player.pauseVideo();
  65523. }
  65524. _gsap2.default.to(this.videoContainer, 0.75, {
  65525. height: 0,
  65526. opacity: 0,
  65527. ease: _gsap2.default.Expo.easeOut
  65528. });
  65529. _gsap2.default.to(this.videoPlayButton, 0.5, {
  65530. opacity: 1,
  65531. delay: 0.5,
  65532. ease: _gsap2.default.Expo.easeOut
  65533. });
  65534. }
  65535. }]);
  65536. return IntroSection;
  65537. }();
  65538. exports.default = IntroSection;
  65539. },{"./../../config.js":242,"gsap":212}],261:[function(require,module,exports){
  65540. 'use strict';
  65541. Object.defineProperty(exports, "__esModule", {
  65542. value: true
  65543. });
  65544. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  65545. var _config = require('./../../config.js');
  65546. var _config2 = _interopRequireDefault(_config);
  65547. var _gsap = require('gsap');
  65548. var _gsap2 = _interopRequireDefault(_gsap);
  65549. var _Button = require('./../components/Button.js');
  65550. var _Button2 = _interopRequireDefault(_Button);
  65551. var _HighlightArrow = require('./../components/HighlightArrow.js');
  65552. var _HighlightArrow2 = _interopRequireDefault(_HighlightArrow);
  65553. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  65554. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  65555. // Copyright 2017 Google Inc.
  65556. //
  65557. // Licensed under the Apache License, Version 2.0 (the "License");
  65558. // you may not use this file except in compliance with the License.
  65559. // You may obtain a copy of the License at
  65560. //
  65561. // http://www.apache.org/licenses/LICENSE-2.0
  65562. //
  65563. // Unless required by applicable law or agreed to in writing, software
  65564. // distributed under the License is distributed on an "AS IS" BASIS,
  65565. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  65566. // See the License for the specific language governing permissions and
  65567. // limitations under the License.
  65568. var LearningClass = function () {
  65569. function LearningClass(options) {
  65570. _classCallCheck(this, LearningClass);
  65571. this.element = options.element;
  65572. this.section = options.section;
  65573. this.canvas = this.element.querySelector('canvas.examples__viewer');
  65574. this.canvas.width = 98;
  65575. this.canvas.height = 98;
  65576. this.context = this.canvas.getContext('2d');
  65577. this.id = this.element.getAttribute('id');
  65578. this.index = options.index;
  65579. this.button = new _Button2.default(this.element.querySelector('a.button--record'));
  65580. this.button.element.addEventListener('mousedown', this.buttonDown.bind(this));
  65581. this.button.element.addEventListener('touchstart', this.buttonDown.bind(this));
  65582. this.button.element.addEventListener('touchend', this.buttonUp.bind(this));
  65583. this.bigLink = this.element.querySelector('.link--reset');
  65584. this.resetLink = this.element.querySelector('.examples__close_reset');
  65585. this.resetLink.id = this.id + "_link--reset";
  65586. this.bigLink.id = this.id + "_link--big";
  65587. // this.button.element.addEventListener('mouseup', this.buttonUp.bind(this));
  65588. this.exampleCounterElement = this.element.querySelector('.examples__counter');
  65589. this.exampleCounter = 0;
  65590. this.percentage = 0;
  65591. this.percentageElement = this.element.querySelector('.machine__value');
  65592. this.percentageGrey = this.element.querySelector('.machine__percentage--grey');
  65593. this.percentageWhite = this.element.querySelector('.machine__percentage--white');
  65594. this.color = options.color;
  65595. this.rgbaColor = options.rgbaColor;
  65596. this.arrow = new _HighlightArrow2.default(3);
  65597. this.arrow.element.style.left = 100 + '%';
  65598. this.arrow.element.style.top = 100 + '%';
  65599. this.arrow.element.width = 60;
  65600. _gsap2.default.set(this.arrow.element, {
  65601. rotation: 90,
  65602. scale: 1,
  65603. x: 10,
  65604. y: -75
  65605. });
  65606. this.element.appendChild(this.arrow.element);
  65607. this.arrowX = new _HighlightArrow2.default(2);
  65608. this.arrowX.element.style.left = 0 + '%';
  65609. this.arrowX.element.style.top = 0 + '%';
  65610. this.arrowX.element.width = 60;
  65611. _gsap2.default.set(this.arrowX.element, {
  65612. rotation: -90,
  65613. scaleX: -0.8,
  65614. scaleY: 0.8,
  65615. x: 37,
  65616. y: -30
  65617. });
  65618. this.element.appendChild(this.arrowX.element);
  65619. this.resetLink.addEventListener('click', this.resetClass.bind(this));
  65620. this.bigLink.addEventListener('click', this.bigClass.bind(this));
  65621. this.size();
  65622. window.addEventListener('resize', this.size.bind(this));
  65623. }
  65624. _createClass(LearningClass, [{
  65625. key: 'hide',
  65626. value: function hide() {
  65627. this.element.style.display = 'none';
  65628. }
  65629. }, {
  65630. key: 'show',
  65631. value: function show() {
  65632. this.element.style.display = 'flex';
  65633. }
  65634. }, {
  65635. key: 'highlight',
  65636. value: function highlight() {
  65637. this.arrow.show();
  65638. _gsap2.default.from(this.arrow.element, 0.3, {
  65639. opacity: 0,
  65640. x: 40
  65641. });
  65642. }
  65643. }, {
  65644. key: 'dehighlight',
  65645. value: function dehighlight() {
  65646. _gsap2.default.killTweensOf(this.arrow.element);
  65647. this.arrow.hide();
  65648. }
  65649. }, {
  65650. key: 'highlightX',
  65651. value: function highlightX() {
  65652. this.arrowX.show();
  65653. _gsap2.default.from(this.arrowX.element, 0.3, { opacity: 0 });
  65654. }
  65655. }, {
  65656. key: 'dehighlightX',
  65657. value: function dehighlightX() {
  65658. _gsap2.default.killTweensOf(this.arrowX.element);
  65659. this.arrowX.hide();
  65660. }
  65661. }, {
  65662. key: 'clear',
  65663. value: function clear() {
  65664. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  65665. this.setSamples(0);
  65666. }
  65667. }, {
  65668. key: 'resetClass',
  65669. value: function resetClass(event) {
  65670. event.preventDefault();
  65671. if (this.exampleCounter > 0) {
  65672. _config2.default.webcamClassifier.imgSrc[this.index] = [];
  65673. _config2.default.inputSection.resetClass(this.index);
  65674. this.clear();
  65675. }
  65676. }
  65677. }, {
  65678. key: 'bigClass',
  65679. value: function bigClass(event) {
  65680. event.preventDefault();
  65681. if (this.exampleCounter > 0) {
  65682. // GLOBALS.inputSection.bigClass(this.index);
  65683. // this.clear();
  65684. var modal = document.createElement('div');
  65685. modal.id = "modal";
  65686. modal.classList.add('modal');
  65687. document.getElementById('wrapper').appendChild(modal);
  65688. var divImg = document.createElement('div');
  65689. divImg.classList.add('modal_div');
  65690. var img = "<span style='left:calc(50% - 500px)' class='leftSpan'><</span>";
  65691. for (var i = 0; i < _config2.default.webcamClassifier.imgSrc[this.index].length; i++) {
  65692. var src = _config2.default.webcamClassifier.imgSrc[this.index][i];
  65693. img = img + ('<img src=' + src + ' />');
  65694. }
  65695. img = img + "<span style='right:calc(50% - 490px)' class='rightSpan'>></span>";
  65696. divImg.innerHTML = img;
  65697. modal.appendChild(divImg);
  65698. modal.addEventListener('click', this.modalHide.bind(this));
  65699. var number = 0;
  65700. var modalScroll = document.getElementsByClassName('modal_div')[0];
  65701. document.getElementsByClassName('leftSpan')[0].onclick = function () {
  65702. number = number - 1000;
  65703. if (number < 0) {
  65704. modalScroll.scrollLeft = 0;
  65705. number = 0;
  65706. } else {
  65707. modalScroll.scrollLeft = number;
  65708. }
  65709. };
  65710. document.getElementsByClassName('rightSpan')[0].onclick = function () {
  65711. number = number + 1000;
  65712. if (number > modalScroll.scrollWidth) {
  65713. modalScroll.scrollLeft = modalScroll.scrollWidth;
  65714. number = modalScroll.scrollWidth;
  65715. } else {
  65716. modalScroll.scrollLeft = number;
  65717. }
  65718. };
  65719. }
  65720. }
  65721. }, {
  65722. key: 'modalHide',
  65723. value: function modalHide(event) {
  65724. console.log();
  65725. if (event.target.tagName !== "IMG" && event.target.tagName !== "SPAN") {
  65726. document.getElementById('wrapper').removeChild(document.getElementById('modal'));
  65727. }
  65728. }
  65729. }, {
  65730. key: 'setSamples',
  65731. value: function setSamples(length) {
  65732. this.exampleCounter = length;
  65733. var text = this.exampleCounter;
  65734. var recommendedNumSamples = _config2.default.inputType === 'cam' ? 30 : 10;
  65735. this.exampleCounterElement.textContent = text;
  65736. if (this.exampleCounter >= recommendedNumSamples && _config2.default.classesTrained[this.id] === false) {
  65737. _config2.default.classesTrained[this.id] = true;
  65738. }
  65739. if (this.exampleCounter > 0) {
  65740. this.resetLink.classList.remove("hide");
  65741. // this.bigClass.classList.remove("hide")
  65742. } else {
  65743. this.resetLink.classList.add("hide");
  65744. // this.bigClass.classList.add("hide")
  65745. }
  65746. }
  65747. }, {
  65748. key: 'setConfidence',
  65749. value: function setConfidence(percentage) {
  65750. if (!_config2.default.clearing) {
  65751. // this.percentage = percentage;
  65752. // this.updatePercentage();
  65753. var that = this;
  65754. _config2.default.recordSection.setMeters(this.id, percentage);
  65755. _gsap2.default.to(this, 0.5, {
  65756. percentage: percentage,
  65757. onUpdate: function onUpdate() {
  65758. that.updatePercentage();
  65759. }
  65760. });
  65761. }
  65762. }
  65763. }, {
  65764. key: 'highlightConfidence',
  65765. value: function highlightConfidence() {
  65766. this.percentageElement.style.background = this.color;
  65767. }
  65768. }, {
  65769. key: 'dehighlightConfidence',
  65770. value: function dehighlightConfidence() {
  65771. this.percentageElement.style.background = '#cfd1d2';
  65772. }
  65773. }, {
  65774. key: 'buttonDown',
  65775. value: function buttonDown() {
  65776. var _this = this;
  65777. var that = this;
  65778. var languare = _config2.default.lang === "en" ? _config2.default.languare.en : _config2.default.lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  65779. var text = languare.training;
  65780. this.button.setText(text);
  65781. this.section.startRecording(this.index);
  65782. this.buttonUpEvent = this.buttonUp.bind(this);
  65783. window.addEventListener('mouseup', this.buttonUpEvent);
  65784. _config2.default.recording = true;
  65785. _config2.default.classId = this.id;
  65786. _config2.default.outputSection.toggleSoundOutput(false);
  65787. clearTimeout(this.buttonClickTimeout);
  65788. this.buttonClickTimeout = setTimeout(function () {
  65789. _config2.default.webcamClassifier.buttonDown(_this.id, _this.canvas, _this);
  65790. }, 100);
  65791. gtag('event', 'training', { 'id': this.index });
  65792. }
  65793. }, {
  65794. key: 'buttonUp',
  65795. value: function buttonUp() {
  65796. var languare = _config2.default.lang === "en" ? _config2.default.languare.en : _config2.default.lang === "hans" ? _config2.default.languare.hans : _config2.default.languare.hant;
  65797. var text = "";
  65798. if (this.id == 'green') {
  65799. text = languare.green;
  65800. } else if (this.id == 'purple') {
  65801. text = languare.purple;
  65802. } else if (this.id == 'orange') {
  65803. text = languare.orange;
  65804. }
  65805. this.button.setText(text);
  65806. this.section.stopRecording();
  65807. clearTimeout(this.buttonClickTimeout);
  65808. this.button.up();
  65809. _config2.default.classId = null;
  65810. _config2.default.recording = false;
  65811. _config2.default.outputSection.toggleSoundOutput(true);
  65812. _config2.default.webcamClassifier.buttonUp(this.id, this.canvas);
  65813. if (this.exampleCounter > 0) {
  65814. var event = new CustomEvent('class-trained', {
  65815. detail: {
  65816. id: this.id,
  65817. numSamples: this.exampleCounter
  65818. }
  65819. });
  65820. window.dispatchEvent(event);
  65821. }
  65822. window.removeEventListener('mouseup', this.buttonUpEvent);
  65823. }
  65824. }, {
  65825. key: 'updatePercentage',
  65826. value: function updatePercentage() {
  65827. var _this2 = this;
  65828. var rounded = Math.floor(this.percentage);
  65829. this.percentageElement.style.width = this.percentage + '%';
  65830. this.percentageWhite.textContent = rounded + '%';
  65831. if (this.timer) {
  65832. clearInterval(this.timer);
  65833. }
  65834. this.timer = setInterval(function () {
  65835. _this2.setConfidence(0);
  65836. }, 500);
  65837. }
  65838. }, {
  65839. key: 'size',
  65840. value: function size() {
  65841. this.percentageElement.style.width = 100 + '%';
  65842. var width = this.percentageElement.offsetWidth;
  65843. this.percentageWhite.style.width = width + 'px';
  65844. this.percentageElement.style.width = 0 + '%';
  65845. }
  65846. }, {
  65847. key: 'start',
  65848. value: function start() {
  65849. this.size();
  65850. }
  65851. }]);
  65852. return LearningClass;
  65853. }();
  65854. exports.default = LearningClass;
  65855. },{"./../../config.js":242,"./../components/Button.js":252,"./../components/HighlightArrow.js":255,"gsap":212}],262:[function(require,module,exports){
  65856. 'use strict';
  65857. Object.defineProperty(exports, "__esModule", {
  65858. value: true
  65859. });
  65860. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  65861. var _config = require('./../../config.js');
  65862. var _config2 = _interopRequireDefault(_config);
  65863. var _gsap = require('gsap');
  65864. var _gsap2 = _interopRequireDefault(_gsap);
  65865. var _WiresLeft = require('./WiresLeft.js');
  65866. var _WiresLeft2 = _interopRequireDefault(_WiresLeft);
  65867. var _WiresRight = require('./WiresRight.js');
  65868. var _WiresRight2 = _interopRequireDefault(_WiresRight);
  65869. var _LearningClass = require('./LearningClass.js');
  65870. var _LearningClass2 = _interopRequireDefault(_LearningClass);
  65871. var _TrainingQuality = require('./TrainingQuality.js');
  65872. var _TrainingQuality2 = _interopRequireDefault(_TrainingQuality);
  65873. var _HighlightArrow = require('./../components/HighlightArrow.js');
  65874. var _HighlightArrow2 = _interopRequireDefault(_HighlightArrow);
  65875. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  65876. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  65877. // Copyright 2017 Google Inc.
  65878. //
  65879. // Licensed under the Apache License, Version 2.0 (the "License");
  65880. // you may not use this file except in compliance with the License.
  65881. // You may obtain a copy of the License at
  65882. //
  65883. // http://www.apache.org/licenses/LICENSE-2.0
  65884. //
  65885. // Unless required by applicable law or agreed to in writing, software
  65886. // distributed under the License is distributed on an "AS IS" BASIS,
  65887. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  65888. // See the License for the specific language governing permissions and
  65889. // limitations under the License.
  65890. var LearningSection = function () {
  65891. function LearningSection(element) {
  65892. _classCallCheck(this, LearningSection);
  65893. this.element = element;
  65894. var learningClassesElements = element.querySelectorAll('.learning__class');
  65895. this.condenseElement = element.querySelector('#learning-condensed-button');
  65896. this.condenseElement.addEventListener('click', this.condenseSection.bind(this));
  65897. var learningClasses = [];
  65898. var that = this;
  65899. this.condensed = false;
  65900. that.learningClasses = [];
  65901. var classNames = _config2.default.classNames;
  65902. var colors = _config2.default.colors;
  65903. learningClassesElements.forEach(function (element, index) {
  65904. var id = classNames[index];
  65905. var color = colors[id];
  65906. var rgbaColor = _config2.default.rgbaColors[id];
  65907. var options = {
  65908. index: index,
  65909. element: element,
  65910. section: that,
  65911. color: color,
  65912. rgbaColor: rgbaColor
  65913. };
  65914. var learningClass = new _LearningClass2.default(options);
  65915. learningClass.index = index;
  65916. learningClasses.push(learningClass);
  65917. that.learningClasses[index] = learningClass;
  65918. // learningClass.start();
  65919. });
  65920. // this.trainingQuality = new TrainingQuality(element.querySelector('.quality'));
  65921. this.wiresLeft = new _WiresLeft2.default(document.querySelector('.wires--left'), learningClassesElements);
  65922. this.wiresRight = new _WiresRight2.default(document.querySelector('.wires--right'), learningClassesElements);
  65923. this.highestIndex = null;
  65924. this.currentIndex = null;
  65925. this.arrow = new _HighlightArrow2.default(2);
  65926. _gsap2.default.set(this.arrow.element, {
  65927. rotation: 90,
  65928. scale: 0.6,
  65929. x: 120,
  65930. y: -175
  65931. });
  65932. this.element.appendChild(this.arrow.element);
  65933. }
  65934. _createClass(LearningSection, [{
  65935. key: 'condenseSection',
  65936. value: function condenseSection() {
  65937. this.condensed ? this.element.classList.remove('condensed') : this.element.classList.add('condensed');
  65938. this.condensed ? this.condensed = false : this.condensed = true;
  65939. }
  65940. }, {
  65941. key: 'ready',
  65942. value: function ready() {
  65943. this.learningClasses.forEach(function (learningClass) {
  65944. learningClass.start();
  65945. });
  65946. }
  65947. }, {
  65948. key: 'highlight',
  65949. value: function highlight() {
  65950. this.arrow.show();
  65951. _gsap2.default.from(this.arrow.element, 0.3, { opacity: 0 });
  65952. }
  65953. }, {
  65954. key: 'dehighlight',
  65955. value: function dehighlight() {
  65956. _gsap2.default.killTweensOf(this.arrow.element, 0.3, { opacity: 0 });
  65957. this.arrow.hide();
  65958. }
  65959. }, {
  65960. key: 'enable',
  65961. value: function enable(highlight) {
  65962. this.element.classList.remove('section--disabled');
  65963. this.wiresLeft.element.classList.remove('wires--disabled');
  65964. this.wiresRight.element.classList.remove('wires--disabled');
  65965. if (highlight) {
  65966. this.highlight();
  65967. }
  65968. }
  65969. }, {
  65970. key: 'disable',
  65971. value: function disable() {
  65972. this.element.classList.add('section--disabled');
  65973. this.wiresLeft.element.classList.add('wires--disabled');
  65974. this.wiresRight.element.classList.add('wires--disabled');
  65975. }
  65976. }, {
  65977. key: 'dim',
  65978. value: function dim() {
  65979. this.element.classList.add('dimmed');
  65980. this.wiresLeft.element.classList.add('dimmed');
  65981. this.wiresRight.element.classList.add('dimmed');
  65982. }
  65983. }, {
  65984. key: 'undim',
  65985. value: function undim() {
  65986. this.element.classList.remove('dimmed');
  65987. this.wiresLeft.element.classList.remove('dimmed');
  65988. this.wiresRight.element.classList.remove('dimmed');
  65989. }
  65990. }, {
  65991. key: 'highlightClass',
  65992. value: function highlightClass(index) {
  65993. this.learningClasses[index].highlight();
  65994. }
  65995. }, {
  65996. key: 'dehighlightClass',
  65997. value: function dehighlightClass(index) {
  65998. this.learningClasses[index].dehighlight();
  65999. }
  66000. }, {
  66001. key: 'highlightClassX',
  66002. value: function highlightClassX(index) {
  66003. this.learningClasses[index].highlightX();
  66004. }
  66005. }, {
  66006. key: 'dehighlightClassX',
  66007. value: function dehighlightClassX(index) {
  66008. this.learningClasses[index].dehighlightX();
  66009. }
  66010. }, {
  66011. key: 'enableClass',
  66012. value: function enableClass(index, highlight) {
  66013. this.learningClasses[index].element.classList.remove('learning__class--disabled');
  66014. if (highlight) {
  66015. this.highlightClass(index);
  66016. }
  66017. }
  66018. }, {
  66019. key: 'disableClass',
  66020. value: function disableClass(index) {
  66021. this.learningClasses[index].element.classList.add('learning__class--disabled');
  66022. }
  66023. }, {
  66024. key: 'clearExamples',
  66025. value: function clearExamples() {
  66026. this.learningClasses.forEach(function (learningClass) {
  66027. learningClass.clear();
  66028. learningClass.setConfidence(0);
  66029. learningClass.dehighlightConfidence();
  66030. });
  66031. }
  66032. }, {
  66033. key: 'startRecording',
  66034. value: function startRecording(id) {
  66035. this.wiresLeft.highlight(id);
  66036. }
  66037. }, {
  66038. key: 'stopRecording',
  66039. value: function stopRecording() {
  66040. this.wiresLeft.dehighlight();
  66041. }
  66042. }, {
  66043. key: 'ledOn',
  66044. value: function ledOn(id) {
  66045. this.wiresRight.dehighlight();
  66046. this.wiresRight.highlight(id);
  66047. }
  66048. }, {
  66049. key: 'getMaxIndex',
  66050. value: function getMaxIndex(array) {
  66051. var max = array[0];
  66052. var maxIndex = 0;
  66053. for (var index = 1; index < array.length; index += 1) {
  66054. if (array[index] > max) {
  66055. maxIndex = index;
  66056. max = array[index];
  66057. }
  66058. }
  66059. return maxIndex;
  66060. }
  66061. }, {
  66062. key: 'setConfidences',
  66063. value: function setConfidences(confidences) {
  66064. var confidencesArry = Object.values(confidences);
  66065. var maxIndex = this.getMaxIndex(confidencesArry);
  66066. var maxValue = confidencesArry[maxIndex];
  66067. // if (maxValue > 0.5 && this.currentIndex !== maxIndex) {
  66068. if (maxValue > 0.5) {
  66069. this.currentIndex = maxIndex;
  66070. var id = _config2.default.classNames[this.currentIndex];
  66071. this.ledOn(id);
  66072. _config2.default.outputSection.trigger(id);
  66073. }
  66074. for (var index = 0; index < 3; index += 1) {
  66075. this.learningClasses[index].setConfidence(confidencesArry[index] * 100);
  66076. if (index === maxIndex) {
  66077. this.learningClasses[index].highlightConfidence();
  66078. } else {
  66079. this.learningClasses[index].dehighlightConfidence();
  66080. }
  66081. }
  66082. }
  66083. }, {
  66084. key: 'setQuality',
  66085. value: function setQuality(quality) {
  66086. // this.trainingQuality.setQuality(quality);
  66087. }
  66088. }]);
  66089. return LearningSection;
  66090. }();
  66091. exports.default = LearningSection;
  66092. },{"./../../config.js":242,"./../components/HighlightArrow.js":255,"./LearningClass.js":261,"./TrainingQuality.js":265,"./WiresLeft.js":266,"./WiresRight.js":267,"gsap":212}],263:[function(require,module,exports){
  66093. 'use strict';
  66094. Object.defineProperty(exports, "__esModule", {
  66095. value: true
  66096. });
  66097. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  66098. var _gsap = require('gsap');
  66099. var _gsap2 = _interopRequireDefault(_gsap);
  66100. var _config = require('./../../config.js');
  66101. var _config2 = _interopRequireDefault(_config);
  66102. var _Selector = require('./../components/Selector.js');
  66103. var _Selector2 = _interopRequireDefault(_Selector);
  66104. var _Button = require('./../components/Button.js');
  66105. var _Button2 = _interopRequireDefault(_Button);
  66106. var _CamInput = require('./../components/CamInput.js');
  66107. var _CamInput2 = _interopRequireDefault(_CamInput);
  66108. var _HighlightArrow = require('./../components/HighlightArrow.js');
  66109. var _HighlightArrow2 = _interopRequireDefault(_HighlightArrow);
  66110. var _SpeechOutput = require('./../../outputs/SpeechOutput.js');
  66111. var _SpeechOutput2 = _interopRequireDefault(_SpeechOutput);
  66112. var _GIFOutput = require('./../../outputs/GIFOutput.js');
  66113. var _GIFOutput2 = _interopRequireDefault(_GIFOutput);
  66114. var _CloudOutput = require('./../../outputs/CloudOutput.js');
  66115. var _CloudOutput2 = _interopRequireDefault(_CloudOutput);
  66116. var _SoundOutput = require('./../../outputs/SoundOutput.js');
  66117. var _SoundOutput2 = _interopRequireDefault(_SoundOutput);
  66118. var _ModuleOutput = require('./../../outputs/ModuleOutput.js');
  66119. var _ModuleOutput2 = _interopRequireDefault(_ModuleOutput);
  66120. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  66121. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  66122. // Copyright 2017 Google Inc.
  66123. //
  66124. // Licensed under the Apache License, Version 2.0 (the "License");
  66125. // you may not use this file except in compliance with the License.
  66126. // You may obtain a copy of the License at
  66127. //
  66128. // http://www.apache.org/licenses/LICENSE-2.0
  66129. //
  66130. // Unless required by applicable law or agreed to in writing, software
  66131. // distributed under the License is distributed on an "AS IS" BASIS,
  66132. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  66133. // See the License for the specific language governing permissions and
  66134. // limitations under the License.
  66135. var OutputSection = function () {
  66136. function OutputSection(element) {
  66137. var _this = this;
  66138. _classCallCheck(this, OutputSection);
  66139. this.element = element;
  66140. var outputs = {
  66141. CloudOutput: new _CloudOutput2.default(),
  66142. // GIFOutput: new GIFOutput(),
  66143. SoundOutput: new _SoundOutput2.default(document.querySelector('#SoundOutput')),
  66144. SpeechOutput: new _SpeechOutput2.default(),
  66145. ModuleOutput: new _ModuleOutput2.default()
  66146. };
  66147. _config2.default.soundOutput = outputs.SoundOutput;
  66148. this.ModuleOutput = new _ModuleOutput2.default();
  66149. this.classNames = _config2.default.classNames;
  66150. _config2.default.predicting = true;
  66151. this.outputs = outputs;
  66152. this.loadedOutputs = [];
  66153. var outputLinks = element.querySelectorAll('.output_selector__option');
  66154. outputLinks.forEach(function (link) {
  66155. link.addEventListener('click', _this.changeOutput.bind(_this));
  66156. });
  66157. this.currentLink = element.querySelector('.output_selector__option--selected');
  66158. this.outputContainer = document.querySelector('#output-player');
  66159. this.currentOutput = null;
  66160. this.currentLink.click();
  66161. this.arrow = new _HighlightArrow2.default(1);
  66162. _gsap2.default.set(this.arrow.element, {
  66163. rotation: -50,
  66164. scale: -0.8,
  66165. x: 140,
  66166. y: -100
  66167. });
  66168. this.element.appendChild(this.arrow.element);
  66169. }
  66170. _createClass(OutputSection, [{
  66171. key: 'enable',
  66172. value: function enable() {
  66173. this.element.classList.remove('section--disabled');
  66174. }
  66175. }, {
  66176. key: 'highlight',
  66177. value: function highlight() {
  66178. this.arrow.show();
  66179. _gsap2.default.from(this.arrow.element, 0.3, { opacity: 0 });
  66180. }
  66181. }, {
  66182. key: 'dehighlight',
  66183. value: function dehighlight() {
  66184. _gsap2.default.killTweensOf(this.arrow.element);
  66185. this.arrow.hide();
  66186. }
  66187. }, {
  66188. key: 'disable',
  66189. value: function disable() {
  66190. this.element.classList.add('section--disabled');
  66191. }
  66192. }, {
  66193. key: 'dim',
  66194. value: function dim() {
  66195. this.element.classList.add('dimmed');
  66196. }
  66197. }, {
  66198. key: 'undim',
  66199. value: function undim() {
  66200. this.element.classList.remove('dimmed');
  66201. }
  66202. }, {
  66203. key: 'changeOutput',
  66204. value: function changeOutput(event) {
  66205. if (this.currentLink) {
  66206. this.currentLink.classList.remove('output_selector__option--selected');
  66207. }
  66208. this.currentLink = event.target;
  66209. this.currentLink.classList.add('output_selector__option--selected');
  66210. var outputId = this.currentLink.id;
  66211. if (this.currentOutput) {
  66212. this.currentOutput.stop();
  66213. this.currentOutput = null;
  66214. }
  66215. if (this.outputs[outputId]) {
  66216. this.currentOutput = this.outputs[outputId];
  66217. }
  66218. if (outputId === "ModuleOutput") {
  66219. var lang = _config2.default.lang;
  66220. var port = lang == 'en' ? 'Port' : lang == 'zh-hant' ? "端口" : "端口";
  66221. var connects = lang == 'en' ? 'Connect' : lang == 'zh-hant' ? "連接" : "连接";
  66222. var disconnects = lang == 'en' ? 'Disconnect' : lang == 'zh-hant' ? "斷開" : "断开";
  66223. if (document.getElementById('port_connect')) {
  66224. document.getElementById('port_connect').innerHTML = '<span id="portNumber">' + port + ':</span><span>' + (_config2.default.port ? _config2.default.port : "") + '</span><button class="send_button ' + (_config2.default.port && 'send_button_color') + '" style="display:block">' + connects + '</button><button class="send_button ' + (_config2.default.port && 'send_button_color') + '" style="display:none">' + disconnects + '</button>';
  66225. }
  66226. }
  66227. if (this.currentOutput) {
  66228. this.outputContainer.appendChild(this.currentOutput.element);
  66229. this.currentOutput.start();
  66230. }
  66231. gtag('event', 'select_output', { 'id': outputId });
  66232. }
  66233. }, {
  66234. key: 'toggleSoundOutput',
  66235. value: function toggleSoundOutput(play) {
  66236. if (this.currentOutput.id === 'SoundOutput' && play) {
  66237. _config2.default.soundOutput.playCurrentSound();
  66238. } else if (this.currentOutput.id === 'SoundOutput' && !play) {
  66239. _config2.default.soundOutput.pauseCurrentSound();
  66240. }
  66241. }
  66242. }, {
  66243. key: 'startWizardMode',
  66244. value: function startWizardMode() {
  66245. this.broadcastEvents = true;
  66246. }
  66247. }, {
  66248. key: 'stopWizardMode',
  66249. value: function stopWizardMode() {
  66250. this.broadcastEvents = false;
  66251. }
  66252. }, {
  66253. key: 'trigger',
  66254. value: function trigger(id) {
  66255. var index = this.classNames.indexOf(id);
  66256. this.currentOutput.trigger(index);
  66257. if (this.broadcastEvents) {
  66258. var event = new CustomEvent('class-triggered', { detail: { id: id } });
  66259. window.dispatchEvent(event);
  66260. }
  66261. }
  66262. }, {
  66263. key: 'clear',
  66264. value: function clear() {
  66265. this.currentOutput.clear();
  66266. }
  66267. }]);
  66268. return OutputSection;
  66269. }();
  66270. exports.default = OutputSection;
  66271. },{"./../../config.js":242,"./../../outputs/CloudOutput.js":244,"./../../outputs/GIFOutput.js":245,"./../../outputs/ModuleOutput.js":246,"./../../outputs/SoundOutput.js":247,"./../../outputs/SpeechOutput.js":248,"./../components/Button.js":252,"./../components/CamInput.js":253,"./../components/HighlightArrow.js":255,"./../components/Selector.js":256,"gsap":212}],264:[function(require,module,exports){
  66272. 'use strict';
  66273. Object.defineProperty(exports, "__esModule", {
  66274. value: true
  66275. });
  66276. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  66277. var _Button = require('./../components/Button.js');
  66278. var _Button2 = _interopRequireDefault(_Button);
  66279. var _config = require('./../../config.js');
  66280. var _config2 = _interopRequireDefault(_config);
  66281. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  66282. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  66283. // Copyright 2017 Google Inc.
  66284. //
  66285. // Licensed under the Apache License, Version 2.0 (the "License");
  66286. // you may not use this file except in compliance with the License.
  66287. // You may obtain a copy of the License at
  66288. //
  66289. // http://www.apache.org/licenses/LICENSE-2.0
  66290. //
  66291. // Unless required by applicable law or agreed to in writing, software
  66292. // distributed under the License is distributed on an "AS IS" BASIS,
  66293. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  66294. // See the License for the specific language governing permissions and
  66295. // limitations under the License.
  66296. var Recording = function () {
  66297. function Recording(element) {
  66298. _classCallCheck(this, Recording);
  66299. this.element = element;
  66300. this.canvas = element.querySelector('#recording__canvas');
  66301. this.startButtonText = element.querySelector('#recording__start-text');
  66302. this.downloadPreText = element.querySelector('#pre-download-message');
  66303. this.downloadLinkSection = element.querySelector('.recording-download-container');
  66304. this.downloadLinkButton = element.querySelector('#recording__download');
  66305. this.recordingVideo = element.querySelector('#recording__video');
  66306. this.recordTimer = element.querySelector('#record__timer');
  66307. this.closeButton = element.querySelector('#close__button');
  66308. this.restart = element.querySelector('#restart');
  66309. this.recordMessage = element.querySelector('#message');
  66310. this.recordMessageAlt = element.querySelector('#message-alt');
  66311. this.downloadLinkSection.style.display = 'none';
  66312. this.sharingNotice = element.querySelector('#sharing-notice');
  66313. this.sendSuccess = false;
  66314. this.legal = document.querySelector('#recording__legal');
  66315. this.checkbox = document.querySelector('#recording__checkbox');
  66316. this.recordMessageAlt.style.display = 'none';
  66317. this.recordingVideo.style.display = 'none';
  66318. this.recordingVideo.setAttribute('src', '');
  66319. this.canvas.width = 680;
  66320. this.canvas.height = 340;
  66321. this.video = document.getElementsByTagName('video')[0];
  66322. this.confidence1 = 0;
  66323. this.confidence2 = 0;
  66324. this.confidence3 = 0;
  66325. this.recordedTime = 10;
  66326. this.count = 3;
  66327. this.showing = false;
  66328. this.closeButton.addEventListener('click', this.hide.bind(this));
  66329. this.restart.addEventListener('click', this.reset.bind(this));
  66330. this.recordingState = 'waiting';
  66331. this.RECORD_TIME = 10000;
  66332. this.startButton = new _Button2.default(document.querySelector('#recording__start-button'));
  66333. this.startRecordEvent = this.onRecordButtonClick.bind(this);
  66334. this.checkbox.addEventListener('click', this.toggleCheckbox.bind(this));
  66335. }
  66336. _createClass(Recording, [{
  66337. key: 'toggleCheckbox',
  66338. value: function toggleCheckbox() {
  66339. if (this.checkbox.checked) {
  66340. this.startButton.element.addEventListener('click', this.startRecordEvent);
  66341. this.startButton.element.classList.remove('recording-start__button--disabled');
  66342. } else {
  66343. this.startButton.element.removeEventListener('click', this.startRecordEvent);
  66344. this.startButton.element.classList.add('recording-start__button--disabled');
  66345. }
  66346. }
  66347. }, {
  66348. key: 'setCanvas',
  66349. value: function setCanvas(element) {
  66350. var _this = this;
  66351. this.show();
  66352. if (element.name === 'gif') {
  66353. this.canvasType = 'gif';
  66354. } else {
  66355. this.canvasType = '';
  66356. }
  66357. document.querySelector('#recording__start-button .button__label #icon--record').style.display = 'inline-block';
  66358. document.querySelector('#recording__start-button .button__label #icon--stop').style.display = 'none';
  66359. this.sourceCanvas = element;
  66360. this.context = this.canvas.getContext('2d');
  66361. this.showing = true;
  66362. this.render();
  66363. var img = new Image();
  66364. var stamp = new Image();
  66365. img.onload = function () {
  66366. _this.wiresImage = img;
  66367. };
  66368. stamp.onload = function () {
  66369. _this.stampImage = stamp;
  66370. };
  66371. img.src = 'assets/wires-recorder.png';
  66372. stamp.src = 'assets/madeby.svg';
  66373. }
  66374. }, {
  66375. key: 'render',
  66376. value: function render() {
  66377. if (!this.showing) {
  66378. return;
  66379. }
  66380. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  66381. this.context.fillStyle = '#e4e5e6';
  66382. this.context.fillRect(0, 0, 680, 340);
  66383. // call its drawImage() function passing it the source canvas directly
  66384. var maxHeight = 200;
  66385. var videoWidth = 266;
  66386. var padding = 20;
  66387. var startX = 26;
  66388. var startY = 16;
  66389. // White boxes
  66390. this.context.fillStyle = '#fff';
  66391. this.context.fillRect(startX, startY, videoWidth + padding, maxHeight + 70);
  66392. this.context.fillRect(340 + startX, startY, videoWidth + padding, maxHeight + 70);
  66393. // The "Output" Canvas
  66394. if (this.canvasType === 'gif') {
  66395. var _videoWidth = 260;
  66396. this.context.drawImage(this.sourceCanvas, startX + 343 + padding / 2, 45, _videoWidth, _videoWidth - 50);
  66397. } else {
  66398. this.context.drawImage(this.sourceCanvas, startX + 355 + padding / 2, 40, videoWidth, videoWidth - 50);
  66399. }
  66400. if (this.wiresImage) {
  66401. this.context.drawImage(this.wiresImage, startX + 276 + padding / 2, 45, 54, videoWidth - 50);
  66402. }
  66403. if (this.stampImage) {
  66404. this.context.drawImage(this.stampImage, this.canvas.width / 2 - videoWidth * 1.2 / 2, 302, videoWidth * 1.2, 20);
  66405. }
  66406. // Bars to cover it:
  66407. // this.context.fillStyle = '#e4e5e6';
  66408. // this.context.fillRect(startX + 340, 0, videoWidth + padding, startY);
  66409. // this.context.fillStyle = '#fff';
  66410. // this.context.fillRect(startX + 340, startY, videoWidth + padding, padding / 2);
  66411. // this.context.fillRect(startX + 340, maxHeight + startY + padding / 2, videoWidth + padding, 30);
  66412. var barsY = maxHeight + startY + padding;
  66413. var boxSize = (videoWidth - padding) / 3;
  66414. var boxStartX = startX + padding / 2;
  66415. this.context.fillStyle = '#e4e5e6';
  66416. this.context.fillRect(boxStartX, barsY, boxSize, 40);
  66417. this.context.fillStyle = '#2baa5e';
  66418. this.context.fillRect(boxStartX, barsY, boxSize * this.confidence1, 40);
  66419. this.context.fillStyle = '#e4e5e6';
  66420. this.context.fillRect(boxStartX + boxSize + padding / 2, barsY, boxSize, 40);
  66421. this.context.fillStyle = '#c95ac5';
  66422. this.context.fillRect(boxStartX + boxSize + padding / 2, barsY, boxSize * this.confidence2, 40);
  66423. this.context.fillStyle = '#e4e5e6';
  66424. this.context.fillRect(boxStartX + boxSize + boxSize + padding, barsY, boxSize, 40);
  66425. this.context.fillStyle = '#dd4d31';
  66426. this.context.fillRect(boxStartX + boxSize + boxSize + padding, barsY, boxSize * this.confidence3, 40);
  66427. // Video comes in mirrored, so let's flip it:
  66428. this.context.save();
  66429. this.context.scale(-1, 1);
  66430. this.context.drawImage(this.video, -(startX + padding / 2), startY + padding / 2, maxHeight * (360 / 270) * -1, maxHeight);
  66431. this.context.restore();
  66432. //
  66433. // this.context.font = '18px Poppins';
  66434. // this.context.fillStyle = '#000';
  66435. // this.context.fillText('MADE AT: ', startX, 320);
  66436. // this.context.fillStyle = '#3e80f6';
  66437. // this.context.fillText('G.CO/TEACHABLEMACHINE', 110, 320);
  66438. requestAnimationFrame(this.render.bind(this));
  66439. }
  66440. }, {
  66441. key: 'setMeters',
  66442. value: function setMeters(colorId, confidence) {
  66443. if (!this.showing) {
  66444. return;
  66445. }
  66446. var confidencePercentage = confidence / 100;
  66447. switch (colorId) {
  66448. case 'green':
  66449. this.confidence1 = confidencePercentage;
  66450. break;
  66451. case 'purple':
  66452. this.confidence2 = confidencePercentage;
  66453. break;
  66454. case 'orange':
  66455. this.confidence3 = confidencePercentage;
  66456. break;
  66457. default:
  66458. break;
  66459. }
  66460. }
  66461. }, {
  66462. key: 'stopRecording',
  66463. value: function stopRecording() {
  66464. // this.recordingState = 'Facebook';
  66465. if (this.mediaRecorder.state !== 'inactive') {
  66466. this.mediaRecorder.stop();
  66467. }
  66468. clearTimeout(this.recordingTimeout);
  66469. _config2.default.webcamClassifier.stopTimer();
  66470. }
  66471. }, {
  66472. key: 'onRecordButtonClick',
  66473. value: function onRecordButtonClick() {
  66474. switch (this.recordingState) {
  66475. case 'waiting':
  66476. this.countdown();
  66477. break;
  66478. case 'countdown':
  66479. this.stopCountdown();
  66480. break;
  66481. case 'recording':
  66482. if (this.mediaRecorder) {
  66483. if (this.mediaRecorder.state !== 'inactive') {
  66484. this.mediaRecorder.stop();
  66485. this.stopRecording();
  66486. }
  66487. this.recordingState = 'waiting';
  66488. this.recordTimer.style.display = 'none';
  66489. this.startButton.element.classList.remove('animate');
  66490. }
  66491. break;
  66492. case 'shareSuccess':
  66493. this.shareOnFb();
  66494. break;
  66495. case 'successMessage':
  66496. this.recordingState = 'waiting';
  66497. break;
  66498. default:
  66499. break;
  66500. }
  66501. }
  66502. }, {
  66503. key: 'onShareButtonClick',
  66504. value: function onShareButtonClick() {
  66505. this.recordingState = 'waiting';
  66506. this.shareOnFb();
  66507. this.downloadLinkSection.style.marginLeft = 0;
  66508. }
  66509. }, {
  66510. key: 'reset',
  66511. value: function reset() {
  66512. _config2.default.webcamClassifier.startTimer();
  66513. this.recordingState = 'waiting';
  66514. this.recordTimer.style.display = 'block';
  66515. this.startButton.element.style.top = 0;
  66516. this.downloadLinkSection.style.marginLeft = '15px';
  66517. this.recordMessage.style.display = 'block';
  66518. this.recordMessageAlt.style.display = 'none';
  66519. this.startButton.element.style.display = 'inline-block';
  66520. this.legal.style.display = 'block';
  66521. this.downloadLinkSection.style.display = 'none';
  66522. document.querySelector('#recording__start-button .button__label #icon--stop').style.display = 'none';
  66523. document.querySelector('#recording__start-button .button__label #icon--record').style.display = 'inline-block';
  66524. document.querySelector('#recording__start-button .button__label #recording__start-text').innerText = 'Start Recording';
  66525. this.canvas.style.display = 'block';
  66526. this.sharingNotice.style.display = 'none';
  66527. this.recordingVideo.style.display = 'none';
  66528. this.recordingVideo.setAttribute('src', '');
  66529. this.stopRecordingTime();
  66530. this.stopCountdown();
  66531. this.downloadPreText.innerText = '';
  66532. }
  66533. }, {
  66534. key: 'countdown',
  66535. value: function countdown() {
  66536. var _this2 = this;
  66537. this.recordingState = 'countdown';
  66538. this.canvas.style.display = 'block';
  66539. this.recordingVideo.style.display = 'none';
  66540. this.downloadLinkSection.style.display = 'none';
  66541. document.querySelector('#recording__start-button .button__label #icon--record').style.display = 'none';
  66542. document.querySelector('#recording__start-button .button__label #recording__start-text').innerText = this.count;
  66543. this.countdownTimeout = setTimeout(function () {
  66544. _this2.count = _this2.count - 1;
  66545. if (_this2.count > 0) {
  66546. document.querySelector('#recording__start-button .button__label #recording__start-text').innerText = _this2.count;
  66547. _this2.countdown();
  66548. } else {
  66549. _this2.startRecording();
  66550. _this2.recordingTime();
  66551. _this2.count = 3;
  66552. }
  66553. }, 1000);
  66554. }
  66555. }, {
  66556. key: 'recordingTime',
  66557. value: function recordingTime() {
  66558. var _this3 = this;
  66559. this.recordingTimeTimeout = setTimeout(function () {
  66560. _this3.recordedTime = _this3.recordedTime - 1;
  66561. if (_this3.recordedTime > 0) {
  66562. _this3.recordTimer.innerText = '0:0' + _this3.recordedTime;
  66563. _this3.recordingTime();
  66564. } else {
  66565. _this3.recordTimer.innerText = '0:00';
  66566. _this3.recordedTime = 10;
  66567. }
  66568. }, 1000);
  66569. }
  66570. }, {
  66571. key: 'stopRecordingTime',
  66572. value: function stopRecordingTime() {
  66573. this.recordingState = 'waiting';
  66574. if (this.recordingTimeTimeout) {
  66575. clearTimeout(this.recordingTimeTimeout);
  66576. }
  66577. this.recordedTime = 10;
  66578. this.recordTimer.innerText = '0:10';
  66579. }
  66580. }, {
  66581. key: 'stopCountdown',
  66582. value: function stopCountdown() {
  66583. this.recordingState = 'waiting';
  66584. clearTimeout(this.countdownTimeout);
  66585. this.count = 3;
  66586. this.startButton.element.classList.remove('animate');
  66587. document.querySelector('#recording__start-button .button__label #recording__start-text').innerText = 'Start Recording';
  66588. }
  66589. }, {
  66590. key: 'startRecording',
  66591. value: function startRecording() {
  66592. var _this4 = this;
  66593. console.log("start recording");
  66594. this.recordingState = 'recording';
  66595. document.querySelector('#recording__start-button .button__label #icon--stop').style.display = 'inline-block';
  66596. document.querySelector('#recording__start-button .button__label #recording__start-text').innerText = 'Stop Recording';
  66597. var recordedChunks = [];
  66598. this.startButton.element.classList.add('animate');
  66599. var finalStream = new MediaStream();
  66600. var canvasStream = this.canvas.captureStream().getVideoTracks()[0];
  66601. finalStream.addTrack(canvasStream);
  66602. finalStream.addTrack(_config2.default.stream.getAudioTracks()[0]);
  66603. this.mediaRecorder = new MediaRecorder(finalStream);
  66604. this.mediaRecorder.ondataavailable = function (event) {
  66605. if (event.data.size > 0) {
  66606. recordedChunks.push(event.data);
  66607. }
  66608. };
  66609. this.mediaRecorder.start();
  66610. this.mediaRecorder.onstop = function () {
  66611. _this4.blob = new Blob(recordedChunks, { type: 'video/webm' });
  66612. var url = URL.createObjectURL(_this4.blob);
  66613. _this4.canvas.style.display = 'none';
  66614. _this4.recordingVideo.style.display = 'block';
  66615. _this4.recordMessage.style.display = 'none';
  66616. _this4.recordMessageAlt.style.display = 'block';
  66617. _this4.recordTimer.style.display = 'none';
  66618. _this4.startButton.element.style.top = '50px';
  66619. document.querySelector('#recording__start-button .button__label #icon--stop').style.display = 'none';
  66620. document.querySelector('#recording__start-button .button__label #recording__start-text').innerText = '';
  66621. _this4.downloadLinkSection.style.display = 'inline-block';
  66622. _this4.downloadLinkButton.href = url;
  66623. _this4.downloadLinkButton.download = 'teachable-machine.webm';
  66624. _this4.startButton.element.style.display = 'none';
  66625. _this4.legal.style.display = 'none';
  66626. _this4.recordingVideo.setAttribute('src', url);
  66627. // this.sharingNotice.style.display = 'block';
  66628. };
  66629. this.recordingTimeout = setTimeout(function () {
  66630. _this4.startButton.element.classList.remove('animate');
  66631. _this4.stopRecording();
  66632. }, this.RECORD_TIME);
  66633. gtag('event', 'recording_start');
  66634. }
  66635. }, {
  66636. key: 'show',
  66637. value: function show() {
  66638. var _this5 = this;
  66639. this.recordingState = 'waiting';
  66640. this.showing = true;
  66641. this.element.style.opacity = 1;
  66642. this.element.style.pointerEvents = 'initial';
  66643. setTimeout(function () {
  66644. _this5.element.classList.add('fadein');
  66645. }, 1);
  66646. }
  66647. }, {
  66648. key: 'hide',
  66649. value: function hide() {
  66650. var _this6 = this;
  66651. this.element.classList.remove('fadein');
  66652. _config2.default.webcamClassifier.startTimer();
  66653. setTimeout(function () {
  66654. _this6.element.style.opacity = 0;
  66655. _this6.element.style.pointerEvents = 'none';
  66656. _config2.default.isRecording = false;
  66657. if (_this6.video) {
  66658. _this6.recordingVideo.setAttribute('src', '');
  66659. }
  66660. _this6.reset();
  66661. }, 300);
  66662. clearTimeout(this.recordingTimeTimeout);
  66663. clearTimeout(this.countdownTimeout);
  66664. this.showing = false;
  66665. }
  66666. }, {
  66667. key: 'shareOnFb',
  66668. value: function shareOnFb() {
  66669. var _this7 = this;
  66670. this.downloadPreText.innerText = 'Posting... ';
  66671. window.fbWindowCallback = function (data) {
  66672. var formData = new FormData();
  66673. formData.append('code', data);
  66674. var fileOfBlob = new File([_this7.blob], 'share.webm');
  66675. formData.append('video', fileOfBlob);
  66676. var xhr = new XMLHttpRequest();
  66677. xhr.open('POST', '/share-video');
  66678. xhr.onload = function () {
  66679. if (xhr.status === 200) {
  66680. _this7.downloadPreText.innerText = 'Posted to Facebook. ';
  66681. // console.log('Something went wrong. Name is now ' + xhr.responseText);
  66682. } else if (xhr.status !== 200) {
  66683. _this7.downloadPreText.innerText = 'Sorry, something went wrong. ';
  66684. // console.log('Request failed. Returned status of ' + xhr.status);
  66685. }
  66686. };
  66687. xhr.send(formData);
  66688. };
  66689. var popup = window.open('/fb', 'Share on Facebook', 'width=600, height=600');
  66690. popup.focus();
  66691. gtag('event', 'recording_share');
  66692. }
  66693. }]);
  66694. return Recording;
  66695. }();
  66696. exports.default = Recording;
  66697. },{"./../../config.js":242,"./../components/Button.js":252}],265:[function(require,module,exports){
  66698. 'use strict';
  66699. Object.defineProperty(exports, "__esModule", {
  66700. value: true
  66701. });
  66702. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  66703. var _gsap = require('gsap');
  66704. var _gsap2 = _interopRequireDefault(_gsap);
  66705. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  66706. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  66707. // Copyright 2017 Google Inc.
  66708. //
  66709. // Licensed under the Apache License, Version 2.0 (the "License");
  66710. // you may not use this file except in compliance with the License.
  66711. // You may obtain a copy of the License at
  66712. //
  66713. // http://www.apache.org/licenses/LICENSE-2.0
  66714. //
  66715. // Unless required by applicable law or agreed to in writing, software
  66716. // distributed under the License is distributed on an "AS IS" BASIS,
  66717. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  66718. // See the License for the specific language governing permissions and
  66719. // limitations under the License.
  66720. var TrainingQuality = function () {
  66721. function TrainingQuality(element) {
  66722. _classCallCheck(this, TrainingQuality);
  66723. this.element = element;
  66724. this.percentage = 0;
  66725. this.percentageElement = element.querySelector('.machine__value');
  66726. this.percentageGrey = element.querySelector('.machine__percentage--grey');
  66727. this.percentageWhite = element.querySelector('.machine__percentage--white');
  66728. this.label = element.querySelector('.quality__status');
  66729. this.percentageWhite.style.width = this.percentageGrey.offsetWidth + 'px';
  66730. this.updatePercentage();
  66731. }
  66732. _createClass(TrainingQuality, [{
  66733. key: 'updatePercentage',
  66734. value: function updatePercentage() {
  66735. var rounded = Math.floor(this.percentage);
  66736. this.percentageElement.style.width = this.percentage + '%';
  66737. this.percentageGrey.textContent = rounded + '%';
  66738. this.percentageWhite.textContent = rounded + '%';
  66739. }
  66740. }, {
  66741. key: 'setQuality',
  66742. value: function setQuality(quality) {
  66743. // this.percentage = quality * 100;
  66744. // this.updatePercentage();
  66745. var that = this;
  66746. var percentage = quality * 100;
  66747. _gsap2.default.to(that, 0.5, {
  66748. percentage: percentage,
  66749. onUpdate: function onUpdate() {
  66750. // console.log(that.percentage);
  66751. that.updatePercentage();
  66752. }
  66753. });
  66754. if (percentage < 65) {
  66755. this.label.textContent = 'Your machine probably won’t work well';
  66756. } else if (percentage > 90) {
  66757. this.label.textContent = 'Perfect!';
  66758. } else {
  66759. this.label.textContent = 'Looking good';
  66760. }
  66761. }
  66762. }, {
  66763. key: 'start',
  66764. value: function start() {
  66765. // let that = this;
  66766. // TweenMax.to(that, (Math.random() * 4) + 0.5, {
  66767. // percentage: Math.floor(Math.random() * 100),
  66768. // onUpdate: function() {
  66769. // that.updatePercentage();
  66770. // },
  66771. // repeat: -1,
  66772. // yoyo: true
  66773. // });
  66774. }
  66775. }]);
  66776. return TrainingQuality;
  66777. }();
  66778. exports.default = TrainingQuality;
  66779. },{"gsap":212}],266:[function(require,module,exports){
  66780. 'use strict';
  66781. Object.defineProperty(exports, "__esModule", {
  66782. value: true
  66783. });
  66784. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // Copyright 2017 Google Inc.
  66785. //
  66786. // Licensed under the Apache License, Version 2.0 (the "License");
  66787. // you may not use this file except in compliance with the License.
  66788. // You may obtain a copy of the License at
  66789. //
  66790. // http://www.apache.org/licenses/LICENSE-2.0
  66791. //
  66792. // Unless required by applicable law or agreed to in writing, software
  66793. // distributed under the License is distributed on an "AS IS" BASIS,
  66794. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  66795. // See the License for the specific language governing permissions and
  66796. // limitations under the License.
  66797. var _config = require('./../../config.js');
  66798. var _config2 = _interopRequireDefault(_config);
  66799. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  66800. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  66801. var WiresLeft = function () {
  66802. function WiresLeft(element, learningClasses) {
  66803. var _this = this;
  66804. _classCallCheck(this, WiresLeft);
  66805. this.element = element;
  66806. this.learningClasses = learningClasses;
  66807. this.offsetY = 0;
  66808. this.canvas = document.createElement('canvas');
  66809. this.size();
  66810. this.element.appendChild(this.canvas);
  66811. this.wireGeneral = this.element.querySelector('.st0');
  66812. this.wireGreen = this.element.querySelector('.wire-green');
  66813. this.wirePurple = this.element.querySelector('.wire-purple');
  66814. this.wireOrange = this.element.querySelector('.wire-orange');
  66815. this.context = this.canvas.getContext('2d');
  66816. this.vertical = true;
  66817. window.addEventListener('resize', function () {
  66818. if (window.innerWidth <= 900) {
  66819. _this.canvas.style.display = 'none';
  66820. } else {
  66821. _this.canvas.style.display = 'block';
  66822. }
  66823. });
  66824. this.currentAnimator = null;
  66825. this.renderOnce = true;
  66826. this.render();
  66827. }
  66828. _createClass(WiresLeft, [{
  66829. key: 'render',
  66830. value: function render(once) {
  66831. this.context.clearRect(0, 0, this.width, this.height);
  66832. this.context.lineWidth = 3;
  66833. for (var index = 0; index < 3; index += 1) {
  66834. var startY = this.startY + this.startSpace * index;
  66835. var endY = this.endY + this.endSpace * index;
  66836. var start = {
  66837. x: 0,
  66838. y: this.startY + this.startSpace * index
  66839. };
  66840. var end = {
  66841. x: this.endX,
  66842. y: this.endY + this.endSpace * index
  66843. };
  66844. var cp1 = {
  66845. x: 35,
  66846. y: start.y
  66847. };
  66848. var cp2 = {
  66849. x: 10,
  66850. y: end.y
  66851. };
  66852. this.context.strokeStyle = '#cfd1d2';
  66853. if (this.animator[index].highlight) {
  66854. this.context.strokeStyle = this.animator[index].color;
  66855. }
  66856. this.context.beginPath();
  66857. this.context.moveTo(start.x, start.y);
  66858. this.context.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y);
  66859. this.context.lineTo(start.x + 100, start.y);
  66860. this.context.stroke();
  66861. }
  66862. if (this.renderOnce) {
  66863. this.renderOnce = false;
  66864. } else {
  66865. this.timer = requestAnimationFrame(this.render.bind(this));
  66866. }
  66867. }
  66868. }, {
  66869. key: 'camMode',
  66870. value: function camMode() {
  66871. if (this.vert) {
  66872. this.element.style.left = 50 + '%';
  66873. }
  66874. this.offsetY = -2;
  66875. this.startY = this.height / 2 + this.offsetY;
  66876. this.renderOnce = true;
  66877. this.render();
  66878. }
  66879. }, {
  66880. key: 'highlight',
  66881. value: function highlight(index) {
  66882. this.currentAnimator = this.animator[index];
  66883. this.currentAnimator.highlight = true;
  66884. this.start();
  66885. switch (index) {
  66886. case 0:
  66887. this.wireGreen.classList.add('animate');
  66888. break;
  66889. case 1:
  66890. this.wireOrange.classList.add('animate');
  66891. break;
  66892. case 2:
  66893. this.wirePurple.classList.add('animate');
  66894. break;
  66895. default:
  66896. }
  66897. }
  66898. }, {
  66899. key: 'dehighlight',
  66900. value: function dehighlight(index) {
  66901. if (this.currentAnimator) {
  66902. this.currentAnimator.highlight = false;
  66903. this.currentAnimator = null;
  66904. this.stop();
  66905. this.renderOnce = true;
  66906. this.render();
  66907. }
  66908. this.wireGreen.classList.remove('animate');
  66909. this.wirePurple.classList.remove('animate');
  66910. this.wireOrange.classList.remove('animate');
  66911. }
  66912. }, {
  66913. key: 'start',
  66914. value: function start() {
  66915. this.stop();
  66916. this.timer = requestAnimationFrame(this.render.bind(this));
  66917. }
  66918. }, {
  66919. key: 'stop',
  66920. value: function stop() {
  66921. if (this.timer) {
  66922. cancelAnimationFrame(this.timer);
  66923. }
  66924. }
  66925. }, {
  66926. key: 'size',
  66927. value: function size() {
  66928. var BREAKPOINT_DESKTOP = 900;
  66929. if (window.innerWidth <= BREAKPOINT_DESKTOP) {
  66930. this.canvas.style.display = 'none';
  66931. }
  66932. this.width = this.element.offsetWidth;
  66933. var firstLearningClass = this.learningClasses[0];
  66934. var lastLearningClass = this.learningClasses[2];
  66935. var classesHeight = lastLearningClass.offsetTop - firstLearningClass.offsetTop;
  66936. this.height = 440;
  66937. // remove offset on desktop
  66938. this.element.setAttribute('style', '');
  66939. this.endSpace = classesHeight / 2;
  66940. this.canvas.width = this.width;
  66941. this.canvas.height = this.height;
  66942. this.startSpace = 3;
  66943. this.startX = 0;
  66944. // this.startY = (this.height / 2);
  66945. this.startY = this.height / 2 + this.offsetY;
  66946. this.endX = this.width;
  66947. this.endY = 80;
  66948. this.animator = {};
  66949. for (var index = 0; index < 3; index += 1) {
  66950. var id = _config2.default.classNames[index];
  66951. this.animator[index] = {
  66952. highlight: false,
  66953. percentage: 0,
  66954. color: _config2.default.colors[id],
  66955. numParticles: 15
  66956. };
  66957. }
  66958. this.renderOnce = true;
  66959. }
  66960. }]);
  66961. return WiresLeft;
  66962. }();
  66963. exports.default = WiresLeft;
  66964. },{"./../../config.js":242}],267:[function(require,module,exports){
  66965. 'use strict';
  66966. Object.defineProperty(exports, "__esModule", {
  66967. value: true
  66968. });
  66969. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  66970. var _config = require('./../../config.js');
  66971. var _config2 = _interopRequireDefault(_config);
  66972. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  66973. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  66974. // Copyright 2017 Google Inc.
  66975. //
  66976. // Licensed under the Apache License, Version 2.0 (the "License");
  66977. // you may not use this file except in compliance with the License.
  66978. // You may obtain a copy of the License at
  66979. //
  66980. // http://www.apache.org/licenses/LICENSE-2.0
  66981. //
  66982. // Unless required by applicable law or agreed to in writing, software
  66983. // distributed under the License is distributed on an "AS IS" BASIS,
  66984. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  66985. // See the License for the specific language governing permissions and
  66986. // limitations under the License.
  66987. var WiresRight = function () {
  66988. function WiresRight(element) {
  66989. var _this = this;
  66990. _classCallCheck(this, WiresRight);
  66991. this.element = element;
  66992. this.canvas = document.createElement('canvas');
  66993. this.bulbVert = true;
  66994. this.bulbSmall = false;
  66995. this.bulbGreen = this.element.querySelector('.wire--right-bulb-green-glow');
  66996. this.bulbPurple = this.element.querySelector('.wire--right-bulb-purple-glow');
  66997. this.bulbOrange = this.element.querySelector('.wire--right-bulb-orange-glow');
  66998. this.element.appendChild(this.canvas);
  66999. this.context = this.canvas.getContext('2d');
  67000. this.offsetY = 0;
  67001. this.animator = {};
  67002. for (var index = 0; index < 3; index += 1) {
  67003. var bulbElement = document.createElement('div');
  67004. bulbElement.classList.add('wires__bulb');
  67005. bulbElement.classList.add('wires__bulb-' + _config2.default.classNames[index]);
  67006. this.size();
  67007. this.element.appendChild(bulbElement);
  67008. this.animator[index] = {
  67009. highlight: false,
  67010. bulb: bulbElement
  67011. };
  67012. }
  67013. window.addEventListener('resize', function () {
  67014. if (window.innerWidth <= 900) {
  67015. _this.canvas.style.display = 'none';
  67016. } else {
  67017. _this.canvas.style.display = 'block';
  67018. }
  67019. });
  67020. window.addEventListener('orientationchange', function () {
  67021. _this.size();
  67022. });
  67023. this.altOffset = 340;
  67024. this.size();
  67025. this.loops = 10;
  67026. this.current = 0;
  67027. this.running = false;
  67028. this.renderOnce = true;
  67029. this.bulbVert ? this.render() : this.renderAlt();
  67030. if (this.bulbVert) {
  67031. this.offsetY = -90;
  67032. this.startY = 190 + this.offsetY;
  67033. this.renderOnce = true;
  67034. this.render();
  67035. } else {
  67036. this.altOffset = 300;
  67037. this.size();
  67038. this.renderAlt();
  67039. }
  67040. }
  67041. _createClass(WiresRight, [{
  67042. key: 'render',
  67043. value: function render(once) {
  67044. this.context.clearRect(0, 0, this.width, this.height);
  67045. this.context.lineWidth = 3;
  67046. for (var index = 0; index < 3; index += 1) {
  67047. var startY = this.startY + this.startSpace * index;
  67048. var start = {
  67049. x: this.startX,
  67050. y: this.startY + this.startSpace * index
  67051. };
  67052. var end = {
  67053. x: this.endX,
  67054. y: this.endY + this.endSpace * index
  67055. };
  67056. var cp1 = {
  67057. x: 5,
  67058. y: start.y
  67059. };
  67060. var cp2 = {
  67061. x: 25,
  67062. y: end.y
  67063. };
  67064. this.context.strokeStyle = '#cfd1d2';
  67065. this.context.beginPath();
  67066. this.context.moveTo(start.x, start.y);
  67067. this.context.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y);
  67068. this.context.stroke();
  67069. }
  67070. if (this.renderOnce) {
  67071. this.renderOnce = false;
  67072. } else {
  67073. if (this.current < this.loops) {
  67074. this.current += 1;
  67075. } else {
  67076. this.dehighlight();
  67077. }
  67078. this.running = true;
  67079. this.timer = requestAnimationFrame(this.render.bind(this));
  67080. }
  67081. }
  67082. }, {
  67083. key: 'renderAlt',
  67084. value: function renderAlt(once) {
  67085. this.context.clearRect(0, 0, this.width, this.height);
  67086. this.context.lineWidth = 3;
  67087. for (var index = 0; index < 4; index += 1) {
  67088. var startY = this.startY + this.startSpace * index;
  67089. var start = {
  67090. x: this.startX,
  67091. y: this.startY + this.startSpace * index
  67092. };
  67093. var end = {
  67094. x: this.endX,
  67095. y: this.endY + this.endSpace * index
  67096. };
  67097. this.context.strokeStyle = '#cfd1d2';
  67098. this.context.beginPath();
  67099. this.context.moveTo(start.x, start.y);
  67100. this.context.lineTo(end.x, start.y);
  67101. this.context.stroke();
  67102. }
  67103. if (this.renderOnce) {
  67104. this.renderOnce = false;
  67105. } else {
  67106. if (this.current < this.loops) {
  67107. this.current += 1;
  67108. } else {
  67109. this.dehighlight();
  67110. }
  67111. this.timer = requestAnimationFrame(this.renderAlt.bind(this));
  67112. }
  67113. }
  67114. }, {
  67115. key: 'highlight',
  67116. value: function highlight(id) {
  67117. var index = _config2.default.classNames.indexOf(id);
  67118. // console.log(index);
  67119. // if (this.animator[index]) {
  67120. // let animator = this.animator[index];
  67121. // animator.bulb.classList.add('wires__bulb--selected');
  67122. // this.highlightedLineIndex = index;
  67123. // this.current = 0;
  67124. // this.start();
  67125. // }
  67126. switch (index) {
  67127. case 0:
  67128. this.bulbGreen.classList.add('bulb--selected');
  67129. break;
  67130. case 1:
  67131. this.bulbOrange.classList.add('bulb--selected');
  67132. break;
  67133. case 2:
  67134. this.bulbPurple.classList.add('bulb--selected');
  67135. break;
  67136. default:
  67137. }
  67138. }
  67139. }, {
  67140. key: 'dehighlight',
  67141. value: function dehighlight() {
  67142. this.bulbGreen.classList.remove('bulb--selected');
  67143. this.bulbPurple.classList.remove('bulb--selected');
  67144. this.bulbOrange.classList.remove('bulb--selected');
  67145. }
  67146. }, {
  67147. key: 'start',
  67148. value: function start() {
  67149. if (!this.running) {
  67150. this.timer = requestAnimationFrame(this.bulbVert ? this.render.bind(this) : this.renderAlt.bind(this));
  67151. }
  67152. }
  67153. }, {
  67154. key: 'stop',
  67155. value: function stop() {
  67156. cancelAnimationFrame(this.timer);
  67157. this.running = false;
  67158. }
  67159. }, {
  67160. key: 'size',
  67161. value: function size() {
  67162. var _this2 = this;
  67163. var BREAKPOINT_DESKTOP = 900;
  67164. var BREAKPOINT_MED = 428;
  67165. this.width = this.element.offsetWidth;
  67166. var bulbs = Array.from(document.getElementsByClassName('wires__bulb'));
  67167. this.startSpace = (this.height - 80) / 3;
  67168. // console.log(this.startSpace);
  67169. this.startSpace = 130;
  67170. this.endSpace = (this.height + 45) / 5;
  67171. this.canvas.width = 70;
  67172. this.canvas.height = this.height;
  67173. // this element rotated in css and using height as width
  67174. // if (window.innerWidth >= BREAKPOINT_DESKTOP) {
  67175. this.height = 450;
  67176. // remove offset on desktop
  67177. this.element.setAttribute('style', '');
  67178. bulbs.forEach(function (bulb, index) {
  67179. bulb.style.top = _this2.endY + index * _this2.endSpace + 'px';
  67180. });
  67181. this.bulbVert = true;
  67182. this.startX = 0;
  67183. this.startY = 190 + this.offsetY;
  67184. // this.endSpace = this.height / 5;
  67185. this.endX = this.width;
  67186. // this.endY = (this.height / 2) - (2 * this.endSpace) + 25;
  67187. this.endY = 145;
  67188. if (window.innerWidth <= BREAKPOINT_DESKTOP) {
  67189. this.canvas.style.display = 'none';
  67190. bulbs.forEach(function (bulb, index) {
  67191. bulb.style.top = 'none';
  67192. });
  67193. }
  67194. }
  67195. }]);
  67196. return WiresRight;
  67197. }();
  67198. exports.default = WiresRight;
  67199. },{"./../../config.js":242}],268:[function(require,module,exports){
  67200. 'use strict';
  67201. Object.defineProperty(exports, "__esModule", {
  67202. value: true
  67203. });
  67204. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  67205. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  67206. // Copyright 2017 Google Inc.
  67207. //
  67208. // Licensed under the Apache License, Version 2.0 (the "License");
  67209. // you may not use this file except in compliance with the License.
  67210. // You may obtain a copy of the License at
  67211. //
  67212. // http://www.apache.org/licenses/LICENSE-2.0
  67213. //
  67214. // Unless required by applicable law or agreed to in writing, software
  67215. // distributed under the License is distributed on an "AS IS" BASIS,
  67216. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  67217. // See the License for the specific language governing permissions and
  67218. // limitations under the License.
  67219. var WizardGIFExample = function () {
  67220. function WizardGIFExample(url) {
  67221. _classCallCheck(this, WizardGIFExample);
  67222. this.element = document.createElement('div');
  67223. this.element.classList.add('wizard__gif');
  67224. var mask = document.createElement('div');
  67225. mask.classList.add('wizard__gif-mask');
  67226. var image = new Image();
  67227. image.classList.add('wizard__gif-image');
  67228. image.src = url;
  67229. mask.appendChild(image);
  67230. this.element.appendChild(mask);
  67231. }
  67232. _createClass(WizardGIFExample, [{
  67233. key: 'show',
  67234. value: function show() {
  67235. this.element.style.display = 'block';
  67236. }
  67237. }, {
  67238. key: 'hide',
  67239. value: function hide() {
  67240. this.element.style.display = 'none';
  67241. }
  67242. }]);
  67243. return WizardGIFExample;
  67244. }();
  67245. exports.default = WizardGIFExample;
  67246. },{}],269:[function(require,module,exports){
  67247. 'use strict';
  67248. Object.defineProperty(exports, "__esModule", {
  67249. value: true
  67250. });
  67251. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  67252. var _gsap = require('gsap');
  67253. var _gsap2 = _interopRequireDefault(_gsap);
  67254. var _ScrollToPlugin = require('gsap/ScrollToPlugin');
  67255. var _ScrollToPlugin2 = _interopRequireDefault(_ScrollToPlugin);
  67256. var _config = require('./../../../config.js');
  67257. var _config2 = _interopRequireDefault(_config);
  67258. var _Button = require('./../../components/Button.js');
  67259. var _Button2 = _interopRequireDefault(_Button);
  67260. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  67261. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  67262. // Copyright 2017 Google Inc.
  67263. //
  67264. // Licensed under the Apache License, Version 2.0 (the "License");
  67265. // you may not use this file except in compliance with the License.
  67266. // You may obtain a copy of the License at
  67267. //
  67268. // http://www.apache.org/licenses/LICENSE-2.0
  67269. //
  67270. // Unless required by applicable law or agreed to in writing, software
  67271. // distributed under the License is distributed on an "AS IS" BASIS,
  67272. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  67273. // See the License for the specific language governing permissions and
  67274. // limitations under the License.
  67275. var LaunchScreen = function () {
  67276. function LaunchScreen() {
  67277. _classCallCheck(this, LaunchScreen);
  67278. this.element = document.querySelector('.intro');
  67279. this.startButton = new _Button2.default(document.querySelector('#start-tutorial-button'));
  67280. this.skipButton = document.querySelector('#skip-tutorial-button');
  67281. this.skipButtonMobile = document.querySelector('#skip-tutorial-button-mobile');
  67282. this.messageIsCompatible = document.querySelector('#is-compatible');
  67283. this.messageIsNotCompatible = document.querySelector('#is-not-compatible');
  67284. this.startButton.element.classList.add('button--disabled');
  67285. document.querySelector('.wizard__launch-skip-paragraph').style.display = 'none';
  67286. document.querySelector('.wizard__browser-warning').style.display = 'block';
  67287. // let facebookButton = document.querySelector('.intro__share-link--facebook');
  67288. // let twitterButton = document.querySelector('.intro__share-link--twitter');
  67289. var intro = document.querySelector('.intro__content-mobile');
  67290. /*eslint-disable */
  67291. var defaultPrevent = function defaultPrevent(event) {
  67292. event.preventDefault();
  67293. };
  67294. /* eslint-enable*/
  67295. intro.addEventListener('touchstart', defaultPrevent);
  67296. intro.addEventListener('touchmove', defaultPrevent);
  67297. // let loader = ((el) => {
  67298. // let ajax = new XMLHttpRequest();
  67299. // ajax.open('GET', 'assets/social-facebook.svg', true);
  67300. // ajax.onload = (event) => {
  67301. // el.innerHTML = ajax.responseText;
  67302. // };
  67303. // ajax.send();
  67304. // })(facebookButton);
  67305. // loader = ((el) => {
  67306. // let ajax = new XMLHttpRequest();
  67307. // ajax.open('GET', 'assets/social-twitter.svg', true);
  67308. // ajax.onload = (event) => {
  67309. // el.innerHTML = ajax.responseText;
  67310. // };
  67311. // ajax.send();
  67312. // })(twitterButton);
  67313. // facebookButton.addEventListener('click', this.openFacebookPopup.bind(this));
  67314. // twitterButton.addEventListener('click', this.openTwitterPopup.bind(this));
  67315. if (_config2.default.browserUtils.isCompatible === true && _config2.default.browserUtils.isMobile === false) {
  67316. this.startButton.element.classList.remove('button--disabled');
  67317. document.querySelector('.wizard__launch-skip-paragraph').style.display = 'block';
  67318. document.querySelector('.wizard__browser-warning').style.display = 'none';
  67319. }
  67320. if (_config2.default.browserUtils.isMobile) {
  67321. this.messageIsCompatible.style.display = 'block';
  67322. } else {
  67323. this.messageIsCompatible.style.display = 'none';
  67324. }
  67325. if (_config2.default.browserUtils.isMobile && !_config2.default.browserUtils.isCompatible) {
  67326. this.messageIsCompatible.style.display = 'none';
  67327. this.messageIsNotCompatible.style.display = 'block';
  67328. }
  67329. this.skipButton.addEventListener('click', this.skipClick.bind(this));
  67330. this.skipButtonMobile.addEventListener('touchend', this.skipClick.bind(this));
  67331. this.skipButtonMobile.addEventListener('click', this.skipClick.bind(this));
  67332. this.startButton.element.addEventListener('click', this.startClick.bind(this));
  67333. this.startButton.element.addEventListener('touchend', this.startClick.bind(this));
  67334. this.startButton.click();
  67335. }
  67336. // openFacebookPopup(event) {
  67337. // event.preventDefault();
  67338. // let url = event.currentTarget.getAttribute('href');
  67339. // /* eslint-disable space-infix-ops */
  67340. // window.open(url, 'fbShareWindow', 'height=450, width=550, top='+(window.innerHeight/2-275)+', left='+(window.innerWidth/2-225)+',toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
  67341. // /* eslint-enable space-infix-ops */
  67342. // }
  67343. // openTwitterPopup(event) {
  67344. // event.preventDefault();
  67345. // let url = event.currentTarget.getAttribute('href');
  67346. // /* eslint-disable space-infix-ops */
  67347. // window.open(url, 'fbShareWindow', 'height=450, width=600, top='+(window.innerHeight/2-150)+', left='+(window.innerWidth/2-225)+', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
  67348. // /* eslint-enable space-infix-ops */
  67349. // }
  67350. _createClass(LaunchScreen, [{
  67351. key: 'skipClick',
  67352. value: function skipClick(event) {
  67353. var _this = this;
  67354. event.preventDefault();
  67355. var intro = document.querySelector('.intro');
  67356. var offset = intro.offsetHeight;
  67357. _config2.default.wizard.skip();
  67358. gtag('event', 'wizard_skip');
  67359. if (_config2.default.browserUtils.isMobile) {
  67360. var msg = new SpeechSynthesisUtterance();
  67361. msg.text = ' ';
  67362. window.speechSynthesis.speak(msg);
  67363. _config2.default.inputSection.createCamInput();
  67364. _config2.default.camInput.start();
  67365. var _event = new CustomEvent('mobileLaunch');
  67366. window.dispatchEvent(_event);
  67367. }
  67368. _gsap2.default.to(intro, 0.5, {
  67369. y: -offset,
  67370. onComplete: function onComplete() {
  67371. _this.destroy();
  67372. if (!_config2.default.browserUtils.isMobile) {
  67373. _config2.default.wizard.startCamera();
  67374. }
  67375. }
  67376. });
  67377. }
  67378. }, {
  67379. key: 'destroy',
  67380. value: function destroy() {
  67381. document.body.classList.remove('no-scroll');
  67382. this.element.style.display = 'none';
  67383. }
  67384. }, {
  67385. key: 'startClick',
  67386. value: function startClick() {
  67387. var _this2 = this;
  67388. var intro = document.querySelector('.intro');
  67389. var offset = intro.offsetHeight;
  67390. if (_config2.default.browserUtils.isMobile || _config2.default.browserUtils.isSafari) {
  67391. _config2.default.inputSection.createCamInput();
  67392. _config2.default.camInput.start();
  67393. _config2.default.wizard.touchPlay();
  67394. var event = new CustomEvent('mobileLaunch');
  67395. window.dispatchEvent(event);
  67396. }
  67397. _gsap2.default.to(intro, 0.5, {
  67398. y: -offset,
  67399. onComplete: function onComplete() {
  67400. _this2.destroy();
  67401. _config2.default.wizard.start();
  67402. _this2.skipButton.click();
  67403. }
  67404. });
  67405. }
  67406. }]);
  67407. return LaunchScreen;
  67408. }();
  67409. exports.default = LaunchScreen;
  67410. },{"./../../../config.js":242,"./../../components/Button.js":252,"gsap":212,"gsap/ScrollToPlugin":210}],270:[function(require,module,exports){
  67411. 'use strict';
  67412. Object.defineProperty(exports, "__esModule", {
  67413. value: true
  67414. });
  67415. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  67416. var _gsap = require('gsap');
  67417. var _gsap2 = _interopRequireDefault(_gsap);
  67418. var _ScrollToPlugin = require('gsap/ScrollToPlugin');
  67419. var _ScrollToPlugin2 = _interopRequireDefault(_ScrollToPlugin);
  67420. var _config = require('./../../../config.js');
  67421. var _config2 = _interopRequireDefault(_config);
  67422. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  67423. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  67424. // Copyright 2017 Google Inc.
  67425. //
  67426. // Licensed under the Apache License, Version 2.0 (the "License");
  67427. // you may not use this file except in compliance with the License.
  67428. // You may obtain a copy of the License at
  67429. //
  67430. // http://www.apache.org/licenses/LICENSE-2.0
  67431. //
  67432. // Unless required by applicable law or agreed to in writing, software
  67433. // distributed under the License is distributed on an "AS IS" BASIS,
  67434. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  67435. // See the License for the specific language governing permissions and
  67436. // limitations under the License.
  67437. var QuickLaunch = function () {
  67438. function QuickLaunch() {
  67439. _classCallCheck(this, QuickLaunch);
  67440. this.machine = document.querySelector('.machine');
  67441. this.wrapper = document.querySelector('.wrapper');
  67442. this.size();
  67443. this.resizeEvent = this.size.bind(this);
  67444. window.addEventListener('resize', this.resizeEvent);
  67445. }
  67446. _createClass(QuickLaunch, [{
  67447. key: 'start',
  67448. value: function start() {
  67449. _config2.default.inputSection.enable();
  67450. _config2.default.inputSection.hideGif(0);
  67451. _config2.default.inputSection.hideGif(1);
  67452. _config2.default.inputSection.hideGif(2);
  67453. _config2.default.inputSection.hideGif(3);
  67454. _config2.default.inputSection.undim();
  67455. _config2.default.learningSection.dehighlight();
  67456. _config2.default.learningSection.dehighlightClass(0);
  67457. _config2.default.learningSection.dehighlightClass(1);
  67458. _config2.default.learningSection.dehighlightClass(2);
  67459. _config2.default.learningSection.enable();
  67460. _config2.default.learningSection.enableClass(0);
  67461. _config2.default.learningSection.enableClass(1);
  67462. _config2.default.learningSection.enableClass(2);
  67463. _config2.default.learningSection.undim();
  67464. _config2.default.outputSection.dehighlight();
  67465. _config2.default.outputSection.enable();
  67466. _config2.default.outputSection.undim();
  67467. if (_config2.default.browserUtils.isMobile || _config2.default.browserUtils.isSafari) {
  67468. _config2.default.inputSection.createCamInput();
  67469. var event = new CustomEvent("mobileLaunch");
  67470. window.dispatchEvent(event);
  67471. }
  67472. window.removeEventListener("class-trained", this.classTrainedEvent);
  67473. // setTimeout(() => {
  67474. // document.querySelector(".webcam--off").click();
  67475. // }, 1000);
  67476. }
  67477. }, {
  67478. key: 'size',
  67479. value: function size() {
  67480. this.wrapper.style.height = window.innerHeight + 'px';
  67481. this.machine.style.top = (window.innerHeight - this.machine.offsetHeight) / 2 + 'px';
  67482. }
  67483. }]);
  67484. return QuickLaunch;
  67485. }();
  67486. // import Button from './../../components/Button.js';
  67487. exports.default = QuickLaunch;
  67488. },{"./../../../config.js":242,"gsap":212,"gsap/ScrollToPlugin":210}]},{},[243]);