12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899 |
- (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.GraphiQL = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
- (function (global){
- 'use strict';
- // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
- // original notice:
- /*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
- * @license MIT
- */
- function compare(a, b) {
- if (a === b) {
- return 0;
- }
- var x = a.length;
- var y = b.length;
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i];
- y = b[i];
- break;
- }
- }
- if (x < y) {
- return -1;
- }
- if (y < x) {
- return 1;
- }
- return 0;
- }
- function isBuffer(b) {
- if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
- return global.Buffer.isBuffer(b);
- }
- return !!(b != null && b._isBuffer);
- }
- // based on node assert, original notice:
- // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
- //
- // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
- //
- // Originally from narwhal.js (http://narwhaljs.org)
- // Copyright (c) 2009 Thomas Robinson <280north.com>
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the 'Software'), to
- // deal in the Software without restriction, including without limitation the
- // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- // sell copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
- // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- var util = require('util/');
- var hasOwn = Object.prototype.hasOwnProperty;
- var pSlice = Array.prototype.slice;
- var functionsHaveNames = (function () {
- return function foo() {}.name === 'foo';
- }());
- function pToString (obj) {
- return Object.prototype.toString.call(obj);
- }
- function isView(arrbuf) {
- if (isBuffer(arrbuf)) {
- return false;
- }
- if (typeof global.ArrayBuffer !== 'function') {
- return false;
- }
- if (typeof ArrayBuffer.isView === 'function') {
- return ArrayBuffer.isView(arrbuf);
- }
- if (!arrbuf) {
- return false;
- }
- if (arrbuf instanceof DataView) {
- return true;
- }
- if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
- return true;
- }
- return false;
- }
- // 1. The assert module provides functions that throw
- // AssertionError's when particular conditions are not met. The
- // assert module must conform to the following interface.
- var assert = module.exports = ok;
- // 2. The AssertionError is defined in assert.
- // new assert.AssertionError({ message: message,
- // actual: actual,
- // expected: expected })
- var regex = /\s*function\s+([^\(\s]*)\s*/;
- // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
- function getName(func) {
- if (!util.isFunction(func)) {
- return;
- }
- if (functionsHaveNames) {
- return func.name;
- }
- var str = func.toString();
- var match = str.match(regex);
- return match && match[1];
- }
- assert.AssertionError = function AssertionError(options) {
- this.name = 'AssertionError';
- this.actual = options.actual;
- this.expected = options.expected;
- this.operator = options.operator;
- if (options.message) {
- this.message = options.message;
- this.generatedMessage = false;
- } else {
- this.message = getMessage(this);
- this.generatedMessage = true;
- }
- var stackStartFunction = options.stackStartFunction || fail;
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, stackStartFunction);
- } else {
- // non v8 browsers so we can have a stacktrace
- var err = new Error();
- if (err.stack) {
- var out = err.stack;
- // try to strip useless frames
- var fn_name = getName(stackStartFunction);
- var idx = out.indexOf('\n' + fn_name);
- if (idx >= 0) {
- // once we have located the function frame
- // we need to strip out everything before it (and its line)
- var next_line = out.indexOf('\n', idx + 1);
- out = out.substring(next_line + 1);
- }
- this.stack = out;
- }
- }
- };
- // assert.AssertionError instanceof Error
- util.inherits(assert.AssertionError, Error);
- function truncate(s, n) {
- if (typeof s === 'string') {
- return s.length < n ? s : s.slice(0, n);
- } else {
- return s;
- }
- }
- function inspect(something) {
- if (functionsHaveNames || !util.isFunction(something)) {
- return util.inspect(something);
- }
- var rawname = getName(something);
- var name = rawname ? ': ' + rawname : '';
- return '[Function' + name + ']';
- }
- function getMessage(self) {
- return truncate(inspect(self.actual), 128) + ' ' +
- self.operator + ' ' +
- truncate(inspect(self.expected), 128);
- }
- // At present only the three keys mentioned above are used and
- // understood by the spec. Implementations or sub modules can pass
- // other keys to the AssertionError's constructor - they will be
- // ignored.
- // 3. All of the following functions must throw an AssertionError
- // when a corresponding condition is not met, with a message that
- // may be undefined if not provided. All assertion methods provide
- // both the actual and expected values to the assertion error for
- // display purposes.
- function fail(actual, expected, message, operator, stackStartFunction) {
- throw new assert.AssertionError({
- message: message,
- actual: actual,
- expected: expected,
- operator: operator,
- stackStartFunction: stackStartFunction
- });
- }
- // EXTENSION! allows for well behaved errors defined elsewhere.
- assert.fail = fail;
- // 4. Pure assertion tests whether a value is truthy, as determined
- // by !!guard.
- // assert.ok(guard, message_opt);
- // This statement is equivalent to assert.equal(true, !!guard,
- // message_opt);. To test strictly for the value true, use
- // assert.strictEqual(true, guard, message_opt);.
- function ok(value, message) {
- if (!value) fail(value, true, message, '==', assert.ok);
- }
- assert.ok = ok;
- // 5. The equality assertion tests shallow, coercive equality with
- // ==.
- // assert.equal(actual, expected, message_opt);
- assert.equal = function equal(actual, expected, message) {
- if (actual != expected) fail(actual, expected, message, '==', assert.equal);
- };
- // 6. The non-equality assertion tests for whether two objects are not equal
- // with != assert.notEqual(actual, expected, message_opt);
- assert.notEqual = function notEqual(actual, expected, message) {
- if (actual == expected) {
- fail(actual, expected, message, '!=', assert.notEqual);
- }
- };
- // 7. The equivalence assertion tests a deep equality relation.
- // assert.deepEqual(actual, expected, message_opt);
- assert.deepEqual = function deepEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'deepEqual', assert.deepEqual);
- }
- };
- assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
- }
- };
- function _deepEqual(actual, expected, strict, memos) {
- // 7.1. All identical values are equivalent, as determined by ===.
- if (actual === expected) {
- return true;
- } else if (isBuffer(actual) && isBuffer(expected)) {
- return compare(actual, expected) === 0;
- // 7.2. If the expected value is a Date object, the actual value is
- // equivalent if it is also a Date object that refers to the same time.
- } else if (util.isDate(actual) && util.isDate(expected)) {
- return actual.getTime() === expected.getTime();
- // 7.3 If the expected value is a RegExp object, the actual value is
- // equivalent if it is also a RegExp object with the same source and
- // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
- } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
- return actual.source === expected.source &&
- actual.global === expected.global &&
- actual.multiline === expected.multiline &&
- actual.lastIndex === expected.lastIndex &&
- actual.ignoreCase === expected.ignoreCase;
- // 7.4. Other pairs that do not both pass typeof value == 'object',
- // equivalence is determined by ==.
- } else if ((actual === null || typeof actual !== 'object') &&
- (expected === null || typeof expected !== 'object')) {
- return strict ? actual === expected : actual == expected;
- // If both values are instances of typed arrays, wrap their underlying
- // ArrayBuffers in a Buffer each to increase performance
- // This optimization requires the arrays to have the same type as checked by
- // Object.prototype.toString (aka pToString). Never perform binary
- // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
- // bit patterns are not identical.
- } else if (isView(actual) && isView(expected) &&
- pToString(actual) === pToString(expected) &&
- !(actual instanceof Float32Array ||
- actual instanceof Float64Array)) {
- return compare(new Uint8Array(actual.buffer),
- new Uint8Array(expected.buffer)) === 0;
- // 7.5 For all other Object pairs, including Array objects, equivalence is
- // determined by having the same number of owned properties (as verified
- // with Object.prototype.hasOwnProperty.call), the same set of keys
- // (although not necessarily the same order), equivalent values for every
- // corresponding key, and an identical 'prototype' property. Note: this
- // accounts for both named and indexed properties on Arrays.
- } else if (isBuffer(actual) !== isBuffer(expected)) {
- return false;
- } else {
- memos = memos || {actual: [], expected: []};
- var actualIndex = memos.actual.indexOf(actual);
- if (actualIndex !== -1) {
- if (actualIndex === memos.expected.indexOf(expected)) {
- return true;
- }
- }
- memos.actual.push(actual);
- memos.expected.push(expected);
- return objEquiv(actual, expected, strict, memos);
- }
- }
- function isArguments(object) {
- return Object.prototype.toString.call(object) == '[object Arguments]';
- }
- function objEquiv(a, b, strict, actualVisitedObjects) {
- if (a === null || a === undefined || b === null || b === undefined)
- return false;
- // if one is a primitive, the other must be same
- if (util.isPrimitive(a) || util.isPrimitive(b))
- return a === b;
- if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
- return false;
- var aIsArgs = isArguments(a);
- var bIsArgs = isArguments(b);
- if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
- return false;
- if (aIsArgs) {
- a = pSlice.call(a);
- b = pSlice.call(b);
- return _deepEqual(a, b, strict);
- }
- var ka = objectKeys(a);
- var kb = objectKeys(b);
- var key, i;
- // having the same number of owned properties (keys incorporates
- // hasOwnProperty)
- if (ka.length !== kb.length)
- return false;
- //the same set of keys (although not necessarily the same order),
- ka.sort();
- kb.sort();
- //~~~cheap key test
- for (i = ka.length - 1; i >= 0; i--) {
- if (ka[i] !== kb[i])
- return false;
- }
- //equivalent values for every corresponding key, and
- //~~~possibly expensive deep test
- for (i = ka.length - 1; i >= 0; i--) {
- key = ka[i];
- if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
- return false;
- }
- return true;
- }
- // 8. The non-equivalence assertion tests for any deep inequality.
- // assert.notDeepEqual(actual, expected, message_opt);
- assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
- }
- };
- assert.notDeepStrictEqual = notDeepStrictEqual;
- function notDeepStrictEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
- }
- }
- // 9. The strict equality assertion tests strict equality, as determined by ===.
- // assert.strictEqual(actual, expected, message_opt);
- assert.strictEqual = function strictEqual(actual, expected, message) {
- if (actual !== expected) {
- fail(actual, expected, message, '===', assert.strictEqual);
- }
- };
- // 10. The strict non-equality assertion tests for strict inequality, as
- // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
- assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
- if (actual === expected) {
- fail(actual, expected, message, '!==', assert.notStrictEqual);
- }
- };
- function expectedException(actual, expected) {
- if (!actual || !expected) {
- return false;
- }
- if (Object.prototype.toString.call(expected) == '[object RegExp]') {
- return expected.test(actual);
- }
- try {
- if (actual instanceof expected) {
- return true;
- }
- } catch (e) {
- // Ignore. The instanceof check doesn't work for arrow functions.
- }
- if (Error.isPrototypeOf(expected)) {
- return false;
- }
- return expected.call({}, actual) === true;
- }
- function _tryBlock(block) {
- var error;
- try {
- block();
- } catch (e) {
- error = e;
- }
- return error;
- }
- function _throws(shouldThrow, block, expected, message) {
- var actual;
- if (typeof block !== 'function') {
- throw new TypeError('"block" argument must be a function');
- }
- if (typeof expected === 'string') {
- message = expected;
- expected = null;
- }
- actual = _tryBlock(block);
- message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
- (message ? ' ' + message : '.');
- if (shouldThrow && !actual) {
- fail(actual, expected, 'Missing expected exception' + message);
- }
- var userProvidedMessage = typeof message === 'string';
- var isUnwantedException = !shouldThrow && util.isError(actual);
- var isUnexpectedException = !shouldThrow && actual && !expected;
- if ((isUnwantedException &&
- userProvidedMessage &&
- expectedException(actual, expected)) ||
- isUnexpectedException) {
- fail(actual, expected, 'Got unwanted exception' + message);
- }
- if ((shouldThrow && actual && expected &&
- !expectedException(actual, expected)) || (!shouldThrow && actual)) {
- throw actual;
- }
- }
- // 11. Expected to throw an error:
- // assert.throws(block, Error_opt, message_opt);
- assert.throws = function(block, /*optional*/error, /*optional*/message) {
- _throws(true, block, error, message);
- };
- // EXTENSION! This is annoying to write outside this module.
- assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
- _throws(false, block, error, message);
- };
- assert.ifError = function(err) { if (err) throw err; };
- var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- if (hasOwn.call(obj, key)) keys.push(key);
- }
- return keys;
- };
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"util/":216}],2:[function(require,module,exports){
- (function (global){
- /*! https://mths.be/punycode v1.4.1 by @mathias */
- ;(function(root) {
- /** Detect free variables */
- var freeExports = typeof exports == 'object' && exports &&
- !exports.nodeType && exports;
- var freeModule = typeof module == 'object' && module &&
- !module.nodeType && module;
- var freeGlobal = typeof global == 'object' && global;
- if (
- freeGlobal.global === freeGlobal ||
- freeGlobal.window === freeGlobal ||
- freeGlobal.self === freeGlobal
- ) {
- root = freeGlobal;
- }
- /**
- * The `punycode` object.
- * @name punycode
- * @type Object
- */
- var punycode,
- /** Highest positive signed 32-bit float value */
- maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
- /** Bootstring parameters */
- base = 36,
- tMin = 1,
- tMax = 26,
- skew = 38,
- damp = 700,
- initialBias = 72,
- initialN = 128, // 0x80
- delimiter = '-', // '\x2D'
- /** Regular expressions */
- regexPunycode = /^xn--/,
- regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
- regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
- /** Error messages */
- errors = {
- 'overflow': 'Overflow: input needs wider integers to process',
- 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
- 'invalid-input': 'Invalid input'
- },
- /** Convenience shortcuts */
- baseMinusTMin = base - tMin,
- floor = Math.floor,
- stringFromCharCode = String.fromCharCode,
- /** Temporary variable */
- key;
- /*--------------------------------------------------------------------------*/
- /**
- * A generic error utility function.
- * @private
- * @param {String} type The error type.
- * @returns {Error} Throws a `RangeError` with the applicable error message.
- */
- function error(type) {
- throw new RangeError(errors[type]);
- }
- /**
- * A generic `Array#map` utility function.
- * @private
- * @param {Array} array The array to iterate over.
- * @param {Function} callback The function that gets called for every array
- * item.
- * @returns {Array} A new array of values returned by the callback function.
- */
- function map(array, fn) {
- var length = array.length;
- var result = [];
- while (length--) {
- result[length] = fn(array[length]);
- }
- return result;
- }
- /**
- * A simple `Array#map`-like wrapper to work with domain name strings or email
- * addresses.
- * @private
- * @param {String} domain The domain name or email address.
- * @param {Function} callback The function that gets called for every
- * character.
- * @returns {Array} A new string of characters returned by the callback
- * function.
- */
- function mapDomain(string, fn) {
- var parts = string.split('@');
- var result = '';
- if (parts.length > 1) {
- // In email addresses, only the domain name should be punycoded. Leave
- // the local part (i.e. everything up to `@`) intact.
- result = parts[0] + '@';
- string = parts[1];
- }
- // Avoid `split(regex)` for IE8 compatibility. See #17.
- string = string.replace(regexSeparators, '\x2E');
- var labels = string.split('.');
- var encoded = map(labels, fn).join('.');
- return result + encoded;
- }
- /**
- * Creates an array containing the numeric code points of each Unicode
- * character in the string. While JavaScript uses UCS-2 internally,
- * this function will convert a pair of surrogate halves (each of which
- * UCS-2 exposes as separate characters) into a single code point,
- * matching UTF-16.
- * @see `punycode.ucs2.encode`
- * @see <https://mathiasbynens.be/notes/javascript-encoding>
- * @memberOf punycode.ucs2
- * @name decode
- * @param {String} string The Unicode input string (UCS-2).
- * @returns {Array} The new array of code points.
- */
- function ucs2decode(string) {
- var output = [],
- counter = 0,
- length = string.length,
- value,
- extra;
- while (counter < length) {
- value = string.charCodeAt(counter++);
- if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
- // high surrogate, and there is a next character
- extra = string.charCodeAt(counter++);
- if ((extra & 0xFC00) == 0xDC00) { // low surrogate
- output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
- } else {
- // unmatched surrogate; only append this code unit, in case the next
- // code unit is the high surrogate of a surrogate pair
- output.push(value);
- counter--;
- }
- } else {
- output.push(value);
- }
- }
- return output;
- }
- /**
- * Creates a string based on an array of numeric code points.
- * @see `punycode.ucs2.decode`
- * @memberOf punycode.ucs2
- * @name encode
- * @param {Array} codePoints The array of numeric code points.
- * @returns {String} The new Unicode string (UCS-2).
- */
- function ucs2encode(array) {
- return map(array, function(value) {
- var output = '';
- if (value > 0xFFFF) {
- value -= 0x10000;
- output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
- value = 0xDC00 | value & 0x3FF;
- }
- output += stringFromCharCode(value);
- return output;
- }).join('');
- }
- /**
- * Converts a basic code point into a digit/integer.
- * @see `digitToBasic()`
- * @private
- * @param {Number} codePoint The basic numeric code point value.
- * @returns {Number} The numeric value of a basic code point (for use in
- * representing integers) in the range `0` to `base - 1`, or `base` if
- * the code point does not represent a value.
- */
- function basicToDigit(codePoint) {
- if (codePoint - 48 < 10) {
- return codePoint - 22;
- }
- if (codePoint - 65 < 26) {
- return codePoint - 65;
- }
- if (codePoint - 97 < 26) {
- return codePoint - 97;
- }
- return base;
- }
- /**
- * Converts a digit/integer into a basic code point.
- * @see `basicToDigit()`
- * @private
- * @param {Number} digit The numeric value of a basic code point.
- * @returns {Number} The basic code point whose value (when used for
- * representing integers) is `digit`, which needs to be in the range
- * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
- * used; else, the lowercase form is used. The behavior is undefined
- * if `flag` is non-zero and `digit` has no uppercase form.
- */
- function digitToBasic(digit, flag) {
- // 0..25 map to ASCII a..z or A..Z
- // 26..35 map to ASCII 0..9
- return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
- }
- /**
- * Bias adaptation function as per section 3.4 of RFC 3492.
- * https://tools.ietf.org/html/rfc3492#section-3.4
- * @private
- */
- function adapt(delta, numPoints, firstTime) {
- var k = 0;
- delta = firstTime ? floor(delta / damp) : delta >> 1;
- delta += floor(delta / numPoints);
- for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
- delta = floor(delta / baseMinusTMin);
- }
- return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
- }
- /**
- * Converts a Punycode string of ASCII-only symbols to a string of Unicode
- * symbols.
- * @memberOf punycode
- * @param {String} input The Punycode string of ASCII-only symbols.
- * @returns {String} The resulting string of Unicode symbols.
- */
- function decode(input) {
- // Don't use UCS-2
- var output = [],
- inputLength = input.length,
- out,
- i = 0,
- n = initialN,
- bias = initialBias,
- basic,
- j,
- index,
- oldi,
- w,
- k,
- digit,
- t,
- /** Cached calculation results */
- baseMinusT;
- // Handle the basic code points: let `basic` be the number of input code
- // points before the last delimiter, or `0` if there is none, then copy
- // the first basic code points to the output.
- basic = input.lastIndexOf(delimiter);
- if (basic < 0) {
- basic = 0;
- }
- for (j = 0; j < basic; ++j) {
- // if it's not a basic code point
- if (input.charCodeAt(j) >= 0x80) {
- error('not-basic');
- }
- output.push(input.charCodeAt(j));
- }
- // Main decoding loop: start just after the last delimiter if any basic code
- // points were copied; start at the beginning otherwise.
- for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
- // `index` is the index of the next character to be consumed.
- // Decode a generalized variable-length integer into `delta`,
- // which gets added to `i`. The overflow checking is easier
- // if we increase `i` as we go, then subtract off its starting
- // value at the end to obtain `delta`.
- for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
- if (index >= inputLength) {
- error('invalid-input');
- }
- digit = basicToDigit(input.charCodeAt(index++));
- if (digit >= base || digit > floor((maxInt - i) / w)) {
- error('overflow');
- }
- i += digit * w;
- t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
- if (digit < t) {
- break;
- }
- baseMinusT = base - t;
- if (w > floor(maxInt / baseMinusT)) {
- error('overflow');
- }
- w *= baseMinusT;
- }
- out = output.length + 1;
- bias = adapt(i - oldi, out, oldi == 0);
- // `i` was supposed to wrap around from `out` to `0`,
- // incrementing `n` each time, so we'll fix that now:
- if (floor(i / out) > maxInt - n) {
- error('overflow');
- }
- n += floor(i / out);
- i %= out;
- // Insert `n` at position `i` of the output
- output.splice(i++, 0, n);
- }
- return ucs2encode(output);
- }
- /**
- * Converts a string of Unicode symbols (e.g. a domain name label) to a
- * Punycode string of ASCII-only symbols.
- * @memberOf punycode
- * @param {String} input The string of Unicode symbols.
- * @returns {String} The resulting Punycode string of ASCII-only symbols.
- */
- function encode(input) {
- var n,
- delta,
- handledCPCount,
- basicLength,
- bias,
- j,
- m,
- q,
- k,
- t,
- currentValue,
- output = [],
- /** `inputLength` will hold the number of code points in `input`. */
- inputLength,
- /** Cached calculation results */
- handledCPCountPlusOne,
- baseMinusT,
- qMinusT;
- // Convert the input in UCS-2 to Unicode
- input = ucs2decode(input);
- // Cache the length
- inputLength = input.length;
- // Initialize the state
- n = initialN;
- delta = 0;
- bias = initialBias;
- // Handle the basic code points
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue < 0x80) {
- output.push(stringFromCharCode(currentValue));
- }
- }
- handledCPCount = basicLength = output.length;
- // `handledCPCount` is the number of code points that have been handled;
- // `basicLength` is the number of basic code points.
- // Finish the basic string - if it is not empty - with a delimiter
- if (basicLength) {
- output.push(delimiter);
- }
- // Main encoding loop:
- while (handledCPCount < inputLength) {
- // All non-basic code points < n have been handled already. Find the next
- // larger one:
- for (m = maxInt, j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue >= n && currentValue < m) {
- m = currentValue;
- }
- }
- // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
- // but guard against overflow
- handledCPCountPlusOne = handledCPCount + 1;
- if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
- error('overflow');
- }
- delta += (m - n) * handledCPCountPlusOne;
- n = m;
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue < n && ++delta > maxInt) {
- error('overflow');
- }
- if (currentValue == n) {
- // Represent delta as a generalized variable-length integer
- for (q = delta, k = base; /* no condition */; k += base) {
- t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
- if (q < t) {
- break;
- }
- qMinusT = q - t;
- baseMinusT = base - t;
- output.push(
- stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
- );
- q = floor(qMinusT / baseMinusT);
- }
- output.push(stringFromCharCode(digitToBasic(q, 0)));
- bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
- delta = 0;
- ++handledCPCount;
- }
- }
- ++delta;
- ++n;
- }
- return output.join('');
- }
- /**
- * Converts a Punycode string representing a domain name or an email address
- * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
- * it doesn't matter if you call it on a string that has already been
- * converted to Unicode.
- * @memberOf punycode
- * @param {String} input The Punycoded domain name or email address to
- * convert to Unicode.
- * @returns {String} The Unicode representation of the given Punycode
- * string.
- */
- function toUnicode(input) {
- return mapDomain(input, function(string) {
- return regexPunycode.test(string)
- ? decode(string.slice(4).toLowerCase())
- : string;
- });
- }
- /**
- * Converts a Unicode string representing a domain name or an email address to
- * Punycode. Only the non-ASCII parts of the domain name will be converted,
- * i.e. it doesn't matter if you call it with a domain that's already in
- * ASCII.
- * @memberOf punycode
- * @param {String} input The domain name or email address to convert, as a
- * Unicode string.
- * @returns {String} The Punycode representation of the given domain name or
- * email address.
- */
- function toASCII(input) {
- return mapDomain(input, function(string) {
- return regexNonASCII.test(string)
- ? 'xn--' + encode(string)
- : string;
- });
- }
- /*--------------------------------------------------------------------------*/
- /** Define the public API */
- punycode = {
- /**
- * A string representing the current Punycode.js version number.
- * @memberOf punycode
- * @type String
- */
- 'version': '1.4.1',
- /**
- * An object of methods to convert from JavaScript's internal character
- * representation (UCS-2) to Unicode code points, and back.
- * @see <https://mathiasbynens.be/notes/javascript-encoding>
- * @memberOf punycode
- * @type Object
- */
- 'ucs2': {
- 'decode': ucs2decode,
- 'encode': ucs2encode
- },
- 'decode': decode,
- 'encode': encode,
- 'toASCII': toASCII,
- 'toUnicode': toUnicode
- };
- /** Expose `punycode` */
- // Some AMD build optimizers, like r.js, check for specific condition patterns
- // like the following:
- if (
- typeof define == 'function' &&
- typeof define.amd == 'object' &&
- define.amd
- ) {
- define('punycode', function() {
- return punycode;
- });
- } else if (freeExports && freeModule) {
- if (module.exports == freeExports) {
- // in Node.js, io.js, or RingoJS v0.8.0+
- freeModule.exports = punycode;
- } else {
- // in Narwhal or RingoJS v0.7.0-
- for (key in punycode) {
- punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
- }
- }
- } else {
- // in Rhino or a web browser
- root.punycode = punycode;
- }
- }(this));
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],3:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
- var noOptions = {};
- var nonWS = /[^\s\u00a0]/;
- var Pos = CodeMirror.Pos;
- function firstNonWS(str) {
- var found = str.search(nonWS);
- return found == -1 ? 0 : found;
- }
- CodeMirror.commands.toggleComment = function(cm) {
- cm.toggleComment();
- };
- CodeMirror.defineExtension("toggleComment", function(options) {
- if (!options) options = noOptions;
- var cm = this;
- var minLine = Infinity, ranges = this.listSelections(), mode = null;
- for (var i = ranges.length - 1; i >= 0; i--) {
- var from = ranges[i].from(), to = ranges[i].to();
- if (from.line >= minLine) continue;
- if (to.line >= minLine) to = Pos(minLine, 0);
- minLine = from.line;
- if (mode == null) {
- if (cm.uncomment(from, to, options)) mode = "un";
- else { cm.lineComment(from, to, options); mode = "line"; }
- } else if (mode == "un") {
- cm.uncomment(from, to, options);
- } else {
- cm.lineComment(from, to, options);
- }
- }
- });
- // Rough heuristic to try and detect lines that are part of multi-line string
- function probablyInsideString(cm, pos, line) {
- return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line)
- }
- function getMode(cm, pos) {
- var mode = cm.getMode()
- return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos)
- }
- CodeMirror.defineExtension("lineComment", function(from, to, options) {
- if (!options) options = noOptions;
- var self = this, mode = getMode(self, from);
- var firstLine = self.getLine(from.line);
- if (firstLine == null || probablyInsideString(self, from, firstLine)) return;
- var commentString = options.lineComment || mode.lineComment;
- if (!commentString) {
- if (options.blockCommentStart || mode.blockCommentStart) {
- options.fullLines = true;
- self.blockComment(from, to, options);
- }
- return;
- }
- var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
- var pad = options.padding == null ? " " : options.padding;
- var blankLines = options.commentBlankLines || from.line == to.line;
- self.operation(function() {
- if (options.indent) {
- var baseString = null;
- for (var i = from.line; i < end; ++i) {
- var line = self.getLine(i);
- var whitespace = line.slice(0, firstNonWS(line));
- if (baseString == null || baseString.length > whitespace.length) {
- baseString = whitespace;
- }
- }
- for (var i = from.line; i < end; ++i) {
- var line = self.getLine(i), cut = baseString.length;
- if (!blankLines && !nonWS.test(line)) continue;
- if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
- self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));
- }
- } else {
- for (var i = from.line; i < end; ++i) {
- if (blankLines || nonWS.test(self.getLine(i)))
- self.replaceRange(commentString + pad, Pos(i, 0));
- }
- }
- });
- });
- CodeMirror.defineExtension("blockComment", function(from, to, options) {
- if (!options) options = noOptions;
- var self = this, mode = getMode(self, from);
- var startString = options.blockCommentStart || mode.blockCommentStart;
- var endString = options.blockCommentEnd || mode.blockCommentEnd;
- if (!startString || !endString) {
- if ((options.lineComment || mode.lineComment) && options.fullLines != false)
- self.lineComment(from, to, options);
- return;
- }
- if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return
- var end = Math.min(to.line, self.lastLine());
- if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
- var pad = options.padding == null ? " " : options.padding;
- if (from.line > end) return;
- self.operation(function() {
- if (options.fullLines != false) {
- var lastLineHasText = nonWS.test(self.getLine(end));
- self.replaceRange(pad + endString, Pos(end));
- self.replaceRange(startString + pad, Pos(from.line, 0));
- var lead = options.blockCommentLead || mode.blockCommentLead;
- if (lead != null) for (var i = from.line + 1; i <= end; ++i)
- if (i != end || lastLineHasText)
- self.replaceRange(lead + pad, Pos(i, 0));
- } else {
- self.replaceRange(endString, to);
- self.replaceRange(startString, from);
- }
- });
- });
- CodeMirror.defineExtension("uncomment", function(from, to, options) {
- if (!options) options = noOptions;
- var self = this, mode = getMode(self, from);
- var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end);
- // Try finding line comments
- var lineString = options.lineComment || mode.lineComment, lines = [];
- var pad = options.padding == null ? " " : options.padding, didSomething;
- lineComment: {
- if (!lineString) break lineComment;
- for (var i = start; i <= end; ++i) {
- var line = self.getLine(i);
- var found = line.indexOf(lineString);
- if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
- if (found == -1 && nonWS.test(line)) break lineComment;
- if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
- lines.push(line);
- }
- self.operation(function() {
- for (var i = start; i <= end; ++i) {
- var line = lines[i - start];
- var pos = line.indexOf(lineString), endPos = pos + lineString.length;
- if (pos < 0) continue;
- if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;
- didSomething = true;
- self.replaceRange("", Pos(i, pos), Pos(i, endPos));
- }
- });
- if (didSomething) return true;
- }
- // Try block comments
- var startString = options.blockCommentStart || mode.blockCommentStart;
- var endString = options.blockCommentEnd || mode.blockCommentEnd;
- if (!startString || !endString) return false;
- var lead = options.blockCommentLead || mode.blockCommentLead;
- var startLine = self.getLine(start), open = startLine.indexOf(startString)
- if (open == -1) return false
- var endLine = end == start ? startLine : self.getLine(end)
- var close = endLine.indexOf(endString, end == start ? open + startString.length : 0);
- var insideStart = Pos(start, open + 1), insideEnd = Pos(end, close + 1)
- if (close == -1 ||
- !/comment/.test(self.getTokenTypeAt(insideStart)) ||
- !/comment/.test(self.getTokenTypeAt(insideEnd)) ||
- self.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1)
- return false;
- // Avoid killing block comments completely outside the selection.
- // Positions of the last startString before the start of the selection, and the first endString after it.
- var lastStart = startLine.lastIndexOf(startString, from.ch);
- var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length);
- if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false;
- // Positions of the first endString after the end of the selection, and the last startString before it.
- firstEnd = endLine.indexOf(endString, to.ch);
- var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch);
- lastStart = (firstEnd == -1 || almostLastStart == -1) ? -1 : to.ch + almostLastStart;
- if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false;
- self.operation(function() {
- self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
- Pos(end, close + endString.length));
- var openEnd = open + startString.length;
- if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;
- self.replaceRange("", Pos(start, open), Pos(start, openEnd));
- if (lead) for (var i = start + 1; i <= end; ++i) {
- var line = self.getLine(i), found = line.indexOf(lead);
- if (found == -1 || nonWS.test(line.slice(0, found))) continue;
- var foundEnd = found + lead.length;
- if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;
- self.replaceRange("", Pos(i, found), Pos(i, foundEnd));
- }
- });
- return true;
- });
- });
- },{"../../lib/codemirror":16}],4:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- // Open simple dialogs on top of an editor. Relies on dialog.css.
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- function dialogDiv(cm, template, bottom) {
- var wrap = cm.getWrapperElement();
- var dialog;
- dialog = wrap.appendChild(document.createElement("div"));
- if (bottom)
- dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
- else
- dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
- if (typeof template == "string") {
- dialog.innerHTML = template;
- } else { // Assuming it's a detached DOM element.
- dialog.appendChild(template);
- }
- CodeMirror.addClass(wrap, 'dialog-opened');
- return dialog;
- }
- function closeNotification(cm, newVal) {
- if (cm.state.currentNotificationClose)
- cm.state.currentNotificationClose();
- cm.state.currentNotificationClose = newVal;
- }
- CodeMirror.defineExtension("openDialog", function(template, callback, options) {
- if (!options) options = {};
- closeNotification(this, null);
- var dialog = dialogDiv(this, template, options.bottom);
- var closed = false, me = this;
- function close(newVal) {
- if (typeof newVal == 'string') {
- inp.value = newVal;
- } else {
- if (closed) return;
- closed = true;
- CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');
- dialog.parentNode.removeChild(dialog);
- me.focus();
- if (options.onClose) options.onClose(dialog);
- }
- }
- var inp = dialog.getElementsByTagName("input")[0], button;
- if (inp) {
- inp.focus();
- if (options.value) {
- inp.value = options.value;
- if (options.selectValueOnOpen !== false) {
- inp.select();
- }
- }
- if (options.onInput)
- CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
- if (options.onKeyUp)
- CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
- CodeMirror.on(inp, "keydown", function(e) {
- if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
- if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
- inp.blur();
- CodeMirror.e_stop(e);
- close();
- }
- if (e.keyCode == 13) callback(inp.value, e);
- });
- if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
- } else if (button = dialog.getElementsByTagName("button")[0]) {
- CodeMirror.on(button, "click", function() {
- close();
- me.focus();
- });
- if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);
- button.focus();
- }
- return close;
- });
- CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
- closeNotification(this, null);
- var dialog = dialogDiv(this, template, options && options.bottom);
- var buttons = dialog.getElementsByTagName("button");
- var closed = false, me = this, blurring = 1;
- function close() {
- if (closed) return;
- closed = true;
- CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');
- dialog.parentNode.removeChild(dialog);
- me.focus();
- }
- buttons[0].focus();
- for (var i = 0; i < buttons.length; ++i) {
- var b = buttons[i];
- (function(callback) {
- CodeMirror.on(b, "click", function(e) {
- CodeMirror.e_preventDefault(e);
- close();
- if (callback) callback(me);
- });
- })(callbacks[i]);
- CodeMirror.on(b, "blur", function() {
- --blurring;
- setTimeout(function() { if (blurring <= 0) close(); }, 200);
- });
- CodeMirror.on(b, "focus", function() { ++blurring; });
- }
- });
- /*
- * openNotification
- * Opens a notification, that can be closed with an optional timer
- * (default 5000ms timer) and always closes on click.
- *
- * If a notification is opened while another is opened, it will close the
- * currently opened one and open the new one immediately.
- */
- CodeMirror.defineExtension("openNotification", function(template, options) {
- closeNotification(this, close);
- var dialog = dialogDiv(this, template, options && options.bottom);
- var closed = false, doneTimer;
- var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
- function close() {
- if (closed) return;
- closed = true;
- clearTimeout(doneTimer);
- CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');
- dialog.parentNode.removeChild(dialog);
- }
- CodeMirror.on(dialog, 'click', function(e) {
- CodeMirror.e_preventDefault(e);
- close();
- });
- if (duration)
- doneTimer = setTimeout(close, duration);
- return close;
- });
- });
- },{"../../lib/codemirror":16}],5:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- var defaults = {
- pairs: "()[]{}''\"\"",
- closeBefore: ")]}'\":;>",
- triples: "",
- explode: "[]{}"
- };
- var Pos = CodeMirror.Pos;
- CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
- if (old && old != CodeMirror.Init) {
- cm.removeKeyMap(keyMap);
- cm.state.closeBrackets = null;
- }
- if (val) {
- ensureBound(getOption(val, "pairs"))
- cm.state.closeBrackets = val;
- cm.addKeyMap(keyMap);
- }
- });
- function getOption(conf, name) {
- if (name == "pairs" && typeof conf == "string") return conf;
- if (typeof conf == "object" && conf[name] != null) return conf[name];
- return defaults[name];
- }
- var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
- function ensureBound(chars) {
- for (var i = 0; i < chars.length; i++) {
- var ch = chars.charAt(i), key = "'" + ch + "'"
- if (!keyMap[key]) keyMap[key] = handler(ch)
- }
- }
- ensureBound(defaults.pairs + "`")
- function handler(ch) {
- return function(cm) { return handleChar(cm, ch); };
- }
- function getConfig(cm) {
- var deflt = cm.state.closeBrackets;
- if (!deflt || deflt.override) return deflt;
- var mode = cm.getModeAt(cm.getCursor());
- return mode.closeBrackets || deflt;
- }
- function handleBackspace(cm) {
- var conf = getConfig(cm);
- if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
- var pairs = getOption(conf, "pairs");
- var ranges = cm.listSelections();
- for (var i = 0; i < ranges.length; i++) {
- if (!ranges[i].empty()) return CodeMirror.Pass;
- var around = charsAround(cm, ranges[i].head);
- if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
- }
- for (var i = ranges.length - 1; i >= 0; i--) {
- var cur = ranges[i].head;
- cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete");
- }
- }
- function handleEnter(cm) {
- var conf = getConfig(cm);
- var explode = conf && getOption(conf, "explode");
- if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;
- var ranges = cm.listSelections();
- for (var i = 0; i < ranges.length; i++) {
- if (!ranges[i].empty()) return CodeMirror.Pass;
- var around = charsAround(cm, ranges[i].head);
- if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
- }
- cm.operation(function() {
- var linesep = cm.lineSeparator() || "\n";
- cm.replaceSelection(linesep + linesep, null);
- cm.execCommand("goCharLeft");
- ranges = cm.listSelections();
- for (var i = 0; i < ranges.length; i++) {
- var line = ranges[i].head.line;
- cm.indentLine(line, null, true);
- cm.indentLine(line + 1, null, true);
- }
- });
- }
- function contractSelection(sel) {
- var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
- return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
- head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
- }
- function handleChar(cm, ch) {
- var conf = getConfig(cm);
- if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
- var pairs = getOption(conf, "pairs");
- var pos = pairs.indexOf(ch);
- if (pos == -1) return CodeMirror.Pass;
- var closeBefore = getOption(conf,"closeBefore");
- var triples = getOption(conf, "triples");
- var identical = pairs.charAt(pos + 1) == ch;
- var ranges = cm.listSelections();
- var opening = pos % 2 == 0;
- var type;
- for (var i = 0; i < ranges.length; i++) {
- var range = ranges[i], cur = range.head, curType;
- var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
- if (opening && !range.empty()) {
- curType = "surround";
- } else if ((identical || !opening) && next == ch) {
- if (identical && stringStartsAfter(cm, cur))
- curType = "both";
- else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
- curType = "skipThree";
- else
- curType = "skip";
- } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
- cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) {
- if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass;
- curType = "addFour";
- } else if (identical) {
- var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur)
- if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";
- else return CodeMirror.Pass;
- } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) {
- curType = "both";
- } else {
- return CodeMirror.Pass;
- }
- if (!type) type = curType;
- else if (type != curType) return CodeMirror.Pass;
- }
- var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
- var right = pos % 2 ? ch : pairs.charAt(pos + 1);
- cm.operation(function() {
- if (type == "skip") {
- cm.execCommand("goCharRight");
- } else if (type == "skipThree") {
- for (var i = 0; i < 3; i++)
- cm.execCommand("goCharRight");
- } else if (type == "surround") {
- var sels = cm.getSelections();
- for (var i = 0; i < sels.length; i++)
- sels[i] = left + sels[i] + right;
- cm.replaceSelections(sels, "around");
- sels = cm.listSelections().slice();
- for (var i = 0; i < sels.length; i++)
- sels[i] = contractSelection(sels[i]);
- cm.setSelections(sels);
- } else if (type == "both") {
- cm.replaceSelection(left + right, null);
- cm.triggerElectric(left + right);
- cm.execCommand("goCharLeft");
- } else if (type == "addFour") {
- cm.replaceSelection(left + left + left + left, "before");
- cm.execCommand("goCharRight");
- }
- });
- }
- function charsAround(cm, pos) {
- var str = cm.getRange(Pos(pos.line, pos.ch - 1),
- Pos(pos.line, pos.ch + 1));
- return str.length == 2 ? str : null;
- }
- function stringStartsAfter(cm, pos) {
- var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
- return /\bstring/.test(token.type) && token.start == pos.ch &&
- (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos)))
- }
- });
- },{"../../lib/codemirror":16}],6:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
- (document.documentMode == null || document.documentMode < 8);
- var Pos = CodeMirror.Pos;
- var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<", "<": ">>", ">": "<<"};
- function bracketRegex(config) {
- return config && config.bracketRegex || /[(){}[\]]/
- }
- function findMatchingBracket(cm, where, config) {
- var line = cm.getLineHandle(where.line), pos = where.ch - 1;
- var afterCursor = config && config.afterCursor
- if (afterCursor == null)
- afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)
- var re = bracketRegex(config)
- // A cursor is defined as between two characters, but in in vim command mode
- // (i.e. not insert mode), the cursor is visually represented as a
- // highlighted box on top of the 2nd character. Otherwise, we allow matches
- // from before or after the cursor.
- var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) ||
- re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)];
- if (!match) return null;
- var dir = match.charAt(1) == ">" ? 1 : -1;
- if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;
- var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
- var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
- if (found == null) return null;
- return {from: Pos(where.line, pos), to: found && found.pos,
- match: found && found.ch == match.charAt(0), forward: dir > 0};
- }
- // bracketRegex is used to specify which type of bracket to scan
- // should be a regexp, e.g. /[[\]]/
- //
- // Note: If "where" is on an open bracket, then this bracket is ignored.
- //
- // Returns false when no bracket was found, null when it reached
- // maxScanLines and gave up
- function scanForBracket(cm, where, dir, style, config) {
- var maxScanLen = (config && config.maxScanLineLength) || 10000;
- var maxScanLines = (config && config.maxScanLines) || 1000;
- var stack = [];
- var re = bracketRegex(config)
- var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
- : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
- for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
- var line = cm.getLine(lineNo);
- if (!line) continue;
- var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
- if (line.length > maxScanLen) continue;
- if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
- for (; pos != end; pos += dir) {
- var ch = line.charAt(pos);
- if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
- var match = matching[ch];
- if (match && (match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
- else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
- else stack.pop();
- }
- }
- }
- return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
- }
- function matchBrackets(cm, autoclear, config) {
- // Disable brace matching in long lines, since it'll cause hugely slow updates
- var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
- var marks = [], ranges = cm.listSelections();
- for (var i = 0; i < ranges.length; i++) {
- var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
- if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
- var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
- marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
- if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
- marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
- }
- }
- if (marks.length) {
- // Kludge to work around the IE bug from issue #1193, where text
- // input stops going to the textare whever this fires.
- if (ie_lt8 && cm.state.focused) cm.focus();
- var clear = function() {
- cm.operation(function() {
- for (var i = 0; i < marks.length; i++) marks[i].clear();
- });
- };
- if (autoclear) setTimeout(clear, 800);
- else return clear;
- }
- }
- function doMatchBrackets(cm) {
- cm.operation(function() {
- if (cm.state.matchBrackets.currentlyHighlighted) {
- cm.state.matchBrackets.currentlyHighlighted();
- cm.state.matchBrackets.currentlyHighlighted = null;
- }
- cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
- });
- }
- CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
- if (old && old != CodeMirror.Init) {
- cm.off("cursorActivity", doMatchBrackets);
- if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
- cm.state.matchBrackets.currentlyHighlighted();
- cm.state.matchBrackets.currentlyHighlighted = null;
- }
- }
- if (val) {
- cm.state.matchBrackets = typeof val == "object" ? val : {};
- cm.on("cursorActivity", doMatchBrackets);
- }
- });
- CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
- CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){
- // Backwards-compatibility kludge
- if (oldConfig || typeof config == "boolean") {
- if (!oldConfig) {
- config = config ? {strict: true} : null
- } else {
- oldConfig.strict = config
- config = oldConfig
- }
- }
- return findMatchingBracket(this, pos, config)
- });
- CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
- return scanForBracket(this, pos, dir, style, config);
- });
- });
- },{"../../lib/codemirror":16}],7:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
- CodeMirror.registerHelper("fold", "brace", function(cm, start) {
- var line = start.line, lineText = cm.getLine(line);
- var tokenType;
- function findOpening(openCh) {
- for (var at = start.ch, pass = 0;;) {
- var found = at <= 0 ? -1 : lineText.lastIndexOf(openCh, at - 1);
- if (found == -1) {
- if (pass == 1) break;
- pass = 1;
- at = lineText.length;
- continue;
- }
- if (pass == 1 && found < start.ch) break;
- tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1));
- if (!/^(comment|string)/.test(tokenType)) return found + 1;
- at = found - 1;
- }
- }
- var startToken = "{", endToken = "}", startCh = findOpening("{");
- if (startCh == null) {
- startToken = "[", endToken = "]";
- startCh = findOpening("[");
- }
- if (startCh == null) return;
- var count = 1, lastLine = cm.lastLine(), end, endCh;
- outer: for (var i = line; i <= lastLine; ++i) {
- var text = cm.getLine(i), pos = i == line ? startCh : 0;
- for (;;) {
- var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
- if (nextOpen < 0) nextOpen = text.length;
- if (nextClose < 0) nextClose = text.length;
- pos = Math.min(nextOpen, nextClose);
- if (pos == text.length) break;
- if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == tokenType) {
- if (pos == nextOpen) ++count;
- else if (!--count) { end = i; endCh = pos; break outer; }
- }
- ++pos;
- }
- }
- if (end == null || line == end) return;
- return {from: CodeMirror.Pos(line, startCh),
- to: CodeMirror.Pos(end, endCh)};
- });
- CodeMirror.registerHelper("fold", "import", function(cm, start) {
- function hasImport(line) {
- if (line < cm.firstLine() || line > cm.lastLine()) return null;
- var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
- if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
- if (start.type != "keyword" || start.string != "import") return null;
- // Now find closing semicolon, return its position
- for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) {
- var text = cm.getLine(i), semi = text.indexOf(";");
- if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)};
- }
- }
- var startLine = start.line, has = hasImport(startLine), prev;
- if (!has || hasImport(startLine - 1) || ((prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1))
- return null;
- for (var end = has.end;;) {
- var next = hasImport(end.line + 1);
- if (next == null) break;
- end = next.end;
- }
- return {from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), to: end};
- });
- CodeMirror.registerHelper("fold", "include", function(cm, start) {
- function hasInclude(line) {
- if (line < cm.firstLine() || line > cm.lastLine()) return null;
- var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
- if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
- if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
- }
- var startLine = start.line, has = hasInclude(startLine);
- if (has == null || hasInclude(startLine - 1) != null) return null;
- for (var end = startLine;;) {
- var next = hasInclude(end + 1);
- if (next == null) break;
- ++end;
- }
- return {from: CodeMirror.Pos(startLine, has + 1),
- to: cm.clipPos(CodeMirror.Pos(end))};
- });
- });
- },{"../../lib/codemirror":16}],8:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
- function doFold(cm, pos, options, force) {
- if (options && options.call) {
- var finder = options;
- options = null;
- } else {
- var finder = getOption(cm, options, "rangeFinder");
- }
- if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
- var minSize = getOption(cm, options, "minFoldSize");
- function getRange(allowFolded) {
- var range = finder(cm, pos);
- if (!range || range.to.line - range.from.line < minSize) return null;
- var marks = cm.findMarksAt(range.from);
- for (var i = 0; i < marks.length; ++i) {
- if (marks[i].__isFold && force !== "fold") {
- if (!allowFolded) return null;
- range.cleared = true;
- marks[i].clear();
- }
- }
- return range;
- }
- var range = getRange(true);
- if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) {
- pos = CodeMirror.Pos(pos.line - 1, 0);
- range = getRange(false);
- }
- if (!range || range.cleared || force === "unfold") return;
- var myWidget = makeWidget(cm, options);
- CodeMirror.on(myWidget, "mousedown", function(e) {
- myRange.clear();
- CodeMirror.e_preventDefault(e);
- });
- var myRange = cm.markText(range.from, range.to, {
- replacedWith: myWidget,
- clearOnEnter: getOption(cm, options, "clearOnEnter"),
- __isFold: true
- });
- myRange.on("clear", function(from, to) {
- CodeMirror.signal(cm, "unfold", cm, from, to);
- });
- CodeMirror.signal(cm, "fold", cm, range.from, range.to);
- }
- function makeWidget(cm, options) {
- var widget = getOption(cm, options, "widget");
- if (typeof widget == "string") {
- var text = document.createTextNode(widget);
- widget = document.createElement("span");
- widget.appendChild(text);
- widget.className = "CodeMirror-foldmarker";
- } else if (widget) {
- widget = widget.cloneNode(true)
- }
- return widget;
- }
- // Clumsy backwards-compatible interface
- CodeMirror.newFoldFunction = function(rangeFinder, widget) {
- return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
- };
- // New-style interface
- CodeMirror.defineExtension("foldCode", function(pos, options, force) {
- doFold(this, pos, options, force);
- });
- CodeMirror.defineExtension("isFolded", function(pos) {
- var marks = this.findMarksAt(pos);
- for (var i = 0; i < marks.length; ++i)
- if (marks[i].__isFold) return true;
- });
- CodeMirror.commands.toggleFold = function(cm) {
- cm.foldCode(cm.getCursor());
- };
- CodeMirror.commands.fold = function(cm) {
- cm.foldCode(cm.getCursor(), null, "fold");
- };
- CodeMirror.commands.unfold = function(cm) {
- cm.foldCode(cm.getCursor(), null, "unfold");
- };
- CodeMirror.commands.foldAll = function(cm) {
- cm.operation(function() {
- for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
- cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
- });
- };
- CodeMirror.commands.unfoldAll = function(cm) {
- cm.operation(function() {
- for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
- cm.foldCode(CodeMirror.Pos(i, 0), null, "unfold");
- });
- };
- CodeMirror.registerHelper("fold", "combine", function() {
- var funcs = Array.prototype.slice.call(arguments, 0);
- return function(cm, start) {
- for (var i = 0; i < funcs.length; ++i) {
- var found = funcs[i](cm, start);
- if (found) return found;
- }
- };
- });
- CodeMirror.registerHelper("fold", "auto", function(cm, start) {
- var helpers = cm.getHelpers(start, "fold");
- for (var i = 0; i < helpers.length; i++) {
- var cur = helpers[i](cm, start);
- if (cur) return cur;
- }
- });
- var defaultOptions = {
- rangeFinder: CodeMirror.fold.auto,
- widget: "\u2194",
- minFoldSize: 0,
- scanUp: false,
- clearOnEnter: true
- };
- CodeMirror.defineOption("foldOptions", null);
- function getOption(cm, options, name) {
- if (options && options[name] !== undefined)
- return options[name];
- var editorOptions = cm.options.foldOptions;
- if (editorOptions && editorOptions[name] !== undefined)
- return editorOptions[name];
- return defaultOptions[name];
- }
- CodeMirror.defineExtension("foldOption", function(options, name) {
- return getOption(this, options, name);
- });
- });
- },{"../../lib/codemirror":16}],9:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"), require("./foldcode"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror", "./foldcode"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
- CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
- if (old && old != CodeMirror.Init) {
- cm.clearGutter(cm.state.foldGutter.options.gutter);
- cm.state.foldGutter = null;
- cm.off("gutterClick", onGutterClick);
- cm.off("change", onChange);
- cm.off("viewportChange", onViewportChange);
- cm.off("fold", onFold);
- cm.off("unfold", onFold);
- cm.off("swapDoc", onChange);
- }
- if (val) {
- cm.state.foldGutter = new State(parseOptions(val));
- updateInViewport(cm);
- cm.on("gutterClick", onGutterClick);
- cm.on("change", onChange);
- cm.on("viewportChange", onViewportChange);
- cm.on("fold", onFold);
- cm.on("unfold", onFold);
- cm.on("swapDoc", onChange);
- }
- });
- var Pos = CodeMirror.Pos;
- function State(options) {
- this.options = options;
- this.from = this.to = 0;
- }
- function parseOptions(opts) {
- if (opts === true) opts = {};
- if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
- if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
- if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
- return opts;
- }
- function isFolded(cm, line) {
- var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0));
- for (var i = 0; i < marks.length; ++i)
- if (marks[i].__isFold && marks[i].find().from.line == line) return marks[i];
- }
- function marker(spec) {
- if (typeof spec == "string") {
- var elt = document.createElement("div");
- elt.className = spec + " CodeMirror-guttermarker-subtle";
- return elt;
- } else {
- return spec.cloneNode(true);
- }
- }
- function updateFoldInfo(cm, from, to) {
- var opts = cm.state.foldGutter.options, cur = from;
- var minSize = cm.foldOption(opts, "minFoldSize");
- var func = cm.foldOption(opts, "rangeFinder");
- cm.eachLine(from, to, function(line) {
- var mark = null;
- if (isFolded(cm, cur)) {
- mark = marker(opts.indicatorFolded);
- } else {
- var pos = Pos(cur, 0);
- var range = func && func(cm, pos);
- if (range && range.to.line - range.from.line >= minSize)
- mark = marker(opts.indicatorOpen);
- }
- cm.setGutterMarker(line, opts.gutter, mark);
- ++cur;
- });
- }
- function updateInViewport(cm) {
- var vp = cm.getViewport(), state = cm.state.foldGutter;
- if (!state) return;
- cm.operation(function() {
- updateFoldInfo(cm, vp.from, vp.to);
- });
- state.from = vp.from; state.to = vp.to;
- }
- function onGutterClick(cm, line, gutter) {
- var state = cm.state.foldGutter;
- if (!state) return;
- var opts = state.options;
- if (gutter != opts.gutter) return;
- var folded = isFolded(cm, line);
- if (folded) folded.clear();
- else cm.foldCode(Pos(line, 0), opts.rangeFinder);
- }
- function onChange(cm) {
- var state = cm.state.foldGutter;
- if (!state) return;
- var opts = state.options;
- state.from = state.to = 0;
- clearTimeout(state.changeUpdate);
- state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600);
- }
- function onViewportChange(cm) {
- var state = cm.state.foldGutter;
- if (!state) return;
- var opts = state.options;
- clearTimeout(state.changeUpdate);
- state.changeUpdate = setTimeout(function() {
- var vp = cm.getViewport();
- if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
- updateInViewport(cm);
- } else {
- cm.operation(function() {
- if (vp.from < state.from) {
- updateFoldInfo(cm, vp.from, state.from);
- state.from = vp.from;
- }
- if (vp.to > state.to) {
- updateFoldInfo(cm, state.to, vp.to);
- state.to = vp.to;
- }
- });
- }
- }, opts.updateViewportTimeSpan || 400);
- }
- function onFold(cm, from) {
- var state = cm.state.foldGutter;
- if (!state) return;
- var line = from.line;
- if (line >= state.from && line < state.to)
- updateFoldInfo(cm, line, line + 1);
- }
- });
- },{"../../lib/codemirror":16,"./foldcode":8}],10:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
- var HINT_ELEMENT_CLASS = "CodeMirror-hint";
- var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
- // This is the old interface, kept around for now to stay
- // backwards-compatible.
- CodeMirror.showHint = function(cm, getHints, options) {
- if (!getHints) return cm.showHint(options);
- if (options && options.async) getHints.async = true;
- var newOpts = {hint: getHints};
- if (options) for (var prop in options) newOpts[prop] = options[prop];
- return cm.showHint(newOpts);
- };
- CodeMirror.defineExtension("showHint", function(options) {
- options = parseOptions(this, this.getCursor("start"), options);
- var selections = this.listSelections()
- if (selections.length > 1) return;
- // By default, don't allow completion when something is selected.
- // A hint function can have a `supportsSelection` property to
- // indicate that it can handle selections.
- if (this.somethingSelected()) {
- if (!options.hint.supportsSelection) return;
- // Don't try with cross-line selections
- for (var i = 0; i < selections.length; i++)
- if (selections[i].head.line != selections[i].anchor.line) return;
- }
- if (this.state.completionActive) this.state.completionActive.close();
- var completion = this.state.completionActive = new Completion(this, options);
- if (!completion.options.hint) return;
- CodeMirror.signal(this, "startCompletion", this);
- completion.update(true);
- });
- CodeMirror.defineExtension("closeHint", function() {
- if (this.state.completionActive) this.state.completionActive.close()
- })
- function Completion(cm, options) {
- this.cm = cm;
- this.options = options;
- this.widget = null;
- this.debounce = 0;
- this.tick = 0;
- this.startPos = this.cm.getCursor("start");
- this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;
- var self = this;
- cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
- }
- var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
- return setTimeout(fn, 1000/60);
- };
- var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
- Completion.prototype = {
- close: function() {
- if (!this.active()) return;
- this.cm.state.completionActive = null;
- this.tick = null;
- this.cm.off("cursorActivity", this.activityFunc);
- if (this.widget && this.data) CodeMirror.signal(this.data, "close");
- if (this.widget) this.widget.close();
- CodeMirror.signal(this.cm, "endCompletion", this.cm);
- },
- active: function() {
- return this.cm.state.completionActive == this;
- },
- pick: function(data, i) {
- var completion = data.list[i];
- if (completion.hint) completion.hint(this.cm, data, completion);
- else this.cm.replaceRange(getText(completion), completion.from || data.from,
- completion.to || data.to, "complete");
- CodeMirror.signal(data, "pick", completion);
- this.close();
- },
- cursorActivity: function() {
- if (this.debounce) {
- cancelAnimationFrame(this.debounce);
- this.debounce = 0;
- }
- var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
- if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
- pos.ch < this.startPos.ch || this.cm.somethingSelected() ||
- (!pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
- this.close();
- } else {
- var self = this;
- this.debounce = requestAnimationFrame(function() {self.update();});
- if (this.widget) this.widget.disable();
- }
- },
- update: function(first) {
- if (this.tick == null) return
- var self = this, myTick = ++this.tick
- fetchHints(this.options.hint, this.cm, this.options, function(data) {
- if (self.tick == myTick) self.finishUpdate(data, first)
- })
- },
- finishUpdate: function(data, first) {
- if (this.data) CodeMirror.signal(this.data, "update");
- var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
- if (this.widget) this.widget.close();
- this.data = data;
- if (data && data.list.length) {
- if (picked && data.list.length == 1) {
- this.pick(data, 0);
- } else {
- this.widget = new Widget(this, data);
- CodeMirror.signal(data, "shown");
- }
- }
- }
- };
- function parseOptions(cm, pos, options) {
- var editor = cm.options.hintOptions;
- var out = {};
- for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
- if (editor) for (var prop in editor)
- if (editor[prop] !== undefined) out[prop] = editor[prop];
- if (options) for (var prop in options)
- if (options[prop] !== undefined) out[prop] = options[prop];
- if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
- return out;
- }
- function getText(completion) {
- if (typeof completion == "string") return completion;
- else return completion.text;
- }
- function buildKeyMap(completion, handle) {
- var baseMap = {
- Up: function() {handle.moveFocus(-1);},
- Down: function() {handle.moveFocus(1);},
- PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
- PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
- Home: function() {handle.setFocus(0);},
- End: function() {handle.setFocus(handle.length - 1);},
- Enter: handle.pick,
- Tab: handle.pick,
- Esc: handle.close
- };
- var mac = /Mac/.test(navigator.platform);
- if (mac) {
- baseMap["Ctrl-P"] = function() {handle.moveFocus(-1);};
- baseMap["Ctrl-N"] = function() {handle.moveFocus(1);};
- }
- var custom = completion.options.customKeys;
- var ourMap = custom ? {} : baseMap;
- function addBinding(key, val) {
- var bound;
- if (typeof val != "string")
- bound = function(cm) { return val(cm, handle); };
- // This mechanism is deprecated
- else if (baseMap.hasOwnProperty(val))
- bound = baseMap[val];
- else
- bound = val;
- ourMap[key] = bound;
- }
- if (custom)
- for (var key in custom) if (custom.hasOwnProperty(key))
- addBinding(key, custom[key]);
- var extra = completion.options.extraKeys;
- if (extra)
- for (var key in extra) if (extra.hasOwnProperty(key))
- addBinding(key, extra[key]);
- return ourMap;
- }
- function getHintElement(hintsElement, el) {
- while (el && el != hintsElement) {
- if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
- el = el.parentNode;
- }
- }
- function Widget(completion, data) {
- this.completion = completion;
- this.data = data;
- this.picked = false;
- var widget = this, cm = completion.cm;
- var ownerDocument = cm.getInputField().ownerDocument;
- var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow;
- var hints = this.hints = ownerDocument.createElement("ul");
- var theme = completion.cm.options.theme;
- hints.className = "CodeMirror-hints " + theme;
- this.selectedHint = data.selectedHint || 0;
- var completions = data.list;
- for (var i = 0; i < completions.length; ++i) {
- var elt = hints.appendChild(ownerDocument.createElement("li")), cur = completions[i];
- var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
- if (cur.className != null) className = cur.className + " " + className;
- elt.className = className;
- if (cur.render) cur.render(elt, data, cur);
- else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur)));
- elt.hintId = i;
- }
- var container = completion.options.container || ownerDocument.body;
- var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
- var left = pos.left, top = pos.bottom, below = true;
- var offsetLeft = 0, offsetTop = 0;
- if (container !== ownerDocument.body) {
- // We offset the cursor position because left and top are relative to the offsetParent's top left corner.
- var isContainerPositioned = ['absolute', 'relative', 'fixed'].indexOf(parentWindow.getComputedStyle(container).position) !== -1;
- var offsetParent = isContainerPositioned ? container : container.offsetParent;
- var offsetParentPosition = offsetParent.getBoundingClientRect();
- var bodyPosition = ownerDocument.body.getBoundingClientRect();
- offsetLeft = (offsetParentPosition.left - bodyPosition.left);
- offsetTop = (offsetParentPosition.top - bodyPosition.top);
- }
- hints.style.left = (left - offsetLeft) + "px";
- hints.style.top = (top - offsetTop) + "px";
- // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
- var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth);
- var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight);
- container.appendChild(hints);
- var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
- var scrolls = hints.scrollHeight > hints.clientHeight + 1
- var startScroll = cm.getScrollInfo();
- if (overlapY > 0) {
- var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
- if (curTop - height > 0) { // Fits above cursor
- hints.style.top = (top = pos.top - height - offsetTop) + "px";
- below = false;
- } else if (height > winH) {
- hints.style.height = (winH - 5) + "px";
- hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px";
- var cursor = cm.getCursor();
- if (data.from.ch != cursor.ch) {
- pos = cm.cursorCoords(cursor);
- hints.style.left = (left = pos.left - offsetLeft) + "px";
- box = hints.getBoundingClientRect();
- }
- }
- }
- var overlapX = box.right - winW;
- if (overlapX > 0) {
- if (box.right - box.left > winW) {
- hints.style.width = (winW - 5) + "px";
- overlapX -= (box.right - box.left) - winW;
- }
- hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px";
- }
- if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
- node.style.paddingRight = cm.display.nativeBarWidth + "px"
- cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
- moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
- setFocus: function(n) { widget.changeActive(n); },
- menuSize: function() { return widget.screenAmount(); },
- length: completions.length,
- close: function() { completion.close(); },
- pick: function() { widget.pick(); },
- data: data
- }));
- if (completion.options.closeOnUnfocus) {
- var closingOnBlur;
- cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
- cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
- }
- cm.on("scroll", this.onScroll = function() {
- var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
- var newTop = top + startScroll.top - curScroll.top;
- var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop);
- if (!below) point += hints.offsetHeight;
- if (point <= editor.top || point >= editor.bottom) return completion.close();
- hints.style.top = newTop + "px";
- hints.style.left = (left + startScroll.left - curScroll.left) + "px";
- });
- CodeMirror.on(hints, "dblclick", function(e) {
- var t = getHintElement(hints, e.target || e.srcElement);
- if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
- });
- CodeMirror.on(hints, "click", function(e) {
- var t = getHintElement(hints, e.target || e.srcElement);
- if (t && t.hintId != null) {
- widget.changeActive(t.hintId);
- if (completion.options.completeOnSingleClick) widget.pick();
- }
- });
- CodeMirror.on(hints, "mousedown", function() {
- setTimeout(function(){cm.focus();}, 20);
- });
- CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]);
- return true;
- }
- Widget.prototype = {
- close: function() {
- if (this.completion.widget != this) return;
- this.completion.widget = null;
- this.hints.parentNode.removeChild(this.hints);
- this.completion.cm.removeKeyMap(this.keyMap);
- var cm = this.completion.cm;
- if (this.completion.options.closeOnUnfocus) {
- cm.off("blur", this.onBlur);
- cm.off("focus", this.onFocus);
- }
- cm.off("scroll", this.onScroll);
- },
- disable: function() {
- this.completion.cm.removeKeyMap(this.keyMap);
- var widget = this;
- this.keyMap = {Enter: function() { widget.picked = true; }};
- this.completion.cm.addKeyMap(this.keyMap);
- },
- pick: function() {
- this.completion.pick(this.data, this.selectedHint);
- },
- changeActive: function(i, avoidWrap) {
- if (i >= this.data.list.length)
- i = avoidWrap ? this.data.list.length - 1 : 0;
- else if (i < 0)
- i = avoidWrap ? 0 : this.data.list.length - 1;
- if (this.selectedHint == i) return;
- var node = this.hints.childNodes[this.selectedHint];
- if (node) node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
- node = this.hints.childNodes[this.selectedHint = i];
- node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
- if (node.offsetTop < this.hints.scrollTop)
- this.hints.scrollTop = node.offsetTop - 3;
- else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
- this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
- CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
- },
- screenAmount: function() {
- return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
- }
- };
- function applicableHelpers(cm, helpers) {
- if (!cm.somethingSelected()) return helpers
- var result = []
- for (var i = 0; i < helpers.length; i++)
- if (helpers[i].supportsSelection) result.push(helpers[i])
- return result
- }
- function fetchHints(hint, cm, options, callback) {
- if (hint.async) {
- hint(cm, callback, options)
- } else {
- var result = hint(cm, options)
- if (result && result.then) result.then(callback)
- else callback(result)
- }
- }
- function resolveAutoHints(cm, pos) {
- var helpers = cm.getHelpers(pos, "hint"), words
- if (helpers.length) {
- var resolved = function(cm, callback, options) {
- var app = applicableHelpers(cm, helpers);
- function run(i) {
- if (i == app.length) return callback(null)
- fetchHints(app[i], cm, options, function(result) {
- if (result && result.list.length > 0) callback(result)
- else run(i + 1)
- })
- }
- run(0)
- }
- resolved.async = true
- resolved.supportsSelection = true
- return resolved
- } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
- return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
- } else if (CodeMirror.hint.anyword) {
- return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
- } else {
- return function() {}
- }
- }
- CodeMirror.registerHelper("hint", "auto", {
- resolve: resolveAutoHints
- });
- CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
- var cur = cm.getCursor(), token = cm.getTokenAt(cur)
- var term, from = CodeMirror.Pos(cur.line, token.start), to = cur
- if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
- term = token.string.substr(0, cur.ch - token.start)
- } else {
- term = ""
- from = cur
- }
- var found = [];
- for (var i = 0; i < options.words.length; i++) {
- var word = options.words[i];
- if (word.slice(0, term.length) == term)
- found.push(word);
- }
- if (found.length) return {list: found, from: from, to: to};
- });
- CodeMirror.commands.autocomplete = CodeMirror.showHint;
- var defaultOptions = {
- hint: CodeMirror.hint.auto,
- completeSingle: true,
- alignWithWord: true,
- closeCharacters: /[\s()\[\]{};:>,]/,
- closeOnUnfocus: true,
- completeOnSingleClick: true,
- container: null,
- customKeys: null,
- extraKeys: null
- };
- CodeMirror.defineOption("hintOptions", null);
- });
- },{"../../lib/codemirror":16}],11:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
- var GUTTER_ID = "CodeMirror-lint-markers";
- function showTooltip(e, content) {
- var tt = document.createElement("div");
- tt.className = "CodeMirror-lint-tooltip";
- tt.appendChild(content.cloneNode(true));
- document.body.appendChild(tt);
- function position(e) {
- if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
- tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
- tt.style.left = (e.clientX + 5) + "px";
- }
- CodeMirror.on(document, "mousemove", position);
- position(e);
- if (tt.style.opacity != null) tt.style.opacity = 1;
- return tt;
- }
- function rm(elt) {
- if (elt.parentNode) elt.parentNode.removeChild(elt);
- }
- function hideTooltip(tt) {
- if (!tt.parentNode) return;
- if (tt.style.opacity == null) rm(tt);
- tt.style.opacity = 0;
- setTimeout(function() { rm(tt); }, 600);
- }
- function showTooltipFor(e, content, node) {
- var tooltip = showTooltip(e, content);
- function hide() {
- CodeMirror.off(node, "mouseout", hide);
- if (tooltip) { hideTooltip(tooltip); tooltip = null; }
- }
- var poll = setInterval(function() {
- if (tooltip) for (var n = node;; n = n.parentNode) {
- if (n && n.nodeType == 11) n = n.host;
- if (n == document.body) return;
- if (!n) { hide(); break; }
- }
- if (!tooltip) return clearInterval(poll);
- }, 400);
- CodeMirror.on(node, "mouseout", hide);
- }
- function LintState(cm, options, hasGutter) {
- this.marked = [];
- this.options = options;
- this.timeout = null;
- this.hasGutter = hasGutter;
- this.onMouseOver = function(e) { onMouseOver(cm, e); };
- this.waitingFor = 0
- }
- function parseOptions(_cm, options) {
- if (options instanceof Function) return {getAnnotations: options};
- if (!options || options === true) options = {};
- return options;
- }
- function clearMarks(cm) {
- var state = cm.state.lint;
- if (state.hasGutter) cm.clearGutter(GUTTER_ID);
- for (var i = 0; i < state.marked.length; ++i)
- state.marked[i].clear();
- state.marked.length = 0;
- }
- function makeMarker(labels, severity, multiple, tooltips) {
- var marker = document.createElement("div"), inner = marker;
- marker.className = "CodeMirror-lint-marker-" + severity;
- if (multiple) {
- inner = marker.appendChild(document.createElement("div"));
- inner.className = "CodeMirror-lint-marker-multiple";
- }
- if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
- showTooltipFor(e, labels, inner);
- });
- return marker;
- }
- function getMaxSeverity(a, b) {
- if (a == "error") return a;
- else return b;
- }
- function groupByLine(annotations) {
- var lines = [];
- for (var i = 0; i < annotations.length; ++i) {
- var ann = annotations[i], line = ann.from.line;
- (lines[line] || (lines[line] = [])).push(ann);
- }
- return lines;
- }
- function annotationTooltip(ann) {
- var severity = ann.severity;
- if (!severity) severity = "error";
- var tip = document.createElement("div");
- tip.className = "CodeMirror-lint-message-" + severity;
- if (typeof ann.messageHTML != 'undefined') {
- tip.innerHTML = ann.messageHTML;
- } else {
- tip.appendChild(document.createTextNode(ann.message));
- }
- return tip;
- }
- function lintAsync(cm, getAnnotations, passOptions) {
- var state = cm.state.lint
- var id = ++state.waitingFor
- function abort() {
- id = -1
- cm.off("change", abort)
- }
- cm.on("change", abort)
- getAnnotations(cm.getValue(), function(annotations, arg2) {
- cm.off("change", abort)
- if (state.waitingFor != id) return
- if (arg2 && annotations instanceof CodeMirror) annotations = arg2
- cm.operation(function() {updateLinting(cm, annotations)})
- }, passOptions, cm);
- }
- function startLinting(cm) {
- var state = cm.state.lint, options = state.options;
- /*
- * Passing rules in `options` property prevents JSHint (and other linters) from complaining
- * about unrecognized rules like `onUpdateLinting`, `delay`, `lintOnChange`, etc.
- */
- var passOptions = options.options || options;
- var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint");
- if (!getAnnotations) return;
- if (options.async || getAnnotations.async) {
- lintAsync(cm, getAnnotations, passOptions)
- } else {
- var annotations = getAnnotations(cm.getValue(), passOptions, cm);
- if (!annotations) return;
- if (annotations.then) annotations.then(function(issues) {
- cm.operation(function() {updateLinting(cm, issues)})
- });
- else cm.operation(function() {updateLinting(cm, annotations)})
- }
- }
- function updateLinting(cm, annotationsNotSorted) {
- clearMarks(cm);
- var state = cm.state.lint, options = state.options;
- var annotations = groupByLine(annotationsNotSorted);
- for (var line = 0; line < annotations.length; ++line) {
- var anns = annotations[line];
- if (!anns) continue;
- var maxSeverity = null;
- var tipLabel = state.hasGutter && document.createDocumentFragment();
- for (var i = 0; i < anns.length; ++i) {
- var ann = anns[i];
- var severity = ann.severity;
- if (!severity) severity = "error";
- maxSeverity = getMaxSeverity(maxSeverity, severity);
- if (options.formatAnnotation) ann = options.formatAnnotation(ann);
- if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
- if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
- className: "CodeMirror-lint-mark-" + severity,
- __annotation: ann
- }));
- }
- if (state.hasGutter)
- cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
- state.options.tooltips));
- }
- if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
- }
- function onChange(cm) {
- var state = cm.state.lint;
- if (!state) return;
- clearTimeout(state.timeout);
- state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
- }
- function popupTooltips(annotations, e) {
- var target = e.target || e.srcElement;
- var tooltip = document.createDocumentFragment();
- for (var i = 0; i < annotations.length; i++) {
- var ann = annotations[i];
- tooltip.appendChild(annotationTooltip(ann));
- }
- showTooltipFor(e, tooltip, target);
- }
- function onMouseOver(cm, e) {
- var target = e.target || e.srcElement;
- if (!/\bCodeMirror-lint-mark-/.test(target.className)) return;
- var box = target.getBoundingClientRect(), x = (box.left + box.right) / 2, y = (box.top + box.bottom) / 2;
- var spans = cm.findMarksAt(cm.coordsChar({left: x, top: y}, "client"));
- var annotations = [];
- for (var i = 0; i < spans.length; ++i) {
- var ann = spans[i].__annotation;
- if (ann) annotations.push(ann);
- }
- if (annotations.length) popupTooltips(annotations, e);
- }
- CodeMirror.defineOption("lint", false, function(cm, val, old) {
- if (old && old != CodeMirror.Init) {
- clearMarks(cm);
- if (cm.state.lint.options.lintOnChange !== false)
- cm.off("change", onChange);
- CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
- clearTimeout(cm.state.lint.timeout);
- delete cm.state.lint;
- }
- if (val) {
- var gutters = cm.getOption("gutters"), hasLintGutter = false;
- for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
- var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
- if (state.options.lintOnChange !== false)
- cm.on("change", onChange);
- if (state.options.tooltips != false && state.options.tooltips != "gutter")
- CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
- startLinting(cm);
- }
- });
- CodeMirror.defineExtension("performLint", function() {
- if (this.state.lint) startLinting(this);
- });
- });
- },{"../../lib/codemirror":16}],12:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- // Defines jumpToLine command. Uses dialog.js if present.
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"), require("../dialog/dialog"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror", "../dialog/dialog"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
- function dialog(cm, text, shortText, deflt, f) {
- if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
- else f(prompt(shortText, deflt));
- }
- function getJumpDialog(cm) {
- return cm.phrase("Jump to line:") + ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">' + cm.phrase("(Use line:column or scroll% syntax)") + '</span>';
- }
- function interpretLine(cm, string) {
- var num = Number(string)
- if (/^[-+]/.test(string)) return cm.getCursor().line + num
- else return num - 1
- }
- CodeMirror.commands.jumpToLine = function(cm) {
- var cur = cm.getCursor();
- dialog(cm, getJumpDialog(cm), cm.phrase("Jump to line:"), (cur.line + 1) + ":" + cur.ch, function(posStr) {
- if (!posStr) return;
- var match;
- if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) {
- cm.setCursor(interpretLine(cm, match[1]), Number(match[2]))
- } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) {
- var line = Math.round(cm.lineCount() * Number(match[1]) / 100);
- if (/^[-+]/.test(match[1])) line = cur.line + line + 1;
- cm.setCursor(line - 1, cur.ch);
- } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) {
- cm.setCursor(interpretLine(cm, match[1]), cur.ch);
- }
- });
- };
- CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine";
- });
- },{"../../lib/codemirror":16,"../dialog/dialog":4}],13:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- // Define search commands. Depends on dialog.js or another
- // implementation of the openDialog method.
- // Replace works a little oddly -- it will do the replace on the next
- // Ctrl-G (or whatever is bound to findNext) press. You prevent a
- // replace by making sure the match is no longer selected when hitting
- // Ctrl-G.
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"), require("./searchcursor"), require("../dialog/dialog"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror", "./searchcursor", "../dialog/dialog"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
- function searchOverlay(query, caseInsensitive) {
- if (typeof query == "string")
- query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
- else if (!query.global)
- query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
- return {token: function(stream) {
- query.lastIndex = stream.pos;
- var match = query.exec(stream.string);
- if (match && match.index == stream.pos) {
- stream.pos += match[0].length || 1;
- return "searching";
- } else if (match) {
- stream.pos = match.index;
- } else {
- stream.skipToEnd();
- }
- }};
- }
- function SearchState() {
- this.posFrom = this.posTo = this.lastQuery = this.query = null;
- this.overlay = null;
- }
- function getSearchState(cm) {
- return cm.state.search || (cm.state.search = new SearchState());
- }
- function queryCaseInsensitive(query) {
- return typeof query == "string" && query == query.toLowerCase();
- }
- function getSearchCursor(cm, query, pos) {
- // Heuristic: if the query string is all lowercase, do a case insensitive search.
- return cm.getSearchCursor(query, pos, {caseFold: queryCaseInsensitive(query), multiline: true});
- }
- function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {
- cm.openDialog(text, onEnter, {
- value: deflt,
- selectValueOnOpen: true,
- closeOnEnter: false,
- onClose: function() { clearSearch(cm); },
- onKeyDown: onKeyDown
- });
- }
- function dialog(cm, text, shortText, deflt, f) {
- if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
- else f(prompt(shortText, deflt));
- }
- function confirmDialog(cm, text, shortText, fs) {
- if (cm.openConfirm) cm.openConfirm(text, fs);
- else if (confirm(shortText)) fs[0]();
- }
- function parseString(string) {
- return string.replace(/\\(.)/g, function(_, ch) {
- if (ch == "n") return "\n"
- if (ch == "r") return "\r"
- return ch
- })
- }
- function parseQuery(query) {
- var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
- if (isRE) {
- try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }
- catch(e) {} // Not a regular expression after all, do a string search
- } else {
- query = parseString(query)
- }
- if (typeof query == "string" ? query == "" : query.test(""))
- query = /x^/;
- return query;
- }
- function startSearch(cm, state, query) {
- state.queryText = query;
- state.query = parseQuery(query);
- cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
- state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
- cm.addOverlay(state.overlay);
- if (cm.showMatchesOnScrollbar) {
- if (state.annotate) { state.annotate.clear(); state.annotate = null; }
- state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
- }
- }
- function doSearch(cm, rev, persistent, immediate) {
- var state = getSearchState(cm);
- if (state.query) return findNext(cm, rev);
- var q = cm.getSelection() || state.lastQuery;
- if (q instanceof RegExp && q.source == "x^") q = null
- if (persistent && cm.openDialog) {
- var hiding = null
- var searchNext = function(query, event) {
- CodeMirror.e_stop(event);
- if (!query) return;
- if (query != state.queryText) {
- startSearch(cm, state, query);
- state.posFrom = state.posTo = cm.getCursor();
- }
- if (hiding) hiding.style.opacity = 1
- findNext(cm, event.shiftKey, function(_, to) {
- var dialog
- if (to.line < 3 && document.querySelector &&
- (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&
- dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
- (hiding = dialog).style.opacity = .4
- })
- };
- persistentDialog(cm, getQueryDialog(cm), q, searchNext, function(event, query) {
- var keyName = CodeMirror.keyName(event)
- var extra = cm.getOption('extraKeys'), cmd = (extra && extra[keyName]) || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]
- if (cmd == "findNext" || cmd == "findPrev" ||
- cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
- CodeMirror.e_stop(event);
- startSearch(cm, getSearchState(cm), query);
- cm.execCommand(cmd);
- } else if (cmd == "find" || cmd == "findPersistent") {
- CodeMirror.e_stop(event);
- searchNext(query, event);
- }
- });
- if (immediate && q) {
- startSearch(cm, state, q);
- findNext(cm, rev);
- }
- } else {
- dialog(cm, getQueryDialog(cm), "Search for:", q, function(query) {
- if (query && !state.query) cm.operation(function() {
- startSearch(cm, state, query);
- state.posFrom = state.posTo = cm.getCursor();
- findNext(cm, rev);
- });
- });
- }
- }
- function findNext(cm, rev, callback) {cm.operation(function() {
- var state = getSearchState(cm);
- var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
- if (!cursor.find(rev)) {
- cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
- if (!cursor.find(rev)) return;
- }
- cm.setSelection(cursor.from(), cursor.to());
- cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
- state.posFrom = cursor.from(); state.posTo = cursor.to();
- if (callback) callback(cursor.from(), cursor.to())
- });}
- function clearSearch(cm) {cm.operation(function() {
- var state = getSearchState(cm);
- state.lastQuery = state.query;
- if (!state.query) return;
- state.query = state.queryText = null;
- cm.removeOverlay(state.overlay);
- if (state.annotate) { state.annotate.clear(); state.annotate = null; }
- });}
- function getQueryDialog(cm) {
- return '<span class="CodeMirror-search-label">' + cm.phrase("Search:") + '</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">' + cm.phrase("(Use /re/ syntax for regexp search)") + '</span>';
- }
- function getReplaceQueryDialog(cm) {
- return ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">' + cm.phrase("(Use /re/ syntax for regexp search)") + '</span>';
- }
- function getReplacementQueryDialog(cm) {
- return '<span class="CodeMirror-search-label">' + cm.phrase("With:") + '</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
- }
- function getDoReplaceConfirm(cm) {
- return '<span class="CodeMirror-search-label">' + cm.phrase("Replace?") + '</span> <button>' + cm.phrase("Yes") + '</button> <button>' + cm.phrase("No") + '</button> <button>' + cm.phrase("All") + '</button> <button>' + cm.phrase("Stop") + '</button> ';
- }
- function replaceAll(cm, query, text) {
- cm.operation(function() {
- for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
- if (typeof query != "string") {
- var match = cm.getRange(cursor.from(), cursor.to()).match(query);
- cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
- } else cursor.replace(text);
- }
- });
- }
- function replace(cm, all) {
- if (cm.getOption("readOnly")) return;
- var query = cm.getSelection() || getSearchState(cm).lastQuery;
- var dialogText = '<span class="CodeMirror-search-label">' + (all ? cm.phrase("Replace all:") : cm.phrase("Replace:")) + '</span>';
- dialog(cm, dialogText + getReplaceQueryDialog(cm), dialogText, query, function(query) {
- if (!query) return;
- query = parseQuery(query);
- dialog(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function(text) {
- text = parseString(text)
- if (all) {
- replaceAll(cm, query, text)
- } else {
- clearSearch(cm);
- var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
- var advance = function() {
- var start = cursor.from(), match;
- if (!(match = cursor.findNext())) {
- cursor = getSearchCursor(cm, query);
- if (!(match = cursor.findNext()) ||
- (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
- }
- cm.setSelection(cursor.from(), cursor.to());
- cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
- confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"),
- [function() {doReplace(match);}, advance,
- function() {replaceAll(cm, query, text)}]);
- };
- var doReplace = function(match) {
- cursor.replace(typeof query == "string" ? text :
- text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
- advance();
- };
- advance();
- }
- });
- });
- }
- CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
- CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
- CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
- CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
- CodeMirror.commands.findNext = doSearch;
- CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
- CodeMirror.commands.clearSearch = clearSearch;
- CodeMirror.commands.replace = replace;
- CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
- });
- },{"../../lib/codemirror":16,"../dialog/dialog":4,"./searchcursor":14}],14:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../../lib/codemirror"))
- else if (typeof define == "function" && define.amd) // AMD
- define(["../../lib/codemirror"], mod)
- else // Plain browser env
- mod(CodeMirror)
- })(function(CodeMirror) {
- "use strict"
- var Pos = CodeMirror.Pos
- function regexpFlags(regexp) {
- var flags = regexp.flags
- return flags != null ? flags : (regexp.ignoreCase ? "i" : "")
- + (regexp.global ? "g" : "")
- + (regexp.multiline ? "m" : "")
- }
- function ensureFlags(regexp, flags) {
- var current = regexpFlags(regexp), target = current
- for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1)
- target += flags.charAt(i)
- return current == target ? regexp : new RegExp(regexp.source, target)
- }
- function maybeMultiline(regexp) {
- return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source)
- }
- function searchRegexpForward(doc, regexp, start) {
- regexp = ensureFlags(regexp, "g")
- for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) {
- regexp.lastIndex = ch
- var string = doc.getLine(line), match = regexp.exec(string)
- if (match)
- return {from: Pos(line, match.index),
- to: Pos(line, match.index + match[0].length),
- match: match}
- }
- }
- function searchRegexpForwardMultiline(doc, regexp, start) {
- if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start)
- regexp = ensureFlags(regexp, "gm")
- var string, chunk = 1
- for (var line = start.line, last = doc.lastLine(); line <= last;) {
- // This grows the search buffer in exponentially-sized chunks
- // between matches, so that nearby matches are fast and don't
- // require concatenating the whole document (in case we're
- // searching for something that has tons of matches), but at the
- // same time, the amount of retries is limited.
- for (var i = 0; i < chunk; i++) {
- if (line > last) break
- var curLine = doc.getLine(line++)
- string = string == null ? curLine : string + "\n" + curLine
- }
- chunk = chunk * 2
- regexp.lastIndex = start.ch
- var match = regexp.exec(string)
- if (match) {
- var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n")
- var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length
- return {from: Pos(startLine, startCh),
- to: Pos(startLine + inside.length - 1,
- inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
- match: match}
- }
- }
- }
- function lastMatchIn(string, regexp) {
- var cutOff = 0, match
- for (;;) {
- regexp.lastIndex = cutOff
- var newMatch = regexp.exec(string)
- if (!newMatch) return match
- match = newMatch
- cutOff = match.index + (match[0].length || 1)
- if (cutOff == string.length) return match
- }
- }
- function searchRegexpBackward(doc, regexp, start) {
- regexp = ensureFlags(regexp, "g")
- for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) {
- var string = doc.getLine(line)
- if (ch > -1) string = string.slice(0, ch)
- var match = lastMatchIn(string, regexp)
- if (match)
- return {from: Pos(line, match.index),
- to: Pos(line, match.index + match[0].length),
- match: match}
- }
- }
- function searchRegexpBackwardMultiline(doc, regexp, start) {
- regexp = ensureFlags(regexp, "gm")
- var string, chunk = 1
- for (var line = start.line, first = doc.firstLine(); line >= first;) {
- for (var i = 0; i < chunk; i++) {
- var curLine = doc.getLine(line--)
- string = string == null ? curLine.slice(0, start.ch) : curLine + "\n" + string
- }
- chunk *= 2
- var match = lastMatchIn(string, regexp)
- if (match) {
- var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n")
- var startLine = line + before.length, startCh = before[before.length - 1].length
- return {from: Pos(startLine, startCh),
- to: Pos(startLine + inside.length - 1,
- inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
- match: match}
- }
- }
- }
- var doFold, noFold
- if (String.prototype.normalize) {
- doFold = function(str) { return str.normalize("NFD").toLowerCase() }
- noFold = function(str) { return str.normalize("NFD") }
- } else {
- doFold = function(str) { return str.toLowerCase() }
- noFold = function(str) { return str }
- }
- // Maps a position in a case-folded line back to a position in the original line
- // (compensating for codepoints increasing in number during folding)
- function adjustPos(orig, folded, pos, foldFunc) {
- if (orig.length == folded.length) return pos
- for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) {
- if (min == max) return min
- var mid = (min + max) >> 1
- var len = foldFunc(orig.slice(0, mid)).length
- if (len == pos) return mid
- else if (len > pos) max = mid
- else min = mid + 1
- }
- }
- function searchStringForward(doc, query, start, caseFold) {
- // Empty string would match anything and never progress, so we
- // define it to match nothing instead.
- if (!query.length) return null
- var fold = caseFold ? doFold : noFold
- var lines = fold(query).split(/\r|\n\r?/)
- search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) {
- var orig = doc.getLine(line).slice(ch), string = fold(orig)
- if (lines.length == 1) {
- var found = string.indexOf(lines[0])
- if (found == -1) continue search
- var start = adjustPos(orig, string, found, fold) + ch
- return {from: Pos(line, adjustPos(orig, string, found, fold) + ch),
- to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch)}
- } else {
- var cutFrom = string.length - lines[0].length
- if (string.slice(cutFrom) != lines[0]) continue search
- for (var i = 1; i < lines.length - 1; i++)
- if (fold(doc.getLine(line + i)) != lines[i]) continue search
- var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1]
- if (endString.slice(0, lastLine.length) != lastLine) continue search
- return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch),
- to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))}
- }
- }
- }
- function searchStringBackward(doc, query, start, caseFold) {
- if (!query.length) return null
- var fold = caseFold ? doFold : noFold
- var lines = fold(query).split(/\r|\n\r?/)
- search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) {
- var orig = doc.getLine(line)
- if (ch > -1) orig = orig.slice(0, ch)
- var string = fold(orig)
- if (lines.length == 1) {
- var found = string.lastIndexOf(lines[0])
- if (found == -1) continue search
- return {from: Pos(line, adjustPos(orig, string, found, fold)),
- to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold))}
- } else {
- var lastLine = lines[lines.length - 1]
- if (string.slice(0, lastLine.length) != lastLine) continue search
- for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++)
- if (fold(doc.getLine(start + i)) != lines[i]) continue search
- var top = doc.getLine(line + 1 - lines.length), topString = fold(top)
- if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search
- return {from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)),
- to: Pos(line, adjustPos(orig, string, lastLine.length, fold))}
- }
- }
- }
- function SearchCursor(doc, query, pos, options) {
- this.atOccurrence = false
- this.doc = doc
- pos = pos ? doc.clipPos(pos) : Pos(0, 0)
- this.pos = {from: pos, to: pos}
- var caseFold
- if (typeof options == "object") {
- caseFold = options.caseFold
- } else { // Backwards compat for when caseFold was the 4th argument
- caseFold = options
- options = null
- }
- if (typeof query == "string") {
- if (caseFold == null) caseFold = false
- this.matches = function(reverse, pos) {
- return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold)
- }
- } else {
- query = ensureFlags(query, "gm")
- if (!options || options.multiline !== false)
- this.matches = function(reverse, pos) {
- return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos)
- }
- else
- this.matches = function(reverse, pos) {
- return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos)
- }
- }
- }
- SearchCursor.prototype = {
- findNext: function() {return this.find(false)},
- findPrevious: function() {return this.find(true)},
- find: function(reverse) {
- var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to))
- // Implements weird auto-growing behavior on null-matches for
- // backwards-compatiblity with the vim code (unfortunately)
- while (result && CodeMirror.cmpPos(result.from, result.to) == 0) {
- if (reverse) {
- if (result.from.ch) result.from = Pos(result.from.line, result.from.ch - 1)
- else if (result.from.line == this.doc.firstLine()) result = null
- else result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1)))
- } else {
- if (result.to.ch < this.doc.getLine(result.to.line).length) result.to = Pos(result.to.line, result.to.ch + 1)
- else if (result.to.line == this.doc.lastLine()) result = null
- else result = this.matches(reverse, Pos(result.to.line + 1, 0))
- }
- }
- if (result) {
- this.pos = result
- this.atOccurrence = true
- return this.pos.match || true
- } else {
- var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0)
- this.pos = {from: end, to: end}
- return this.atOccurrence = false
- }
- },
- from: function() {if (this.atOccurrence) return this.pos.from},
- to: function() {if (this.atOccurrence) return this.pos.to},
- replace: function(newText, origin) {
- if (!this.atOccurrence) return
- var lines = CodeMirror.splitLines(newText)
- this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin)
- this.pos.to = Pos(this.pos.from.line + lines.length - 1,
- lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0))
- }
- }
- CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
- return new SearchCursor(this.doc, query, pos, caseFold)
- })
- CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
- return new SearchCursor(this, query, pos, caseFold)
- })
- CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
- var ranges = []
- var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold)
- while (cur.findNext()) {
- if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break
- ranges.push({anchor: cur.from(), head: cur.to()})
- }
- if (ranges.length)
- this.setSelections(ranges, 0)
- })
- });
- },{"../../lib/codemirror":16}],15:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- // A rough approximation of Sublime Text's keybindings
- // Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js
- (function(mod) {
- if (typeof exports == "object" && typeof module == "object") // CommonJS
- mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets"));
- else if (typeof define == "function" && define.amd) // AMD
- define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod);
- else // Plain browser env
- mod(CodeMirror);
- })(function(CodeMirror) {
- "use strict";
- var cmds = CodeMirror.commands;
- var Pos = CodeMirror.Pos;
- // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that.
- function findPosSubword(doc, start, dir) {
- if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));
- var line = doc.getLine(start.line);
- if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));
- var state = "start", type;
- for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {
- var next = line.charAt(dir < 0 ? pos - 1 : pos);
- var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o";
- if (cat == "w" && next.toUpperCase() == next) cat = "W";
- if (state == "start") {
- if (cat != "o") { state = "in"; type = cat; }
- } else if (state == "in") {
- if (type != cat) {
- if (type == "w" && cat == "W" && dir < 0) pos--;
- if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; }
- break;
- }
- }
- }
- return Pos(start.line, pos);
- }
- function moveSubword(cm, dir) {
- cm.extendSelectionsBy(function(range) {
- if (cm.display.shift || cm.doc.extend || range.empty())
- return findPosSubword(cm.doc, range.head, dir);
- else
- return dir < 0 ? range.from() : range.to();
- });
- }
- cmds.goSubwordLeft = function(cm) { moveSubword(cm, -1); };
- cmds.goSubwordRight = function(cm) { moveSubword(cm, 1); };
- cmds.scrollLineUp = function(cm) {
- var info = cm.getScrollInfo();
- if (!cm.somethingSelected()) {
- var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local");
- if (cm.getCursor().line >= visibleBottomLine)
- cm.execCommand("goLineUp");
- }
- cm.scrollTo(null, info.top - cm.defaultTextHeight());
- };
- cmds.scrollLineDown = function(cm) {
- var info = cm.getScrollInfo();
- if (!cm.somethingSelected()) {
- var visibleTopLine = cm.lineAtHeight(info.top, "local")+1;
- if (cm.getCursor().line <= visibleTopLine)
- cm.execCommand("goLineDown");
- }
- cm.scrollTo(null, info.top + cm.defaultTextHeight());
- };
- cmds.splitSelectionByLine = function(cm) {
- var ranges = cm.listSelections(), lineRanges = [];
- for (var i = 0; i < ranges.length; i++) {
- var from = ranges[i].from(), to = ranges[i].to();
- for (var line = from.line; line <= to.line; ++line)
- if (!(to.line > from.line && line == to.line && to.ch == 0))
- lineRanges.push({anchor: line == from.line ? from : Pos(line, 0),
- head: line == to.line ? to : Pos(line)});
- }
- cm.setSelections(lineRanges, 0);
- };
- cmds.singleSelectionTop = function(cm) {
- var range = cm.listSelections()[0];
- cm.setSelection(range.anchor, range.head, {scroll: false});
- };
- cmds.selectLine = function(cm) {
- var ranges = cm.listSelections(), extended = [];
- for (var i = 0; i < ranges.length; i++) {
- var range = ranges[i];
- extended.push({anchor: Pos(range.from().line, 0),
- head: Pos(range.to().line + 1, 0)});
- }
- cm.setSelections(extended);
- };
- function insertLine(cm, above) {
- if (cm.isReadOnly()) return CodeMirror.Pass
- cm.operation(function() {
- var len = cm.listSelections().length, newSelection = [], last = -1;
- for (var i = 0; i < len; i++) {
- var head = cm.listSelections()[i].head;
- if (head.line <= last) continue;
- var at = Pos(head.line + (above ? 0 : 1), 0);
- cm.replaceRange("\n", at, null, "+insertLine");
- cm.indentLine(at.line, null, true);
- newSelection.push({head: at, anchor: at});
- last = head.line + 1;
- }
- cm.setSelections(newSelection);
- });
- cm.execCommand("indentAuto");
- }
- cmds.insertLineAfter = function(cm) { return insertLine(cm, false); };
- cmds.insertLineBefore = function(cm) { return insertLine(cm, true); };
- function wordAt(cm, pos) {
- var start = pos.ch, end = start, line = cm.getLine(pos.line);
- while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;
- while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;
- return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};
- }
- cmds.selectNextOccurrence = function(cm) {
- var from = cm.getCursor("from"), to = cm.getCursor("to");
- var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel;
- if (CodeMirror.cmpPos(from, to) == 0) {
- var word = wordAt(cm, from);
- if (!word.word) return;
- cm.setSelection(word.from, word.to);
- fullWord = true;
- } else {
- var text = cm.getRange(from, to);
- var query = fullWord ? new RegExp("\\b" + text + "\\b") : text;
- var cur = cm.getSearchCursor(query, to);
- var found = cur.findNext();
- if (!found) {
- cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0));
- found = cur.findNext();
- }
- if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to()))
- return CodeMirror.Pass
- cm.addSelection(cur.from(), cur.to());
- }
- if (fullWord)
- cm.state.sublimeFindFullWord = cm.doc.sel;
- };
- function addCursorToSelection(cm, dir) {
- var ranges = cm.listSelections(), newRanges = [];
- for (var i = 0; i < ranges.length; i++) {
- var range = ranges[i];
- var newAnchor = cm.findPosV(
- range.anchor, dir, "line", range.anchor.goalColumn);
- var newHead = cm.findPosV(
- range.head, dir, "line", range.head.goalColumn);
- newAnchor.goalColumn = range.anchor.goalColumn != null ?
- range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left;
- newHead.goalColumn = range.head.goalColumn != null ?
- range.head.goalColumn : cm.cursorCoords(range.head, "div").left;
- var newRange = {anchor: newAnchor, head: newHead};
- newRanges.push(range);
- newRanges.push(newRange);
- }
- cm.setSelections(newRanges);
- }
- cmds.addCursorToPrevLine = function(cm) { addCursorToSelection(cm, -1); };
- cmds.addCursorToNextLine = function(cm) { addCursorToSelection(cm, 1); };
- function isSelectedRange(ranges, from, to) {
- for (var i = 0; i < ranges.length; i++)
- if (ranges[i].from() == from && ranges[i].to() == to) return true
- return false
- }
- var mirror = "(){}[]";
- function selectBetweenBrackets(cm) {
- var ranges = cm.listSelections(), newRanges = []
- for (var i = 0; i < ranges.length; i++) {
- var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1);
- if (!opening) return false;
- for (;;) {
- var closing = cm.scanForBracket(pos, 1);
- if (!closing) return false;
- if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
- var startPos = Pos(opening.pos.line, opening.pos.ch + 1);
- if (CodeMirror.cmpPos(startPos, range.from()) == 0 &&
- CodeMirror.cmpPos(closing.pos, range.to()) == 0) {
- opening = cm.scanForBracket(opening.pos, -1);
- if (!opening) return false;
- } else {
- newRanges.push({anchor: startPos, head: closing.pos});
- break;
- }
- }
- pos = Pos(closing.pos.line, closing.pos.ch + 1);
- }
- }
- cm.setSelections(newRanges);
- return true;
- }
- cmds.selectScope = function(cm) {
- selectBetweenBrackets(cm) || cm.execCommand("selectAll");
- };
- cmds.selectBetweenBrackets = function(cm) {
- if (!selectBetweenBrackets(cm)) return CodeMirror.Pass;
- };
- cmds.goToBracket = function(cm) {
- cm.extendSelectionsBy(function(range) {
- var next = cm.scanForBracket(range.head, 1);
- if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos;
- var prev = cm.scanForBracket(range.head, -1);
- return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head;
- });
- };
- cmds.swapLineUp = function(cm) {
- if (cm.isReadOnly()) return CodeMirror.Pass
- var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = [];
- for (var i = 0; i < ranges.length; i++) {
- var range = ranges[i], from = range.from().line - 1, to = range.to().line;
- newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch),
- head: Pos(range.head.line - 1, range.head.ch)});
- if (range.to().ch == 0 && !range.empty()) --to;
- if (from > at) linesToMove.push(from, to);
- else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
- at = to;
- }
- cm.operation(function() {
- for (var i = 0; i < linesToMove.length; i += 2) {
- var from = linesToMove[i], to = linesToMove[i + 1];
- var line = cm.getLine(from);
- cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
- if (to > cm.lastLine())
- cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");
- else
- cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
- }
- cm.setSelections(newSels);
- cm.scrollIntoView();
- });
- };
- cmds.swapLineDown = function(cm) {
- if (cm.isReadOnly()) return CodeMirror.Pass
- var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1;
- for (var i = ranges.length - 1; i >= 0; i--) {
- var range = ranges[i], from = range.to().line + 1, to = range.from().line;
- if (range.to().ch == 0 && !range.empty()) from--;
- if (from < at) linesToMove.push(from, to);
- else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
- at = to;
- }
- cm.operation(function() {
- for (var i = linesToMove.length - 2; i >= 0; i -= 2) {
- var from = linesToMove[i], to = linesToMove[i + 1];
- var line = cm.getLine(from);
- if (from == cm.lastLine())
- cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine");
- else
- cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
- cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
- }
- cm.scrollIntoView();
- });
- };
- cmds.toggleCommentIndented = function(cm) {
- cm.toggleComment({ indent: true });
- }
- cmds.joinLines = function(cm) {
- var ranges = cm.listSelections(), joined = [];
- for (var i = 0; i < ranges.length; i++) {
- var range = ranges[i], from = range.from();
- var start = from.line, end = range.to().line;
- while (i < ranges.length - 1 && ranges[i + 1].from().line == end)
- end = ranges[++i].to().line;
- joined.push({start: start, end: end, anchor: !range.empty() && from});
- }
- cm.operation(function() {
- var offset = 0, ranges = [];
- for (var i = 0; i < joined.length; i++) {
- var obj = joined[i];
- var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head;
- for (var line = obj.start; line <= obj.end; line++) {
- var actual = line - offset;
- if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1);
- if (actual < cm.lastLine()) {
- cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length));
- ++offset;
- }
- }
- ranges.push({anchor: anchor || head, head: head});
- }
- cm.setSelections(ranges, 0);
- });
- };
- cmds.duplicateLine = function(cm) {
- cm.operation(function() {
- var rangeCount = cm.listSelections().length;
- for (var i = 0; i < rangeCount; i++) {
- var range = cm.listSelections()[i];
- if (range.empty())
- cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));
- else
- cm.replaceRange(cm.getRange(range.from(), range.to()), range.from());
- }
- cm.scrollIntoView();
- });
- };
- function sortLines(cm, caseSensitive) {
- if (cm.isReadOnly()) return CodeMirror.Pass
- var ranges = cm.listSelections(), toSort = [], selected;
- for (var i = 0; i < ranges.length; i++) {
- var range = ranges[i];
- if (range.empty()) continue;
- var from = range.from().line, to = range.to().line;
- while (i < ranges.length - 1 && ranges[i + 1].from().line == to)
- to = ranges[++i].to().line;
- if (!ranges[i].to().ch) to--;
- toSort.push(from, to);
- }
- if (toSort.length) selected = true;
- else toSort.push(cm.firstLine(), cm.lastLine());
- cm.operation(function() {
- var ranges = [];
- for (var i = 0; i < toSort.length; i += 2) {
- var from = toSort[i], to = toSort[i + 1];
- var start = Pos(from, 0), end = Pos(to);
- var lines = cm.getRange(start, end, false);
- if (caseSensitive)
- lines.sort();
- else
- lines.sort(function(a, b) {
- var au = a.toUpperCase(), bu = b.toUpperCase();
- if (au != bu) { a = au; b = bu; }
- return a < b ? -1 : a == b ? 0 : 1;
- });
- cm.replaceRange(lines, start, end);
- if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)});
- }
- if (selected) cm.setSelections(ranges, 0);
- });
- }
- cmds.sortLines = function(cm) { sortLines(cm, true); };
- cmds.sortLinesInsensitive = function(cm) { sortLines(cm, false); };
- cmds.nextBookmark = function(cm) {
- var marks = cm.state.sublimeBookmarks;
- if (marks) while (marks.length) {
- var current = marks.shift();
- var found = current.find();
- if (found) {
- marks.push(current);
- return cm.setSelection(found.from, found.to);
- }
- }
- };
- cmds.prevBookmark = function(cm) {
- var marks = cm.state.sublimeBookmarks;
- if (marks) while (marks.length) {
- marks.unshift(marks.pop());
- var found = marks[marks.length - 1].find();
- if (!found)
- marks.pop();
- else
- return cm.setSelection(found.from, found.to);
- }
- };
- cmds.toggleBookmark = function(cm) {
- var ranges = cm.listSelections();
- var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []);
- for (var i = 0; i < ranges.length; i++) {
- var from = ranges[i].from(), to = ranges[i].to();
- var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to);
- for (var j = 0; j < found.length; j++) {
- if (found[j].sublimeBookmark) {
- found[j].clear();
- for (var k = 0; k < marks.length; k++)
- if (marks[k] == found[j])
- marks.splice(k--, 1);
- break;
- }
- }
- if (j == found.length)
- marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false}));
- }
- };
- cmds.clearBookmarks = function(cm) {
- var marks = cm.state.sublimeBookmarks;
- if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();
- marks.length = 0;
- };
- cmds.selectBookmarks = function(cm) {
- var marks = cm.state.sublimeBookmarks, ranges = [];
- if (marks) for (var i = 0; i < marks.length; i++) {
- var found = marks[i].find();
- if (!found)
- marks.splice(i--, 0);
- else
- ranges.push({anchor: found.from, head: found.to});
- }
- if (ranges.length)
- cm.setSelections(ranges, 0);
- };
- function modifyWordOrSelection(cm, mod) {
- cm.operation(function() {
- var ranges = cm.listSelections(), indices = [], replacements = [];
- for (var i = 0; i < ranges.length; i++) {
- var range = ranges[i];
- if (range.empty()) { indices.push(i); replacements.push(""); }
- else replacements.push(mod(cm.getRange(range.from(), range.to())));
- }
- cm.replaceSelections(replacements, "around", "case");
- for (var i = indices.length - 1, at; i >= 0; i--) {
- var range = ranges[indices[i]];
- if (at && CodeMirror.cmpPos(range.head, at) > 0) continue;
- var word = wordAt(cm, range.head);
- at = word.from;
- cm.replaceRange(mod(word.word), word.from, word.to);
- }
- });
- }
- cmds.smartBackspace = function(cm) {
- if (cm.somethingSelected()) return CodeMirror.Pass;
- cm.operation(function() {
- var cursors = cm.listSelections();
- var indentUnit = cm.getOption("indentUnit");
- for (var i = cursors.length - 1; i >= 0; i--) {
- var cursor = cursors[i].head;
- var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor);
- var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize"));
- // Delete by one character by default
- var deletePos = cm.findPosH(cursor, -1, "char", false);
- if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) {
- var prevIndent = new Pos(cursor.line,
- CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit));
- // Smart delete only if we found a valid prevIndent location
- if (prevIndent.ch != cursor.ch) deletePos = prevIndent;
- }
- cm.replaceRange("", deletePos, cursor, "+delete");
- }
- });
- };
- cmds.delLineRight = function(cm) {
- cm.operation(function() {
- var ranges = cm.listSelections();
- for (var i = ranges.length - 1; i >= 0; i--)
- cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete");
- cm.scrollIntoView();
- });
- };
- cmds.upcaseAtCursor = function(cm) {
- modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });
- };
- cmds.downcaseAtCursor = function(cm) {
- modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });
- };
- cmds.setSublimeMark = function(cm) {
- if (cm.state.sublimeMark) cm.state.sublimeMark.clear();
- cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
- };
- cmds.selectToSublimeMark = function(cm) {
- var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
- if (found) cm.setSelection(cm.getCursor(), found);
- };
- cmds.deleteToSublimeMark = function(cm) {
- var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
- if (found) {
- var from = cm.getCursor(), to = found;
- if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; }
- cm.state.sublimeKilled = cm.getRange(from, to);
- cm.replaceRange("", from, to);
- }
- };
- cmds.swapWithSublimeMark = function(cm) {
- var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
- if (found) {
- cm.state.sublimeMark.clear();
- cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
- cm.setCursor(found);
- }
- };
- cmds.sublimeYank = function(cm) {
- if (cm.state.sublimeKilled != null)
- cm.replaceSelection(cm.state.sublimeKilled, null, "paste");
- };
- cmds.showInCenter = function(cm) {
- var pos = cm.cursorCoords(null, "local");
- cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);
- };
- function getTarget(cm) {
- var from = cm.getCursor("from"), to = cm.getCursor("to");
- if (CodeMirror.cmpPos(from, to) == 0) {
- var word = wordAt(cm, from);
- if (!word.word) return;
- from = word.from;
- to = word.to;
- }
- return {from: from, to: to, query: cm.getRange(from, to), word: word};
- }
- function findAndGoTo(cm, forward) {
- var target = getTarget(cm);
- if (!target) return;
- var query = target.query;
- var cur = cm.getSearchCursor(query, forward ? target.to : target.from);
- if (forward ? cur.findNext() : cur.findPrevious()) {
- cm.setSelection(cur.from(), cur.to());
- } else {
- cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0)
- : cm.clipPos(Pos(cm.lastLine())));
- if (forward ? cur.findNext() : cur.findPrevious())
- cm.setSelection(cur.from(), cur.to());
- else if (target.word)
- cm.setSelection(target.from, target.to);
- }
- };
- cmds.findUnder = function(cm) { findAndGoTo(cm, true); };
- cmds.findUnderPrevious = function(cm) { findAndGoTo(cm,false); };
- cmds.findAllUnder = function(cm) {
- var target = getTarget(cm);
- if (!target) return;
- var cur = cm.getSearchCursor(target.query);
- var matches = [];
- var primaryIndex = -1;
- while (cur.findNext()) {
- matches.push({anchor: cur.from(), head: cur.to()});
- if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch)
- primaryIndex++;
- }
- cm.setSelections(matches, primaryIndex);
- };
- var keyMap = CodeMirror.keyMap;
- keyMap.macSublime = {
- "Cmd-Left": "goLineStartSmart",
- "Shift-Tab": "indentLess",
- "Shift-Ctrl-K": "deleteLine",
- "Alt-Q": "wrapLines",
- "Ctrl-Left": "goSubwordLeft",
- "Ctrl-Right": "goSubwordRight",
- "Ctrl-Alt-Up": "scrollLineUp",
- "Ctrl-Alt-Down": "scrollLineDown",
- "Cmd-L": "selectLine",
- "Shift-Cmd-L": "splitSelectionByLine",
- "Esc": "singleSelectionTop",
- "Cmd-Enter": "insertLineAfter",
- "Shift-Cmd-Enter": "insertLineBefore",
- "Cmd-D": "selectNextOccurrence",
- "Shift-Cmd-Space": "selectScope",
- "Shift-Cmd-M": "selectBetweenBrackets",
- "Cmd-M": "goToBracket",
- "Cmd-Ctrl-Up": "swapLineUp",
- "Cmd-Ctrl-Down": "swapLineDown",
- "Cmd-/": "toggleCommentIndented",
- "Cmd-J": "joinLines",
- "Shift-Cmd-D": "duplicateLine",
- "F5": "sortLines",
- "Cmd-F5": "sortLinesInsensitive",
- "F2": "nextBookmark",
- "Shift-F2": "prevBookmark",
- "Cmd-F2": "toggleBookmark",
- "Shift-Cmd-F2": "clearBookmarks",
- "Alt-F2": "selectBookmarks",
- "Backspace": "smartBackspace",
- "Cmd-K Cmd-K": "delLineRight",
- "Cmd-K Cmd-U": "upcaseAtCursor",
- "Cmd-K Cmd-L": "downcaseAtCursor",
- "Cmd-K Cmd-Space": "setSublimeMark",
- "Cmd-K Cmd-A": "selectToSublimeMark",
- "Cmd-K Cmd-W": "deleteToSublimeMark",
- "Cmd-K Cmd-X": "swapWithSublimeMark",
- "Cmd-K Cmd-Y": "sublimeYank",
- "Cmd-K Cmd-C": "showInCenter",
- "Cmd-K Cmd-G": "clearBookmarks",
- "Cmd-K Cmd-Backspace": "delLineLeft",
- "Cmd-K Cmd-0": "unfoldAll",
- "Cmd-K Cmd-J": "unfoldAll",
- "Ctrl-Shift-Up": "addCursorToPrevLine",
- "Ctrl-Shift-Down": "addCursorToNextLine",
- "Cmd-F3": "findUnder",
- "Shift-Cmd-F3": "findUnderPrevious",
- "Alt-F3": "findAllUnder",
- "Shift-Cmd-[": "fold",
- "Shift-Cmd-]": "unfold",
- "Cmd-I": "findIncremental",
- "Shift-Cmd-I": "findIncrementalReverse",
- "Cmd-H": "replace",
- "F3": "findNext",
- "Shift-F3": "findPrev",
- "fallthrough": "macDefault"
- };
- CodeMirror.normalizeKeyMap(keyMap.macSublime);
- keyMap.pcSublime = {
- "Shift-Tab": "indentLess",
- "Shift-Ctrl-K": "deleteLine",
- "Alt-Q": "wrapLines",
- "Ctrl-T": "transposeChars",
- "Alt-Left": "goSubwordLeft",
- "Alt-Right": "goSubwordRight",
- "Ctrl-Up": "scrollLineUp",
- "Ctrl-Down": "scrollLineDown",
- "Ctrl-L": "selectLine",
- "Shift-Ctrl-L": "splitSelectionByLine",
- "Esc": "singleSelectionTop",
- "Ctrl-Enter": "insertLineAfter",
- "Shift-Ctrl-Enter": "insertLineBefore",
- "Ctrl-D": "selectNextOccurrence",
- "Shift-Ctrl-Space": "selectScope",
- "Shift-Ctrl-M": "selectBetweenBrackets",
- "Ctrl-M": "goToBracket",
- "Shift-Ctrl-Up": "swapLineUp",
- "Shift-Ctrl-Down": "swapLineDown",
- "Ctrl-/": "toggleCommentIndented",
- "Ctrl-J": "joinLines",
- "Shift-Ctrl-D": "duplicateLine",
- "F9": "sortLines",
- "Ctrl-F9": "sortLinesInsensitive",
- "F2": "nextBookmark",
- "Shift-F2": "prevBookmark",
- "Ctrl-F2": "toggleBookmark",
- "Shift-Ctrl-F2": "clearBookmarks",
- "Alt-F2": "selectBookmarks",
- "Backspace": "smartBackspace",
- "Ctrl-K Ctrl-K": "delLineRight",
- "Ctrl-K Ctrl-U": "upcaseAtCursor",
- "Ctrl-K Ctrl-L": "downcaseAtCursor",
- "Ctrl-K Ctrl-Space": "setSublimeMark",
- "Ctrl-K Ctrl-A": "selectToSublimeMark",
- "Ctrl-K Ctrl-W": "deleteToSublimeMark",
- "Ctrl-K Ctrl-X": "swapWithSublimeMark",
- "Ctrl-K Ctrl-Y": "sublimeYank",
- "Ctrl-K Ctrl-C": "showInCenter",
- "Ctrl-K Ctrl-G": "clearBookmarks",
- "Ctrl-K Ctrl-Backspace": "delLineLeft",
- "Ctrl-K Ctrl-0": "unfoldAll",
- "Ctrl-K Ctrl-J": "unfoldAll",
- "Ctrl-Alt-Up": "addCursorToPrevLine",
- "Ctrl-Alt-Down": "addCursorToNextLine",
- "Ctrl-F3": "findUnder",
- "Shift-Ctrl-F3": "findUnderPrevious",
- "Alt-F3": "findAllUnder",
- "Shift-Ctrl-[": "fold",
- "Shift-Ctrl-]": "unfold",
- "Ctrl-I": "findIncremental",
- "Shift-Ctrl-I": "findIncrementalReverse",
- "Ctrl-H": "replace",
- "F3": "findNext",
- "Shift-F3": "findPrev",
- "fallthrough": "pcDefault"
- };
- CodeMirror.normalizeKeyMap(keyMap.pcSublime);
- var mac = keyMap.default == keyMap.macDefault;
- keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime;
- });
- },{"../addon/edit/matchbrackets":6,"../addon/search/searchcursor":14,"../lib/codemirror":16}],16:[function(require,module,exports){
- // CodeMirror, copyright (c) by Marijn Haverbeke and others
- // Distributed under an MIT license: https://codemirror.net/LICENSE
- // This is CodeMirror (https://codemirror.net), a code editor
- // implemented in JavaScript on top of the browser's DOM.
- //
- // You can find some technical background for some of the code below
- // at http://marijnhaverbeke.nl/blog/#cm-internals .
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global.CodeMirror = factory());
- }(this, (function () { 'use strict';
- // Kludges for bugs and behavior differences that can't be feature
- // detected are enabled based on userAgent etc sniffing.
- var userAgent = navigator.userAgent;
- var platform = navigator.platform;
- var gecko = /gecko\/\d/i.test(userAgent);
- var ie_upto10 = /MSIE \d/.test(userAgent);
- var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
- var edge = /Edge\/(\d+)/.exec(userAgent);
- var ie = ie_upto10 || ie_11up || edge;
- var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
- var webkit = !edge && /WebKit\//.test(userAgent);
- var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
- var chrome = !edge && /Chrome\//.test(userAgent);
- var presto = /Opera\//.test(userAgent);
- var safari = /Apple Computer/.test(navigator.vendor);
- var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
- var phantom = /PhantomJS/.test(userAgent);
- var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
- var android = /Android/.test(userAgent);
- // This is woefully incomplete. Suggestions for alternative methods welcome.
- var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
- var mac = ios || /Mac/.test(platform);
- var chromeOS = /\bCrOS\b/.test(userAgent);
- var windows = /win/i.test(platform);
- var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
- if (presto_version) { presto_version = Number(presto_version[1]); }
- if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
- // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
- var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
- var captureRightClick = gecko || (ie && ie_version >= 9);
- function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
- var rmClass = function(node, cls) {
- var current = node.className;
- var match = classTest(cls).exec(current);
- if (match) {
- var after = current.slice(match.index + match[0].length);
- node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
- }
- };
- function removeChildren(e) {
- for (var count = e.childNodes.length; count > 0; --count)
- { e.removeChild(e.firstChild); }
- return e
- }
- function removeChildrenAndAdd(parent, e) {
- return removeChildren(parent).appendChild(e)
- }
- function elt(tag, content, className, style) {
- var e = document.createElement(tag);
- if (className) { e.className = className; }
- if (style) { e.style.cssText = style; }
- if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
- else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
- return e
- }
- // wrapper for elt, which removes the elt from the accessibility tree
- function eltP(tag, content, className, style) {
- var e = elt(tag, content, className, style);
- e.setAttribute("role", "presentation");
- return e
- }
- var range;
- if (document.createRange) { range = function(node, start, end, endNode) {
- var r = document.createRange();
- r.setEnd(endNode || node, end);
- r.setStart(node, start);
- return r
- }; }
- else { range = function(node, start, end) {
- var r = document.body.createTextRange();
- try { r.moveToElementText(node.parentNode); }
- catch(e) { return r }
- r.collapse(true);
- r.moveEnd("character", end);
- r.moveStart("character", start);
- return r
- }; }
- function contains(parent, child) {
- if (child.nodeType == 3) // Android browser always returns false when child is a textnode
- { child = child.parentNode; }
- if (parent.contains)
- { return parent.contains(child) }
- do {
- if (child.nodeType == 11) { child = child.host; }
- if (child == parent) { return true }
- } while (child = child.parentNode)
- }
- function activeElt() {
- // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
- // IE < 10 will throw when accessed while the page is loading or in an iframe.
- // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
- var activeElement;
- try {
- activeElement = document.activeElement;
- } catch(e) {
- activeElement = document.body || null;
- }
- while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
- { activeElement = activeElement.shadowRoot.activeElement; }
- return activeElement
- }
- function addClass(node, cls) {
- var current = node.className;
- if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
- }
- function joinClasses(a, b) {
- var as = a.split(" ");
- for (var i = 0; i < as.length; i++)
- { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
- return b
- }
- var selectInput = function(node) { node.select(); };
- if (ios) // Mobile Safari apparently has a bug where select() is broken.
- { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
- else if (ie) // Suppress mysterious IE10 errors
- { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
- function bind(f) {
- var args = Array.prototype.slice.call(arguments, 1);
- return function(){return f.apply(null, args)}
- }
- function copyObj(obj, target, overwrite) {
- if (!target) { target = {}; }
- for (var prop in obj)
- { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
- { target[prop] = obj[prop]; } }
- return target
- }
- // Counts the column offset in a string, taking tabs into account.
- // Used mostly to find indentation.
- function countColumn(string, end, tabSize, startIndex, startValue) {
- if (end == null) {
- end = string.search(/[^\s\u00a0]/);
- if (end == -1) { end = string.length; }
- }
- for (var i = startIndex || 0, n = startValue || 0;;) {
- var nextTab = string.indexOf("\t", i);
- if (nextTab < 0 || nextTab >= end)
- { return n + (end - i) }
- n += nextTab - i;
- n += tabSize - (n % tabSize);
- i = nextTab + 1;
- }
- }
- var Delayed = function() {this.id = null;};
- Delayed.prototype.set = function (ms, f) {
- clearTimeout(this.id);
- this.id = setTimeout(f, ms);
- };
- function indexOf(array, elt) {
- for (var i = 0; i < array.length; ++i)
- { if (array[i] == elt) { return i } }
- return -1
- }
- // Number of pixels added to scroller and sizer to hide scrollbar
- var scrollerGap = 30;
- // Returned or thrown by various protocols to signal 'I'm not
- // handling this'.
- var Pass = {toString: function(){return "CodeMirror.Pass"}};
- // Reused option objects for setSelection & friends
- var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
- // The inverse of countColumn -- find the offset that corresponds to
- // a particular column.
- function findColumn(string, goal, tabSize) {
- for (var pos = 0, col = 0;;) {
- var nextTab = string.indexOf("\t", pos);
- if (nextTab == -1) { nextTab = string.length; }
- var skipped = nextTab - pos;
- if (nextTab == string.length || col + skipped >= goal)
- { return pos + Math.min(skipped, goal - col) }
- col += nextTab - pos;
- col += tabSize - (col % tabSize);
- pos = nextTab + 1;
- if (col >= goal) { return pos }
- }
- }
- var spaceStrs = [""];
- function spaceStr(n) {
- while (spaceStrs.length <= n)
- { spaceStrs.push(lst(spaceStrs) + " "); }
- return spaceStrs[n]
- }
- function lst(arr) { return arr[arr.length-1] }
- function map(array, f) {
- var out = [];
- for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
- return out
- }
- function insertSorted(array, value, score) {
- var pos = 0, priority = score(value);
- while (pos < array.length && score(array[pos]) <= priority) { pos++; }
- array.splice(pos, 0, value);
- }
- function nothing() {}
- function createObj(base, props) {
- var inst;
- if (Object.create) {
- inst = Object.create(base);
- } else {
- nothing.prototype = base;
- inst = new nothing();
- }
- if (props) { copyObj(props, inst); }
- return inst
- }
- var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
- function isWordCharBasic(ch) {
- return /\w/.test(ch) || ch > "\x80" &&
- (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
- }
- function isWordChar(ch, helper) {
- if (!helper) { return isWordCharBasic(ch) }
- if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
- return helper.test(ch)
- }
- function isEmpty(obj) {
- for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
- return true
- }
- // Extending unicode characters. A series of a non-extending char +
- // any number of extending chars is treated as a single unit as far
- // as editing and measuring is concerned. This is not fully correct,
- // since some scripts/fonts/browsers also treat other configurations
- // of code points as a group.
- var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
- function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
- // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
- function skipExtendingChars(str, pos, dir) {
- while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
- return pos
- }
- // Returns the value from the range [`from`; `to`] that satisfies
- // `pred` and is closest to `from`. Assumes that at least `to`
- // satisfies `pred`. Supports `from` being greater than `to`.
- function findFirst(pred, from, to) {
- // At any point we are certain `to` satisfies `pred`, don't know
- // whether `from` does.
- var dir = from > to ? -1 : 1;
- for (;;) {
- if (from == to) { return from }
- var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
- if (mid == from) { return pred(mid) ? from : to }
- if (pred(mid)) { to = mid; }
- else { from = mid + dir; }
- }
- }
- // BIDI HELPERS
- function iterateBidiSections(order, from, to, f) {
- if (!order) { return f(from, to, "ltr", 0) }
- var found = false;
- for (var i = 0; i < order.length; ++i) {
- var part = order[i];
- if (part.from < to && part.to > from || from == to && part.to == from) {
- f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
- found = true;
- }
- }
- if (!found) { f(from, to, "ltr"); }
- }
- var bidiOther = null;
- function getBidiPartAt(order, ch, sticky) {
- var found;
- bidiOther = null;
- for (var i = 0; i < order.length; ++i) {
- var cur = order[i];
- if (cur.from < ch && cur.to > ch) { return i }
- if (cur.to == ch) {
- if (cur.from != cur.to && sticky == "before") { found = i; }
- else { bidiOther = i; }
- }
- if (cur.from == ch) {
- if (cur.from != cur.to && sticky != "before") { found = i; }
- else { bidiOther = i; }
- }
- }
- return found != null ? found : bidiOther
- }
- // Bidirectional ordering algorithm
- // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
- // that this (partially) implements.
- // One-char codes used for character types:
- // L (L): Left-to-Right
- // R (R): Right-to-Left
- // r (AL): Right-to-Left Arabic
- // 1 (EN): European Number
- // + (ES): European Number Separator
- // % (ET): European Number Terminator
- // n (AN): Arabic Number
- // , (CS): Common Number Separator
- // m (NSM): Non-Spacing Mark
- // b (BN): Boundary Neutral
- // s (B): Paragraph Separator
- // t (S): Segment Separator
- // w (WS): Whitespace
- // N (ON): Other Neutrals
- // Returns null if characters are ordered as they appear
- // (left-to-right), or an array of sections ({from, to, level}
- // objects) in the order in which they occur visually.
- var bidiOrdering = (function() {
- // Character types for codepoints 0 to 0xff
- var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
- // Character types for codepoints 0x600 to 0x6f9
- var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
- function charType(code) {
- if (code <= 0xf7) { return lowTypes.charAt(code) }
- else if (0x590 <= code && code <= 0x5f4) { return "R" }
- else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
- else if (0x6ee <= code && code <= 0x8ac) { return "r" }
- else if (0x2000 <= code && code <= 0x200b) { return "w" }
- else if (code == 0x200c) { return "b" }
- else { return "L" }
- }
- var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
- var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
- function BidiSpan(level, from, to) {
- this.level = level;
- this.from = from; this.to = to;
- }
- return function(str, direction) {
- var outerType = direction == "ltr" ? "L" : "R";
- if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
- var len = str.length, types = [];
- for (var i = 0; i < len; ++i)
- { types.push(charType(str.charCodeAt(i))); }
- // W1. Examine each non-spacing mark (NSM) in the level run, and
- // change the type of the NSM to the type of the previous
- // character. If the NSM is at the start of the level run, it will
- // get the type of sor.
- for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
- var type = types[i$1];
- if (type == "m") { types[i$1] = prev; }
- else { prev = type; }
- }
- // W2. Search backwards from each instance of a European number
- // until the first strong type (R, L, AL, or sor) is found. If an
- // AL is found, change the type of the European number to Arabic
- // number.
- // W3. Change all ALs to R.
- for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
- var type$1 = types[i$2];
- if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
- else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
- }
- // W4. A single European separator between two European numbers
- // changes to a European number. A single common separator between
- // two numbers of the same type changes to that type.
- for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
- var type$2 = types[i$3];
- if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
- else if (type$2 == "," && prev$1 == types[i$3+1] &&
- (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
- prev$1 = type$2;
- }
- // W5. A sequence of European terminators adjacent to European
- // numbers changes to all European numbers.
- // W6. Otherwise, separators and terminators change to Other
- // Neutral.
- for (var i$4 = 0; i$4 < len; ++i$4) {
- var type$3 = types[i$4];
- if (type$3 == ",") { types[i$4] = "N"; }
- else if (type$3 == "%") {
- var end = (void 0);
- for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
- var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
- for (var j = i$4; j < end; ++j) { types[j] = replace; }
- i$4 = end - 1;
- }
- }
- // W7. Search backwards from each instance of a European number
- // until the first strong type (R, L, or sor) is found. If an L is
- // found, then change the type of the European number to L.
- for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
- var type$4 = types[i$5];
- if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
- else if (isStrong.test(type$4)) { cur$1 = type$4; }
- }
- // N1. A sequence of neutrals takes the direction of the
- // surrounding strong text if the text on both sides has the same
- // direction. European and Arabic numbers act as if they were R in
- // terms of their influence on neutrals. Start-of-level-run (sor)
- // and end-of-level-run (eor) are used at level run boundaries.
- // N2. Any remaining neutrals take the embedding direction.
- for (var i$6 = 0; i$6 < len; ++i$6) {
- if (isNeutral.test(types[i$6])) {
- var end$1 = (void 0);
- for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
- var before = (i$6 ? types[i$6-1] : outerType) == "L";
- var after = (end$1 < len ? types[end$1] : outerType) == "L";
- var replace$1 = before == after ? (before ? "L" : "R") : outerType;
- for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
- i$6 = end$1 - 1;
- }
- }
- // Here we depart from the documented algorithm, in order to avoid
- // building up an actual levels array. Since there are only three
- // levels (0, 1, 2) in an implementation that doesn't take
- // explicit embedding into account, we can build up the order on
- // the fly, without following the level-based algorithm.
- var order = [], m;
- for (var i$7 = 0; i$7 < len;) {
- if (countsAsLeft.test(types[i$7])) {
- var start = i$7;
- for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
- order.push(new BidiSpan(0, start, i$7));
- } else {
- var pos = i$7, at = order.length;
- for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
- for (var j$2 = pos; j$2 < i$7;) {
- if (countsAsNum.test(types[j$2])) {
- if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
- var nstart = j$2;
- for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
- order.splice(at, 0, new BidiSpan(2, nstart, j$2));
- pos = j$2;
- } else { ++j$2; }
- }
- if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
- }
- }
- if (direction == "ltr") {
- if (order[0].level == 1 && (m = str.match(/^\s+/))) {
- order[0].from = m[0].length;
- order.unshift(new BidiSpan(0, 0, m[0].length));
- }
- if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
- lst(order).to -= m[0].length;
- order.push(new BidiSpan(0, len - m[0].length, len));
- }
- }
- return direction == "rtl" ? order.reverse() : order
- }
- })();
- // Get the bidi ordering for the given line (and cache it). Returns
- // false for lines that are fully left-to-right, and an array of
- // BidiSpan objects otherwise.
- function getOrder(line, direction) {
- var order = line.order;
- if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
- return order
- }
- // EVENT HANDLING
- // Lightweight event framework. on/off also work on DOM nodes,
- // registering native DOM handlers.
- var noHandlers = [];
- var on = function(emitter, type, f) {
- if (emitter.addEventListener) {
- emitter.addEventListener(type, f, false);
- } else if (emitter.attachEvent) {
- emitter.attachEvent("on" + type, f);
- } else {
- var map$$1 = emitter._handlers || (emitter._handlers = {});
- map$$1[type] = (map$$1[type] || noHandlers).concat(f);
- }
- };
- function getHandlers(emitter, type) {
- return emitter._handlers && emitter._handlers[type] || noHandlers
- }
- function off(emitter, type, f) {
- if (emitter.removeEventListener) {
- emitter.removeEventListener(type, f, false);
- } else if (emitter.detachEvent) {
- emitter.detachEvent("on" + type, f);
- } else {
- var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
- if (arr) {
- var index = indexOf(arr, f);
- if (index > -1)
- { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
- }
- }
- }
- function signal(emitter, type /*, values...*/) {
- var handlers = getHandlers(emitter, type);
- if (!handlers.length) { return }
- var args = Array.prototype.slice.call(arguments, 2);
- for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
- }
- // The DOM events that CodeMirror handles can be overridden by
- // registering a (non-DOM) handler on the editor for the event name,
- // and preventDefault-ing the event in that handler.
- function signalDOMEvent(cm, e, override) {
- if (typeof e == "string")
- { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
- signal(cm, override || e.type, cm, e);
- return e_defaultPrevented(e) || e.codemirrorIgnore
- }
- function signalCursorActivity(cm) {
- var arr = cm._handlers && cm._handlers.cursorActivity;
- if (!arr) { return }
- var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
- for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
- { set.push(arr[i]); } }
- }
- function hasHandler(emitter, type) {
- return getHandlers(emitter, type).length > 0
- }
- // Add on and off methods to a constructor's prototype, to make
- // registering events on such objects more convenient.
- function eventMixin(ctor) {
- ctor.prototype.on = function(type, f) {on(this, type, f);};
- ctor.prototype.off = function(type, f) {off(this, type, f);};
- }
- // Due to the fact that we still support jurassic IE versions, some
- // compatibility wrappers are needed.
- function e_preventDefault(e) {
- if (e.preventDefault) { e.preventDefault(); }
- else { e.returnValue = false; }
- }
- function e_stopPropagation(e) {
- if (e.stopPropagation) { e.stopPropagation(); }
- else { e.cancelBubble = true; }
- }
- function e_defaultPrevented(e) {
- return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
- }
- function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
- function e_target(e) {return e.target || e.srcElement}
- function e_button(e) {
- var b = e.which;
- if (b == null) {
- if (e.button & 1) { b = 1; }
- else if (e.button & 2) { b = 3; }
- else if (e.button & 4) { b = 2; }
- }
- if (mac && e.ctrlKey && b == 1) { b = 3; }
- return b
- }
- // Detect drag-and-drop
- var dragAndDrop = function() {
- // There is *some* kind of drag-and-drop support in IE6-8, but I
- // couldn't get it to work yet.
- if (ie && ie_version < 9) { return false }
- var div = elt('div');
- return "draggable" in div || "dragDrop" in div
- }();
- var zwspSupported;
- function zeroWidthElement(measure) {
- if (zwspSupported == null) {
- var test = elt("span", "\u200b");
- removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
- if (measure.firstChild.offsetHeight != 0)
- { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
- }
- var node = zwspSupported ? elt("span", "\u200b") :
- elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
- node.setAttribute("cm-text", "");
- return node
- }
- // Feature-detect IE's crummy client rect reporting for bidi text
- var badBidiRects;
- function hasBadBidiRects(measure) {
- if (badBidiRects != null) { return badBidiRects }
- var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
- var r0 = range(txt, 0, 1).getBoundingClientRect();
- var r1 = range(txt, 1, 2).getBoundingClientRect();
- removeChildren(measure);
- if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
- return badBidiRects = (r1.right - r0.right < 3)
- }
- // See if "".split is the broken IE version, if so, provide an
- // alternative way to split lines.
- var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
- var pos = 0, result = [], l = string.length;
- while (pos <= l) {
- var nl = string.indexOf("\n", pos);
- if (nl == -1) { nl = string.length; }
- var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
- var rt = line.indexOf("\r");
- if (rt != -1) {
- result.push(line.slice(0, rt));
- pos += rt + 1;
- } else {
- result.push(line);
- pos = nl + 1;
- }
- }
- return result
- } : function (string) { return string.split(/\r\n?|\n/); };
- var hasSelection = window.getSelection ? function (te) {
- try { return te.selectionStart != te.selectionEnd }
- catch(e) { return false }
- } : function (te) {
- var range$$1;
- try {range$$1 = te.ownerDocument.selection.createRange();}
- catch(e) {}
- if (!range$$1 || range$$1.parentElement() != te) { return false }
- return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
- };
- var hasCopyEvent = (function () {
- var e = elt("div");
- if ("oncopy" in e) { return true }
- e.setAttribute("oncopy", "return;");
- return typeof e.oncopy == "function"
- })();
- var badZoomedRects = null;
- function hasBadZoomedRects(measure) {
- if (badZoomedRects != null) { return badZoomedRects }
- var node = removeChildrenAndAdd(measure, elt("span", "x"));
- var normal = node.getBoundingClientRect();
- var fromRange = range(node, 0, 1).getBoundingClientRect();
- return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
- }
- // Known modes, by name and by MIME
- var modes = {}, mimeModes = {};
- // Extra arguments are stored as the mode's dependencies, which is
- // used by (legacy) mechanisms like loadmode.js to automatically
- // load a mode. (Preferred mechanism is the require/define calls.)
- function defineMode(name, mode) {
- if (arguments.length > 2)
- { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
- modes[name] = mode;
- }
- function defineMIME(mime, spec) {
- mimeModes[mime] = spec;
- }
- // Given a MIME type, a {name, ...options} config object, or a name
- // string, return a mode config object.
- function resolveMode(spec) {
- if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
- spec = mimeModes[spec];
- } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
- var found = mimeModes[spec.name];
- if (typeof found == "string") { found = {name: found}; }
- spec = createObj(found, spec);
- spec.name = found.name;
- } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
- return resolveMode("application/xml")
- } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
- return resolveMode("application/json")
- }
- if (typeof spec == "string") { return {name: spec} }
- else { return spec || {name: "null"} }
- }
- // Given a mode spec (anything that resolveMode accepts), find and
- // initialize an actual mode object.
- function getMode(options, spec) {
- spec = resolveMode(spec);
- var mfactory = modes[spec.name];
- if (!mfactory) { return getMode(options, "text/plain") }
- var modeObj = mfactory(options, spec);
- if (modeExtensions.hasOwnProperty(spec.name)) {
- var exts = modeExtensions[spec.name];
- for (var prop in exts) {
- if (!exts.hasOwnProperty(prop)) { continue }
- if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
- modeObj[prop] = exts[prop];
- }
- }
- modeObj.name = spec.name;
- if (spec.helperType) { modeObj.helperType = spec.helperType; }
- if (spec.modeProps) { for (var prop$1 in spec.modeProps)
- { modeObj[prop$1] = spec.modeProps[prop$1]; } }
- return modeObj
- }
- // This can be used to attach properties to mode objects from
- // outside the actual mode definition.
- var modeExtensions = {};
- function extendMode(mode, properties) {
- var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
- copyObj(properties, exts);
- }
- function copyState(mode, state) {
- if (state === true) { return state }
- if (mode.copyState) { return mode.copyState(state) }
- var nstate = {};
- for (var n in state) {
- var val = state[n];
- if (val instanceof Array) { val = val.concat([]); }
- nstate[n] = val;
- }
- return nstate
- }
- // Given a mode and a state (for that mode), find the inner mode and
- // state at the position that the state refers to.
- function innerMode(mode, state) {
- var info;
- while (mode.innerMode) {
- info = mode.innerMode(state);
- if (!info || info.mode == mode) { break }
- state = info.state;
- mode = info.mode;
- }
- return info || {mode: mode, state: state}
- }
- function startState(mode, a1, a2) {
- return mode.startState ? mode.startState(a1, a2) : true
- }
- // STRING STREAM
- // Fed to the mode parsers, provides helper functions to make
- // parsers more succinct.
- var StringStream = function(string, tabSize, lineOracle) {
- this.pos = this.start = 0;
- this.string = string;
- this.tabSize = tabSize || 8;
- this.lastColumnPos = this.lastColumnValue = 0;
- this.lineStart = 0;
- this.lineOracle = lineOracle;
- };
- StringStream.prototype.eol = function () {return this.pos >= this.string.length};
- StringStream.prototype.sol = function () {return this.pos == this.lineStart};
- StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
- StringStream.prototype.next = function () {
- if (this.pos < this.string.length)
- { return this.string.charAt(this.pos++) }
- };
- StringStream.prototype.eat = function (match) {
- var ch = this.string.charAt(this.pos);
- var ok;
- if (typeof match == "string") { ok = ch == match; }
- else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
- if (ok) {++this.pos; return ch}
- };
- StringStream.prototype.eatWhile = function (match) {
- var start = this.pos;
- while (this.eat(match)){}
- return this.pos > start
- };
- StringStream.prototype.eatSpace = function () {
- var this$1 = this;
- var start = this.pos;
- while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
- return this.pos > start
- };
- StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
- StringStream.prototype.skipTo = function (ch) {
- var found = this.string.indexOf(ch, this.pos);
- if (found > -1) {this.pos = found; return true}
- };
- StringStream.prototype.backUp = function (n) {this.pos -= n;};
- StringStream.prototype.column = function () {
- if (this.lastColumnPos < this.start) {
- this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
- this.lastColumnPos = this.start;
- }
- return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
- };
- StringStream.prototype.indentation = function () {
- return countColumn(this.string, null, this.tabSize) -
- (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
- };
- StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
- if (typeof pattern == "string") {
- var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
- var substr = this.string.substr(this.pos, pattern.length);
- if (cased(substr) == cased(pattern)) {
- if (consume !== false) { this.pos += pattern.length; }
- return true
- }
- } else {
- var match = this.string.slice(this.pos).match(pattern);
- if (match && match.index > 0) { return null }
- if (match && consume !== false) { this.pos += match[0].length; }
- return match
- }
- };
- StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
- StringStream.prototype.hideFirstChars = function (n, inner) {
- this.lineStart += n;
- try { return inner() }
- finally { this.lineStart -= n; }
- };
- StringStream.prototype.lookAhead = function (n) {
- var oracle = this.lineOracle;
- return oracle && oracle.lookAhead(n)
- };
- StringStream.prototype.baseToken = function () {
- var oracle = this.lineOracle;
- return oracle && oracle.baseToken(this.pos)
- };
- // Find the line object corresponding to the given line number.
- function getLine(doc, n) {
- n -= doc.first;
- if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
- var chunk = doc;
- while (!chunk.lines) {
- for (var i = 0;; ++i) {
- var child = chunk.children[i], sz = child.chunkSize();
- if (n < sz) { chunk = child; break }
- n -= sz;
- }
- }
- return chunk.lines[n]
- }
- // Get the part of a document between two positions, as an array of
- // strings.
- function getBetween(doc, start, end) {
- var out = [], n = start.line;
- doc.iter(start.line, end.line + 1, function (line) {
- var text = line.text;
- if (n == end.line) { text = text.slice(0, end.ch); }
- if (n == start.line) { text = text.slice(start.ch); }
- out.push(text);
- ++n;
- });
- return out
- }
- // Get the lines between from and to, as array of strings.
- function getLines(doc, from, to) {
- var out = [];
- doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
- return out
- }
- // Update the height of a line, propagating the height change
- // upwards to parent nodes.
- function updateLineHeight(line, height) {
- var diff = height - line.height;
- if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
- }
- // Given a line object, find its line number by walking up through
- // its parent links.
- function lineNo(line) {
- if (line.parent == null) { return null }
- var cur = line.parent, no = indexOf(cur.lines, line);
- for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
- for (var i = 0;; ++i) {
- if (chunk.children[i] == cur) { break }
- no += chunk.children[i].chunkSize();
- }
- }
- return no + cur.first
- }
- // Find the line at the given vertical position, using the height
- // information in the document tree.
- function lineAtHeight(chunk, h) {
- var n = chunk.first;
- outer: do {
- for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
- var child = chunk.children[i$1], ch = child.height;
- if (h < ch) { chunk = child; continue outer }
- h -= ch;
- n += child.chunkSize();
- }
- return n
- } while (!chunk.lines)
- var i = 0;
- for (; i < chunk.lines.length; ++i) {
- var line = chunk.lines[i], lh = line.height;
- if (h < lh) { break }
- h -= lh;
- }
- return n + i
- }
- function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
- function lineNumberFor(options, i) {
- return String(options.lineNumberFormatter(i + options.firstLineNumber))
- }
- // A Pos instance represents a position within the text.
- function Pos(line, ch, sticky) {
- if ( sticky === void 0 ) sticky = null;
- if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
- this.line = line;
- this.ch = ch;
- this.sticky = sticky;
- }
- // Compare two positions, return 0 if they are the same, a negative
- // number when a is less, and a positive number otherwise.
- function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
- function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
- function copyPos(x) {return Pos(x.line, x.ch)}
- function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
- function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
- // Most of the external API clips given positions to make sure they
- // actually exist within the document.
- function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
- function clipPos(doc, pos) {
- if (pos.line < doc.first) { return Pos(doc.first, 0) }
- var last = doc.first + doc.size - 1;
- if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
- return clipToLen(pos, getLine(doc, pos.line).text.length)
- }
- function clipToLen(pos, linelen) {
- var ch = pos.ch;
- if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
- else if (ch < 0) { return Pos(pos.line, 0) }
- else { return pos }
- }
- function clipPosArray(doc, array) {
- var out = [];
- for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
- return out
- }
- var SavedContext = function(state, lookAhead) {
- this.state = state;
- this.lookAhead = lookAhead;
- };
- var Context = function(doc, state, line, lookAhead) {
- this.state = state;
- this.doc = doc;
- this.line = line;
- this.maxLookAhead = lookAhead || 0;
- this.baseTokens = null;
- this.baseTokenPos = 1;
- };
- Context.prototype.lookAhead = function (n) {
- var line = this.doc.getLine(this.line + n);
- if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
- return line
- };
- Context.prototype.baseToken = function (n) {
- var this$1 = this;
- if (!this.baseTokens) { return null }
- while (this.baseTokens[this.baseTokenPos] <= n)
- { this$1.baseTokenPos += 2; }
- var type = this.baseTokens[this.baseTokenPos + 1];
- return {type: type && type.replace(/( |^)overlay .*/, ""),
- size: this.baseTokens[this.baseTokenPos] - n}
- };
- Context.prototype.nextLine = function () {
- this.line++;
- if (this.maxLookAhead > 0) { this.maxLookAhead--; }
- };
- Context.fromSaved = function (doc, saved, line) {
- if (saved instanceof SavedContext)
- { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
- else
- { return new Context(doc, copyState(doc.mode, saved), line) }
- };
- Context.prototype.save = function (copy) {
- var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
- return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
- };
- // Compute a style array (an array starting with a mode generation
- // -- for invalidation -- followed by pairs of end positions and
- // style strings), which is used to highlight the tokens on the
- // line.
- function highlightLine(cm, line, context, forceToEnd) {
- // A styles array always starts with a number identifying the
- // mode/overlays that it is based on (for easy invalidation).
- var st = [cm.state.modeGen], lineClasses = {};
- // Compute the base array of styles
- runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
- lineClasses, forceToEnd);
- var state = context.state;
- // Run overlays, adjust style array.
- var loop = function ( o ) {
- context.baseTokens = st;
- var overlay = cm.state.overlays[o], i = 1, at = 0;
- context.state = true;
- runMode(cm, line.text, overlay.mode, context, function (end, style) {
- var start = i;
- // Ensure there's a token end at the current position, and that i points at it
- while (at < end) {
- var i_end = st[i];
- if (i_end > end)
- { st.splice(i, 1, end, st[i+1], i_end); }
- i += 2;
- at = Math.min(end, i_end);
- }
- if (!style) { return }
- if (overlay.opaque) {
- st.splice(start, i - start, end, "overlay " + style);
- i = start + 2;
- } else {
- for (; start < i; start += 2) {
- var cur = st[start+1];
- st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
- }
- }
- }, lineClasses);
- context.state = state;
- context.baseTokens = null;
- context.baseTokenPos = 1;
- };
- for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
- return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
- }
- function getLineStyles(cm, line, updateFrontier) {
- if (!line.styles || line.styles[0] != cm.state.modeGen) {
- var context = getContextBefore(cm, lineNo(line));
- var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
- var result = highlightLine(cm, line, context);
- if (resetState) { context.state = resetState; }
- line.stateAfter = context.save(!resetState);
- line.styles = result.styles;
- if (result.classes) { line.styleClasses = result.classes; }
- else if (line.styleClasses) { line.styleClasses = null; }
- if (updateFrontier === cm.doc.highlightFrontier)
- { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
- }
- return line.styles
- }
- function getContextBefore(cm, n, precise) {
- var doc = cm.doc, display = cm.display;
- if (!doc.mode.startState) { return new Context(doc, true, n) }
- var start = findStartLine(cm, n, precise);
- var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
- var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
- doc.iter(start, n, function (line) {
- processLine(cm, line.text, context);
- var pos = context.line;
- line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
- context.nextLine();
- });
- if (precise) { doc.modeFrontier = context.line; }
- return context
- }
- // Lightweight form of highlight -- proceed over this line and
- // update state, but don't save a style array. Used for lines that
- // aren't currently visible.
- function processLine(cm, text, context, startAt) {
- var mode = cm.doc.mode;
- var stream = new StringStream(text, cm.options.tabSize, context);
- stream.start = stream.pos = startAt || 0;
- if (text == "") { callBlankLine(mode, context.state); }
- while (!stream.eol()) {
- readToken(mode, stream, context.state);
- stream.start = stream.pos;
- }
- }
- function callBlankLine(mode, state) {
- if (mode.blankLine) { return mode.blankLine(state) }
- if (!mode.innerMode) { return }
- var inner = innerMode(mode, state);
- if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
- }
- function readToken(mode, stream, state, inner) {
- for (var i = 0; i < 10; i++) {
- if (inner) { inner[0] = innerMode(mode, state).mode; }
- var style = mode.token(stream, state);
- if (stream.pos > stream.start) { return style }
- }
- throw new Error("Mode " + mode.name + " failed to advance stream.")
- }
- var Token = function(stream, type, state) {
- this.start = stream.start; this.end = stream.pos;
- this.string = stream.current();
- this.type = type || null;
- this.state = state;
- };
- // Utility for getTokenAt and getLineTokens
- function takeToken(cm, pos, precise, asArray) {
- var doc = cm.doc, mode = doc.mode, style;
- pos = clipPos(doc, pos);
- var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
- var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
- if (asArray) { tokens = []; }
- while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
- stream.start = stream.pos;
- style = readToken(mode, stream, context.state);
- if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
- }
- return asArray ? tokens : new Token(stream, style, context.state)
- }
- function extractLineClasses(type, output) {
- if (type) { for (;;) {
- var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
- if (!lineClass) { break }
- type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
- var prop = lineClass[1] ? "bgClass" : "textClass";
- if (output[prop] == null)
- { output[prop] = lineClass[2]; }
- else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
- { output[prop] += " " + lineClass[2]; }
- } }
- return type
- }
- // Run the given mode's parser over a line, calling f for each token.
- function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
- var flattenSpans = mode.flattenSpans;
- if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
- var curStart = 0, curStyle = null;
- var stream = new StringStream(text, cm.options.tabSize, context), style;
- var inner = cm.options.addModeClass && [null];
- if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
- while (!stream.eol()) {
- if (stream.pos > cm.options.maxHighlightLength) {
- flattenSpans = false;
- if (forceToEnd) { processLine(cm, text, context, stream.pos); }
- stream.pos = text.length;
- style = null;
- } else {
- style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
- }
- if (inner) {
- var mName = inner[0].name;
- if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
- }
- if (!flattenSpans || curStyle != style) {
- while (curStart < stream.start) {
- curStart = Math.min(stream.start, curStart + 5000);
- f(curStart, curStyle);
- }
- curStyle = style;
- }
- stream.start = stream.pos;
- }
- while (curStart < stream.pos) {
- // Webkit seems to refuse to render text nodes longer than 57444
- // characters, and returns inaccurate measurements in nodes
- // starting around 5000 chars.
- var pos = Math.min(stream.pos, curStart + 5000);
- f(pos, curStyle);
- curStart = pos;
- }
- }
- // Finds the line to start with when starting a parse. Tries to
- // find a line with a stateAfter, so that it can start with a
- // valid state. If that fails, it returns the line with the
- // smallest indentation, which tends to need the least context to
- // parse correctly.
- function findStartLine(cm, n, precise) {
- var minindent, minline, doc = cm.doc;
- var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
- for (var search = n; search > lim; --search) {
- if (search <= doc.first) { return doc.first }
- var line = getLine(doc, search - 1), after = line.stateAfter;
- if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
- { return search }
- var indented = countColumn(line.text, null, cm.options.tabSize);
- if (minline == null || minindent > indented) {
- minline = search - 1;
- minindent = indented;
- }
- }
- return minline
- }
- function retreatFrontier(doc, n) {
- doc.modeFrontier = Math.min(doc.modeFrontier, n);
- if (doc.highlightFrontier < n - 10) { return }
- var start = doc.first;
- for (var line = n - 1; line > start; line--) {
- var saved = getLine(doc, line).stateAfter;
- // change is on 3
- // state on line 1 looked ahead 2 -- so saw 3
- // test 1 + 2 < 3 should cover this
- if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
- start = line + 1;
- break
- }
- }
- doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
- }
- // Optimize some code when these features are not used.
- var sawReadOnlySpans = false, sawCollapsedSpans = false;
- function seeReadOnlySpans() {
- sawReadOnlySpans = true;
- }
- function seeCollapsedSpans() {
- sawCollapsedSpans = true;
- }
- // TEXTMARKER SPANS
- function MarkedSpan(marker, from, to) {
- this.marker = marker;
- this.from = from; this.to = to;
- }
- // Search an array of spans for a span matching the given marker.
- function getMarkedSpanFor(spans, marker) {
- if (spans) { for (var i = 0; i < spans.length; ++i) {
- var span = spans[i];
- if (span.marker == marker) { return span }
- } }
- }
- // Remove a span from an array, returning undefined if no spans are
- // left (we don't store arrays for lines without spans).
- function removeMarkedSpan(spans, span) {
- var r;
- for (var i = 0; i < spans.length; ++i)
- { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
- return r
- }
- // Add a span to a line.
- function addMarkedSpan(line, span) {
- line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
- span.marker.attachLine(line);
- }
- // Used for the algorithm that adjusts markers for a change in the
- // document. These functions cut an array of spans at a given
- // character position, returning an array of remaining chunks (or
- // undefined if nothing remains).
- function markedSpansBefore(old, startCh, isInsert) {
- var nw;
- if (old) { for (var i = 0; i < old.length; ++i) {
- var span = old[i], marker = span.marker;
- var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
- if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
- var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
- ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
- }
- } }
- return nw
- }
- function markedSpansAfter(old, endCh, isInsert) {
- var nw;
- if (old) { for (var i = 0; i < old.length; ++i) {
- var span = old[i], marker = span.marker;
- var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
- if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
- var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
- ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
- span.to == null ? null : span.to - endCh));
- }
- } }
- return nw
- }
- // Given a change object, compute the new set of marker spans that
- // cover the line in which the change took place. Removes spans
- // entirely within the change, reconnects spans belonging to the
- // same marker that appear on both sides of the change, and cuts off
- // spans partially within the change. Returns an array of span
- // arrays with one element for each line in (after) the change.
- function stretchSpansOverChange(doc, change) {
- if (change.full) { return null }
- var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
- var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
- if (!oldFirst && !oldLast) { return null }
- var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
- // Get the spans that 'stick out' on both sides
- var first = markedSpansBefore(oldFirst, startCh, isInsert);
- var last = markedSpansAfter(oldLast, endCh, isInsert);
- // Next, merge those two ends
- var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
- if (first) {
- // Fix up .to properties of first
- for (var i = 0; i < first.length; ++i) {
- var span = first[i];
- if (span.to == null) {
- var found = getMarkedSpanFor(last, span.marker);
- if (!found) { span.to = startCh; }
- else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
- }
- }
- }
- if (last) {
- // Fix up .from in last (or move them into first in case of sameLine)
- for (var i$1 = 0; i$1 < last.length; ++i$1) {
- var span$1 = last[i$1];
- if (span$1.to != null) { span$1.to += offset; }
- if (span$1.from == null) {
- var found$1 = getMarkedSpanFor(first, span$1.marker);
- if (!found$1) {
- span$1.from = offset;
- if (sameLine) { (first || (first = [])).push(span$1); }
- }
- } else {
- span$1.from += offset;
- if (sameLine) { (first || (first = [])).push(span$1); }
- }
- }
- }
- // Make sure we didn't create any zero-length spans
- if (first) { first = clearEmptySpans(first); }
- if (last && last != first) { last = clearEmptySpans(last); }
- var newMarkers = [first];
- if (!sameLine) {
- // Fill gap with whole-line-spans
- var gap = change.text.length - 2, gapMarkers;
- if (gap > 0 && first)
- { for (var i$2 = 0; i$2 < first.length; ++i$2)
- { if (first[i$2].to == null)
- { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
- for (var i$3 = 0; i$3 < gap; ++i$3)
- { newMarkers.push(gapMarkers); }
- newMarkers.push(last);
- }
- return newMarkers
- }
- // Remove spans that are empty and don't have a clearWhenEmpty
- // option of false.
- function clearEmptySpans(spans) {
- for (var i = 0; i < spans.length; ++i) {
- var span = spans[i];
- if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
- { spans.splice(i--, 1); }
- }
- if (!spans.length) { return null }
- return spans
- }
- // Used to 'clip' out readOnly ranges when making a change.
- function removeReadOnlyRanges(doc, from, to) {
- var markers = null;
- doc.iter(from.line, to.line + 1, function (line) {
- if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
- var mark = line.markedSpans[i].marker;
- if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
- { (markers || (markers = [])).push(mark); }
- } }
- });
- if (!markers) { return null }
- var parts = [{from: from, to: to}];
- for (var i = 0; i < markers.length; ++i) {
- var mk = markers[i], m = mk.find(0);
- for (var j = 0; j < parts.length; ++j) {
- var p = parts[j];
- if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
- var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
- if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
- { newParts.push({from: p.from, to: m.from}); }
- if (dto > 0 || !mk.inclusiveRight && !dto)
- { newParts.push({from: m.to, to: p.to}); }
- parts.splice.apply(parts, newParts);
- j += newParts.length - 3;
- }
- }
- return parts
- }
- // Connect or disconnect spans from a line.
- function detachMarkedSpans(line) {
- var spans = line.markedSpans;
- if (!spans) { return }
- for (var i = 0; i < spans.length; ++i)
- { spans[i].marker.detachLine(line); }
- line.markedSpans = null;
- }
- function attachMarkedSpans(line, spans) {
- if (!spans) { return }
- for (var i = 0; i < spans.length; ++i)
- { spans[i].marker.attachLine(line); }
- line.markedSpans = spans;
- }
- // Helpers used when computing which overlapping collapsed span
- // counts as the larger one.
- function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
- function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
- // Returns a number indicating which of two overlapping collapsed
- // spans is larger (and thus includes the other). Falls back to
- // comparing ids when the spans cover exactly the same range.
- function compareCollapsedMarkers(a, b) {
- var lenDiff = a.lines.length - b.lines.length;
- if (lenDiff != 0) { return lenDiff }
- var aPos = a.find(), bPos = b.find();
- var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
- if (fromCmp) { return -fromCmp }
- var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
- if (toCmp) { return toCmp }
- return b.id - a.id
- }
- // Find out whether a line ends or starts in a collapsed span. If
- // so, return the marker for that span.
- function collapsedSpanAtSide(line, start) {
- var sps = sawCollapsedSpans && line.markedSpans, found;
- if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
- sp = sps[i];
- if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
- (!found || compareCollapsedMarkers(found, sp.marker) < 0))
- { found = sp.marker; }
- } }
- return found
- }
- function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
- function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
- function collapsedSpanAround(line, ch) {
- var sps = sawCollapsedSpans && line.markedSpans, found;
- if (sps) { for (var i = 0; i < sps.length; ++i) {
- var sp = sps[i];
- if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
- (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
- } }
- return found
- }
- // Test whether there exists a collapsed span that partially
- // overlaps (covers the start or end, but not both) of a new span.
- // Such overlap is not allowed.
- function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
- var line = getLine(doc, lineNo$$1);
- var sps = sawCollapsedSpans && line.markedSpans;
- if (sps) { for (var i = 0; i < sps.length; ++i) {
- var sp = sps[i];
- if (!sp.marker.collapsed) { continue }
- var found = sp.marker.find(0);
- var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
- var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
- if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
- if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
- fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
- { return true }
- } }
- }
- // A visual line is a line as drawn on the screen. Folding, for
- // example, can cause multiple logical lines to appear on the same
- // visual line. This finds the start of the visual line that the
- // given line is part of (usually that is the line itself).
- function visualLine(line) {
- var merged;
- while (merged = collapsedSpanAtStart(line))
- { line = merged.find(-1, true).line; }
- return line
- }
- function visualLineEnd(line) {
- var merged;
- while (merged = collapsedSpanAtEnd(line))
- { line = merged.find(1, true).line; }
- return line
- }
- // Returns an array of logical lines that continue the visual line
- // started by the argument, or undefined if there are no such lines.
- function visualLineContinued(line) {
- var merged, lines;
- while (merged = collapsedSpanAtEnd(line)) {
- line = merged.find(1, true).line
- ;(lines || (lines = [])).push(line);
- }
- return lines
- }
- // Get the line number of the start of the visual line that the
- // given line number is part of.
- function visualLineNo(doc, lineN) {
- var line = getLine(doc, lineN), vis = visualLine(line);
- if (line == vis) { return lineN }
- return lineNo(vis)
- }
- // Get the line number of the start of the next visual line after
- // the given line.
- function visualLineEndNo(doc, lineN) {
- if (lineN > doc.lastLine()) { return lineN }
- var line = getLine(doc, lineN), merged;
- if (!lineIsHidden(doc, line)) { return lineN }
- while (merged = collapsedSpanAtEnd(line))
- { line = merged.find(1, true).line; }
- return lineNo(line) + 1
- }
- // Compute whether a line is hidden. Lines count as hidden when they
- // are part of a visual line that starts with another line, or when
- // they are entirely covered by collapsed, non-widget span.
- function lineIsHidden(doc, line) {
- var sps = sawCollapsedSpans && line.markedSpans;
- if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
- sp = sps[i];
- if (!sp.marker.collapsed) { continue }
- if (sp.from == null) { return true }
- if (sp.marker.widgetNode) { continue }
- if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
- { return true }
- } }
- }
- function lineIsHiddenInner(doc, line, span) {
- if (span.to == null) {
- var end = span.marker.find(1, true);
- return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
- }
- if (span.marker.inclusiveRight && span.to == line.text.length)
- { return true }
- for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
- sp = line.markedSpans[i];
- if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
- (sp.to == null || sp.to != span.from) &&
- (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
- lineIsHiddenInner(doc, line, sp)) { return true }
- }
- }
- // Find the height above the given line.
- function heightAtLine(lineObj) {
- lineObj = visualLine(lineObj);
- var h = 0, chunk = lineObj.parent;
- for (var i = 0; i < chunk.lines.length; ++i) {
- var line = chunk.lines[i];
- if (line == lineObj) { break }
- else { h += line.height; }
- }
- for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
- for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
- var cur = p.children[i$1];
- if (cur == chunk) { break }
- else { h += cur.height; }
- }
- }
- return h
- }
- // Compute the character length of a line, taking into account
- // collapsed ranges (see markText) that might hide parts, and join
- // other lines onto it.
- function lineLength(line) {
- if (line.height == 0) { return 0 }
- var len = line.text.length, merged, cur = line;
- while (merged = collapsedSpanAtStart(cur)) {
- var found = merged.find(0, true);
- cur = found.from.line;
- len += found.from.ch - found.to.ch;
- }
- cur = line;
- while (merged = collapsedSpanAtEnd(cur)) {
- var found$1 = merged.find(0, true);
- len -= cur.text.length - found$1.from.ch;
- cur = found$1.to.line;
- len += cur.text.length - found$1.to.ch;
- }
- return len
- }
- // Find the longest line in the document.
- function findMaxLine(cm) {
- var d = cm.display, doc = cm.doc;
- d.maxLine = getLine(doc, doc.first);
- d.maxLineLength = lineLength(d.maxLine);
- d.maxLineChanged = true;
- doc.iter(function (line) {
- var len = lineLength(line);
- if (len > d.maxLineLength) {
- d.maxLineLength = len;
- d.maxLine = line;
- }
- });
- }
- // LINE DATA STRUCTURE
- // Line objects. These hold state related to a line, including
- // highlighting info (the styles array).
- var Line = function(text, markedSpans, estimateHeight) {
- this.text = text;
- attachMarkedSpans(this, markedSpans);
- this.height = estimateHeight ? estimateHeight(this) : 1;
- };
- Line.prototype.lineNo = function () { return lineNo(this) };
- eventMixin(Line);
- // Change the content (text, markers) of a line. Automatically
- // invalidates cached information and tries to re-estimate the
- // line's height.
- function updateLine(line, text, markedSpans, estimateHeight) {
- line.text = text;
- if (line.stateAfter) { line.stateAfter = null; }
- if (line.styles) { line.styles = null; }
- if (line.order != null) { line.order = null; }
- detachMarkedSpans(line);
- attachMarkedSpans(line, markedSpans);
- var estHeight = estimateHeight ? estimateHeight(line) : 1;
- if (estHeight != line.height) { updateLineHeight(line, estHeight); }
- }
- // Detach a line from the document tree and its markers.
- function cleanUpLine(line) {
- line.parent = null;
- detachMarkedSpans(line);
- }
- // Convert a style as returned by a mode (either null, or a string
- // containing one or more styles) to a CSS style. This is cached,
- // and also looks for line-wide styles.
- var styleToClassCache = {}, styleToClassCacheWithMode = {};
- function interpretTokenStyle(style, options) {
- if (!style || /^\s*$/.test(style)) { return null }
- var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
- return cache[style] ||
- (cache[style] = style.replace(/\S+/g, "cm-$&"))
- }
- // Render the DOM representation of the text of a line. Also builds
- // up a 'line map', which points at the DOM nodes that represent
- // specific stretches of text, and is used by the measuring code.
- // The returned object contains the DOM node, this map, and
- // information about line-wide styles that were set by the mode.
- function buildLineContent(cm, lineView) {
- // The padding-right forces the element to have a 'border', which
- // is needed on Webkit to be able to get line-level bounding
- // rectangles for it (in measureChar).
- var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
- var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
- col: 0, pos: 0, cm: cm,
- trailingSpace: false,
- splitSpaces: cm.getOption("lineWrapping")};
- lineView.measure = {};
- // Iterate over the logical lines that make up this visual line.
- for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
- var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
- builder.pos = 0;
- builder.addToken = buildToken;
- // Optionally wire in some hacks into the token-rendering
- // algorithm, to deal with browser quirks.
- if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
- { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
- builder.map = [];
- var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
- insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
- if (line.styleClasses) {
- if (line.styleClasses.bgClass)
- { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
- if (line.styleClasses.textClass)
- { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
- }
- // Ensure at least a single node is present, for measuring.
- if (builder.map.length == 0)
- { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
- // Store the map and a cache object for the current logical line
- if (i == 0) {
- lineView.measure.map = builder.map;
- lineView.measure.cache = {};
- } else {
- (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
- ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
- }
- }
- // See issue #2901
- if (webkit) {
- var last = builder.content.lastChild;
- if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
- { builder.content.className = "cm-tab-wrap-hack"; }
- }
- signal(cm, "renderLine", cm, lineView.line, builder.pre);
- if (builder.pre.className)
- { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
- return builder
- }
- function defaultSpecialCharPlaceholder(ch) {
- var token = elt("span", "\u2022", "cm-invalidchar");
- token.title = "\\u" + ch.charCodeAt(0).toString(16);
- token.setAttribute("aria-label", token.title);
- return token
- }
- // Build up the DOM representation for a single token, and add it to
- // the line map. Takes care to render special characters separately.
- function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
- if (!text) { return }
- var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
- var special = builder.cm.state.specialChars, mustWrap = false;
- var content;
- if (!special.test(text)) {
- builder.col += text.length;
- content = document.createTextNode(displayText);
- builder.map.push(builder.pos, builder.pos + text.length, content);
- if (ie && ie_version < 9) { mustWrap = true; }
- builder.pos += text.length;
- } else {
- content = document.createDocumentFragment();
- var pos = 0;
- while (true) {
- special.lastIndex = pos;
- var m = special.exec(text);
- var skipped = m ? m.index - pos : text.length - pos;
- if (skipped) {
- var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
- if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
- else { content.appendChild(txt); }
- builder.map.push(builder.pos, builder.pos + skipped, txt);
- builder.col += skipped;
- builder.pos += skipped;
- }
- if (!m) { break }
- pos += skipped + 1;
- var txt$1 = (void 0);
- if (m[0] == "\t") {
- var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
- txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
- txt$1.setAttribute("role", "presentation");
- txt$1.setAttribute("cm-text", "\t");
- builder.col += tabWidth;
- } else if (m[0] == "\r" || m[0] == "\n") {
- txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
- txt$1.setAttribute("cm-text", m[0]);
- builder.col += 1;
- } else {
- txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
- txt$1.setAttribute("cm-text", m[0]);
- if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
- else { content.appendChild(txt$1); }
- builder.col += 1;
- }
- builder.map.push(builder.pos, builder.pos + 1, txt$1);
- builder.pos++;
- }
- }
- builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
- if (style || startStyle || endStyle || mustWrap || css) {
- var fullStyle = style || "";
- if (startStyle) { fullStyle += startStyle; }
- if (endStyle) { fullStyle += endStyle; }
- var token = elt("span", [content], fullStyle, css);
- if (attributes) {
- for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
- { token.setAttribute(attr, attributes[attr]); } }
- }
- return builder.content.appendChild(token)
- }
- builder.content.appendChild(content);
- }
- // Change some spaces to NBSP to prevent the browser from collapsing
- // trailing spaces at the end of a line when rendering text (issue #1362).
- function splitSpaces(text, trailingBefore) {
- if (text.length > 1 && !/ /.test(text)) { return text }
- var spaceBefore = trailingBefore, result = "";
- for (var i = 0; i < text.length; i++) {
- var ch = text.charAt(i);
- if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
- { ch = "\u00a0"; }
- result += ch;
- spaceBefore = ch == " ";
- }
- return result
- }
- // Work around nonsense dimensions being reported for stretches of
- // right-to-left text.
- function buildTokenBadBidi(inner, order) {
- return function (builder, text, style, startStyle, endStyle, css, attributes) {
- style = style ? style + " cm-force-border" : "cm-force-border";
- var start = builder.pos, end = start + text.length;
- for (;;) {
- // Find the part that overlaps with the start of this text
- var part = (void 0);
- for (var i = 0; i < order.length; i++) {
- part = order[i];
- if (part.to > start && part.from <= start) { break }
- }
- if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
- inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
- startStyle = null;
- text = text.slice(part.to - start);
- start = part.to;
- }
- }
- }
- function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
- var widget = !ignoreWidget && marker.widgetNode;
- if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
- if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
- if (!widget)
- { widget = builder.content.appendChild(document.createElement("span")); }
- widget.setAttribute("cm-marker", marker.id);
- }
- if (widget) {
- builder.cm.display.input.setUneditable(widget);
- builder.content.appendChild(widget);
- }
- builder.pos += size;
- builder.trailingSpace = false;
- }
- // Outputs a number of spans to make up a line, taking highlighting
- // and marked text into account.
- function insertLineContent(line, builder, styles) {
- var spans = line.markedSpans, allText = line.text, at = 0;
- if (!spans) {
- for (var i$1 = 1; i$1 < styles.length; i$1+=2)
- { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
- return
- }
- var len = allText.length, pos = 0, i = 1, text = "", style, css;
- var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
- for (;;) {
- if (nextChange == pos) { // Update current marker set
- spanStyle = spanEndStyle = spanStartStyle = css = "";
- attributes = null;
- collapsed = null; nextChange = Infinity;
- var foundBookmarks = [], endStyles = (void 0);
- for (var j = 0; j < spans.length; ++j) {
- var sp = spans[j], m = sp.marker;
- if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
- foundBookmarks.push(m);
- } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
- if (sp.to != null && sp.to != pos && nextChange > sp.to) {
- nextChange = sp.to;
- spanEndStyle = "";
- }
- if (m.className) { spanStyle += " " + m.className; }
- if (m.css) { css = (css ? css + ";" : "") + m.css; }
- if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
- if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
- // support for the old title property
- // https://github.com/codemirror/CodeMirror/pull/5673
- if (m.title) { (attributes || (attributes = {})).title = m.title; }
- if (m.attributes) {
- for (var attr in m.attributes)
- { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
- }
- if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
- { collapsed = sp; }
- } else if (sp.from > pos && nextChange > sp.from) {
- nextChange = sp.from;
- }
- }
- if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
- { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
- if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
- { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
- if (collapsed && (collapsed.from || 0) == pos) {
- buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
- collapsed.marker, collapsed.from == null);
- if (collapsed.to == null) { return }
- if (collapsed.to == pos) { collapsed = false; }
- }
- }
- if (pos >= len) { break }
- var upto = Math.min(len, nextChange);
- while (true) {
- if (text) {
- var end = pos + text.length;
- if (!collapsed) {
- var tokenText = end > upto ? text.slice(0, upto - pos) : text;
- builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
- spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
- }
- if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
- pos = end;
- spanStartStyle = "";
- }
- text = allText.slice(at, at = styles[i++]);
- style = interpretTokenStyle(styles[i++], builder.cm.options);
- }
- }
- }
- // These objects are used to represent the visible (currently drawn)
- // part of the document. A LineView may correspond to multiple
- // logical lines, if those are connected by collapsed ranges.
- function LineView(doc, line, lineN) {
- // The starting line
- this.line = line;
- // Continuing lines, if any
- this.rest = visualLineContinued(line);
- // Number of logical lines in this visual line
- this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
- this.node = this.text = null;
- this.hidden = lineIsHidden(doc, line);
- }
- // Create a range of LineView objects for the given lines.
- function buildViewArray(cm, from, to) {
- var array = [], nextPos;
- for (var pos = from; pos < to; pos = nextPos) {
- var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
- nextPos = pos + view.size;
- array.push(view);
- }
- return array
- }
- var operationGroup = null;
- function pushOperation(op) {
- if (operationGroup) {
- operationGroup.ops.push(op);
- } else {
- op.ownsGroup = operationGroup = {
- ops: [op],
- delayedCallbacks: []
- };
- }
- }
- function fireCallbacksForOps(group) {
- // Calls delayed callbacks and cursorActivity handlers until no
- // new ones appear
- var callbacks = group.delayedCallbacks, i = 0;
- do {
- for (; i < callbacks.length; i++)
- { callbacks[i].call(null); }
- for (var j = 0; j < group.ops.length; j++) {
- var op = group.ops[j];
- if (op.cursorActivityHandlers)
- { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
- { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
- }
- } while (i < callbacks.length)
- }
- function finishOperation(op, endCb) {
- var group = op.ownsGroup;
- if (!group) { return }
- try { fireCallbacksForOps(group); }
- finally {
- operationGroup = null;
- endCb(group);
- }
- }
- var orphanDelayedCallbacks = null;
- // Often, we want to signal events at a point where we are in the
- // middle of some work, but don't want the handler to start calling
- // other methods on the editor, which might be in an inconsistent
- // state or simply not expect any other events to happen.
- // signalLater looks whether there are any handlers, and schedules
- // them to be executed when the last operation ends, or, if no
- // operation is active, when a timeout fires.
- function signalLater(emitter, type /*, values...*/) {
- var arr = getHandlers(emitter, type);
- if (!arr.length) { return }
- var args = Array.prototype.slice.call(arguments, 2), list;
- if (operationGroup) {
- list = operationGroup.delayedCallbacks;
- } else if (orphanDelayedCallbacks) {
- list = orphanDelayedCallbacks;
- } else {
- list = orphanDelayedCallbacks = [];
- setTimeout(fireOrphanDelayed, 0);
- }
- var loop = function ( i ) {
- list.push(function () { return arr[i].apply(null, args); });
- };
- for (var i = 0; i < arr.length; ++i)
- loop( i );
- }
- function fireOrphanDelayed() {
- var delayed = orphanDelayedCallbacks;
- orphanDelayedCallbacks = null;
- for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
- }
- // When an aspect of a line changes, a string is added to
- // lineView.changes. This updates the relevant part of the line's
- // DOM structure.
- function updateLineForChanges(cm, lineView, lineN, dims) {
- for (var j = 0; j < lineView.changes.length; j++) {
- var type = lineView.changes[j];
- if (type == "text") { updateLineText(cm, lineView); }
- else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
- else if (type == "class") { updateLineClasses(cm, lineView); }
- else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
- }
- lineView.changes = null;
- }
- // Lines with gutter elements, widgets or a background class need to
- // be wrapped, and have the extra elements added to the wrapper div
- function ensureLineWrapped(lineView) {
- if (lineView.node == lineView.text) {
- lineView.node = elt("div", null, null, "position: relative");
- if (lineView.text.parentNode)
- { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
- lineView.node.appendChild(lineView.text);
- if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
- }
- return lineView.node
- }
- function updateLineBackground(cm, lineView) {
- var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
- if (cls) { cls += " CodeMirror-linebackground"; }
- if (lineView.background) {
- if (cls) { lineView.background.className = cls; }
- else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
- } else if (cls) {
- var wrap = ensureLineWrapped(lineView);
- lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
- cm.display.input.setUneditable(lineView.background);
- }
- }
- // Wrapper around buildLineContent which will reuse the structure
- // in display.externalMeasured when possible.
- function getLineContent(cm, lineView) {
- var ext = cm.display.externalMeasured;
- if (ext && ext.line == lineView.line) {
- cm.display.externalMeasured = null;
- lineView.measure = ext.measure;
- return ext.built
- }
- return buildLineContent(cm, lineView)
- }
- // Redraw the line's text. Interacts with the background and text
- // classes because the mode may output tokens that influence these
- // classes.
- function updateLineText(cm, lineView) {
- var cls = lineView.text.className;
- var built = getLineContent(cm, lineView);
- if (lineView.text == lineView.node) { lineView.node = built.pre; }
- lineView.text.parentNode.replaceChild(built.pre, lineView.text);
- lineView.text = built.pre;
- if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
- lineView.bgClass = built.bgClass;
- lineView.textClass = built.textClass;
- updateLineClasses(cm, lineView);
- } else if (cls) {
- lineView.text.className = cls;
- }
- }
- function updateLineClasses(cm, lineView) {
- updateLineBackground(cm, lineView);
- if (lineView.line.wrapClass)
- { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
- else if (lineView.node != lineView.text)
- { lineView.node.className = ""; }
- var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
- lineView.text.className = textClass || "";
- }
- function updateLineGutter(cm, lineView, lineN, dims) {
- if (lineView.gutter) {
- lineView.node.removeChild(lineView.gutter);
- lineView.gutter = null;
- }
- if (lineView.gutterBackground) {
- lineView.node.removeChild(lineView.gutterBackground);
- lineView.gutterBackground = null;
- }
- if (lineView.line.gutterClass) {
- var wrap = ensureLineWrapped(lineView);
- lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
- ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
- cm.display.input.setUneditable(lineView.gutterBackground);
- wrap.insertBefore(lineView.gutterBackground, lineView.text);
- }
- var markers = lineView.line.gutterMarkers;
- if (cm.options.lineNumbers || markers) {
- var wrap$1 = ensureLineWrapped(lineView);
- var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
- cm.display.input.setUneditable(gutterWrap);
- wrap$1.insertBefore(gutterWrap, lineView.text);
- if (lineView.line.gutterClass)
- { gutterWrap.className += " " + lineView.line.gutterClass; }
- if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
- { lineView.lineNumber = gutterWrap.appendChild(
- elt("div", lineNumberFor(cm.options, lineN),
- "CodeMirror-linenumber CodeMirror-gutter-elt",
- ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
- if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
- var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
- if (found)
- { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
- ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
- } }
- }
- }
- function updateLineWidgets(cm, lineView, dims) {
- if (lineView.alignable) { lineView.alignable = null; }
- for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
- next = node.nextSibling;
- if (node.className == "CodeMirror-linewidget")
- { lineView.node.removeChild(node); }
- }
- insertLineWidgets(cm, lineView, dims);
- }
- // Build a line's DOM representation from scratch
- function buildLineElement(cm, lineView, lineN, dims) {
- var built = getLineContent(cm, lineView);
- lineView.text = lineView.node = built.pre;
- if (built.bgClass) { lineView.bgClass = built.bgClass; }
- if (built.textClass) { lineView.textClass = built.textClass; }
- updateLineClasses(cm, lineView);
- updateLineGutter(cm, lineView, lineN, dims);
- insertLineWidgets(cm, lineView, dims);
- return lineView.node
- }
- // A lineView may contain multiple logical lines (when merged by
- // collapsed spans). The widgets for all of them need to be drawn.
- function insertLineWidgets(cm, lineView, dims) {
- insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
- if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
- { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
- }
- function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
- if (!line.widgets) { return }
- var wrap = ensureLineWrapped(lineView);
- for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
- var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
- if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
- positionLineWidget(widget, node, lineView, dims);
- cm.display.input.setUneditable(node);
- if (allowAbove && widget.above)
- { wrap.insertBefore(node, lineView.gutter || lineView.text); }
- else
- { wrap.appendChild(node); }
- signalLater(widget, "redraw");
- }
- }
- function positionLineWidget(widget, node, lineView, dims) {
- if (widget.noHScroll) {
- (lineView.alignable || (lineView.alignable = [])).push(node);
- var width = dims.wrapperWidth;
- node.style.left = dims.fixedPos + "px";
- if (!widget.coverGutter) {
- width -= dims.gutterTotalWidth;
- node.style.paddingLeft = dims.gutterTotalWidth + "px";
- }
- node.style.width = width + "px";
- }
- if (widget.coverGutter) {
- node.style.zIndex = 5;
- node.style.position = "relative";
- if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
- }
- }
- function widgetHeight(widget) {
- if (widget.height != null) { return widget.height }
- var cm = widget.doc.cm;
- if (!cm) { return 0 }
- if (!contains(document.body, widget.node)) {
- var parentStyle = "position: relative;";
- if (widget.coverGutter)
- { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
- if (widget.noHScroll)
- { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
- removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
- }
- return widget.height = widget.node.parentNode.offsetHeight
- }
- // Return true when the given mouse event happened in a widget
- function eventInWidget(display, e) {
- for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
- if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
- (n.parentNode == display.sizer && n != display.mover))
- { return true }
- }
- }
- // POSITION MEASUREMENT
- function paddingTop(display) {return display.lineSpace.offsetTop}
- function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
- function paddingH(display) {
- if (display.cachedPaddingH) { return display.cachedPaddingH }
- var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
- var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
- var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
- if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
- return data
- }
- function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
- function displayWidth(cm) {
- return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
- }
- function displayHeight(cm) {
- return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
- }
- // Ensure the lineView.wrapping.heights array is populated. This is
- // an array of bottom offsets for the lines that make up a drawn
- // line. When lineWrapping is on, there might be more than one
- // height.
- function ensureLineHeights(cm, lineView, rect) {
- var wrapping = cm.options.lineWrapping;
- var curWidth = wrapping && displayWidth(cm);
- if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
- var heights = lineView.measure.heights = [];
- if (wrapping) {
- lineView.measure.width = curWidth;
- var rects = lineView.text.firstChild.getClientRects();
- for (var i = 0; i < rects.length - 1; i++) {
- var cur = rects[i], next = rects[i + 1];
- if (Math.abs(cur.bottom - next.bottom) > 2)
- { heights.push((cur.bottom + next.top) / 2 - rect.top); }
- }
- }
- heights.push(rect.bottom - rect.top);
- }
- }
- // Find a line map (mapping character offsets to text nodes) and a
- // measurement cache for the given line number. (A line view might
- // contain multiple lines when collapsed ranges are present.)
- function mapFromLineView(lineView, line, lineN) {
- if (lineView.line == line)
- { return {map: lineView.measure.map, cache: lineView.measure.cache} }
- for (var i = 0; i < lineView.rest.length; i++)
- { if (lineView.rest[i] == line)
- { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
- for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
- { if (lineNo(lineView.rest[i$1]) > lineN)
- { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
- }
- // Render a line into the hidden node display.externalMeasured. Used
- // when measurement is needed for a line that's not in the viewport.
- function updateExternalMeasurement(cm, line) {
- line = visualLine(line);
- var lineN = lineNo(line);
- var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
- view.lineN = lineN;
- var built = view.built = buildLineContent(cm, view);
- view.text = built.pre;
- removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
- return view
- }
- // Get a {top, bottom, left, right} box (in line-local coordinates)
- // for a given character.
- function measureChar(cm, line, ch, bias) {
- return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
- }
- // Find a line view that corresponds to the given line number.
- function findViewForLine(cm, lineN) {
- if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
- { return cm.display.view[findViewIndex(cm, lineN)] }
- var ext = cm.display.externalMeasured;
- if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
- { return ext }
- }
- // Measurement can be split in two steps, the set-up work that
- // applies to the whole line, and the measurement of the actual
- // character. Functions like coordsChar, that need to do a lot of
- // measurements in a row, can thus ensure that the set-up work is
- // only done once.
- function prepareMeasureForLine(cm, line) {
- var lineN = lineNo(line);
- var view = findViewForLine(cm, lineN);
- if (view && !view.text) {
- view = null;
- } else if (view && view.changes) {
- updateLineForChanges(cm, view, lineN, getDimensions(cm));
- cm.curOp.forceUpdate = true;
- }
- if (!view)
- { view = updateExternalMeasurement(cm, line); }
- var info = mapFromLineView(view, line, lineN);
- return {
- line: line, view: view, rect: null,
- map: info.map, cache: info.cache, before: info.before,
- hasHeights: false
- }
- }
- // Given a prepared measurement object, measures the position of an
- // actual character (or fetches it from the cache).
- function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
- if (prepared.before) { ch = -1; }
- var key = ch + (bias || ""), found;
- if (prepared.cache.hasOwnProperty(key)) {
- found = prepared.cache[key];
- } else {
- if (!prepared.rect)
- { prepared.rect = prepared.view.text.getBoundingClientRect(); }
- if (!prepared.hasHeights) {
- ensureLineHeights(cm, prepared.view, prepared.rect);
- prepared.hasHeights = true;
- }
- found = measureCharInner(cm, prepared, ch, bias);
- if (!found.bogus) { prepared.cache[key] = found; }
- }
- return {left: found.left, right: found.right,
- top: varHeight ? found.rtop : found.top,
- bottom: varHeight ? found.rbottom : found.bottom}
- }
- var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
- function nodeAndOffsetInLineMap(map$$1, ch, bias) {
- var node, start, end, collapse, mStart, mEnd;
- // First, search the line map for the text node corresponding to,
- // or closest to, the target character.
- for (var i = 0; i < map$$1.length; i += 3) {
- mStart = map$$1[i];
- mEnd = map$$1[i + 1];
- if (ch < mStart) {
- start = 0; end = 1;
- collapse = "left";
- } else if (ch < mEnd) {
- start = ch - mStart;
- end = start + 1;
- } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
- end = mEnd - mStart;
- start = end - 1;
- if (ch >= mEnd) { collapse = "right"; }
- }
- if (start != null) {
- node = map$$1[i + 2];
- if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
- { collapse = bias; }
- if (bias == "left" && start == 0)
- { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
- node = map$$1[(i -= 3) + 2];
- collapse = "left";
- } }
- if (bias == "right" && start == mEnd - mStart)
- { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
- node = map$$1[(i += 3) + 2];
- collapse = "right";
- } }
- break
- }
- }
- return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
- }
- function getUsefulRect(rects, bias) {
- var rect = nullRect;
- if (bias == "left") { for (var i = 0; i < rects.length; i++) {
- if ((rect = rects[i]).left != rect.right) { break }
- } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
- if ((rect = rects[i$1]).left != rect.right) { break }
- } }
- return rect
- }
- function measureCharInner(cm, prepared, ch, bias) {
- var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
- var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
- var rect;
- if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
- for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
- while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
- while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
- if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
- { rect = node.parentNode.getBoundingClientRect(); }
- else
- { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
- if (rect.left || rect.right || start == 0) { break }
- end = start;
- start = start - 1;
- collapse = "right";
- }
- if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
- } else { // If it is a widget, simply get the box for the whole widget.
- if (start > 0) { collapse = bias = "right"; }
- var rects;
- if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
- { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
- else
- { rect = node.getBoundingClientRect(); }
- }
- if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
- var rSpan = node.parentNode.getClientRects()[0];
- if (rSpan)
- { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
- else
- { rect = nullRect; }
- }
- var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
- var mid = (rtop + rbot) / 2;
- var heights = prepared.view.measure.heights;
- var i = 0;
- for (; i < heights.length - 1; i++)
- { if (mid < heights[i]) { break } }
- var top = i ? heights[i - 1] : 0, bot = heights[i];
- var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
- right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
- top: top, bottom: bot};
- if (!rect.left && !rect.right) { result.bogus = true; }
- if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
- return result
- }
- // Work around problem with bounding client rects on ranges being
- // returned incorrectly when zoomed on IE10 and below.
- function maybeUpdateRectForZooming(measure, rect) {
- if (!window.screen || screen.logicalXDPI == null ||
- screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
- { return rect }
- var scaleX = screen.logicalXDPI / screen.deviceXDPI;
- var scaleY = screen.logicalYDPI / screen.deviceYDPI;
- return {left: rect.left * scaleX, right: rect.right * scaleX,
- top: rect.top * scaleY, bottom: rect.bottom * scaleY}
- }
- function clearLineMeasurementCacheFor(lineView) {
- if (lineView.measure) {
- lineView.measure.cache = {};
- lineView.measure.heights = null;
- if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
- { lineView.measure.caches[i] = {}; } }
- }
- }
- function clearLineMeasurementCache(cm) {
- cm.display.externalMeasure = null;
- removeChildren(cm.display.lineMeasure);
- for (var i = 0; i < cm.display.view.length; i++)
- { clearLineMeasurementCacheFor(cm.display.view[i]); }
- }
- function clearCaches(cm) {
- clearLineMeasurementCache(cm);
- cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
- if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
- cm.display.lineNumChars = null;
- }
- function pageScrollX() {
- // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
- // which causes page_Offset and bounding client rects to use
- // different reference viewports and invalidate our calculations.
- if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
- return window.pageXOffset || (document.documentElement || document.body).scrollLeft
- }
- function pageScrollY() {
- if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
- return window.pageYOffset || (document.documentElement || document.body).scrollTop
- }
- function widgetTopHeight(lineObj) {
- var height = 0;
- if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
- { height += widgetHeight(lineObj.widgets[i]); } } }
- return height
- }
- // Converts a {top, bottom, left, right} box from line-local
- // coordinates into another coordinate system. Context may be one of
- // "line", "div" (display.lineDiv), "local"./null (editor), "window",
- // or "page".
- function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
- if (!includeWidgets) {
- var height = widgetTopHeight(lineObj);
- rect.top += height; rect.bottom += height;
- }
- if (context == "line") { return rect }
- if (!context) { context = "local"; }
- var yOff = heightAtLine(lineObj);
- if (context == "local") { yOff += paddingTop(cm.display); }
- else { yOff -= cm.display.viewOffset; }
- if (context == "page" || context == "window") {
- var lOff = cm.display.lineSpace.getBoundingClientRect();
- yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
- var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
- rect.left += xOff; rect.right += xOff;
- }
- rect.top += yOff; rect.bottom += yOff;
- return rect
- }
- // Coverts a box from "div" coords to another coordinate system.
- // Context may be "window", "page", "div", or "local"./null.
- function fromCoordSystem(cm, coords, context) {
- if (context == "div") { return coords }
- var left = coords.left, top = coords.top;
- // First move into "page" coordinate system
- if (context == "page") {
- left -= pageScrollX();
- top -= pageScrollY();
- } else if (context == "local" || !context) {
- var localBox = cm.display.sizer.getBoundingClientRect();
- left += localBox.left;
- top += localBox.top;
- }
- var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
- return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
- }
- function charCoords(cm, pos, context, lineObj, bias) {
- if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
- return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
- }
- // Returns a box for a given cursor position, which may have an
- // 'other' property containing the position of the secondary cursor
- // on a bidi boundary.
- // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
- // and after `char - 1` in writing order of `char - 1`
- // A cursor Pos(line, char, "after") is on the same visual line as `char`
- // and before `char` in writing order of `char`
- // Examples (upper-case letters are RTL, lower-case are LTR):
- // Pos(0, 1, ...)
- // before after
- // ab a|b a|b
- // aB a|B aB|
- // Ab |Ab A|b
- // AB B|A B|A
- // Every position after the last character on a line is considered to stick
- // to the last character on the line.
- function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
- lineObj = lineObj || getLine(cm.doc, pos.line);
- if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
- function get(ch, right) {
- var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
- if (right) { m.left = m.right; } else { m.right = m.left; }
- return intoCoordSystem(cm, lineObj, m, context)
- }
- var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
- if (ch >= lineObj.text.length) {
- ch = lineObj.text.length;
- sticky = "before";
- } else if (ch <= 0) {
- ch = 0;
- sticky = "after";
- }
- if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
- function getBidi(ch, partPos, invert) {
- var part = order[partPos], right = part.level == 1;
- return get(invert ? ch - 1 : ch, right != invert)
- }
- var partPos = getBidiPartAt(order, ch, sticky);
- var other = bidiOther;
- var val = getBidi(ch, partPos, sticky == "before");
- if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
- return val
- }
- // Used to cheaply estimate the coordinates for a position. Used for
- // intermediate scroll updates.
- function estimateCoords(cm, pos) {
- var left = 0;
- pos = clipPos(cm.doc, pos);
- if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
- var lineObj = getLine(cm.doc, pos.line);
- var top = heightAtLine(lineObj) + paddingTop(cm.display);
- return {left: left, right: left, top: top, bottom: top + lineObj.height}
- }
- // Positions returned by coordsChar contain some extra information.
- // xRel is the relative x position of the input coordinates compared
- // to the found position (so xRel > 0 means the coordinates are to
- // the right of the character position, for example). When outside
- // is true, that means the coordinates lie outside the line's
- // vertical range.
- function PosWithInfo(line, ch, sticky, outside, xRel) {
- var pos = Pos(line, ch, sticky);
- pos.xRel = xRel;
- if (outside) { pos.outside = true; }
- return pos
- }
- // Compute the character position closest to the given coordinates.
- // Input must be lineSpace-local ("div" coordinate system).
- function coordsChar(cm, x, y) {
- var doc = cm.doc;
- y += cm.display.viewOffset;
- if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
- var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
- if (lineN > last)
- { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
- if (x < 0) { x = 0; }
- var lineObj = getLine(doc, lineN);
- for (;;) {
- var found = coordsCharInner(cm, lineObj, lineN, x, y);
- var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));
- if (!collapsed) { return found }
- var rangeEnd = collapsed.find(1);
- if (rangeEnd.line == lineN) { return rangeEnd }
- lineObj = getLine(doc, lineN = rangeEnd.line);
- }
- }
- function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
- y -= widgetTopHeight(lineObj);
- var end = lineObj.text.length;
- var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
- end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
- return {begin: begin, end: end}
- }
- function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
- if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
- var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
- return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
- }
- // Returns true if the given side of a box is after the given
- // coordinates, in top-to-bottom, left-to-right order.
- function boxIsAfter(box, x, y, left) {
- return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
- }
- function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
- // Move y into line-local coordinate space
- y -= heightAtLine(lineObj);
- var preparedMeasure = prepareMeasureForLine(cm, lineObj);
- // When directly calling `measureCharPrepared`, we have to adjust
- // for the widgets at this line.
- var widgetHeight$$1 = widgetTopHeight(lineObj);
- var begin = 0, end = lineObj.text.length, ltr = true;
- var order = getOrder(lineObj, cm.doc.direction);
- // If the line isn't plain left-to-right text, first figure out
- // which bidi section the coordinates fall into.
- if (order) {
- var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
- (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
- ltr = part.level != 1;
- // The awkward -1 offsets are needed because findFirst (called
- // on these below) will treat its first bound as inclusive,
- // second as exclusive, but we want to actually address the
- // characters in the part's range
- begin = ltr ? part.from : part.to - 1;
- end = ltr ? part.to : part.from - 1;
- }
- // A binary search to find the first character whose bounding box
- // starts after the coordinates. If we run across any whose box wrap
- // the coordinates, store that.
- var chAround = null, boxAround = null;
- var ch = findFirst(function (ch) {
- var box = measureCharPrepared(cm, preparedMeasure, ch);
- box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
- if (!boxIsAfter(box, x, y, false)) { return false }
- if (box.top <= y && box.left <= x) {
- chAround = ch;
- boxAround = box;
- }
- return true
- }, begin, end);
- var baseX, sticky, outside = false;
- // If a box around the coordinates was found, use that
- if (boxAround) {
- // Distinguish coordinates nearer to the left or right side of the box
- var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
- ch = chAround + (atStart ? 0 : 1);
- sticky = atStart ? "after" : "before";
- baseX = atLeft ? boxAround.left : boxAround.right;
- } else {
- // (Adjust for extended bound, if necessary.)
- if (!ltr && (ch == end || ch == begin)) { ch++; }
- // To determine which side to associate with, get the box to the
- // left of the character and compare it's vertical position to the
- // coordinates
- sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
- (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
- "after" : "before";
- // Now get accurate coordinates for this place, in order to get a
- // base X position
- var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
- baseX = coords.left;
- outside = y < coords.top || y >= coords.bottom;
- }
- ch = skipExtendingChars(lineObj.text, ch, 1);
- return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
- }
- function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
- // Bidi parts are sorted left-to-right, and in a non-line-wrapping
- // situation, we can take this ordering to correspond to the visual
- // ordering. This finds the first part whose end is after the given
- // coordinates.
- var index = findFirst(function (i) {
- var part = order[i], ltr = part.level != 1;
- return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
- "line", lineObj, preparedMeasure), x, y, true)
- }, 0, order.length - 1);
- var part = order[index];
- // If this isn't the first part, the part's start is also after
- // the coordinates, and the coordinates aren't on the same line as
- // that start, move one part back.
- if (index > 0) {
- var ltr = part.level != 1;
- var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
- "line", lineObj, preparedMeasure);
- if (boxIsAfter(start, x, y, true) && start.top > y)
- { part = order[index - 1]; }
- }
- return part
- }
- function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
- // In a wrapped line, rtl text on wrapping boundaries can do things
- // that don't correspond to the ordering in our `order` array at
- // all, so a binary search doesn't work, and we want to return a
- // part that only spans one line so that the binary search in
- // coordsCharInner is safe. As such, we first find the extent of the
- // wrapped line, and then do a flat search in which we discard any
- // spans that aren't on the line.
- var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
- var begin = ref.begin;
- var end = ref.end;
- if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
- var part = null, closestDist = null;
- for (var i = 0; i < order.length; i++) {
- var p = order[i];
- if (p.from >= end || p.to <= begin) { continue }
- var ltr = p.level != 1;
- var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
- // Weigh against spans ending before this, so that they are only
- // picked if nothing ends after
- var dist = endX < x ? x - endX + 1e9 : endX - x;
- if (!part || closestDist > dist) {
- part = p;
- closestDist = dist;
- }
- }
- if (!part) { part = order[order.length - 1]; }
- // Clip the part to the wrapped line.
- if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
- if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
- return part
- }
- var measureText;
- // Compute the default text height.
- function textHeight(display) {
- if (display.cachedTextHeight != null) { return display.cachedTextHeight }
- if (measureText == null) {
- measureText = elt("pre");
- // Measure a bunch of lines, for browsers that compute
- // fractional heights.
- for (var i = 0; i < 49; ++i) {
- measureText.appendChild(document.createTextNode("x"));
- measureText.appendChild(elt("br"));
- }
- measureText.appendChild(document.createTextNode("x"));
- }
- removeChildrenAndAdd(display.measure, measureText);
- var height = measureText.offsetHeight / 50;
- if (height > 3) { display.cachedTextHeight = height; }
- removeChildren(display.measure);
- return height || 1
- }
- // Compute the default character width.
- function charWidth(display) {
- if (display.cachedCharWidth != null) { return display.cachedCharWidth }
- var anchor = elt("span", "xxxxxxxxxx");
- var pre = elt("pre", [anchor]);
- removeChildrenAndAdd(display.measure, pre);
- var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
- if (width > 2) { display.cachedCharWidth = width; }
- return width || 10
- }
- // Do a bulk-read of the DOM positions and sizes needed to draw the
- // view, so that we don't interleave reading and writing to the DOM.
- function getDimensions(cm) {
- var d = cm.display, left = {}, width = {};
- var gutterLeft = d.gutters.clientLeft;
- for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
- var id = cm.display.gutterSpecs[i].className;
- left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
- width[id] = n.clientWidth;
- }
- return {fixedPos: compensateForHScroll(d),
- gutterTotalWidth: d.gutters.offsetWidth,
- gutterLeft: left,
- gutterWidth: width,
- wrapperWidth: d.wrapper.clientWidth}
- }
- // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
- // but using getBoundingClientRect to get a sub-pixel-accurate
- // result.
- function compensateForHScroll(display) {
- return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
- }
- // Returns a function that estimates the height of a line, to use as
- // first approximation until the line becomes visible (and is thus
- // properly measurable).
- function estimateHeight(cm) {
- var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
- var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
- return function (line) {
- if (lineIsHidden(cm.doc, line)) { return 0 }
- var widgetsHeight = 0;
- if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
- if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
- } }
- if (wrapping)
- { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
- else
- { return widgetsHeight + th }
- }
- }
- function estimateLineHeights(cm) {
- var doc = cm.doc, est = estimateHeight(cm);
- doc.iter(function (line) {
- var estHeight = est(line);
- if (estHeight != line.height) { updateLineHeight(line, estHeight); }
- });
- }
- // Given a mouse event, find the corresponding position. If liberal
- // is false, it checks whether a gutter or scrollbar was clicked,
- // and returns null if it was. forRect is used by rectangular
- // selections, and tries to estimate a character position even for
- // coordinates beyond the right of the text.
- function posFromMouse(cm, e, liberal, forRect) {
- var display = cm.display;
- if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
- var x, y, space = display.lineSpace.getBoundingClientRect();
- // Fails unpredictably on IE[67] when mouse is dragged around quickly.
- try { x = e.clientX - space.left; y = e.clientY - space.top; }
- catch (e) { return null }
- var coords = coordsChar(cm, x, y), line;
- if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
- var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
- coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
- }
- return coords
- }
- // Find the view element corresponding to a given line. Return null
- // when the line isn't visible.
- function findViewIndex(cm, n) {
- if (n >= cm.display.viewTo) { return null }
- n -= cm.display.viewFrom;
- if (n < 0) { return null }
- var view = cm.display.view;
- for (var i = 0; i < view.length; i++) {
- n -= view[i].size;
- if (n < 0) { return i }
- }
- }
- // Updates the display.view data structure for a given change to the
- // document. From and to are in pre-change coordinates. Lendiff is
- // the amount of lines added or subtracted by the change. This is
- // used for changes that span multiple lines, or change the way
- // lines are divided into visual lines. regLineChange (below)
- // registers single-line changes.
- function regChange(cm, from, to, lendiff) {
- if (from == null) { from = cm.doc.first; }
- if (to == null) { to = cm.doc.first + cm.doc.size; }
- if (!lendiff) { lendiff = 0; }
- var display = cm.display;
- if (lendiff && to < display.viewTo &&
- (display.updateLineNumbers == null || display.updateLineNumbers > from))
- { display.updateLineNumbers = from; }
- cm.curOp.viewChanged = true;
- if (from >= display.viewTo) { // Change after
- if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
- { resetView(cm); }
- } else if (to <= display.viewFrom) { // Change before
- if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
- resetView(cm);
- } else {
- display.viewFrom += lendiff;
- display.viewTo += lendiff;
- }
- } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
- resetView(cm);
- } else if (from <= display.viewFrom) { // Top overlap
- var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
- if (cut) {
- display.view = display.view.slice(cut.index);
- display.viewFrom = cut.lineN;
- display.viewTo += lendiff;
- } else {
- resetView(cm);
- }
- } else if (to >= display.viewTo) { // Bottom overlap
- var cut$1 = viewCuttingPoint(cm, from, from, -1);
- if (cut$1) {
- display.view = display.view.slice(0, cut$1.index);
- display.viewTo = cut$1.lineN;
- } else {
- resetView(cm);
- }
- } else { // Gap in the middle
- var cutTop = viewCuttingPoint(cm, from, from, -1);
- var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
- if (cutTop && cutBot) {
- display.view = display.view.slice(0, cutTop.index)
- .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
- .concat(display.view.slice(cutBot.index));
- display.viewTo += lendiff;
- } else {
- resetView(cm);
- }
- }
- var ext = display.externalMeasured;
- if (ext) {
- if (to < ext.lineN)
- { ext.lineN += lendiff; }
- else if (from < ext.lineN + ext.size)
- { display.externalMeasured = null; }
- }
- }
- // Register a change to a single line. Type must be one of "text",
- // "gutter", "class", "widget"
- function regLineChange(cm, line, type) {
- cm.curOp.viewChanged = true;
- var display = cm.display, ext = cm.display.externalMeasured;
- if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
- { display.externalMeasured = null; }
- if (line < display.viewFrom || line >= display.viewTo) { return }
- var lineView = display.view[findViewIndex(cm, line)];
- if (lineView.node == null) { return }
- var arr = lineView.changes || (lineView.changes = []);
- if (indexOf(arr, type) == -1) { arr.push(type); }
- }
- // Clear the view.
- function resetView(cm) {
- cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
- cm.display.view = [];
- cm.display.viewOffset = 0;
- }
- function viewCuttingPoint(cm, oldN, newN, dir) {
- var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
- if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
- { return {index: index, lineN: newN} }
- var n = cm.display.viewFrom;
- for (var i = 0; i < index; i++)
- { n += view[i].size; }
- if (n != oldN) {
- if (dir > 0) {
- if (index == view.length - 1) { return null }
- diff = (n + view[index].size) - oldN;
- index++;
- } else {
- diff = n - oldN;
- }
- oldN += diff; newN += diff;
- }
- while (visualLineNo(cm.doc, newN) != newN) {
- if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
- newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
- index += dir;
- }
- return {index: index, lineN: newN}
- }
- // Force the view to cover a given range, adding empty view element
- // or clipping off existing ones as needed.
- function adjustView(cm, from, to) {
- var display = cm.display, view = display.view;
- if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
- display.view = buildViewArray(cm, from, to);
- display.viewFrom = from;
- } else {
- if (display.viewFrom > from)
- { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
- else if (display.viewFrom < from)
- { display.view = display.view.slice(findViewIndex(cm, from)); }
- display.viewFrom = from;
- if (display.viewTo < to)
- { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
- else if (display.viewTo > to)
- { display.view = display.view.slice(0, findViewIndex(cm, to)); }
- }
- display.viewTo = to;
- }
- // Count the number of lines in the view whose DOM representation is
- // out of date (or nonexistent).
- function countDirtyView(cm) {
- var view = cm.display.view, dirty = 0;
- for (var i = 0; i < view.length; i++) {
- var lineView = view[i];
- if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
- }
- return dirty
- }
- function updateSelection(cm) {
- cm.display.input.showSelection(cm.display.input.prepareSelection());
- }
- function prepareSelection(cm, primary) {
- if ( primary === void 0 ) primary = true;
- var doc = cm.doc, result = {};
- var curFragment = result.cursors = document.createDocumentFragment();
- var selFragment = result.selection = document.createDocumentFragment();
- for (var i = 0; i < doc.sel.ranges.length; i++) {
- if (!primary && i == doc.sel.primIndex) { continue }
- var range$$1 = doc.sel.ranges[i];
- if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
- var collapsed = range$$1.empty();
- if (collapsed || cm.options.showCursorWhenSelecting)
- { drawSelectionCursor(cm, range$$1.head, curFragment); }
- if (!collapsed)
- { drawSelectionRange(cm, range$$1, selFragment); }
- }
- return result
- }
- // Draws a cursor for the given range
- function drawSelectionCursor(cm, head, output) {
- var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
- var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
- cursor.style.left = pos.left + "px";
- cursor.style.top = pos.top + "px";
- cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
- if (pos.other) {
- // Secondary cursor, shown when on a 'jump' in bi-directional text
- var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
- otherCursor.style.display = "";
- otherCursor.style.left = pos.other.left + "px";
- otherCursor.style.top = pos.other.top + "px";
- otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
- }
- }
- function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
- // Draws the given range as a highlighted selection
- function drawSelectionRange(cm, range$$1, output) {
- var display = cm.display, doc = cm.doc;
- var fragment = document.createDocumentFragment();
- var padding = paddingH(cm.display), leftSide = padding.left;
- var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
- var docLTR = doc.direction == "ltr";
- function add(left, top, width, bottom) {
- if (top < 0) { top = 0; }
- top = Math.round(top);
- bottom = Math.round(bottom);
- fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
- }
- function drawForLine(line, fromArg, toArg) {
- var lineObj = getLine(doc, line);
- var lineLen = lineObj.text.length;
- var start, end;
- function coords(ch, bias) {
- return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
- }
- function wrapX(pos, dir, side) {
- var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
- var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
- var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
- return coords(ch, prop)[prop]
- }
- var order = getOrder(lineObj, doc.direction);
- iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
- var ltr = dir == "ltr";
- var fromPos = coords(from, ltr ? "left" : "right");
- var toPos = coords(to - 1, ltr ? "right" : "left");
- var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
- var first = i == 0, last = !order || i == order.length - 1;
- if (toPos.top - fromPos.top <= 3) { // Single line
- var openLeft = (docLTR ? openStart : openEnd) && first;
- var openRight = (docLTR ? openEnd : openStart) && last;
- var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
- var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
- add(left, fromPos.top, right - left, fromPos.bottom);
- } else { // Multiple lines
- var topLeft, topRight, botLeft, botRight;
- if (ltr) {
- topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
- topRight = docLTR ? rightSide : wrapX(from, dir, "before");
- botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
- botRight = docLTR && openEnd && last ? rightSide : toPos.right;
- } else {
- topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
- topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
- botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
- botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
- }
- add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
- if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
- add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
- }
- if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
- if (cmpCoords(toPos, start) < 0) { start = toPos; }
- if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
- if (cmpCoords(toPos, end) < 0) { end = toPos; }
- });
- return {start: start, end: end}
- }
- var sFrom = range$$1.from(), sTo = range$$1.to();
- if (sFrom.line == sTo.line) {
- drawForLine(sFrom.line, sFrom.ch, sTo.ch);
- } else {
- var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
- var singleVLine = visualLine(fromLine) == visualLine(toLine);
- var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
- var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
- if (singleVLine) {
- if (leftEnd.top < rightStart.top - 2) {
- add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
- add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
- } else {
- add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
- }
- }
- if (leftEnd.bottom < rightStart.top)
- { add(leftSide, leftEnd.bottom, null, rightStart.top); }
- }
- output.appendChild(fragment);
- }
- // Cursor-blinking
- function restartBlink(cm) {
- if (!cm.state.focused) { return }
- var display = cm.display;
- clearInterval(display.blinker);
- var on = true;
- display.cursorDiv.style.visibility = "";
- if (cm.options.cursorBlinkRate > 0)
- { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
- cm.options.cursorBlinkRate); }
- else if (cm.options.cursorBlinkRate < 0)
- { display.cursorDiv.style.visibility = "hidden"; }
- }
- function ensureFocus(cm) {
- if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
- }
- function delayBlurEvent(cm) {
- cm.state.delayingBlurEvent = true;
- setTimeout(function () { if (cm.state.delayingBlurEvent) {
- cm.state.delayingBlurEvent = false;
- onBlur(cm);
- } }, 100);
- }
- function onFocus(cm, e) {
- if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
- if (cm.options.readOnly == "nocursor") { return }
- if (!cm.state.focused) {
- signal(cm, "focus", cm, e);
- cm.state.focused = true;
- addClass(cm.display.wrapper, "CodeMirror-focused");
- // This test prevents this from firing when a context
- // menu is closed (since the input reset would kill the
- // select-all detection hack)
- if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
- cm.display.input.reset();
- if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
- }
- cm.display.input.receivedFocus();
- }
- restartBlink(cm);
- }
- function onBlur(cm, e) {
- if (cm.state.delayingBlurEvent) { return }
- if (cm.state.focused) {
- signal(cm, "blur", cm, e);
- cm.state.focused = false;
- rmClass(cm.display.wrapper, "CodeMirror-focused");
- }
- clearInterval(cm.display.blinker);
- setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
- }
- // Read the actual heights of the rendered lines, and update their
- // stored heights to match.
- function updateHeightsInViewport(cm) {
- var display = cm.display;
- var prevBottom = display.lineDiv.offsetTop;
- for (var i = 0; i < display.view.length; i++) {
- var cur = display.view[i], wrapping = cm.options.lineWrapping;
- var height = (void 0), width = 0;
- if (cur.hidden) { continue }
- if (ie && ie_version < 8) {
- var bot = cur.node.offsetTop + cur.node.offsetHeight;
- height = bot - prevBottom;
- prevBottom = bot;
- } else {
- var box = cur.node.getBoundingClientRect();
- height = box.bottom - box.top;
- // Check that lines don't extend past the right of the current
- // editor width
- if (!wrapping && cur.text.firstChild)
- { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
- }
- var diff = cur.line.height - height;
- if (diff > .005 || diff < -.005) {
- updateLineHeight(cur.line, height);
- updateWidgetHeight(cur.line);
- if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
- { updateWidgetHeight(cur.rest[j]); } }
- }
- if (width > cm.display.sizerWidth) {
- var chWidth = Math.ceil(width / charWidth(cm.display));
- if (chWidth > cm.display.maxLineLength) {
- cm.display.maxLineLength = chWidth;
- cm.display.maxLine = cur.line;
- cm.display.maxLineChanged = true;
- }
- }
- }
- }
- // Read and store the height of line widgets associated with the
- // given line.
- function updateWidgetHeight(line) {
- if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
- var w = line.widgets[i], parent = w.node.parentNode;
- if (parent) { w.height = parent.offsetHeight; }
- } }
- }
- // Compute the lines that are visible in a given viewport (defaults
- // the the current scroll position). viewport may contain top,
- // height, and ensure (see op.scrollToPos) properties.
- function visibleLines(display, doc, viewport) {
- var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
- top = Math.floor(top - paddingTop(display));
- var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
- var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
- // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
- // forces those lines into the viewport (if possible).
- if (viewport && viewport.ensure) {
- var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
- if (ensureFrom < from) {
- from = ensureFrom;
- to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
- } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
- from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
- to = ensureTo;
- }
- }
- return {from: from, to: Math.max(to, from + 1)}
- }
- // SCROLLING THINGS INTO VIEW
- // If an editor sits on the top or bottom of the window, partially
- // scrolled out of view, this ensures that the cursor is visible.
- function maybeScrollWindow(cm, rect) {
- if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
- var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
- if (rect.top + box.top < 0) { doScroll = true; }
- else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
- if (doScroll != null && !phantom) {
- var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
- cm.display.lineSpace.appendChild(scrollNode);
- scrollNode.scrollIntoView(doScroll);
- cm.display.lineSpace.removeChild(scrollNode);
- }
- }
- // Scroll a given position into view (immediately), verifying that
- // it actually became visible (as line heights are accurately
- // measured, the position of something may 'drift' during drawing).
- function scrollPosIntoView(cm, pos, end, margin) {
- if (margin == null) { margin = 0; }
- var rect;
- if (!cm.options.lineWrapping && pos == end) {
- // Set pos and end to the cursor positions around the character pos sticks to
- // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
- // If pos == Pos(_, 0, "before"), pos and end are unchanged
- pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
- end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
- }
- for (var limit = 0; limit < 5; limit++) {
- var changed = false;
- var coords = cursorCoords(cm, pos);
- var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
- rect = {left: Math.min(coords.left, endCoords.left),
- top: Math.min(coords.top, endCoords.top) - margin,
- right: Math.max(coords.left, endCoords.left),
- bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
- var scrollPos = calculateScrollPos(cm, rect);
- var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
- if (scrollPos.scrollTop != null) {
- updateScrollTop(cm, scrollPos.scrollTop);
- if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
- }
- if (scrollPos.scrollLeft != null) {
- setScrollLeft(cm, scrollPos.scrollLeft);
- if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
- }
- if (!changed) { break }
- }
- return rect
- }
- // Scroll a given set of coordinates into view (immediately).
- function scrollIntoView(cm, rect) {
- var scrollPos = calculateScrollPos(cm, rect);
- if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
- if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
- }
- // Calculate a new scroll position needed to scroll the given
- // rectangle into view. Returns an object with scrollTop and
- // scrollLeft properties. When these are undefined, the
- // vertical/horizontal position does not need to be adjusted.
- function calculateScrollPos(cm, rect) {
- var display = cm.display, snapMargin = textHeight(cm.display);
- if (rect.top < 0) { rect.top = 0; }
- var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
- var screen = displayHeight(cm), result = {};
- if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
- var docBottom = cm.doc.height + paddingVert(display);
- var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
- if (rect.top < screentop) {
- result.scrollTop = atTop ? 0 : rect.top;
- } else if (rect.bottom > screentop + screen) {
- var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
- if (newTop != screentop) { result.scrollTop = newTop; }
- }
- var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
- var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
- var tooWide = rect.right - rect.left > screenw;
- if (tooWide) { rect.right = rect.left + screenw; }
- if (rect.left < 10)
- { result.scrollLeft = 0; }
- else if (rect.left < screenleft)
- { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
- else if (rect.right > screenw + screenleft - 3)
- { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
- return result
- }
- // Store a relative adjustment to the scroll position in the current
- // operation (to be applied when the operation finishes).
- function addToScrollTop(cm, top) {
- if (top == null) { return }
- resolveScrollToPos(cm);
- cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
- }
- // Make sure that at the end of the operation the current cursor is
- // shown.
- function ensureCursorVisible(cm) {
- resolveScrollToPos(cm);
- var cur = cm.getCursor();
- cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
- }
- function scrollToCoords(cm, x, y) {
- if (x != null || y != null) { resolveScrollToPos(cm); }
- if (x != null) { cm.curOp.scrollLeft = x; }
- if (y != null) { cm.curOp.scrollTop = y; }
- }
- function scrollToRange(cm, range$$1) {
- resolveScrollToPos(cm);
- cm.curOp.scrollToPos = range$$1;
- }
- // When an operation has its scrollToPos property set, and another
- // scroll action is applied before the end of the operation, this
- // 'simulates' scrolling that position into view in a cheap way, so
- // that the effect of intermediate scroll commands is not ignored.
- function resolveScrollToPos(cm) {
- var range$$1 = cm.curOp.scrollToPos;
- if (range$$1) {
- cm.curOp.scrollToPos = null;
- var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
- scrollToCoordsRange(cm, from, to, range$$1.margin);
- }
- }
- function scrollToCoordsRange(cm, from, to, margin) {
- var sPos = calculateScrollPos(cm, {
- left: Math.min(from.left, to.left),
- top: Math.min(from.top, to.top) - margin,
- right: Math.max(from.right, to.right),
- bottom: Math.max(from.bottom, to.bottom) + margin
- });
- scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
- }
- // Sync the scrollable area and scrollbars, ensure the viewport
- // covers the visible area.
- function updateScrollTop(cm, val) {
- if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
- if (!gecko) { updateDisplaySimple(cm, {top: val}); }
- setScrollTop(cm, val, true);
- if (gecko) { updateDisplaySimple(cm); }
- startWorker(cm, 100);
- }
- function setScrollTop(cm, val, forceScroll) {
- val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
- if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
- cm.doc.scrollTop = val;
- cm.display.scrollbars.setScrollTop(val);
- if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
- }
- // Sync scroller and scrollbar, ensure the gutter elements are
- // aligned.
- function setScrollLeft(cm, val, isScroller, forceScroll) {
- val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
- if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
- cm.doc.scrollLeft = val;
- alignHorizontally(cm);
- if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
- cm.display.scrollbars.setScrollLeft(val);
- }
- // SCROLLBARS
- // Prepare DOM reads needed to update the scrollbars. Done in one
- // shot to minimize update/measure roundtrips.
- function measureForScrollbars(cm) {
- var d = cm.display, gutterW = d.gutters.offsetWidth;
- var docH = Math.round(cm.doc.height + paddingVert(cm.display));
- return {
- clientHeight: d.scroller.clientHeight,
- viewHeight: d.wrapper.clientHeight,
- scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
- viewWidth: d.wrapper.clientWidth,
- barLeft: cm.options.fixedGutter ? gutterW : 0,
- docHeight: docH,
- scrollHeight: docH + scrollGap(cm) + d.barHeight,
- nativeBarWidth: d.nativeBarWidth,
- gutterWidth: gutterW
- }
- }
- var NativeScrollbars = function(place, scroll, cm) {
- this.cm = cm;
- var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
- var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
- vert.tabIndex = horiz.tabIndex = -1;
- place(vert); place(horiz);
- on(vert, "scroll", function () {
- if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
- });
- on(horiz, "scroll", function () {
- if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
- });
- this.checkedZeroWidth = false;
- // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
- if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
- };
- NativeScrollbars.prototype.update = function (measure) {
- var needsH = measure.scrollWidth > measure.clientWidth + 1;
- var needsV = measure.scrollHeight > measure.clientHeight + 1;
- var sWidth = measure.nativeBarWidth;
- if (needsV) {
- this.vert.style.display = "block";
- this.vert.style.bottom = needsH ? sWidth + "px" : "0";
- var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
- // A bug in IE8 can cause this value to be negative, so guard it.
- this.vert.firstChild.style.height =
- Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
- } else {
- this.vert.style.display = "";
- this.vert.firstChild.style.height = "0";
- }
- if (needsH) {
- this.horiz.style.display = "block";
- this.horiz.style.right = needsV ? sWidth + "px" : "0";
- this.horiz.style.left = measure.barLeft + "px";
- var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
- this.horiz.firstChild.style.width =
- Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
- } else {
- this.horiz.style.display = "";
- this.horiz.firstChild.style.width = "0";
- }
- if (!this.checkedZeroWidth && measure.clientHeight > 0) {
- if (sWidth == 0) { this.zeroWidthHack(); }
- this.checkedZeroWidth = true;
- }
- return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
- };
- NativeScrollbars.prototype.setScrollLeft = function (pos) {
- if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
- if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
- };
- NativeScrollbars.prototype.setScrollTop = function (pos) {
- if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
- if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
- };
- NativeScrollbars.prototype.zeroWidthHack = function () {
- var w = mac && !mac_geMountainLion ? "12px" : "18px";
- this.horiz.style.height = this.vert.style.width = w;
- this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
- this.disableHoriz = new Delayed;
- this.disableVert = new Delayed;
- };
- NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
- bar.style.pointerEvents = "auto";
- function maybeDisable() {
- // To find out whether the scrollbar is still visible, we
- // check whether the element under the pixel in the bottom
- // right corner of the scrollbar box is the scrollbar box
- // itself (when the bar is still visible) or its filler child
- // (when the bar is hidden). If it is still visible, we keep
- // it enabled, if it's hidden, we disable pointer events.
- var box = bar.getBoundingClientRect();
- var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
- : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
- if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
- else { delay.set(1000, maybeDisable); }
- }
- delay.set(1000, maybeDisable);
- };
- NativeScrollbars.prototype.clear = function () {
- var parent = this.horiz.parentNode;
- parent.removeChild(this.horiz);
- parent.removeChild(this.vert);
- };
- var NullScrollbars = function () {};
- NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
- NullScrollbars.prototype.setScrollLeft = function () {};
- NullScrollbars.prototype.setScrollTop = function () {};
- NullScrollbars.prototype.clear = function () {};
- function updateScrollbars(cm, measure) {
- if (!measure) { measure = measureForScrollbars(cm); }
- var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
- updateScrollbarsInner(cm, measure);
- for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
- if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
- { updateHeightsInViewport(cm); }
- updateScrollbarsInner(cm, measureForScrollbars(cm));
- startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
- }
- }
- // Re-synchronize the fake scrollbars with the actual size of the
- // content.
- function updateScrollbarsInner(cm, measure) {
- var d = cm.display;
- var sizes = d.scrollbars.update(measure);
- d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
- d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
- d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
- if (sizes.right && sizes.bottom) {
- d.scrollbarFiller.style.display = "block";
- d.scrollbarFiller.style.height = sizes.bottom + "px";
- d.scrollbarFiller.style.width = sizes.right + "px";
- } else { d.scrollbarFiller.style.display = ""; }
- if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
- d.gutterFiller.style.display = "block";
- d.gutterFiller.style.height = sizes.bottom + "px";
- d.gutterFiller.style.width = measure.gutterWidth + "px";
- } else { d.gutterFiller.style.display = ""; }
- }
- var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
- function initScrollbars(cm) {
- if (cm.display.scrollbars) {
- cm.display.scrollbars.clear();
- if (cm.display.scrollbars.addClass)
- { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
- }
- cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
- cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
- // Prevent clicks in the scrollbars from killing focus
- on(node, "mousedown", function () {
- if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
- });
- node.setAttribute("cm-not-content", "true");
- }, function (pos, axis) {
- if (axis == "horizontal") { setScrollLeft(cm, pos); }
- else { updateScrollTop(cm, pos); }
- }, cm);
- if (cm.display.scrollbars.addClass)
- { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
- }
- // Operations are used to wrap a series of changes to the editor
- // state in such a way that each change won't have to update the
- // cursor and display (which would be awkward, slow, and
- // error-prone). Instead, display updates are batched and then all
- // combined and executed at once.
- var nextOpId = 0;
- // Start a new operation.
- function startOperation(cm) {
- cm.curOp = {
- cm: cm,
- viewChanged: false, // Flag that indicates that lines might need to be redrawn
- startHeight: cm.doc.height, // Used to detect need to update scrollbar
- forceUpdate: false, // Used to force a redraw
- updateInput: 0, // Whether to reset the input textarea
- typing: false, // Whether this reset should be careful to leave existing text (for compositing)
- changeObjs: null, // Accumulated changes, for firing change events
- cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
- cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
- selectionChanged: false, // Whether the selection needs to be redrawn
- updateMaxLine: false, // Set when the widest line needs to be determined anew
- scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
- scrollToPos: null, // Used to scroll to a specific position
- focus: false,
- id: ++nextOpId // Unique ID
- };
- pushOperation(cm.curOp);
- }
- // Finish an operation, updating the display and signalling delayed events
- function endOperation(cm) {
- var op = cm.curOp;
- if (op) { finishOperation(op, function (group) {
- for (var i = 0; i < group.ops.length; i++)
- { group.ops[i].cm.curOp = null; }
- endOperations(group);
- }); }
- }
- // The DOM updates done when an operation finishes are batched so
- // that the minimum number of relayouts are required.
- function endOperations(group) {
- var ops = group.ops;
- for (var i = 0; i < ops.length; i++) // Read DOM
- { endOperation_R1(ops[i]); }
- for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
- { endOperation_W1(ops[i$1]); }
- for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
- { endOperation_R2(ops[i$2]); }
- for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
- { endOperation_W2(ops[i$3]); }
- for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
- { endOperation_finish(ops[i$4]); }
- }
- function endOperation_R1(op) {
- var cm = op.cm, display = cm.display;
- maybeClipScrollbars(cm);
- if (op.updateMaxLine) { findMaxLine(cm); }
- op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
- op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
- op.scrollToPos.to.line >= display.viewTo) ||
- display.maxLineChanged && cm.options.lineWrapping;
- op.update = op.mustUpdate &&
- new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
- }
- function endOperation_W1(op) {
- op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
- }
- function endOperation_R2(op) {
- var cm = op.cm, display = cm.display;
- if (op.updatedDisplay) { updateHeightsInViewport(cm); }
- op.barMeasure = measureForScrollbars(cm);
- // If the max line changed since it was last measured, measure it,
- // and ensure the document's width matches it.
- // updateDisplay_W2 will use these properties to do the actual resizing
- if (display.maxLineChanged && !cm.options.lineWrapping) {
- op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
- cm.display.sizerWidth = op.adjustWidthTo;
- op.barMeasure.scrollWidth =
- Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
- op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
- }
- if (op.updatedDisplay || op.selectionChanged)
- { op.preparedSelection = display.input.prepareSelection(); }
- }
- function endOperation_W2(op) {
- var cm = op.cm;
- if (op.adjustWidthTo != null) {
- cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
- if (op.maxScrollLeft < cm.doc.scrollLeft)
- { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
- cm.display.maxLineChanged = false;
- }
- var takeFocus = op.focus && op.focus == activeElt();
- if (op.preparedSelection)
- { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
- if (op.updatedDisplay || op.startHeight != cm.doc.height)
- { updateScrollbars(cm, op.barMeasure); }
- if (op.updatedDisplay)
- { setDocumentHeight(cm, op.barMeasure); }
- if (op.selectionChanged) { restartBlink(cm); }
- if (cm.state.focused && op.updateInput)
- { cm.display.input.reset(op.typing); }
- if (takeFocus) { ensureFocus(op.cm); }
- }
- function endOperation_finish(op) {
- var cm = op.cm, display = cm.display, doc = cm.doc;
- if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
- // Abort mouse wheel delta measurement, when scrolling explicitly
- if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
- { display.wheelStartX = display.wheelStartY = null; }
- // Propagate the scroll position to the actual DOM scroller
- if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
- if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
- // If we need to scroll a specific position into view, do so.
- if (op.scrollToPos) {
- var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
- clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
- maybeScrollWindow(cm, rect);
- }
- // Fire events for markers that are hidden/unidden by editing or
- // undoing
- var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
- if (hidden) { for (var i = 0; i < hidden.length; ++i)
- { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
- if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
- { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
- if (display.wrapper.offsetHeight)
- { doc.scrollTop = cm.display.scroller.scrollTop; }
- // Fire change events, and delayed event handlers
- if (op.changeObjs)
- { signal(cm, "changes", cm, op.changeObjs); }
- if (op.update)
- { op.update.finish(); }
- }
- // Run the given function in an operation
- function runInOp(cm, f) {
- if (cm.curOp) { return f() }
- startOperation(cm);
- try { return f() }
- finally { endOperation(cm); }
- }
- // Wraps a function in an operation. Returns the wrapped function.
- function operation(cm, f) {
- return function() {
- if (cm.curOp) { return f.apply(cm, arguments) }
- startOperation(cm);
- try { return f.apply(cm, arguments) }
- finally { endOperation(cm); }
- }
- }
- // Used to add methods to editor and doc instances, wrapping them in
- // operations.
- function methodOp(f) {
- return function() {
- if (this.curOp) { return f.apply(this, arguments) }
- startOperation(this);
- try { return f.apply(this, arguments) }
- finally { endOperation(this); }
- }
- }
- function docMethodOp(f) {
- return function() {
- var cm = this.cm;
- if (!cm || cm.curOp) { return f.apply(this, arguments) }
- startOperation(cm);
- try { return f.apply(this, arguments) }
- finally { endOperation(cm); }
- }
- }
- // HIGHLIGHT WORKER
- function startWorker(cm, time) {
- if (cm.doc.highlightFrontier < cm.display.viewTo)
- { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
- }
- function highlightWorker(cm) {
- var doc = cm.doc;
- if (doc.highlightFrontier >= cm.display.viewTo) { return }
- var end = +new Date + cm.options.workTime;
- var context = getContextBefore(cm, doc.highlightFrontier);
- var changedLines = [];
- doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
- if (context.line >= cm.display.viewFrom) { // Visible
- var oldStyles = line.styles;
- var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
- var highlighted = highlightLine(cm, line, context, true);
- if (resetState) { context.state = resetState; }
- line.styles = highlighted.styles;
- var oldCls = line.styleClasses, newCls = highlighted.classes;
- if (newCls) { line.styleClasses = newCls; }
- else if (oldCls) { line.styleClasses = null; }
- var ischange = !oldStyles || oldStyles.length != line.styles.length ||
- oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
- for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
- if (ischange) { changedLines.push(context.line); }
- line.stateAfter = context.save();
- context.nextLine();
- } else {
- if (line.text.length <= cm.options.maxHighlightLength)
- { processLine(cm, line.text, context); }
- line.stateAfter = context.line % 5 == 0 ? context.save() : null;
- context.nextLine();
- }
- if (+new Date > end) {
- startWorker(cm, cm.options.workDelay);
- return true
- }
- });
- doc.highlightFrontier = context.line;
- doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
- if (changedLines.length) { runInOp(cm, function () {
- for (var i = 0; i < changedLines.length; i++)
- { regLineChange(cm, changedLines[i], "text"); }
- }); }
- }
- // DISPLAY DRAWING
- var DisplayUpdate = function(cm, viewport, force) {
- var display = cm.display;
- this.viewport = viewport;
- // Store some values that we'll need later (but don't want to force a relayout for)
- this.visible = visibleLines(display, cm.doc, viewport);
- this.editorIsHidden = !display.wrapper.offsetWidth;
- this.wrapperHeight = display.wrapper.clientHeight;
- this.wrapperWidth = display.wrapper.clientWidth;
- this.oldDisplayWidth = displayWidth(cm);
- this.force = force;
- this.dims = getDimensions(cm);
- this.events = [];
- };
- DisplayUpdate.prototype.signal = function (emitter, type) {
- if (hasHandler(emitter, type))
- { this.events.push(arguments); }
- };
- DisplayUpdate.prototype.finish = function () {
- var this$1 = this;
- for (var i = 0; i < this.events.length; i++)
- { signal.apply(null, this$1.events[i]); }
- };
- function maybeClipScrollbars(cm) {
- var display = cm.display;
- if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
- display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
- display.heightForcer.style.height = scrollGap(cm) + "px";
- display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
- display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
- display.scrollbarsClipped = true;
- }
- }
- function selectionSnapshot(cm) {
- if (cm.hasFocus()) { return null }
- var active = activeElt();
- if (!active || !contains(cm.display.lineDiv, active)) { return null }
- var result = {activeElt: active};
- if (window.getSelection) {
- var sel = window.getSelection();
- if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
- result.anchorNode = sel.anchorNode;
- result.anchorOffset = sel.anchorOffset;
- result.focusNode = sel.focusNode;
- result.focusOffset = sel.focusOffset;
- }
- }
- return result
- }
- function restoreSelection(snapshot) {
- if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
- snapshot.activeElt.focus();
- if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
- var sel = window.getSelection(), range$$1 = document.createRange();
- range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
- range$$1.collapse(false);
- sel.removeAllRanges();
- sel.addRange(range$$1);
- sel.extend(snapshot.focusNode, snapshot.focusOffset);
- }
- }
- // Does the actual updating of the line display. Bails out
- // (returning false) when there is nothing to be done and forced is
- // false.
- function updateDisplayIfNeeded(cm, update) {
- var display = cm.display, doc = cm.doc;
- if (update.editorIsHidden) {
- resetView(cm);
- return false
- }
- // Bail out if the visible area is already rendered and nothing changed.
- if (!update.force &&
- update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
- (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
- display.renderedView == display.view && countDirtyView(cm) == 0)
- { return false }
- if (maybeUpdateLineNumberWidth(cm)) {
- resetView(cm);
- update.dims = getDimensions(cm);
- }
- // Compute a suitable new viewport (from & to)
- var end = doc.first + doc.size;
- var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
- var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
- if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
- if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
- if (sawCollapsedSpans) {
- from = visualLineNo(cm.doc, from);
- to = visualLineEndNo(cm.doc, to);
- }
- var different = from != display.viewFrom || to != display.viewTo ||
- display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
- adjustView(cm, from, to);
- display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
- // Position the mover div to align with the current scroll position
- cm.display.mover.style.top = display.viewOffset + "px";
- var toUpdate = countDirtyView(cm);
- if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
- (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
- { return false }
- // For big changes, we hide the enclosing element during the
- // update, since that speeds up the operations on most browsers.
- var selSnapshot = selectionSnapshot(cm);
- if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
- patchDisplay(cm, display.updateLineNumbers, update.dims);
- if (toUpdate > 4) { display.lineDiv.style.display = ""; }
- display.renderedView = display.view;
- // There might have been a widget with a focused element that got
- // hidden or updated, if so re-focus it.
- restoreSelection(selSnapshot);
- // Prevent selection and cursors from interfering with the scroll
- // width and height.
- removeChildren(display.cursorDiv);
- removeChildren(display.selectionDiv);
- display.gutters.style.height = display.sizer.style.minHeight = 0;
- if (different) {
- display.lastWrapHeight = update.wrapperHeight;
- display.lastWrapWidth = update.wrapperWidth;
- startWorker(cm, 400);
- }
- display.updateLineNumbers = null;
- return true
- }
- function postUpdateDisplay(cm, update) {
- var viewport = update.viewport;
- for (var first = true;; first = false) {
- if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
- // Clip forced viewport to actual scrollable area.
- if (viewport && viewport.top != null)
- { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
- // Updated line heights might result in the drawn area not
- // actually covering the viewport. Keep looping until it does.
- update.visible = visibleLines(cm.display, cm.doc, viewport);
- if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
- { break }
- }
- if (!updateDisplayIfNeeded(cm, update)) { break }
- updateHeightsInViewport(cm);
- var barMeasure = measureForScrollbars(cm);
- updateSelection(cm);
- updateScrollbars(cm, barMeasure);
- setDocumentHeight(cm, barMeasure);
- update.force = false;
- }
- update.signal(cm, "update", cm);
- if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
- update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
- cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
- }
- }
- function updateDisplaySimple(cm, viewport) {
- var update = new DisplayUpdate(cm, viewport);
- if (updateDisplayIfNeeded(cm, update)) {
- updateHeightsInViewport(cm);
- postUpdateDisplay(cm, update);
- var barMeasure = measureForScrollbars(cm);
- updateSelection(cm);
- updateScrollbars(cm, barMeasure);
- setDocumentHeight(cm, barMeasure);
- update.finish();
- }
- }
- // Sync the actual display DOM structure with display.view, removing
- // nodes for lines that are no longer in view, and creating the ones
- // that are not there yet, and updating the ones that are out of
- // date.
- function patchDisplay(cm, updateNumbersFrom, dims) {
- var display = cm.display, lineNumbers = cm.options.lineNumbers;
- var container = display.lineDiv, cur = container.firstChild;
- function rm(node) {
- var next = node.nextSibling;
- // Works around a throw-scroll bug in OS X Webkit
- if (webkit && mac && cm.display.currentWheelTarget == node)
- { node.style.display = "none"; }
- else
- { node.parentNode.removeChild(node); }
- return next
- }
- var view = display.view, lineN = display.viewFrom;
- // Loop over the elements in the view, syncing cur (the DOM nodes
- // in display.lineDiv) with the view as we go.
- for (var i = 0; i < view.length; i++) {
- var lineView = view[i];
- if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
- var node = buildLineElement(cm, lineView, lineN, dims);
- container.insertBefore(node, cur);
- } else { // Already drawn
- while (cur != lineView.node) { cur = rm(cur); }
- var updateNumber = lineNumbers && updateNumbersFrom != null &&
- updateNumbersFrom <= lineN && lineView.lineNumber;
- if (lineView.changes) {
- if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
- updateLineForChanges(cm, lineView, lineN, dims);
- }
- if (updateNumber) {
- removeChildren(lineView.lineNumber);
- lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
- }
- cur = lineView.node.nextSibling;
- }
- lineN += lineView.size;
- }
- while (cur) { cur = rm(cur); }
- }
- function updateGutterSpace(display) {
- var width = display.gutters.offsetWidth;
- display.sizer.style.marginLeft = width + "px";
- }
- function setDocumentHeight(cm, measure) {
- cm.display.sizer.style.minHeight = measure.docHeight + "px";
- cm.display.heightForcer.style.top = measure.docHeight + "px";
- cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
- }
- // Re-align line numbers and gutter marks to compensate for
- // horizontal scrolling.
- function alignHorizontally(cm) {
- var display = cm.display, view = display.view;
- if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
- var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
- var gutterW = display.gutters.offsetWidth, left = comp + "px";
- for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
- if (cm.options.fixedGutter) {
- if (view[i].gutter)
- { view[i].gutter.style.left = left; }
- if (view[i].gutterBackground)
- { view[i].gutterBackground.style.left = left; }
- }
- var align = view[i].alignable;
- if (align) { for (var j = 0; j < align.length; j++)
- { align[j].style.left = left; } }
- } }
- if (cm.options.fixedGutter)
- { display.gutters.style.left = (comp + gutterW) + "px"; }
- }
- // Used to ensure that the line number gutter is still the right
- // size for the current document size. Returns true when an update
- // is needed.
- function maybeUpdateLineNumberWidth(cm) {
- if (!cm.options.lineNumbers) { return false }
- var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
- if (last.length != display.lineNumChars) {
- var test = display.measure.appendChild(elt("div", [elt("div", last)],
- "CodeMirror-linenumber CodeMirror-gutter-elt"));
- var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
- display.lineGutter.style.width = "";
- display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
- display.lineNumWidth = display.lineNumInnerWidth + padding;
- display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
- display.lineGutter.style.width = display.lineNumWidth + "px";
- updateGutterSpace(cm.display);
- return true
- }
- return false
- }
- function getGutters(gutters, lineNumbers) {
- var result = [], sawLineNumbers = false;
- for (var i = 0; i < gutters.length; i++) {
- var name = gutters[i], style = null;
- if (typeof name != "string") { style = name.style; name = name.className; }
- if (name == "CodeMirror-linenumbers") {
- if (!lineNumbers) { continue }
- else { sawLineNumbers = true; }
- }
- result.push({className: name, style: style});
- }
- if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
- return result
- }
- // Rebuild the gutter elements, ensure the margin to the left of the
- // code matches their width.
- function renderGutters(display) {
- var gutters = display.gutters, specs = display.gutterSpecs;
- removeChildren(gutters);
- display.lineGutter = null;
- for (var i = 0; i < specs.length; ++i) {
- var ref = specs[i];
- var className = ref.className;
- var style = ref.style;
- var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
- if (style) { gElt.style.cssText = style; }
- if (className == "CodeMirror-linenumbers") {
- display.lineGutter = gElt;
- gElt.style.width = (display.lineNumWidth || 1) + "px";
- }
- }
- gutters.style.display = specs.length ? "" : "none";
- updateGutterSpace(display);
- }
- function updateGutters(cm) {
- renderGutters(cm.display);
- regChange(cm);
- alignHorizontally(cm);
- }
- // The display handles the DOM integration, both for input reading
- // and content drawing. It holds references to DOM nodes and
- // display-related state.
- function Display(place, doc, input, options) {
- var d = this;
- this.input = input;
- // Covers bottom-right square when both scrollbars are present.
- d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
- d.scrollbarFiller.setAttribute("cm-not-content", "true");
- // Covers bottom of gutter when coverGutterNextToScrollbar is on
- // and h scrollbar is present.
- d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
- d.gutterFiller.setAttribute("cm-not-content", "true");
- // Will contain the actual code, positioned to cover the viewport.
- d.lineDiv = eltP("div", null, "CodeMirror-code");
- // Elements are added to these to represent selection and cursors.
- d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
- d.cursorDiv = elt("div", null, "CodeMirror-cursors");
- // A visibility: hidden element used to find the size of things.
- d.measure = elt("div", null, "CodeMirror-measure");
- // When lines outside of the viewport are measured, they are drawn in this.
- d.lineMeasure = elt("div", null, "CodeMirror-measure");
- // Wraps everything that needs to exist inside the vertically-padded coordinate system
- d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
- null, "position: relative; outline: none");
- var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
- // Moved around its parent to cover visible view.
- d.mover = elt("div", [lines], null, "position: relative");
- // Set to the height of the document, allowing scrolling.
- d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
- d.sizerWidth = null;
- // Behavior of elts with overflow: auto and padding is
- // inconsistent across browsers. This is used to ensure the
- // scrollable area is big enough.
- d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
- // Will contain the gutters, if any.
- d.gutters = elt("div", null, "CodeMirror-gutters");
- d.lineGutter = null;
- // Actual scrollable element.
- d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
- d.scroller.setAttribute("tabIndex", "-1");
- // The element in which the editor lives.
- d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
- // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
- if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
- if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
- if (place) {
- if (place.appendChild) { place.appendChild(d.wrapper); }
- else { place(d.wrapper); }
- }
- // Current rendered range (may be bigger than the view window).
- d.viewFrom = d.viewTo = doc.first;
- d.reportedViewFrom = d.reportedViewTo = doc.first;
- // Information about the rendered lines.
- d.view = [];
- d.renderedView = null;
- // Holds info about a single rendered line when it was rendered
- // for measurement, while not in view.
- d.externalMeasured = null;
- // Empty space (in pixels) above the view
- d.viewOffset = 0;
- d.lastWrapHeight = d.lastWrapWidth = 0;
- d.updateLineNumbers = null;
- d.nativeBarWidth = d.barHeight = d.barWidth = 0;
- d.scrollbarsClipped = false;
- // Used to only resize the line number gutter when necessary (when
- // the amount of lines crosses a boundary that makes its width change)
- d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
- // Set to true when a non-horizontal-scrolling line widget is
- // added. As an optimization, line widget aligning is skipped when
- // this is false.
- d.alignWidgets = false;
- d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
- // Tracks the maximum line length so that the horizontal scrollbar
- // can be kept static when scrolling.
- d.maxLine = null;
- d.maxLineLength = 0;
- d.maxLineChanged = false;
- // Used for measuring wheel scrolling granularity
- d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
- // True when shift is held down.
- d.shift = false;
- // Used to track whether anything happened since the context menu
- // was opened.
- d.selForContextMenu = null;
- d.activeTouch = null;
- d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
- renderGutters(d);
- input.init(d);
- }
- // Since the delta values reported on mouse wheel events are
- // unstandardized between browsers and even browser versions, and
- // generally horribly unpredictable, this code starts by measuring
- // the scroll effect that the first few mouse wheel events have,
- // and, from that, detects the way it can convert deltas to pixel
- // offsets afterwards.
- //
- // The reason we want to know the amount a wheel event will scroll
- // is that it gives us a chance to update the display before the
- // actual scrolling happens, reducing flickering.
- var wheelSamples = 0, wheelPixelsPerUnit = null;
- // Fill in a browser-detected starting value on browsers where we
- // know one. These don't have to be accurate -- the result of them
- // being wrong would just be a slight flicker on the first wheel
- // scroll (if it is large enough).
- if (ie) { wheelPixelsPerUnit = -.53; }
- else if (gecko) { wheelPixelsPerUnit = 15; }
- else if (chrome) { wheelPixelsPerUnit = -.7; }
- else if (safari) { wheelPixelsPerUnit = -1/3; }
- function wheelEventDelta(e) {
- var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
- if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
- if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
- else if (dy == null) { dy = e.wheelDelta; }
- return {x: dx, y: dy}
- }
- function wheelEventPixels(e) {
- var delta = wheelEventDelta(e);
- delta.x *= wheelPixelsPerUnit;
- delta.y *= wheelPixelsPerUnit;
- return delta
- }
- function onScrollWheel(cm, e) {
- var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
- var display = cm.display, scroll = display.scroller;
- // Quit if there's nothing to scroll here
- var canScrollX = scroll.scrollWidth > scroll.clientWidth;
- var canScrollY = scroll.scrollHeight > scroll.clientHeight;
- if (!(dx && canScrollX || dy && canScrollY)) { return }
- // Webkit browsers on OS X abort momentum scrolls when the target
- // of the scroll event is removed from the scrollable element.
- // This hack (see related code in patchDisplay) makes sure the
- // element is kept around.
- if (dy && mac && webkit) {
- outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
- for (var i = 0; i < view.length; i++) {
- if (view[i].node == cur) {
- cm.display.currentWheelTarget = cur;
- break outer
- }
- }
- }
- }
- // On some browsers, horizontal scrolling will cause redraws to
- // happen before the gutter has been realigned, causing it to
- // wriggle around in a most unseemly way. When we have an
- // estimated pixels/delta value, we just handle horizontal
- // scrolling entirely here. It'll be slightly off from native, but
- // better than glitching out.
- if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
- if (dy && canScrollY)
- { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
- setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
- // Only prevent default scrolling if vertical scrolling is
- // actually possible. Otherwise, it causes vertical scroll
- // jitter on OSX trackpads when deltaX is small and deltaY
- // is large (issue #3579)
- if (!dy || (dy && canScrollY))
- { e_preventDefault(e); }
- display.wheelStartX = null; // Abort measurement, if in progress
- return
- }
- // 'Project' the visible viewport to cover the area that is being
- // scrolled into view (if we know enough to estimate it).
- if (dy && wheelPixelsPerUnit != null) {
- var pixels = dy * wheelPixelsPerUnit;
- var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
- if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
- else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
- updateDisplaySimple(cm, {top: top, bottom: bot});
- }
- if (wheelSamples < 20) {
- if (display.wheelStartX == null) {
- display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
- display.wheelDX = dx; display.wheelDY = dy;
- setTimeout(function () {
- if (display.wheelStartX == null) { return }
- var movedX = scroll.scrollLeft - display.wheelStartX;
- var movedY = scroll.scrollTop - display.wheelStartY;
- var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
- (movedX && display.wheelDX && movedX / display.wheelDX);
- display.wheelStartX = display.wheelStartY = null;
- if (!sample) { return }
- wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
- ++wheelSamples;
- }, 200);
- } else {
- display.wheelDX += dx; display.wheelDY += dy;
- }
- }
- }
- // Selection objects are immutable. A new one is created every time
- // the selection changes. A selection is one or more non-overlapping
- // (and non-touching) ranges, sorted, and an integer that indicates
- // which one is the primary selection (the one that's scrolled into
- // view, that getCursor returns, etc).
- var Selection = function(ranges, primIndex) {
- this.ranges = ranges;
- this.primIndex = primIndex;
- };
- Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
- Selection.prototype.equals = function (other) {
- var this$1 = this;
- if (other == this) { return true }
- if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
- for (var i = 0; i < this.ranges.length; i++) {
- var here = this$1.ranges[i], there = other.ranges[i];
- if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
- }
- return true
- };
- Selection.prototype.deepCopy = function () {
- var this$1 = this;
- var out = [];
- for (var i = 0; i < this.ranges.length; i++)
- { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
- return new Selection(out, this.primIndex)
- };
- Selection.prototype.somethingSelected = function () {
- var this$1 = this;
- for (var i = 0; i < this.ranges.length; i++)
- { if (!this$1.ranges[i].empty()) { return true } }
- return false
- };
- Selection.prototype.contains = function (pos, end) {
- var this$1 = this;
- if (!end) { end = pos; }
- for (var i = 0; i < this.ranges.length; i++) {
- var range = this$1.ranges[i];
- if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
- { return i }
- }
- return -1
- };
- var Range = function(anchor, head) {
- this.anchor = anchor; this.head = head;
- };
- Range.prototype.from = function () { return minPos(this.anchor, this.head) };
- Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
- Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
- // Take an unsorted, potentially overlapping set of ranges, and
- // build a selection out of it. 'Consumes' ranges array (modifying
- // it).
- function normalizeSelection(cm, ranges, primIndex) {
- var mayTouch = cm && cm.options.selectionsMayTouch;
- var prim = ranges[primIndex];
- ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
- primIndex = indexOf(ranges, prim);
- for (var i = 1; i < ranges.length; i++) {
- var cur = ranges[i], prev = ranges[i - 1];
- var diff = cmp(prev.to(), cur.from());
- if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
- var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
- var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
- if (i <= primIndex) { --primIndex; }
- ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
- }
- }
- return new Selection(ranges, primIndex)
- }
- function simpleSelection(anchor, head) {
- return new Selection([new Range(anchor, head || anchor)], 0)
- }
- // Compute the position of the end of a change (its 'to' property
- // refers to the pre-change end).
- function changeEnd(change) {
- if (!change.text) { return change.to }
- return Pos(change.from.line + change.text.length - 1,
- lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
- }
- // Adjust a position to refer to the post-change position of the
- // same text, or the end of the change if the change covers it.
- function adjustForChange(pos, change) {
- if (cmp(pos, change.from) < 0) { return pos }
- if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
- var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
- if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
- return Pos(line, ch)
- }
- function computeSelAfterChange(doc, change) {
- var out = [];
- for (var i = 0; i < doc.sel.ranges.length; i++) {
- var range = doc.sel.ranges[i];
- out.push(new Range(adjustForChange(range.anchor, change),
- adjustForChange(range.head, change)));
- }
- return normalizeSelection(doc.cm, out, doc.sel.primIndex)
- }
- function offsetPos(pos, old, nw) {
- if (pos.line == old.line)
- { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
- else
- { return Pos(nw.line + (pos.line - old.line), pos.ch) }
- }
- // Used by replaceSelections to allow moving the selection to the
- // start or around the replaced test. Hint may be "start" or "around".
- function computeReplacedSel(doc, changes, hint) {
- var out = [];
- var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
- for (var i = 0; i < changes.length; i++) {
- var change = changes[i];
- var from = offsetPos(change.from, oldPrev, newPrev);
- var to = offsetPos(changeEnd(change), oldPrev, newPrev);
- oldPrev = change.to;
- newPrev = to;
- if (hint == "around") {
- var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
- out[i] = new Range(inv ? to : from, inv ? from : to);
- } else {
- out[i] = new Range(from, from);
- }
- }
- return new Selection(out, doc.sel.primIndex)
- }
- // Used to get the editor into a consistent state again when options change.
- function loadMode(cm) {
- cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
- resetModeState(cm);
- }
- function resetModeState(cm) {
- cm.doc.iter(function (line) {
- if (line.stateAfter) { line.stateAfter = null; }
- if (line.styles) { line.styles = null; }
- });
- cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
- startWorker(cm, 100);
- cm.state.modeGen++;
- if (cm.curOp) { regChange(cm); }
- }
- // DOCUMENT DATA STRUCTURE
- // By default, updates that start and end at the beginning of a line
- // are treated specially, in order to make the association of line
- // widgets and marker elements with the text behave more intuitive.
- function isWholeLineUpdate(doc, change) {
- return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
- (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
- }
- // Perform a change on the document data structure.
- function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
- function spansFor(n) {return markedSpans ? markedSpans[n] : null}
- function update(line, text, spans) {
- updateLine(line, text, spans, estimateHeight$$1);
- signalLater(line, "change", line, change);
- }
- function linesFor(start, end) {
- var result = [];
- for (var i = start; i < end; ++i)
- { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
- return result
- }
- var from = change.from, to = change.to, text = change.text;
- var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
- var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
- // Adjust the line structure
- if (change.full) {
- doc.insert(0, linesFor(0, text.length));
- doc.remove(text.length, doc.size - text.length);
- } else if (isWholeLineUpdate(doc, change)) {
- // This is a whole-line replace. Treated specially to make
- // sure line objects move the way they are supposed to.
- var added = linesFor(0, text.length - 1);
- update(lastLine, lastLine.text, lastSpans);
- if (nlines) { doc.remove(from.line, nlines); }
- if (added.length) { doc.insert(from.line, added); }
- } else if (firstLine == lastLine) {
- if (text.length == 1) {
- update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
- } else {
- var added$1 = linesFor(1, text.length - 1);
- added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
- doc.insert(from.line + 1, added$1);
- }
- } else if (text.length == 1) {
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
- doc.remove(from.line + 1, nlines);
- } else {
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
- update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
- var added$2 = linesFor(1, text.length - 1);
- if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
- doc.insert(from.line + 1, added$2);
- }
- signalLater(doc, "change", doc, change);
- }
- // Call f for all linked documents.
- function linkedDocs(doc, f, sharedHistOnly) {
- function propagate(doc, skip, sharedHist) {
- if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
- var rel = doc.linked[i];
- if (rel.doc == skip) { continue }
- var shared = sharedHist && rel.sharedHist;
- if (sharedHistOnly && !shared) { continue }
- f(rel.doc, shared);
- propagate(rel.doc, doc, shared);
- } }
- }
- propagate(doc, null, true);
- }
- // Attach a document to an editor.
- function attachDoc(cm, doc) {
- if (doc.cm) { throw new Error("This document is already in use.") }
- cm.doc = doc;
- doc.cm = cm;
- estimateLineHeights(cm);
- loadMode(cm);
- setDirectionClass(cm);
- if (!cm.options.lineWrapping) { findMaxLine(cm); }
- cm.options.mode = doc.modeOption;
- regChange(cm);
- }
- function setDirectionClass(cm) {
- (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
- }
- function directionChanged(cm) {
- runInOp(cm, function () {
- setDirectionClass(cm);
- regChange(cm);
- });
- }
- function History(startGen) {
- // Arrays of change events and selections. Doing something adds an
- // event to done and clears undo. Undoing moves events from done
- // to undone, redoing moves them in the other direction.
- this.done = []; this.undone = [];
- this.undoDepth = Infinity;
- // Used to track when changes can be merged into a single undo
- // event
- this.lastModTime = this.lastSelTime = 0;
- this.lastOp = this.lastSelOp = null;
- this.lastOrigin = this.lastSelOrigin = null;
- // Used by the isClean() method
- this.generation = this.maxGeneration = startGen || 1;
- }
- // Create a history change event from an updateDoc-style change
- // object.
- function historyChangeFromChange(doc, change) {
- var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
- attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
- linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
- return histChange
- }
- // Pop all selection events off the end of a history array. Stop at
- // a change event.
- function clearSelectionEvents(array) {
- while (array.length) {
- var last = lst(array);
- if (last.ranges) { array.pop(); }
- else { break }
- }
- }
- // Find the top change event in the history. Pop off selection
- // events that are in the way.
- function lastChangeEvent(hist, force) {
- if (force) {
- clearSelectionEvents(hist.done);
- return lst(hist.done)
- } else if (hist.done.length && !lst(hist.done).ranges) {
- return lst(hist.done)
- } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
- hist.done.pop();
- return lst(hist.done)
- }
- }
- // Register a change in the history. Merges changes that are within
- // a single operation, or are close together with an origin that
- // allows merging (starting with "+") into a single event.
- function addChangeToHistory(doc, change, selAfter, opId) {
- var hist = doc.history;
- hist.undone.length = 0;
- var time = +new Date, cur;
- var last;
- if ((hist.lastOp == opId ||
- hist.lastOrigin == change.origin && change.origin &&
- ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
- change.origin.charAt(0) == "*")) &&
- (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
- // Merge this change into the last event
- last = lst(cur.changes);
- if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
- // Optimized case for simple insertion -- don't want to add
- // new changesets for every character typed
- last.to = changeEnd(change);
- } else {
- // Add new sub-event
- cur.changes.push(historyChangeFromChange(doc, change));
- }
- } else {
- // Can not be merged, start a new event.
- var before = lst(hist.done);
- if (!before || !before.ranges)
- { pushSelectionToHistory(doc.sel, hist.done); }
- cur = {changes: [historyChangeFromChange(doc, change)],
- generation: hist.generation};
- hist.done.push(cur);
- while (hist.done.length > hist.undoDepth) {
- hist.done.shift();
- if (!hist.done[0].ranges) { hist.done.shift(); }
- }
- }
- hist.done.push(selAfter);
- hist.generation = ++hist.maxGeneration;
- hist.lastModTime = hist.lastSelTime = time;
- hist.lastOp = hist.lastSelOp = opId;
- hist.lastOrigin = hist.lastSelOrigin = change.origin;
- if (!last) { signal(doc, "historyAdded"); }
- }
- function selectionEventCanBeMerged(doc, origin, prev, sel) {
- var ch = origin.charAt(0);
- return ch == "*" ||
- ch == "+" &&
- prev.ranges.length == sel.ranges.length &&
- prev.somethingSelected() == sel.somethingSelected() &&
- new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
- }
- // Called whenever the selection changes, sets the new selection as
- // the pending selection in the history, and pushes the old pending
- // selection into the 'done' array when it was significantly
- // different (in number of selected ranges, emptiness, or time).
- function addSelectionToHistory(doc, sel, opId, options) {
- var hist = doc.history, origin = options && options.origin;
- // A new event is started when the previous origin does not match
- // the current, or the origins don't allow matching. Origins
- // starting with * are always merged, those starting with + are
- // merged when similar and close together in time.
- if (opId == hist.lastSelOp ||
- (origin && hist.lastSelOrigin == origin &&
- (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
- selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
- { hist.done[hist.done.length - 1] = sel; }
- else
- { pushSelectionToHistory(sel, hist.done); }
- hist.lastSelTime = +new Date;
- hist.lastSelOrigin = origin;
- hist.lastSelOp = opId;
- if (options && options.clearRedo !== false)
- { clearSelectionEvents(hist.undone); }
- }
- function pushSelectionToHistory(sel, dest) {
- var top = lst(dest);
- if (!(top && top.ranges && top.equals(sel)))
- { dest.push(sel); }
- }
- // Used to store marked span information in the history.
- function attachLocalSpans(doc, change, from, to) {
- var existing = change["spans_" + doc.id], n = 0;
- doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
- if (line.markedSpans)
- { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
- ++n;
- });
- }
- // When un/re-doing restores text containing marked spans, those
- // that have been explicitly cleared should not be restored.
- function removeClearedSpans(spans) {
- if (!spans) { return null }
- var out;
- for (var i = 0; i < spans.length; ++i) {
- if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
- else if (out) { out.push(spans[i]); }
- }
- return !out ? spans : out.length ? out : null
- }
- // Retrieve and filter the old marked spans stored in a change event.
- function getOldSpans(doc, change) {
- var found = change["spans_" + doc.id];
- if (!found) { return null }
- var nw = [];
- for (var i = 0; i < change.text.length; ++i)
- { nw.push(removeClearedSpans(found[i])); }
- return nw
- }
- // Used for un/re-doing changes from the history. Combines the
- // result of computing the existing spans with the set of spans that
- // existed in the history (so that deleting around a span and then
- // undoing brings back the span).
- function mergeOldSpans(doc, change) {
- var old = getOldSpans(doc, change);
- var stretched = stretchSpansOverChange(doc, change);
- if (!old) { return stretched }
- if (!stretched) { return old }
- for (var i = 0; i < old.length; ++i) {
- var oldCur = old[i], stretchCur = stretched[i];
- if (oldCur && stretchCur) {
- spans: for (var j = 0; j < stretchCur.length; ++j) {
- var span = stretchCur[j];
- for (var k = 0; k < oldCur.length; ++k)
- { if (oldCur[k].marker == span.marker) { continue spans } }
- oldCur.push(span);
- }
- } else if (stretchCur) {
- old[i] = stretchCur;
- }
- }
- return old
- }
- // Used both to provide a JSON-safe object in .getHistory, and, when
- // detaching a document, to split the history in two
- function copyHistoryArray(events, newGroup, instantiateSel) {
- var copy = [];
- for (var i = 0; i < events.length; ++i) {
- var event = events[i];
- if (event.ranges) {
- copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
- continue
- }
- var changes = event.changes, newChanges = [];
- copy.push({changes: newChanges});
- for (var j = 0; j < changes.length; ++j) {
- var change = changes[j], m = (void 0);
- newChanges.push({from: change.from, to: change.to, text: change.text});
- if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
- if (indexOf(newGroup, Number(m[1])) > -1) {
- lst(newChanges)[prop] = change[prop];
- delete change[prop];
- }
- } } }
- }
- }
- return copy
- }
- // The 'scroll' parameter given to many of these indicated whether
- // the new cursor position should be scrolled into view after
- // modifying the selection.
- // If shift is held or the extend flag is set, extends a range to
- // include a given position (and optionally a second position).
- // Otherwise, simply returns the range between the given positions.
- // Used for cursor motion and such.
- function extendRange(range, head, other, extend) {
- if (extend) {
- var anchor = range.anchor;
- if (other) {
- var posBefore = cmp(head, anchor) < 0;
- if (posBefore != (cmp(other, anchor) < 0)) {
- anchor = head;
- head = other;
- } else if (posBefore != (cmp(head, other) < 0)) {
- head = other;
- }
- }
- return new Range(anchor, head)
- } else {
- return new Range(other || head, head)
- }
- }
- // Extend the primary selection range, discard the rest.
- function extendSelection(doc, head, other, options, extend) {
- if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
- setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
- }
- // Extend all selections (pos is an array of selections with length
- // equal the number of selections)
- function extendSelections(doc, heads, options) {
- var out = [];
- var extend = doc.cm && (doc.cm.display.shift || doc.extend);
- for (var i = 0; i < doc.sel.ranges.length; i++)
- { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
- var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
- setSelection(doc, newSel, options);
- }
- // Updates a single range in the selection.
- function replaceOneSelection(doc, i, range, options) {
- var ranges = doc.sel.ranges.slice(0);
- ranges[i] = range;
- setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
- }
- // Reset the selection to a single range.
- function setSimpleSelection(doc, anchor, head, options) {
- setSelection(doc, simpleSelection(anchor, head), options);
- }
- // Give beforeSelectionChange handlers a change to influence a
- // selection update.
- function filterSelectionChange(doc, sel, options) {
- var obj = {
- ranges: sel.ranges,
- update: function(ranges) {
- var this$1 = this;
- this.ranges = [];
- for (var i = 0; i < ranges.length; i++)
- { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
- clipPos(doc, ranges[i].head)); }
- },
- origin: options && options.origin
- };
- signal(doc, "beforeSelectionChange", doc, obj);
- if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
- if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
- else { return sel }
- }
- function setSelectionReplaceHistory(doc, sel, options) {
- var done = doc.history.done, last = lst(done);
- if (last && last.ranges) {
- done[done.length - 1] = sel;
- setSelectionNoUndo(doc, sel, options);
- } else {
- setSelection(doc, sel, options);
- }
- }
- // Set a new selection.
- function setSelection(doc, sel, options) {
- setSelectionNoUndo(doc, sel, options);
- addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
- }
- function setSelectionNoUndo(doc, sel, options) {
- if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
- { sel = filterSelectionChange(doc, sel, options); }
- var bias = options && options.bias ||
- (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
- setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
- if (!(options && options.scroll === false) && doc.cm)
- { ensureCursorVisible(doc.cm); }
- }
- function setSelectionInner(doc, sel) {
- if (sel.equals(doc.sel)) { return }
- doc.sel = sel;
- if (doc.cm) {
- doc.cm.curOp.updateInput = 1;
- doc.cm.curOp.selectionChanged = true;
- signalCursorActivity(doc.cm);
- }
- signalLater(doc, "cursorActivity", doc);
- }
- // Verify that the selection does not partially select any atomic
- // marked ranges.
- function reCheckSelection(doc) {
- setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
- }
- // Return a selection that does not partially select any atomic
- // ranges.
- function skipAtomicInSelection(doc, sel, bias, mayClear) {
- var out;
- for (var i = 0; i < sel.ranges.length; i++) {
- var range = sel.ranges[i];
- var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
- var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
- var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
- if (out || newAnchor != range.anchor || newHead != range.head) {
- if (!out) { out = sel.ranges.slice(0, i); }
- out[i] = new Range(newAnchor, newHead);
- }
- }
- return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
- }
- function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
- var line = getLine(doc, pos.line);
- if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
- var sp = line.markedSpans[i], m = sp.marker;
- if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
- (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
- if (mayClear) {
- signal(m, "beforeCursorEnter");
- if (m.explicitlyCleared) {
- if (!line.markedSpans) { break }
- else {--i; continue}
- }
- }
- if (!m.atomic) { continue }
- if (oldPos) {
- var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
- if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
- { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
- if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
- { return skipAtomicInner(doc, near, pos, dir, mayClear) }
- }
- var far = m.find(dir < 0 ? -1 : 1);
- if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
- { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
- return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
- }
- } }
- return pos
- }
- // Ensure a given position is not inside an atomic range.
- function skipAtomic(doc, pos, oldPos, bias, mayClear) {
- var dir = bias || 1;
- var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
- (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
- skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
- (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
- if (!found) {
- doc.cantEdit = true;
- return Pos(doc.first, 0)
- }
- return found
- }
- function movePos(doc, pos, dir, line) {
- if (dir < 0 && pos.ch == 0) {
- if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
- else { return null }
- } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
- if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
- else { return null }
- } else {
- return new Pos(pos.line, pos.ch + dir)
- }
- }
- function selectAll(cm) {
- cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
- }
- // UPDATING
- // Allow "beforeChange" event handlers to influence a change
- function filterChange(doc, change, update) {
- var obj = {
- canceled: false,
- from: change.from,
- to: change.to,
- text: change.text,
- origin: change.origin,
- cancel: function () { return obj.canceled = true; }
- };
- if (update) { obj.update = function (from, to, text, origin) {
- if (from) { obj.from = clipPos(doc, from); }
- if (to) { obj.to = clipPos(doc, to); }
- if (text) { obj.text = text; }
- if (origin !== undefined) { obj.origin = origin; }
- }; }
- signal(doc, "beforeChange", doc, obj);
- if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
- if (obj.canceled) {
- if (doc.cm) { doc.cm.curOp.updateInput = 2; }
- return null
- }
- return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
- }
- // Apply a change to a document, and add it to the document's
- // history, and propagating it to all linked documents.
- function makeChange(doc, change, ignoreReadOnly) {
- if (doc.cm) {
- if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
- if (doc.cm.state.suppressEdits) { return }
- }
- if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
- change = filterChange(doc, change, true);
- if (!change) { return }
- }
- // Possibly split or suppress the update based on the presence
- // of read-only spans in its range.
- var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
- if (split) {
- for (var i = split.length - 1; i >= 0; --i)
- { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
- } else {
- makeChangeInner(doc, change);
- }
- }
- function makeChangeInner(doc, change) {
- if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
- var selAfter = computeSelAfterChange(doc, change);
- addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
- makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
- var rebased = [];
- linkedDocs(doc, function (doc, sharedHist) {
- if (!sharedHist && indexOf(rebased, doc.history) == -1) {
- rebaseHist(doc.history, change);
- rebased.push(doc.history);
- }
- makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
- });
- }
- // Revert a change stored in a document's history.
- function makeChangeFromHistory(doc, type, allowSelectionOnly) {
- var suppress = doc.cm && doc.cm.state.suppressEdits;
- if (suppress && !allowSelectionOnly) { return }
- var hist = doc.history, event, selAfter = doc.sel;
- var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
- // Verify that there is a useable event (so that ctrl-z won't
- // needlessly clear selection events)
- var i = 0;
- for (; i < source.length; i++) {
- event = source[i];
- if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
- { break }
- }
- if (i == source.length) { return }
- hist.lastOrigin = hist.lastSelOrigin = null;
- for (;;) {
- event = source.pop();
- if (event.ranges) {
- pushSelectionToHistory(event, dest);
- if (allowSelectionOnly && !event.equals(doc.sel)) {
- setSelection(doc, event, {clearRedo: false});
- return
- }
- selAfter = event;
- } else if (suppress) {
- source.push(event);
- return
- } else { break }
- }
- // Build up a reverse change object to add to the opposite history
- // stack (redo when undoing, and vice versa).
- var antiChanges = [];
- pushSelectionToHistory(selAfter, dest);
- dest.push({changes: antiChanges, generation: hist.generation});
- hist.generation = event.generation || ++hist.maxGeneration;
- var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
- var loop = function ( i ) {
- var change = event.changes[i];
- change.origin = type;
- if (filter && !filterChange(doc, change, false)) {
- source.length = 0;
- return {}
- }
- antiChanges.push(historyChangeFromChange(doc, change));
- var after = i ? computeSelAfterChange(doc, change) : lst(source);
- makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
- if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
- var rebased = [];
- // Propagate to the linked documents
- linkedDocs(doc, function (doc, sharedHist) {
- if (!sharedHist && indexOf(rebased, doc.history) == -1) {
- rebaseHist(doc.history, change);
- rebased.push(doc.history);
- }
- makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
- });
- };
- for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
- var returned = loop( i$1 );
- if ( returned ) return returned.v;
- }
- }
- // Sub-views need their line numbers shifted when text is added
- // above or below them in the parent document.
- function shiftDoc(doc, distance) {
- if (distance == 0) { return }
- doc.first += distance;
- doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
- Pos(range.anchor.line + distance, range.anchor.ch),
- Pos(range.head.line + distance, range.head.ch)
- ); }), doc.sel.primIndex);
- if (doc.cm) {
- regChange(doc.cm, doc.first, doc.first - distance, distance);
- for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
- { regLineChange(doc.cm, l, "gutter"); }
- }
- }
- // More lower-level change function, handling only a single document
- // (not linked ones).
- function makeChangeSingleDoc(doc, change, selAfter, spans) {
- if (doc.cm && !doc.cm.curOp)
- { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
- if (change.to.line < doc.first) {
- shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
- return
- }
- if (change.from.line > doc.lastLine()) { return }
- // Clip the change to the size of this doc
- if (change.from.line < doc.first) {
- var shift = change.text.length - 1 - (doc.first - change.from.line);
- shiftDoc(doc, shift);
- change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
- text: [lst(change.text)], origin: change.origin};
- }
- var last = doc.lastLine();
- if (change.to.line > last) {
- change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
- text: [change.text[0]], origin: change.origin};
- }
- change.removed = getBetween(doc, change.from, change.to);
- if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
- if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
- else { updateDoc(doc, change, spans); }
- setSelectionNoUndo(doc, selAfter, sel_dontScroll);
- }
- // Handle the interaction of a change to a document with the editor
- // that this document is part of.
- function makeChangeSingleDocInEditor(cm, change, spans) {
- var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
- var recomputeMaxLength = false, checkWidthStart = from.line;
- if (!cm.options.lineWrapping) {
- checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
- doc.iter(checkWidthStart, to.line + 1, function (line) {
- if (line == display.maxLine) {
- recomputeMaxLength = true;
- return true
- }
- });
- }
- if (doc.sel.contains(change.from, change.to) > -1)
- { signalCursorActivity(cm); }
- updateDoc(doc, change, spans, estimateHeight(cm));
- if (!cm.options.lineWrapping) {
- doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
- var len = lineLength(line);
- if (len > display.maxLineLength) {
- display.maxLine = line;
- display.maxLineLength = len;
- display.maxLineChanged = true;
- recomputeMaxLength = false;
- }
- });
- if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
- }
- retreatFrontier(doc, from.line);
- startWorker(cm, 400);
- var lendiff = change.text.length - (to.line - from.line) - 1;
- // Remember that these lines changed, for updating the display
- if (change.full)
- { regChange(cm); }
- else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
- { regLineChange(cm, from.line, "text"); }
- else
- { regChange(cm, from.line, to.line + 1, lendiff); }
- var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
- if (changeHandler || changesHandler) {
- var obj = {
- from: from, to: to,
- text: change.text,
- removed: change.removed,
- origin: change.origin
- };
- if (changeHandler) { signalLater(cm, "change", cm, obj); }
- if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
- }
- cm.display.selForContextMenu = null;
- }
- function replaceRange(doc, code, from, to, origin) {
- var assign;
- if (!to) { to = from; }
- if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
- if (typeof code == "string") { code = doc.splitLines(code); }
- makeChange(doc, {from: from, to: to, text: code, origin: origin});
- }
- // Rebasing/resetting history to deal with externally-sourced changes
- function rebaseHistSelSingle(pos, from, to, diff) {
- if (to < pos.line) {
- pos.line += diff;
- } else if (from < pos.line) {
- pos.line = from;
- pos.ch = 0;
- }
- }
- // Tries to rebase an array of history events given a change in the
- // document. If the change touches the same lines as the event, the
- // event, and everything 'behind' it, is discarded. If the change is
- // before the event, the event's positions are updated. Uses a
- // copy-on-write scheme for the positions, to avoid having to
- // reallocate them all on every rebase, but also avoid problems with
- // shared position objects being unsafely updated.
- function rebaseHistArray(array, from, to, diff) {
- for (var i = 0; i < array.length; ++i) {
- var sub = array[i], ok = true;
- if (sub.ranges) {
- if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
- for (var j = 0; j < sub.ranges.length; j++) {
- rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
- rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
- }
- continue
- }
- for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
- var cur = sub.changes[j$1];
- if (to < cur.from.line) {
- cur.from = Pos(cur.from.line + diff, cur.from.ch);
- cur.to = Pos(cur.to.line + diff, cur.to.ch);
- } else if (from <= cur.to.line) {
- ok = false;
- break
- }
- }
- if (!ok) {
- array.splice(0, i + 1);
- i = 0;
- }
- }
- }
- function rebaseHist(hist, change) {
- var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
- rebaseHistArray(hist.done, from, to, diff);
- rebaseHistArray(hist.undone, from, to, diff);
- }
- // Utility for applying a change to a line by handle or number,
- // returning the number and optionally registering the line as
- // changed.
- function changeLine(doc, handle, changeType, op) {
- var no = handle, line = handle;
- if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
- else { no = lineNo(handle); }
- if (no == null) { return null }
- if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
- return line
- }
- // The document is represented as a BTree consisting of leaves, with
- // chunk of lines in them, and branches, with up to ten leaves or
- // other branch nodes below them. The top node is always a branch
- // node, and is the document object itself (meaning it has
- // additional methods and properties).
- //
- // All nodes have parent links. The tree is used both to go from
- // line numbers to line objects, and to go from objects to numbers.
- // It also indexes by height, and is used to convert between height
- // and line object, and to find the total height of the document.
- //
- // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
- function LeafChunk(lines) {
- var this$1 = this;
- this.lines = lines;
- this.parent = null;
- var height = 0;
- for (var i = 0; i < lines.length; ++i) {
- lines[i].parent = this$1;
- height += lines[i].height;
- }
- this.height = height;
- }
- LeafChunk.prototype = {
- chunkSize: function() { return this.lines.length },
- // Remove the n lines at offset 'at'.
- removeInner: function(at, n) {
- var this$1 = this;
- for (var i = at, e = at + n; i < e; ++i) {
- var line = this$1.lines[i];
- this$1.height -= line.height;
- cleanUpLine(line);
- signalLater(line, "delete");
- }
- this.lines.splice(at, n);
- },
- // Helper used to collapse a small branch into a single leaf.
- collapse: function(lines) {
- lines.push.apply(lines, this.lines);
- },
- // Insert the given array of lines at offset 'at', count them as
- // having the given height.
- insertInner: function(at, lines, height) {
- var this$1 = this;
- this.height += height;
- this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
- for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
- },
- // Used to iterate over a part of the tree.
- iterN: function(at, n, op) {
- var this$1 = this;
- for (var e = at + n; at < e; ++at)
- { if (op(this$1.lines[at])) { return true } }
- }
- };
- function BranchChunk(children) {
- var this$1 = this;
- this.children = children;
- var size = 0, height = 0;
- for (var i = 0; i < children.length; ++i) {
- var ch = children[i];
- size += ch.chunkSize(); height += ch.height;
- ch.parent = this$1;
- }
- this.size = size;
- this.height = height;
- this.parent = null;
- }
- BranchChunk.prototype = {
- chunkSize: function() { return this.size },
- removeInner: function(at, n) {
- var this$1 = this;
- this.size -= n;
- for (var i = 0; i < this.children.length; ++i) {
- var child = this$1.children[i], sz = child.chunkSize();
- if (at < sz) {
- var rm = Math.min(n, sz - at), oldHeight = child.height;
- child.removeInner(at, rm);
- this$1.height -= oldHeight - child.height;
- if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
- if ((n -= rm) == 0) { break }
- at = 0;
- } else { at -= sz; }
- }
- // If the result is smaller than 25 lines, ensure that it is a
- // single leaf node.
- if (this.size - n < 25 &&
- (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
- var lines = [];
- this.collapse(lines);
- this.children = [new LeafChunk(lines)];
- this.children[0].parent = this;
- }
- },
- collapse: function(lines) {
- var this$1 = this;
- for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
- },
- insertInner: function(at, lines, height) {
- var this$1 = this;
- this.size += lines.length;
- this.height += height;
- for (var i = 0; i < this.children.length; ++i) {
- var child = this$1.children[i], sz = child.chunkSize();
- if (at <= sz) {
- child.insertInner(at, lines, height);
- if (child.lines && child.lines.length > 50) {
- // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
- // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
- var remaining = child.lines.length % 25 + 25;
- for (var pos = remaining; pos < child.lines.length;) {
- var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
- child.height -= leaf.height;
- this$1.children.splice(++i, 0, leaf);
- leaf.parent = this$1;
- }
- child.lines = child.lines.slice(0, remaining);
- this$1.maybeSpill();
- }
- break
- }
- at -= sz;
- }
- },
- // When a node has grown, check whether it should be split.
- maybeSpill: function() {
- if (this.children.length <= 10) { return }
- var me = this;
- do {
- var spilled = me.children.splice(me.children.length - 5, 5);
- var sibling = new BranchChunk(spilled);
- if (!me.parent) { // Become the parent node
- var copy = new BranchChunk(me.children);
- copy.parent = me;
- me.children = [copy, sibling];
- me = copy;
- } else {
- me.size -= sibling.size;
- me.height -= sibling.height;
- var myIndex = indexOf(me.parent.children, me);
- me.parent.children.splice(myIndex + 1, 0, sibling);
- }
- sibling.parent = me.parent;
- } while (me.children.length > 10)
- me.parent.maybeSpill();
- },
- iterN: function(at, n, op) {
- var this$1 = this;
- for (var i = 0; i < this.children.length; ++i) {
- var child = this$1.children[i], sz = child.chunkSize();
- if (at < sz) {
- var used = Math.min(n, sz - at);
- if (child.iterN(at, used, op)) { return true }
- if ((n -= used) == 0) { break }
- at = 0;
- } else { at -= sz; }
- }
- }
- };
- // Line widgets are block elements displayed above or below a line.
- var LineWidget = function(doc, node, options) {
- var this$1 = this;
- if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
- { this$1[opt] = options[opt]; } } }
- this.doc = doc;
- this.node = node;
- };
- LineWidget.prototype.clear = function () {
- var this$1 = this;
- var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
- if (no == null || !ws) { return }
- for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
- if (!ws.length) { line.widgets = null; }
- var height = widgetHeight(this);
- updateLineHeight(line, Math.max(0, line.height - height));
- if (cm) {
- runInOp(cm, function () {
- adjustScrollWhenAboveVisible(cm, line, -height);
- regLineChange(cm, no, "widget");
- });
- signalLater(cm, "lineWidgetCleared", cm, this, no);
- }
- };
- LineWidget.prototype.changed = function () {
- var this$1 = this;
- var oldH = this.height, cm = this.doc.cm, line = this.line;
- this.height = null;
- var diff = widgetHeight(this) - oldH;
- if (!diff) { return }
- if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
- if (cm) {
- runInOp(cm, function () {
- cm.curOp.forceUpdate = true;
- adjustScrollWhenAboveVisible(cm, line, diff);
- signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
- });
- }
- };
- eventMixin(LineWidget);
- function adjustScrollWhenAboveVisible(cm, line, diff) {
- if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
- { addToScrollTop(cm, diff); }
- }
- function addLineWidget(doc, handle, node, options) {
- var widget = new LineWidget(doc, node, options);
- var cm = doc.cm;
- if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
- changeLine(doc, handle, "widget", function (line) {
- var widgets = line.widgets || (line.widgets = []);
- if (widget.insertAt == null) { widgets.push(widget); }
- else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
- widget.line = line;
- if (cm && !lineIsHidden(doc, line)) {
- var aboveVisible = heightAtLine(line) < doc.scrollTop;
- updateLineHeight(line, line.height + widgetHeight(widget));
- if (aboveVisible) { addToScrollTop(cm, widget.height); }
- cm.curOp.forceUpdate = true;
- }
- return true
- });
- if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
- return widget
- }
- // TEXTMARKERS
- // Created with markText and setBookmark methods. A TextMarker is a
- // handle that can be used to clear or find a marked position in the
- // document. Line objects hold arrays (markedSpans) containing
- // {from, to, marker} object pointing to such marker objects, and
- // indicating that such a marker is present on that line. Multiple
- // lines may point to the same marker when it spans across lines.
- // The spans will have null for their from/to properties when the
- // marker continues beyond the start/end of the line. Markers have
- // links back to the lines they currently touch.
- // Collapsed markers have unique ids, in order to be able to order
- // them, which is needed for uniquely determining an outer marker
- // when they overlap (they may nest, but not partially overlap).
- var nextMarkerId = 0;
- var TextMarker = function(doc, type) {
- this.lines = [];
- this.type = type;
- this.doc = doc;
- this.id = ++nextMarkerId;
- };
- // Clear the marker.
- TextMarker.prototype.clear = function () {
- var this$1 = this;
- if (this.explicitlyCleared) { return }
- var cm = this.doc.cm, withOp = cm && !cm.curOp;
- if (withOp) { startOperation(cm); }
- if (hasHandler(this, "clear")) {
- var found = this.find();
- if (found) { signalLater(this, "clear", found.from, found.to); }
- }
- var min = null, max = null;
- for (var i = 0; i < this.lines.length; ++i) {
- var line = this$1.lines[i];
- var span = getMarkedSpanFor(line.markedSpans, this$1);
- if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
- else if (cm) {
- if (span.to != null) { max = lineNo(line); }
- if (span.from != null) { min = lineNo(line); }
- }
- line.markedSpans = removeMarkedSpan(line.markedSpans, span);
- if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
- { updateLineHeight(line, textHeight(cm.display)); }
- }
- if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
- var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
- if (len > cm.display.maxLineLength) {
- cm.display.maxLine = visual;
- cm.display.maxLineLength = len;
- cm.display.maxLineChanged = true;
- }
- } }
- if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
- this.lines.length = 0;
- this.explicitlyCleared = true;
- if (this.atomic && this.doc.cantEdit) {
- this.doc.cantEdit = false;
- if (cm) { reCheckSelection(cm.doc); }
- }
- if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
- if (withOp) { endOperation(cm); }
- if (this.parent) { this.parent.clear(); }
- };
- // Find the position of the marker in the document. Returns a {from,
- // to} object by default. Side can be passed to get a specific side
- // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
- // Pos objects returned contain a line object, rather than a line
- // number (used to prevent looking up the same line twice).
- TextMarker.prototype.find = function (side, lineObj) {
- var this$1 = this;
- if (side == null && this.type == "bookmark") { side = 1; }
- var from, to;
- for (var i = 0; i < this.lines.length; ++i) {
- var line = this$1.lines[i];
- var span = getMarkedSpanFor(line.markedSpans, this$1);
- if (span.from != null) {
- from = Pos(lineObj ? line : lineNo(line), span.from);
- if (side == -1) { return from }
- }
- if (span.to != null) {
- to = Pos(lineObj ? line : lineNo(line), span.to);
- if (side == 1) { return to }
- }
- }
- return from && {from: from, to: to}
- };
- // Signals that the marker's widget changed, and surrounding layout
- // should be recomputed.
- TextMarker.prototype.changed = function () {
- var this$1 = this;
- var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
- if (!pos || !cm) { return }
- runInOp(cm, function () {
- var line = pos.line, lineN = lineNo(pos.line);
- var view = findViewForLine(cm, lineN);
- if (view) {
- clearLineMeasurementCacheFor(view);
- cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
- }
- cm.curOp.updateMaxLine = true;
- if (!lineIsHidden(widget.doc, line) && widget.height != null) {
- var oldHeight = widget.height;
- widget.height = null;
- var dHeight = widgetHeight(widget) - oldHeight;
- if (dHeight)
- { updateLineHeight(line, line.height + dHeight); }
- }
- signalLater(cm, "markerChanged", cm, this$1);
- });
- };
- TextMarker.prototype.attachLine = function (line) {
- if (!this.lines.length && this.doc.cm) {
- var op = this.doc.cm.curOp;
- if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
- { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
- }
- this.lines.push(line);
- };
- TextMarker.prototype.detachLine = function (line) {
- this.lines.splice(indexOf(this.lines, line), 1);
- if (!this.lines.length && this.doc.cm) {
- var op = this.doc.cm.curOp
- ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
- }
- };
- eventMixin(TextMarker);
- // Create a marker, wire it up to the right lines, and
- function markText(doc, from, to, options, type) {
- // Shared markers (across linked documents) are handled separately
- // (markTextShared will call out to this again, once per
- // document).
- if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
- // Ensure we are in an operation.
- if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
- var marker = new TextMarker(doc, type), diff = cmp(from, to);
- if (options) { copyObj(options, marker, false); }
- // Don't connect empty markers unless clearWhenEmpty is false
- if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
- { return marker }
- if (marker.replacedWith) {
- // Showing up as a widget implies collapsed (widget replaces text)
- marker.collapsed = true;
- marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
- if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
- if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
- }
- if (marker.collapsed) {
- if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
- from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
- { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
- seeCollapsedSpans();
- }
- if (marker.addToHistory)
- { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
- var curLine = from.line, cm = doc.cm, updateMaxLine;
- doc.iter(curLine, to.line + 1, function (line) {
- if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
- { updateMaxLine = true; }
- if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
- addMarkedSpan(line, new MarkedSpan(marker,
- curLine == from.line ? from.ch : null,
- curLine == to.line ? to.ch : null));
- ++curLine;
- });
- // lineIsHidden depends on the presence of the spans, so needs a second pass
- if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
- if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
- }); }
- if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
- if (marker.readOnly) {
- seeReadOnlySpans();
- if (doc.history.done.length || doc.history.undone.length)
- { doc.clearHistory(); }
- }
- if (marker.collapsed) {
- marker.id = ++nextMarkerId;
- marker.atomic = true;
- }
- if (cm) {
- // Sync editor state
- if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
- if (marker.collapsed)
- { regChange(cm, from.line, to.line + 1); }
- else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
- marker.attributes || marker.title)
- { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
- if (marker.atomic) { reCheckSelection(cm.doc); }
- signalLater(cm, "markerAdded", cm, marker);
- }
- return marker
- }
- // SHARED TEXTMARKERS
- // A shared marker spans multiple linked documents. It is
- // implemented as a meta-marker-object controlling multiple normal
- // markers.
- var SharedTextMarker = function(markers, primary) {
- var this$1 = this;
- this.markers = markers;
- this.primary = primary;
- for (var i = 0; i < markers.length; ++i)
- { markers[i].parent = this$1; }
- };
- SharedTextMarker.prototype.clear = function () {
- var this$1 = this;
- if (this.explicitlyCleared) { return }
- this.explicitlyCleared = true;
- for (var i = 0; i < this.markers.length; ++i)
- { this$1.markers[i].clear(); }
- signalLater(this, "clear");
- };
- SharedTextMarker.prototype.find = function (side, lineObj) {
- return this.primary.find(side, lineObj)
- };
- eventMixin(SharedTextMarker);
- function markTextShared(doc, from, to, options, type) {
- options = copyObj(options);
- options.shared = false;
- var markers = [markText(doc, from, to, options, type)], primary = markers[0];
- var widget = options.widgetNode;
- linkedDocs(doc, function (doc) {
- if (widget) { options.widgetNode = widget.cloneNode(true); }
- markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
- for (var i = 0; i < doc.linked.length; ++i)
- { if (doc.linked[i].isParent) { return } }
- primary = lst(markers);
- });
- return new SharedTextMarker(markers, primary)
- }
- function findSharedMarkers(doc) {
- return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
- }
- function copySharedMarkers(doc, markers) {
- for (var i = 0; i < markers.length; i++) {
- var marker = markers[i], pos = marker.find();
- var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
- if (cmp(mFrom, mTo)) {
- var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
- marker.markers.push(subMark);
- subMark.parent = marker;
- }
- }
- }
- function detachSharedMarkers(markers) {
- var loop = function ( i ) {
- var marker = markers[i], linked = [marker.primary.doc];
- linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
- for (var j = 0; j < marker.markers.length; j++) {
- var subMarker = marker.markers[j];
- if (indexOf(linked, subMarker.doc) == -1) {
- subMarker.parent = null;
- marker.markers.splice(j--, 1);
- }
- }
- };
- for (var i = 0; i < markers.length; i++) loop( i );
- }
- var nextDocId = 0;
- var Doc = function(text, mode, firstLine, lineSep, direction) {
- if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
- if (firstLine == null) { firstLine = 0; }
- BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
- this.first = firstLine;
- this.scrollTop = this.scrollLeft = 0;
- this.cantEdit = false;
- this.cleanGeneration = 1;
- this.modeFrontier = this.highlightFrontier = firstLine;
- var start = Pos(firstLine, 0);
- this.sel = simpleSelection(start);
- this.history = new History(null);
- this.id = ++nextDocId;
- this.modeOption = mode;
- this.lineSep = lineSep;
- this.direction = (direction == "rtl") ? "rtl" : "ltr";
- this.extend = false;
- if (typeof text == "string") { text = this.splitLines(text); }
- updateDoc(this, {from: start, to: start, text: text});
- setSelection(this, simpleSelection(start), sel_dontScroll);
- };
- Doc.prototype = createObj(BranchChunk.prototype, {
- constructor: Doc,
- // Iterate over the document. Supports two forms -- with only one
- // argument, it calls that for each line in the document. With
- // three, it iterates over the range given by the first two (with
- // the second being non-inclusive).
- iter: function(from, to, op) {
- if (op) { this.iterN(from - this.first, to - from, op); }
- else { this.iterN(this.first, this.first + this.size, from); }
- },
- // Non-public interface for adding and removing lines.
- insert: function(at, lines) {
- var height = 0;
- for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
- this.insertInner(at - this.first, lines, height);
- },
- remove: function(at, n) { this.removeInner(at - this.first, n); },
- // From here, the methods are part of the public interface. Most
- // are also available from CodeMirror (editor) instances.
- getValue: function(lineSep) {
- var lines = getLines(this, this.first, this.first + this.size);
- if (lineSep === false) { return lines }
- return lines.join(lineSep || this.lineSeparator())
- },
- setValue: docMethodOp(function(code) {
- var top = Pos(this.first, 0), last = this.first + this.size - 1;
- makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
- text: this.splitLines(code), origin: "setValue", full: true}, true);
- if (this.cm) { scrollToCoords(this.cm, 0, 0); }
- setSelection(this, simpleSelection(top), sel_dontScroll);
- }),
- replaceRange: function(code, from, to, origin) {
- from = clipPos(this, from);
- to = to ? clipPos(this, to) : from;
- replaceRange(this, code, from, to, origin);
- },
- getRange: function(from, to, lineSep) {
- var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
- if (lineSep === false) { return lines }
- return lines.join(lineSep || this.lineSeparator())
- },
- getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
- getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
- getLineNumber: function(line) {return lineNo(line)},
- getLineHandleVisualStart: function(line) {
- if (typeof line == "number") { line = getLine(this, line); }
- return visualLine(line)
- },
- lineCount: function() {return this.size},
- firstLine: function() {return this.first},
- lastLine: function() {return this.first + this.size - 1},
- clipPos: function(pos) {return clipPos(this, pos)},
- getCursor: function(start) {
- var range$$1 = this.sel.primary(), pos;
- if (start == null || start == "head") { pos = range$$1.head; }
- else if (start == "anchor") { pos = range$$1.anchor; }
- else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
- else { pos = range$$1.from(); }
- return pos
- },
- listSelections: function() { return this.sel.ranges },
- somethingSelected: function() {return this.sel.somethingSelected()},
- setCursor: docMethodOp(function(line, ch, options) {
- setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
- }),
- setSelection: docMethodOp(function(anchor, head, options) {
- setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
- }),
- extendSelection: docMethodOp(function(head, other, options) {
- extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
- }),
- extendSelections: docMethodOp(function(heads, options) {
- extendSelections(this, clipPosArray(this, heads), options);
- }),
- extendSelectionsBy: docMethodOp(function(f, options) {
- var heads = map(this.sel.ranges, f);
- extendSelections(this, clipPosArray(this, heads), options);
- }),
- setSelections: docMethodOp(function(ranges, primary, options) {
- var this$1 = this;
- if (!ranges.length) { return }
- var out = [];
- for (var i = 0; i < ranges.length; i++)
- { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
- clipPos(this$1, ranges[i].head)); }
- if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
- setSelection(this, normalizeSelection(this.cm, out, primary), options);
- }),
- addSelection: docMethodOp(function(anchor, head, options) {
- var ranges = this.sel.ranges.slice(0);
- ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
- setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
- }),
- getSelection: function(lineSep) {
- var this$1 = this;
- var ranges = this.sel.ranges, lines;
- for (var i = 0; i < ranges.length; i++) {
- var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
- lines = lines ? lines.concat(sel) : sel;
- }
- if (lineSep === false) { return lines }
- else { return lines.join(lineSep || this.lineSeparator()) }
- },
- getSelections: function(lineSep) {
- var this$1 = this;
- var parts = [], ranges = this.sel.ranges;
- for (var i = 0; i < ranges.length; i++) {
- var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
- if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
- parts[i] = sel;
- }
- return parts
- },
- replaceSelection: function(code, collapse, origin) {
- var dup = [];
- for (var i = 0; i < this.sel.ranges.length; i++)
- { dup[i] = code; }
- this.replaceSelections(dup, collapse, origin || "+input");
- },
- replaceSelections: docMethodOp(function(code, collapse, origin) {
- var this$1 = this;
- var changes = [], sel = this.sel;
- for (var i = 0; i < sel.ranges.length; i++) {
- var range$$1 = sel.ranges[i];
- changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
- }
- var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
- for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
- { makeChange(this$1, changes[i$1]); }
- if (newSel) { setSelectionReplaceHistory(this, newSel); }
- else if (this.cm) { ensureCursorVisible(this.cm); }
- }),
- undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
- redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
- undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
- redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
- setExtending: function(val) {this.extend = val;},
- getExtending: function() {return this.extend},
- historySize: function() {
- var hist = this.history, done = 0, undone = 0;
- for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
- for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
- return {undo: done, redo: undone}
- },
- clearHistory: function() {this.history = new History(this.history.maxGeneration);},
- markClean: function() {
- this.cleanGeneration = this.changeGeneration(true);
- },
- changeGeneration: function(forceSplit) {
- if (forceSplit)
- { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
- return this.history.generation
- },
- isClean: function (gen) {
- return this.history.generation == (gen || this.cleanGeneration)
- },
- getHistory: function() {
- return {done: copyHistoryArray(this.history.done),
- undone: copyHistoryArray(this.history.undone)}
- },
- setHistory: function(histData) {
- var hist = this.history = new History(this.history.maxGeneration);
- hist.done = copyHistoryArray(histData.done.slice(0), null, true);
- hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
- },
- setGutterMarker: docMethodOp(function(line, gutterID, value) {
- return changeLine(this, line, "gutter", function (line) {
- var markers = line.gutterMarkers || (line.gutterMarkers = {});
- markers[gutterID] = value;
- if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
- return true
- })
- }),
- clearGutter: docMethodOp(function(gutterID) {
- var this$1 = this;
- this.iter(function (line) {
- if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
- changeLine(this$1, line, "gutter", function () {
- line.gutterMarkers[gutterID] = null;
- if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
- return true
- });
- }
- });
- }),
- lineInfo: function(line) {
- var n;
- if (typeof line == "number") {
- if (!isLine(this, line)) { return null }
- n = line;
- line = getLine(this, line);
- if (!line) { return null }
- } else {
- n = lineNo(line);
- if (n == null) { return null }
- }
- return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
- textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
- widgets: line.widgets}
- },
- addLineClass: docMethodOp(function(handle, where, cls) {
- return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
- var prop = where == "text" ? "textClass"
- : where == "background" ? "bgClass"
- : where == "gutter" ? "gutterClass" : "wrapClass";
- if (!line[prop]) { line[prop] = cls; }
- else if (classTest(cls).test(line[prop])) { return false }
- else { line[prop] += " " + cls; }
- return true
- })
- }),
- removeLineClass: docMethodOp(function(handle, where, cls) {
- return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
- var prop = where == "text" ? "textClass"
- : where == "background" ? "bgClass"
- : where == "gutter" ? "gutterClass" : "wrapClass";
- var cur = line[prop];
- if (!cur) { return false }
- else if (cls == null) { line[prop] = null; }
- else {
- var found = cur.match(classTest(cls));
- if (!found) { return false }
- var end = found.index + found[0].length;
- line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
- }
- return true
- })
- }),
- addLineWidget: docMethodOp(function(handle, node, options) {
- return addLineWidget(this, handle, node, options)
- }),
- removeLineWidget: function(widget) { widget.clear(); },
- markText: function(from, to, options) {
- return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
- },
- setBookmark: function(pos, options) {
- var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
- insertLeft: options && options.insertLeft,
- clearWhenEmpty: false, shared: options && options.shared,
- handleMouseEvents: options && options.handleMouseEvents};
- pos = clipPos(this, pos);
- return markText(this, pos, pos, realOpts, "bookmark")
- },
- findMarksAt: function(pos) {
- pos = clipPos(this, pos);
- var markers = [], spans = getLine(this, pos.line).markedSpans;
- if (spans) { for (var i = 0; i < spans.length; ++i) {
- var span = spans[i];
- if ((span.from == null || span.from <= pos.ch) &&
- (span.to == null || span.to >= pos.ch))
- { markers.push(span.marker.parent || span.marker); }
- } }
- return markers
- },
- findMarks: function(from, to, filter) {
- from = clipPos(this, from); to = clipPos(this, to);
- var found = [], lineNo$$1 = from.line;
- this.iter(from.line, to.line + 1, function (line) {
- var spans = line.markedSpans;
- if (spans) { for (var i = 0; i < spans.length; i++) {
- var span = spans[i];
- if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
- span.from == null && lineNo$$1 != from.line ||
- span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
- (!filter || filter(span.marker)))
- { found.push(span.marker.parent || span.marker); }
- } }
- ++lineNo$$1;
- });
- return found
- },
- getAllMarks: function() {
- var markers = [];
- this.iter(function (line) {
- var sps = line.markedSpans;
- if (sps) { for (var i = 0; i < sps.length; ++i)
- { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
- });
- return markers
- },
- posFromIndex: function(off) {
- var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
- this.iter(function (line) {
- var sz = line.text.length + sepSize;
- if (sz > off) { ch = off; return true }
- off -= sz;
- ++lineNo$$1;
- });
- return clipPos(this, Pos(lineNo$$1, ch))
- },
- indexFromPos: function (coords) {
- coords = clipPos(this, coords);
- var index = coords.ch;
- if (coords.line < this.first || coords.ch < 0) { return 0 }
- var sepSize = this.lineSeparator().length;
- this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
- index += line.text.length + sepSize;
- });
- return index
- },
- copy: function(copyHistory) {
- var doc = new Doc(getLines(this, this.first, this.first + this.size),
- this.modeOption, this.first, this.lineSep, this.direction);
- doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
- doc.sel = this.sel;
- doc.extend = false;
- if (copyHistory) {
- doc.history.undoDepth = this.history.undoDepth;
- doc.setHistory(this.getHistory());
- }
- return doc
- },
- linkedDoc: function(options) {
- if (!options) { options = {}; }
- var from = this.first, to = this.first + this.size;
- if (options.from != null && options.from > from) { from = options.from; }
- if (options.to != null && options.to < to) { to = options.to; }
- var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
- if (options.sharedHist) { copy.history = this.history
- ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
- copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
- copySharedMarkers(copy, findSharedMarkers(this));
- return copy
- },
- unlinkDoc: function(other) {
- var this$1 = this;
- if (other instanceof CodeMirror) { other = other.doc; }
- if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
- var link = this$1.linked[i];
- if (link.doc != other) { continue }
- this$1.linked.splice(i, 1);
- other.unlinkDoc(this$1);
- detachSharedMarkers(findSharedMarkers(this$1));
- break
- } }
- // If the histories were shared, split them again
- if (other.history == this.history) {
- var splitIds = [other.id];
- linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
- other.history = new History(null);
- other.history.done = copyHistoryArray(this.history.done, splitIds);
- other.history.undone = copyHistoryArray(this.history.undone, splitIds);
- }
- },
- iterLinkedDocs: function(f) {linkedDocs(this, f);},
- getMode: function() {return this.mode},
- getEditor: function() {return this.cm},
- splitLines: function(str) {
- if (this.lineSep) { return str.split(this.lineSep) }
- return splitLinesAuto(str)
- },
- lineSeparator: function() { return this.lineSep || "\n" },
- setDirection: docMethodOp(function (dir) {
- if (dir != "rtl") { dir = "ltr"; }
- if (dir == this.direction) { return }
- this.direction = dir;
- this.iter(function (line) { return line.order = null; });
- if (this.cm) { directionChanged(this.cm); }
- })
- });
- // Public alias.
- Doc.prototype.eachLine = Doc.prototype.iter;
- // Kludge to work around strange IE behavior where it'll sometimes
- // re-fire a series of drag-related events right after the drop (#1551)
- var lastDrop = 0;
- function onDrop(e) {
- var cm = this;
- clearDragCursor(cm);
- if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
- { return }
- e_preventDefault(e);
- if (ie) { lastDrop = +new Date; }
- var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
- if (!pos || cm.isReadOnly()) { return }
- // Might be a file drop, in which case we simply extract the text
- // and insert it.
- if (files && files.length && window.FileReader && window.File) {
- var n = files.length, text = Array(n), read = 0;
- var loadFile = function (file, i) {
- if (cm.options.allowDropFileTypes &&
- indexOf(cm.options.allowDropFileTypes, file.type) == -1)
- { return }
- var reader = new FileReader;
- reader.onload = operation(cm, function () {
- var content = reader.result;
- if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
- text[i] = content;
- if (++read == n) {
- pos = clipPos(cm.doc, pos);
- var change = {from: pos, to: pos,
- text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
- origin: "paste"};
- makeChange(cm.doc, change);
- setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
- }
- });
- reader.readAsText(file);
- };
- for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
- } else { // Normal drop
- // Don't do a replace if the drop happened inside of the selected text.
- if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
- cm.state.draggingText(e);
- // Ensure the editor is re-focused
- setTimeout(function () { return cm.display.input.focus(); }, 20);
- return
- }
- try {
- var text$1 = e.dataTransfer.getData("Text");
- if (text$1) {
- var selected;
- if (cm.state.draggingText && !cm.state.draggingText.copy)
- { selected = cm.listSelections(); }
- setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
- if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
- { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
- cm.replaceSelection(text$1, "around", "paste");
- cm.display.input.focus();
- }
- }
- catch(e){}
- }
- }
- function onDragStart(cm, e) {
- if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
- if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
- e.dataTransfer.setData("Text", cm.getSelection());
- e.dataTransfer.effectAllowed = "copyMove";
- // Use dummy image instead of default browsers image.
- // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
- if (e.dataTransfer.setDragImage && !safari) {
- var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
- img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
- if (presto) {
- img.width = img.height = 1;
- cm.display.wrapper.appendChild(img);
- // Force a relayout, or Opera won't use our image for some obscure reason
- img._top = img.offsetTop;
- }
- e.dataTransfer.setDragImage(img, 0, 0);
- if (presto) { img.parentNode.removeChild(img); }
- }
- }
- function onDragOver(cm, e) {
- var pos = posFromMouse(cm, e);
- if (!pos) { return }
- var frag = document.createDocumentFragment();
- drawSelectionCursor(cm, pos, frag);
- if (!cm.display.dragCursor) {
- cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
- cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
- }
- removeChildrenAndAdd(cm.display.dragCursor, frag);
- }
- function clearDragCursor(cm) {
- if (cm.display.dragCursor) {
- cm.display.lineSpace.removeChild(cm.display.dragCursor);
- cm.display.dragCursor = null;
- }
- }
- // These must be handled carefully, because naively registering a
- // handler for each editor will cause the editors to never be
- // garbage collected.
- function forEachCodeMirror(f) {
- if (!document.getElementsByClassName) { return }
- var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
- for (var i = 0; i < byClass.length; i++) {
- var cm = byClass[i].CodeMirror;
- if (cm) { editors.push(cm); }
- }
- if (editors.length) { editors[0].operation(function () {
- for (var i = 0; i < editors.length; i++) { f(editors[i]); }
- }); }
- }
- var globalsRegistered = false;
- function ensureGlobalHandlers() {
- if (globalsRegistered) { return }
- registerGlobalHandlers();
- globalsRegistered = true;
- }
- function registerGlobalHandlers() {
- // When the window resizes, we need to refresh active editors.
- var resizeTimer;
- on(window, "resize", function () {
- if (resizeTimer == null) { resizeTimer = setTimeout(function () {
- resizeTimer = null;
- forEachCodeMirror(onResize);
- }, 100); }
- });
- // When the window loses focus, we want to show the editor as blurred
- on(window, "blur", function () { return forEachCodeMirror(onBlur); });
- }
- // Called when the window resizes
- function onResize(cm) {
- var d = cm.display;
- // Might be a text scaling operation, clear size caches.
- d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
- d.scrollbarsClipped = false;
- cm.setSize();
- }
- var keyNames = {
- 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
- 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
- 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
- 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
- 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
- 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
- 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
- 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
- };
- // Number keys
- for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
- // Alphabetic keys
- for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
- // Function keys
- for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
- var keyMap = {};
- keyMap.basic = {
- "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
- "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
- "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
- "Tab": "defaultTab", "Shift-Tab": "indentAuto",
- "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
- "Esc": "singleSelection"
- };
- // Note that the save and find-related commands aren't defined by
- // default. User code or addons can define them. Unknown commands
- // are simply ignored.
- keyMap.pcDefault = {
- "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
- "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
- "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
- "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
- "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
- "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
- "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
- "fallthrough": "basic"
- };
- // Very basic readline/emacs-style bindings, which are standard on Mac.
- keyMap.emacsy = {
- "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
- "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
- "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
- "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
- "Ctrl-O": "openLine"
- };
- keyMap.macDefault = {
- "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
- "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
- "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
- "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
- "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
- "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
- "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
- "fallthrough": ["basic", "emacsy"]
- };
- keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
- // KEYMAP DISPATCH
- function normalizeKeyName(name) {
- var parts = name.split(/-(?!$)/);
- name = parts[parts.length - 1];
- var alt, ctrl, shift, cmd;
- for (var i = 0; i < parts.length - 1; i++) {
- var mod = parts[i];
- if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
- else if (/^a(lt)?$/i.test(mod)) { alt = true; }
- else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
- else if (/^s(hift)?$/i.test(mod)) { shift = true; }
- else { throw new Error("Unrecognized modifier name: " + mod) }
- }
- if (alt) { name = "Alt-" + name; }
- if (ctrl) { name = "Ctrl-" + name; }
- if (cmd) { name = "Cmd-" + name; }
- if (shift) { name = "Shift-" + name; }
- return name
- }
- // This is a kludge to keep keymaps mostly working as raw objects
- // (backwards compatibility) while at the same time support features
- // like normalization and multi-stroke key bindings. It compiles a
- // new normalized keymap, and then updates the old object to reflect
- // this.
- function normalizeKeyMap(keymap) {
- var copy = {};
- for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
- var value = keymap[keyname];
- if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
- if (value == "...") { delete keymap[keyname]; continue }
- var keys = map(keyname.split(" "), normalizeKeyName);
- for (var i = 0; i < keys.length; i++) {
- var val = (void 0), name = (void 0);
- if (i == keys.length - 1) {
- name = keys.join(" ");
- val = value;
- } else {
- name = keys.slice(0, i + 1).join(" ");
- val = "...";
- }
- var prev = copy[name];
- if (!prev) { copy[name] = val; }
- else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
- }
- delete keymap[keyname];
- } }
- for (var prop in copy) { keymap[prop] = copy[prop]; }
- return keymap
- }
- function lookupKey(key, map$$1, handle, context) {
- map$$1 = getKeyMap(map$$1);
- var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
- if (found === false) { return "nothing" }
- if (found === "...") { return "multi" }
- if (found != null && handle(found)) { return "handled" }
- if (map$$1.fallthrough) {
- if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
- { return lookupKey(key, map$$1.fallthrough, handle, context) }
- for (var i = 0; i < map$$1.fallthrough.length; i++) {
- var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
- if (result) { return result }
- }
- }
- }
- // Modifier key presses don't count as 'real' key presses for the
- // purpose of keymap fallthrough.
- function isModifierKey(value) {
- var name = typeof value == "string" ? value : keyNames[value.keyCode];
- return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
- }
- function addModifierNames(name, event, noShift) {
- var base = name;
- if (event.altKey && base != "Alt") { name = "Alt-" + name; }
- if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
- if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
- if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
- return name
- }
- // Look up the name of a key as indicated by an event object.
- function keyName(event, noShift) {
- if (presto && event.keyCode == 34 && event["char"]) { return false }
- var name = keyNames[event.keyCode];
- if (name == null || event.altGraphKey) { return false }
- // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
- // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
- if (event.keyCode == 3 && event.code) { name = event.code; }
- return addModifierNames(name, event, noShift)
- }
- function getKeyMap(val) {
- return typeof val == "string" ? keyMap[val] : val
- }
- // Helper for deleting text near the selection(s), used to implement
- // backspace, delete, and similar functionality.
- function deleteNearSelection(cm, compute) {
- var ranges = cm.doc.sel.ranges, kill = [];
- // Build up a set of ranges to kill first, merging overlapping
- // ranges.
- for (var i = 0; i < ranges.length; i++) {
- var toKill = compute(ranges[i]);
- while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
- var replaced = kill.pop();
- if (cmp(replaced.from, toKill.from) < 0) {
- toKill.from = replaced.from;
- break
- }
- }
- kill.push(toKill);
- }
- // Next, remove those actual ranges.
- runInOp(cm, function () {
- for (var i = kill.length - 1; i >= 0; i--)
- { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
- ensureCursorVisible(cm);
- });
- }
- function moveCharLogically(line, ch, dir) {
- var target = skipExtendingChars(line.text, ch + dir, dir);
- return target < 0 || target > line.text.length ? null : target
- }
- function moveLogically(line, start, dir) {
- var ch = moveCharLogically(line, start.ch, dir);
- return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
- }
- function endOfLine(visually, cm, lineObj, lineNo, dir) {
- if (visually) {
- var order = getOrder(lineObj, cm.doc.direction);
- if (order) {
- var part = dir < 0 ? lst(order) : order[0];
- var moveInStorageOrder = (dir < 0) == (part.level == 1);
- var sticky = moveInStorageOrder ? "after" : "before";
- var ch;
- // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
- // it could be that the last bidi part is not on the last visual line,
- // since visual lines contain content order-consecutive chunks.
- // Thus, in rtl, we are looking for the first (content-order) character
- // in the rtl chunk that is on the last line (that is, the same line
- // as the last (content-order) character).
- if (part.level > 0 || cm.doc.direction == "rtl") {
- var prep = prepareMeasureForLine(cm, lineObj);
- ch = dir < 0 ? lineObj.text.length - 1 : 0;
- var targetTop = measureCharPrepared(cm, prep, ch).top;
- ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
- if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
- } else { ch = dir < 0 ? part.to : part.from; }
- return new Pos(lineNo, ch, sticky)
- }
- }
- return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
- }
- function moveVisually(cm, line, start, dir) {
- var bidi = getOrder(line, cm.doc.direction);
- if (!bidi) { return moveLogically(line, start, dir) }
- if (start.ch >= line.text.length) {
- start.ch = line.text.length;
- start.sticky = "before";
- } else if (start.ch <= 0) {
- start.ch = 0;
- start.sticky = "after";
- }
- var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
- if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
- // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
- // nothing interesting happens.
- return moveLogically(line, start, dir)
- }
- var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
- var prep;
- var getWrappedLineExtent = function (ch) {
- if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
- prep = prep || prepareMeasureForLine(cm, line);
- return wrappedLineExtentChar(cm, line, prep, ch)
- };
- var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
- if (cm.doc.direction == "rtl" || part.level == 1) {
- var moveInStorageOrder = (part.level == 1) == (dir < 0);
- var ch = mv(start, moveInStorageOrder ? 1 : -1);
- if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
- // Case 2: We move within an rtl part or in an rtl editor on the same visual line
- var sticky = moveInStorageOrder ? "before" : "after";
- return new Pos(start.line, ch, sticky)
- }
- }
- // Case 3: Could not move within this bidi part in this visual line, so leave
- // the current bidi part
- var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
- var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
- ? new Pos(start.line, mv(ch, 1), "before")
- : new Pos(start.line, ch, "after"); };
- for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
- var part = bidi[partPos];
- var moveInStorageOrder = (dir > 0) == (part.level != 1);
- var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
- if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
- ch = moveInStorageOrder ? part.from : mv(part.to, -1);
- if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
- }
- };
- // Case 3a: Look for other bidi parts on the same visual line
- var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
- if (res) { return res }
- // Case 3b: Look for other bidi parts on the next visual line
- var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
- if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
- res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
- if (res) { return res }
- }
- // Case 4: Nowhere to move
- return null
- }
- // Commands are parameter-less actions that can be performed on an
- // editor, mostly used for keybindings.
- var commands = {
- selectAll: selectAll,
- singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
- killLine: function (cm) { return deleteNearSelection(cm, function (range) {
- if (range.empty()) {
- var len = getLine(cm.doc, range.head.line).text.length;
- if (range.head.ch == len && range.head.line < cm.lastLine())
- { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
- else
- { return {from: range.head, to: Pos(range.head.line, len)} }
- } else {
- return {from: range.from(), to: range.to()}
- }
- }); },
- deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
- from: Pos(range.from().line, 0),
- to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
- }); }); },
- delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
- from: Pos(range.from().line, 0), to: range.from()
- }); }); },
- delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
- var top = cm.charCoords(range.head, "div").top + 5;
- var leftPos = cm.coordsChar({left: 0, top: top}, "div");
- return {from: leftPos, to: range.from()}
- }); },
- delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
- var top = cm.charCoords(range.head, "div").top + 5;
- var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
- return {from: range.from(), to: rightPos }
- }); },
- undo: function (cm) { return cm.undo(); },
- redo: function (cm) { return cm.redo(); },
- undoSelection: function (cm) { return cm.undoSelection(); },
- redoSelection: function (cm) { return cm.redoSelection(); },
- goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
- goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
- goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
- {origin: "+move", bias: 1}
- ); },
- goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
- {origin: "+move", bias: 1}
- ); },
- goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
- {origin: "+move", bias: -1}
- ); },
- goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
- var top = cm.cursorCoords(range.head, "div").top + 5;
- return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
- }, sel_move); },
- goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
- var top = cm.cursorCoords(range.head, "div").top + 5;
- return cm.coordsChar({left: 0, top: top}, "div")
- }, sel_move); },
- goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
- var top = cm.cursorCoords(range.head, "div").top + 5;
- var pos = cm.coordsChar({left: 0, top: top}, "div");
- if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
- return pos
- }, sel_move); },
- goLineUp: function (cm) { return cm.moveV(-1, "line"); },
- goLineDown: function (cm) { return cm.moveV(1, "line"); },
- goPageUp: function (cm) { return cm.moveV(-1, "page"); },
- goPageDown: function (cm) { return cm.moveV(1, "page"); },
- goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
- goCharRight: function (cm) { return cm.moveH(1, "char"); },
- goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
- goColumnRight: function (cm) { return cm.moveH(1, "column"); },
- goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
- goGroupRight: function (cm) { return cm.moveH(1, "group"); },
- goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
- goWordRight: function (cm) { return cm.moveH(1, "word"); },
- delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
- delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
- delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
- delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
- delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
- delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
- indentAuto: function (cm) { return cm.indentSelection("smart"); },
- indentMore: function (cm) { return cm.indentSelection("add"); },
- indentLess: function (cm) { return cm.indentSelection("subtract"); },
- insertTab: function (cm) { return cm.replaceSelection("\t"); },
- insertSoftTab: function (cm) {
- var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
- for (var i = 0; i < ranges.length; i++) {
- var pos = ranges[i].from();
- var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
- spaces.push(spaceStr(tabSize - col % tabSize));
- }
- cm.replaceSelections(spaces);
- },
- defaultTab: function (cm) {
- if (cm.somethingSelected()) { cm.indentSelection("add"); }
- else { cm.execCommand("insertTab"); }
- },
- // Swap the two chars left and right of each selection's head.
- // Move cursor behind the two swapped characters afterwards.
- //
- // Doesn't consider line feeds a character.
- // Doesn't scan more than one line above to find a character.
- // Doesn't do anything on an empty line.
- // Doesn't do anything with non-empty selections.
- transposeChars: function (cm) { return runInOp(cm, function () {
- var ranges = cm.listSelections(), newSel = [];
- for (var i = 0; i < ranges.length; i++) {
- if (!ranges[i].empty()) { continue }
- var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
- if (line) {
- if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
- if (cur.ch > 0) {
- cur = new Pos(cur.line, cur.ch + 1);
- cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
- Pos(cur.line, cur.ch - 2), cur, "+transpose");
- } else if (cur.line > cm.doc.first) {
- var prev = getLine(cm.doc, cur.line - 1).text;
- if (prev) {
- cur = new Pos(cur.line, 1);
- cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
- prev.charAt(prev.length - 1),
- Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
- }
- }
- }
- newSel.push(new Range(cur, cur));
- }
- cm.setSelections(newSel);
- }); },
- newlineAndIndent: function (cm) { return runInOp(cm, function () {
- var sels = cm.listSelections();
- for (var i = sels.length - 1; i >= 0; i--)
- { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
- sels = cm.listSelections();
- for (var i$1 = 0; i$1 < sels.length; i$1++)
- { cm.indentLine(sels[i$1].from().line, null, true); }
- ensureCursorVisible(cm);
- }); },
- openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
- toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
- };
- function lineStart(cm, lineN) {
- var line = getLine(cm.doc, lineN);
- var visual = visualLine(line);
- if (visual != line) { lineN = lineNo(visual); }
- return endOfLine(true, cm, visual, lineN, 1)
- }
- function lineEnd(cm, lineN) {
- var line = getLine(cm.doc, lineN);
- var visual = visualLineEnd(line);
- if (visual != line) { lineN = lineNo(visual); }
- return endOfLine(true, cm, line, lineN, -1)
- }
- function lineStartSmart(cm, pos) {
- var start = lineStart(cm, pos.line);
- var line = getLine(cm.doc, start.line);
- var order = getOrder(line, cm.doc.direction);
- if (!order || order[0].level == 0) {
- var firstNonWS = Math.max(0, line.text.search(/\S/));
- var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
- return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
- }
- return start
- }
- // Run a handler that was bound to a key.
- function doHandleBinding(cm, bound, dropShift) {
- if (typeof bound == "string") {
- bound = commands[bound];
- if (!bound) { return false }
- }
- // Ensure previous input has been read, so that the handler sees a
- // consistent view of the document
- cm.display.input.ensurePolled();
- var prevShift = cm.display.shift, done = false;
- try {
- if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
- if (dropShift) { cm.display.shift = false; }
- done = bound(cm) != Pass;
- } finally {
- cm.display.shift = prevShift;
- cm.state.suppressEdits = false;
- }
- return done
- }
- function lookupKeyForEditor(cm, name, handle) {
- for (var i = 0; i < cm.state.keyMaps.length; i++) {
- var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
- if (result) { return result }
- }
- return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
- || lookupKey(name, cm.options.keyMap, handle, cm)
- }
- // Note that, despite the name, this function is also used to check
- // for bound mouse clicks.
- var stopSeq = new Delayed;
- function dispatchKey(cm, name, e, handle) {
- var seq = cm.state.keySeq;
- if (seq) {
- if (isModifierKey(name)) { return "handled" }
- if (/\'$/.test(name))
- { cm.state.keySeq = null; }
- else
- { stopSeq.set(50, function () {
- if (cm.state.keySeq == seq) {
- cm.state.keySeq = null;
- cm.display.input.reset();
- }
- }); }
- if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
- }
- return dispatchKeyInner(cm, name, e, handle)
- }
- function dispatchKeyInner(cm, name, e, handle) {
- var result = lookupKeyForEditor(cm, name, handle);
- if (result == "multi")
- { cm.state.keySeq = name; }
- if (result == "handled")
- { signalLater(cm, "keyHandled", cm, name, e); }
- if (result == "handled" || result == "multi") {
- e_preventDefault(e);
- restartBlink(cm);
- }
- return !!result
- }
- // Handle a key from the keydown event.
- function handleKeyBinding(cm, e) {
- var name = keyName(e, true);
- if (!name) { return false }
- if (e.shiftKey && !cm.state.keySeq) {
- // First try to resolve full name (including 'Shift-'). Failing
- // that, see if there is a cursor-motion command (starting with
- // 'go') bound to the keyname without 'Shift-'.
- return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
- || dispatchKey(cm, name, e, function (b) {
- if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
- { return doHandleBinding(cm, b) }
- })
- } else {
- return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
- }
- }
- // Handle a key from the keypress event
- function handleCharBinding(cm, e, ch) {
- return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
- }
- var lastStoppedKey = null;
- function onKeyDown(e) {
- var cm = this;
- cm.curOp.focus = activeElt();
- if (signalDOMEvent(cm, e)) { return }
- // IE does strange things with escape.
- if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
- var code = e.keyCode;
- cm.display.shift = code == 16 || e.shiftKey;
- var handled = handleKeyBinding(cm, e);
- if (presto) {
- lastStoppedKey = handled ? code : null;
- // Opera has no cut event... we try to at least catch the key combo
- if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
- { cm.replaceSelection("", null, "cut"); }
- }
- // Turn mouse into crosshair when Alt is held on Mac.
- if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
- { showCrossHair(cm); }
- }
- function showCrossHair(cm) {
- var lineDiv = cm.display.lineDiv;
- addClass(lineDiv, "CodeMirror-crosshair");
- function up(e) {
- if (e.keyCode == 18 || !e.altKey) {
- rmClass(lineDiv, "CodeMirror-crosshair");
- off(document, "keyup", up);
- off(document, "mouseover", up);
- }
- }
- on(document, "keyup", up);
- on(document, "mouseover", up);
- }
- function onKeyUp(e) {
- if (e.keyCode == 16) { this.doc.sel.shift = false; }
- signalDOMEvent(this, e);
- }
- function onKeyPress(e) {
- var cm = this;
- if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
- var keyCode = e.keyCode, charCode = e.charCode;
- if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
- if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
- var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
- // Some browsers fire keypress events for backspace
- if (ch == "\x08") { return }
- if (handleCharBinding(cm, e, ch)) { return }
- cm.display.input.onKeyPress(e);
- }
- var DOUBLECLICK_DELAY = 400;
- var PastClick = function(time, pos, button) {
- this.time = time;
- this.pos = pos;
- this.button = button;
- };
- PastClick.prototype.compare = function (time, pos, button) {
- return this.time + DOUBLECLICK_DELAY > time &&
- cmp(pos, this.pos) == 0 && button == this.button
- };
- var lastClick, lastDoubleClick;
- function clickRepeat(pos, button) {
- var now = +new Date;
- if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
- lastClick = lastDoubleClick = null;
- return "triple"
- } else if (lastClick && lastClick.compare(now, pos, button)) {
- lastDoubleClick = new PastClick(now, pos, button);
- lastClick = null;
- return "double"
- } else {
- lastClick = new PastClick(now, pos, button);
- lastDoubleClick = null;
- return "single"
- }
- }
- // A mouse down can be a single click, double click, triple click,
- // start of selection drag, start of text drag, new cursor
- // (ctrl-click), rectangle drag (alt-drag), or xwin
- // middle-click-paste. Or it might be a click on something we should
- // not interfere with, such as a scrollbar or widget.
- function onMouseDown(e) {
- var cm = this, display = cm.display;
- if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
- display.input.ensurePolled();
- display.shift = e.shiftKey;
- if (eventInWidget(display, e)) {
- if (!webkit) {
- // Briefly turn off draggability, to allow widgets to do
- // normal dragging things.
- display.scroller.draggable = false;
- setTimeout(function () { return display.scroller.draggable = true; }, 100);
- }
- return
- }
- if (clickInGutter(cm, e)) { return }
- var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
- window.focus();
- // #3261: make sure, that we're not starting a second selection
- if (button == 1 && cm.state.selectingText)
- { cm.state.selectingText(e); }
- if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
- if (button == 1) {
- if (pos) { leftButtonDown(cm, pos, repeat, e); }
- else if (e_target(e) == display.scroller) { e_preventDefault(e); }
- } else if (button == 2) {
- if (pos) { extendSelection(cm.doc, pos); }
- setTimeout(function () { return display.input.focus(); }, 20);
- } else if (button == 3) {
- if (captureRightClick) { cm.display.input.onContextMenu(e); }
- else { delayBlurEvent(cm); }
- }
- }
- function handleMappedButton(cm, button, pos, repeat, event) {
- var name = "Click";
- if (repeat == "double") { name = "Double" + name; }
- else if (repeat == "triple") { name = "Triple" + name; }
- name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
- return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
- if (typeof bound == "string") { bound = commands[bound]; }
- if (!bound) { return false }
- var done = false;
- try {
- if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
- done = bound(cm, pos) != Pass;
- } finally {
- cm.state.suppressEdits = false;
- }
- return done
- })
- }
- function configureMouse(cm, repeat, event) {
- var option = cm.getOption("configureMouse");
- var value = option ? option(cm, repeat, event) : {};
- if (value.unit == null) {
- var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
- value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
- }
- if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
- if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
- if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
- return value
- }
- function leftButtonDown(cm, pos, repeat, event) {
- if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
- else { cm.curOp.focus = activeElt(); }
- var behavior = configureMouse(cm, repeat, event);
- var sel = cm.doc.sel, contained;
- if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
- repeat == "single" && (contained = sel.contains(pos)) > -1 &&
- (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
- (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
- { leftButtonStartDrag(cm, event, pos, behavior); }
- else
- { leftButtonSelect(cm, event, pos, behavior); }
- }
- // Start a text drag. When it ends, see if any dragging actually
- // happen, and treat as a click if it didn't.
- function leftButtonStartDrag(cm, event, pos, behavior) {
- var display = cm.display, moved = false;
- var dragEnd = operation(cm, function (e) {
- if (webkit) { display.scroller.draggable = false; }
- cm.state.draggingText = false;
- off(display.wrapper.ownerDocument, "mouseup", dragEnd);
- off(display.wrapper.ownerDocument, "mousemove", mouseMove);
- off(display.scroller, "dragstart", dragStart);
- off(display.scroller, "drop", dragEnd);
- if (!moved) {
- e_preventDefault(e);
- if (!behavior.addNew)
- { extendSelection(cm.doc, pos, null, null, behavior.extend); }
- // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
- if (webkit || ie && ie_version == 9)
- { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }
- else
- { display.input.focus(); }
- }
- });
- var mouseMove = function(e2) {
- moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
- };
- var dragStart = function () { return moved = true; };
- // Let the drag handler handle this.
- if (webkit) { display.scroller.draggable = true; }
- cm.state.draggingText = dragEnd;
- dragEnd.copy = !behavior.moveOnDrag;
- // IE's approach to draggable
- if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
- on(display.wrapper.ownerDocument, "mouseup", dragEnd);
- on(display.wrapper.ownerDocument, "mousemove", mouseMove);
- on(display.scroller, "dragstart", dragStart);
- on(display.scroller, "drop", dragEnd);
- delayBlurEvent(cm);
- setTimeout(function () { return display.input.focus(); }, 20);
- }
- function rangeForUnit(cm, pos, unit) {
- if (unit == "char") { return new Range(pos, pos) }
- if (unit == "word") { return cm.findWordAt(pos) }
- if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
- var result = unit(cm, pos);
- return new Range(result.from, result.to)
- }
- // Normal selection, as opposed to text dragging.
- function leftButtonSelect(cm, event, start, behavior) {
- var display = cm.display, doc = cm.doc;
- e_preventDefault(event);
- var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
- if (behavior.addNew && !behavior.extend) {
- ourIndex = doc.sel.contains(start);
- if (ourIndex > -1)
- { ourRange = ranges[ourIndex]; }
- else
- { ourRange = new Range(start, start); }
- } else {
- ourRange = doc.sel.primary();
- ourIndex = doc.sel.primIndex;
- }
- if (behavior.unit == "rectangle") {
- if (!behavior.addNew) { ourRange = new Range(start, start); }
- start = posFromMouse(cm, event, true, true);
- ourIndex = -1;
- } else {
- var range$$1 = rangeForUnit(cm, start, behavior.unit);
- if (behavior.extend)
- { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
- else
- { ourRange = range$$1; }
- }
- if (!behavior.addNew) {
- ourIndex = 0;
- setSelection(doc, new Selection([ourRange], 0), sel_mouse);
- startSel = doc.sel;
- } else if (ourIndex == -1) {
- ourIndex = ranges.length;
- setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
- {scroll: false, origin: "*mouse"});
- } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
- setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
- {scroll: false, origin: "*mouse"});
- startSel = doc.sel;
- } else {
- replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
- }
- var lastPos = start;
- function extendTo(pos) {
- if (cmp(lastPos, pos) == 0) { return }
- lastPos = pos;
- if (behavior.unit == "rectangle") {
- var ranges = [], tabSize = cm.options.tabSize;
- var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
- var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
- var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
- for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
- line <= end; line++) {
- var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
- if (left == right)
- { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
- else if (text.length > leftPos)
- { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
- }
- if (!ranges.length) { ranges.push(new Range(start, start)); }
- setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
- {origin: "*mouse", scroll: false});
- cm.scrollIntoView(pos);
- } else {
- var oldRange = ourRange;
- var range$$1 = rangeForUnit(cm, pos, behavior.unit);
- var anchor = oldRange.anchor, head;
- if (cmp(range$$1.anchor, anchor) > 0) {
- head = range$$1.head;
- anchor = minPos(oldRange.from(), range$$1.anchor);
- } else {
- head = range$$1.anchor;
- anchor = maxPos(oldRange.to(), range$$1.head);
- }
- var ranges$1 = startSel.ranges.slice(0);
- ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
- setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
- }
- }
- var editorSize = display.wrapper.getBoundingClientRect();
- // Used to ensure timeout re-tries don't fire when another extend
- // happened in the meantime (clearTimeout isn't reliable -- at
- // least on Chrome, the timeouts still happen even when cleared,
- // if the clear happens after their scheduled firing time).
- var counter = 0;
- function extend(e) {
- var curCount = ++counter;
- var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
- if (!cur) { return }
- if (cmp(cur, lastPos) != 0) {
- cm.curOp.focus = activeElt();
- extendTo(cur);
- var visible = visibleLines(display, doc);
- if (cur.line >= visible.to || cur.line < visible.from)
- { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
- } else {
- var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
- if (outside) { setTimeout(operation(cm, function () {
- if (counter != curCount) { return }
- display.scroller.scrollTop += outside;
- extend(e);
- }), 50); }
- }
- }
- function done(e) {
- cm.state.selectingText = false;
- counter = Infinity;
- // If e is null or undefined we interpret this as someone trying
- // to explicitly cancel the selection rather than the user
- // letting go of the mouse button.
- if (e) {
- e_preventDefault(e);
- display.input.focus();
- }
- off(display.wrapper.ownerDocument, "mousemove", move);
- off(display.wrapper.ownerDocument, "mouseup", up);
- doc.history.lastSelOrigin = null;
- }
- var move = operation(cm, function (e) {
- if (e.buttons === 0 || !e_button(e)) { done(e); }
- else { extend(e); }
- });
- var up = operation(cm, done);
- cm.state.selectingText = up;
- on(display.wrapper.ownerDocument, "mousemove", move);
- on(display.wrapper.ownerDocument, "mouseup", up);
- }
- // Used when mouse-selecting to adjust the anchor to the proper side
- // of a bidi jump depending on the visual position of the head.
- function bidiSimplify(cm, range$$1) {
- var anchor = range$$1.anchor;
- var head = range$$1.head;
- var anchorLine = getLine(cm.doc, anchor.line);
- if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
- var order = getOrder(anchorLine);
- if (!order) { return range$$1 }
- var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
- if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
- var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
- if (boundary == 0 || boundary == order.length) { return range$$1 }
- // Compute the relative visual position of the head compared to the
- // anchor (<0 is to the left, >0 to the right)
- var leftSide;
- if (head.line != anchor.line) {
- leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
- } else {
- var headIndex = getBidiPartAt(order, head.ch, head.sticky);
- var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
- if (headIndex == boundary - 1 || headIndex == boundary)
- { leftSide = dir < 0; }
- else
- { leftSide = dir > 0; }
- }
- var usePart = order[boundary + (leftSide ? -1 : 0)];
- var from = leftSide == (usePart.level == 1);
- var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
- return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
- }
- // Determines whether an event happened in the gutter, and fires the
- // handlers for the corresponding event.
- function gutterEvent(cm, e, type, prevent) {
- var mX, mY;
- if (e.touches) {
- mX = e.touches[0].clientX;
- mY = e.touches[0].clientY;
- } else {
- try { mX = e.clientX; mY = e.clientY; }
- catch(e) { return false }
- }
- if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
- if (prevent) { e_preventDefault(e); }
- var display = cm.display;
- var lineBox = display.lineDiv.getBoundingClientRect();
- if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
- mY -= lineBox.top - display.viewOffset;
- for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
- var g = display.gutters.childNodes[i];
- if (g && g.getBoundingClientRect().right >= mX) {
- var line = lineAtHeight(cm.doc, mY);
- var gutter = cm.display.gutterSpecs[i];
- signal(cm, type, cm, line, gutter.className, e);
- return e_defaultPrevented(e)
- }
- }
- }
- function clickInGutter(cm, e) {
- return gutterEvent(cm, e, "gutterClick", true)
- }
- // CONTEXT MENU HANDLING
- // To make the context menu work, we need to briefly unhide the
- // textarea (making it as unobtrusive as possible) to let the
- // right-click take effect on it.
- function onContextMenu(cm, e) {
- if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
- if (signalDOMEvent(cm, e, "contextmenu")) { return }
- if (!captureRightClick) { cm.display.input.onContextMenu(e); }
- }
- function contextMenuInGutter(cm, e) {
- if (!hasHandler(cm, "gutterContextMenu")) { return false }
- return gutterEvent(cm, e, "gutterContextMenu", false)
- }
- function themeChanged(cm) {
- cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
- cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
- clearCaches(cm);
- }
- var Init = {toString: function(){return "CodeMirror.Init"}};
- var defaults = {};
- var optionHandlers = {};
- function defineOptions(CodeMirror) {
- var optionHandlers = CodeMirror.optionHandlers;
- function option(name, deflt, handle, notOnInit) {
- CodeMirror.defaults[name] = deflt;
- if (handle) { optionHandlers[name] =
- notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
- }
- CodeMirror.defineOption = option;
- // Passed to option handlers when there is no old value.
- CodeMirror.Init = Init;
- // These two are, on init, called from the constructor because they
- // have to be initialized before the editor can start at all.
- option("value", "", function (cm, val) { return cm.setValue(val); }, true);
- option("mode", null, function (cm, val) {
- cm.doc.modeOption = val;
- loadMode(cm);
- }, true);
- option("indentUnit", 2, loadMode, true);
- option("indentWithTabs", false);
- option("smartIndent", true);
- option("tabSize", 4, function (cm) {
- resetModeState(cm);
- clearCaches(cm);
- regChange(cm);
- }, true);
- option("lineSeparator", null, function (cm, val) {
- cm.doc.lineSep = val;
- if (!val) { return }
- var newBreaks = [], lineNo = cm.doc.first;
- cm.doc.iter(function (line) {
- for (var pos = 0;;) {
- var found = line.text.indexOf(val, pos);
- if (found == -1) { break }
- pos = found + val.length;
- newBreaks.push(Pos(lineNo, found));
- }
- lineNo++;
- });
- for (var i = newBreaks.length - 1; i >= 0; i--)
- { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
- });
- option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
- cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
- if (old != Init) { cm.refresh(); }
- });
- option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
- option("electricChars", true);
- option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
- throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
- }, true);
- option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
- option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
- option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
- option("rtlMoveVisually", !windows);
- option("wholeLineUpdateBefore", true);
- option("theme", "default", function (cm) {
- themeChanged(cm);
- updateGutters(cm);
- }, true);
- option("keyMap", "default", function (cm, val, old) {
- var next = getKeyMap(val);
- var prev = old != Init && getKeyMap(old);
- if (prev && prev.detach) { prev.detach(cm, next); }
- if (next.attach) { next.attach(cm, prev || null); }
- });
- option("extraKeys", null);
- option("configureMouse", null);
- option("lineWrapping", false, wrappingChanged, true);
- option("gutters", [], function (cm, val) {
- cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
- updateGutters(cm);
- }, true);
- option("fixedGutter", true, function (cm, val) {
- cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
- cm.refresh();
- }, true);
- option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
- option("scrollbarStyle", "native", function (cm) {
- initScrollbars(cm);
- updateScrollbars(cm);
- cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
- cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
- }, true);
- option("lineNumbers", false, function (cm, val) {
- cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
- updateGutters(cm);
- }, true);
- option("firstLineNumber", 1, updateGutters, true);
- option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
- option("showCursorWhenSelecting", false, updateSelection, true);
- option("resetSelectionOnContextMenu", true);
- option("lineWiseCopyCut", true);
- option("pasteLinesPerSelection", true);
- option("selectionsMayTouch", false);
- option("readOnly", false, function (cm, val) {
- if (val == "nocursor") {
- onBlur(cm);
- cm.display.input.blur();
- }
- cm.display.input.readOnlyChanged(val);
- });
- option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
- option("dragDrop", true, dragDropChanged);
- option("allowDropFileTypes", null);
- option("cursorBlinkRate", 530);
- option("cursorScrollMargin", 0);
- option("cursorHeight", 1, updateSelection, true);
- option("singleCursorHeightPerLine", true, updateSelection, true);
- option("workTime", 100);
- option("workDelay", 100);
- option("flattenSpans", true, resetModeState, true);
- option("addModeClass", false, resetModeState, true);
- option("pollInterval", 100);
- option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
- option("historyEventDelay", 1250);
- option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
- option("maxHighlightLength", 10000, resetModeState, true);
- option("moveInputWithCursor", true, function (cm, val) {
- if (!val) { cm.display.input.resetPosition(); }
- });
- option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
- option("autofocus", null);
- option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
- option("phrases", null);
- }
- function dragDropChanged(cm, value, old) {
- var wasOn = old && old != Init;
- if (!value != !wasOn) {
- var funcs = cm.display.dragFunctions;
- var toggle = value ? on : off;
- toggle(cm.display.scroller, "dragstart", funcs.start);
- toggle(cm.display.scroller, "dragenter", funcs.enter);
- toggle(cm.display.scroller, "dragover", funcs.over);
- toggle(cm.display.scroller, "dragleave", funcs.leave);
- toggle(cm.display.scroller, "drop", funcs.drop);
- }
- }
- function wrappingChanged(cm) {
- if (cm.options.lineWrapping) {
- addClass(cm.display.wrapper, "CodeMirror-wrap");
- cm.display.sizer.style.minWidth = "";
- cm.display.sizerWidth = null;
- } else {
- rmClass(cm.display.wrapper, "CodeMirror-wrap");
- findMaxLine(cm);
- }
- estimateLineHeights(cm);
- regChange(cm);
- clearCaches(cm);
- setTimeout(function () { return updateScrollbars(cm); }, 100);
- }
- // A CodeMirror instance represents an editor. This is the object
- // that user code is usually dealing with.
- function CodeMirror(place, options) {
- var this$1 = this;
- if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
- this.options = options = options ? copyObj(options) : {};
- // Determine effective options based on given values and defaults.
- copyObj(defaults, options, false);
- var doc = options.value;
- if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
- else if (options.mode) { doc.modeOption = options.mode; }
- this.doc = doc;
- var input = new CodeMirror.inputStyles[options.inputStyle](this);
- var display = this.display = new Display(place, doc, input, options);
- display.wrapper.CodeMirror = this;
- themeChanged(this);
- if (options.lineWrapping)
- { this.display.wrapper.className += " CodeMirror-wrap"; }
- initScrollbars(this);
- this.state = {
- keyMaps: [], // stores maps added by addKeyMap
- overlays: [], // highlighting overlays, as added by addOverlay
- modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
- overwrite: false,
- delayingBlurEvent: false,
- focused: false,
- suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
- pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
- selectingText: false,
- draggingText: false,
- highlight: new Delayed(), // stores highlight worker timeout
- keySeq: null, // Unfinished key sequence
- specialChars: null
- };
- if (options.autofocus && !mobile) { display.input.focus(); }
- // Override magic textarea content restore that IE sometimes does
- // on our hidden textarea on reload
- if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
- registerEventHandlers(this);
- ensureGlobalHandlers();
- startOperation(this);
- this.curOp.forceUpdate = true;
- attachDoc(this, doc);
- if ((options.autofocus && !mobile) || this.hasFocus())
- { setTimeout(bind(onFocus, this), 20); }
- else
- { onBlur(this); }
- for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
- { optionHandlers[opt](this$1, options[opt], Init); } }
- maybeUpdateLineNumberWidth(this);
- if (options.finishInit) { options.finishInit(this); }
- for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
- endOperation(this);
- // Suppress optimizelegibility in Webkit, since it breaks text
- // measuring on line wrapping boundaries.
- if (webkit && options.lineWrapping &&
- getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
- { display.lineDiv.style.textRendering = "auto"; }
- }
- // The default configuration options.
- CodeMirror.defaults = defaults;
- // Functions to run when options are changed.
- CodeMirror.optionHandlers = optionHandlers;
- // Attach the necessary event handlers when initializing the editor
- function registerEventHandlers(cm) {
- var d = cm.display;
- on(d.scroller, "mousedown", operation(cm, onMouseDown));
- // Older IE's will not fire a second mousedown for a double click
- if (ie && ie_version < 11)
- { on(d.scroller, "dblclick", operation(cm, function (e) {
- if (signalDOMEvent(cm, e)) { return }
- var pos = posFromMouse(cm, e);
- if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
- e_preventDefault(e);
- var word = cm.findWordAt(pos);
- extendSelection(cm.doc, word.anchor, word.head);
- })); }
- else
- { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
- // Some browsers fire contextmenu *after* opening the menu, at
- // which point we can't mess with it anymore. Context menu is
- // handled in onMouseDown for these browsers.
- on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
- // Used to suppress mouse event handling when a touch happens
- var touchFinished, prevTouch = {end: 0};
- function finishTouch() {
- if (d.activeTouch) {
- touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
- prevTouch = d.activeTouch;
- prevTouch.end = +new Date;
- }
- }
- function isMouseLikeTouchEvent(e) {
- if (e.touches.length != 1) { return false }
- var touch = e.touches[0];
- return touch.radiusX <= 1 && touch.radiusY <= 1
- }
- function farAway(touch, other) {
- if (other.left == null) { return true }
- var dx = other.left - touch.left, dy = other.top - touch.top;
- return dx * dx + dy * dy > 20 * 20
- }
- on(d.scroller, "touchstart", function (e) {
- if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
- d.input.ensurePolled();
- clearTimeout(touchFinished);
- var now = +new Date;
- d.activeTouch = {start: now, moved: false,
- prev: now - prevTouch.end <= 300 ? prevTouch : null};
- if (e.touches.length == 1) {
- d.activeTouch.left = e.touches[0].pageX;
- d.activeTouch.top = e.touches[0].pageY;
- }
- }
- });
- on(d.scroller, "touchmove", function () {
- if (d.activeTouch) { d.activeTouch.moved = true; }
- });
- on(d.scroller, "touchend", function (e) {
- var touch = d.activeTouch;
- if (touch && !eventInWidget(d, e) && touch.left != null &&
- !touch.moved && new Date - touch.start < 300) {
- var pos = cm.coordsChar(d.activeTouch, "page"), range;
- if (!touch.prev || farAway(touch, touch.prev)) // Single tap
- { range = new Range(pos, pos); }
- else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
- { range = cm.findWordAt(pos); }
- else // Triple tap
- { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
- cm.setSelection(range.anchor, range.head);
- cm.focus();
- e_preventDefault(e);
- }
- finishTouch();
- });
- on(d.scroller, "touchcancel", finishTouch);
- // Sync scrolling between fake scrollbars and real scrollable
- // area, ensure viewport is updated when scrolling.
- on(d.scroller, "scroll", function () {
- if (d.scroller.clientHeight) {
- updateScrollTop(cm, d.scroller.scrollTop);
- setScrollLeft(cm, d.scroller.scrollLeft, true);
- signal(cm, "scroll", cm);
- }
- });
- // Listen to wheel events in order to try and update the viewport on time.
- on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
- on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
- // Prevent wrapper from ever scrolling
- on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
- d.dragFunctions = {
- enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
- over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
- start: function (e) { return onDragStart(cm, e); },
- drop: operation(cm, onDrop),
- leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
- };
- var inp = d.input.getField();
- on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
- on(inp, "keydown", operation(cm, onKeyDown));
- on(inp, "keypress", operation(cm, onKeyPress));
- on(inp, "focus", function (e) { return onFocus(cm, e); });
- on(inp, "blur", function (e) { return onBlur(cm, e); });
- }
- var initHooks = [];
- CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
- // Indent the given line. The how parameter can be "smart",
- // "add"/null, "subtract", or "prev". When aggressive is false
- // (typically set to true for forced single-line indents), empty
- // lines are not indented, and places where the mode returns Pass
- // are left alone.
- function indentLine(cm, n, how, aggressive) {
- var doc = cm.doc, state;
- if (how == null) { how = "add"; }
- if (how == "smart") {
- // Fall back to "prev" when the mode doesn't have an indentation
- // method.
- if (!doc.mode.indent) { how = "prev"; }
- else { state = getContextBefore(cm, n).state; }
- }
- var tabSize = cm.options.tabSize;
- var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
- if (line.stateAfter) { line.stateAfter = null; }
- var curSpaceString = line.text.match(/^\s*/)[0], indentation;
- if (!aggressive && !/\S/.test(line.text)) {
- indentation = 0;
- how = "not";
- } else if (how == "smart") {
- indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
- if (indentation == Pass || indentation > 150) {
- if (!aggressive) { return }
- how = "prev";
- }
- }
- if (how == "prev") {
- if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
- else { indentation = 0; }
- } else if (how == "add") {
- indentation = curSpace + cm.options.indentUnit;
- } else if (how == "subtract") {
- indentation = curSpace - cm.options.indentUnit;
- } else if (typeof how == "number") {
- indentation = curSpace + how;
- }
- indentation = Math.max(0, indentation);
- var indentString = "", pos = 0;
- if (cm.options.indentWithTabs)
- { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
- if (pos < indentation) { indentString += spaceStr(indentation - pos); }
- if (indentString != curSpaceString) {
- replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
- line.stateAfter = null;
- return true
- } else {
- // Ensure that, if the cursor was in the whitespace at the start
- // of the line, it is moved to the end of that space.
- for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
- var range = doc.sel.ranges[i$1];
- if (range.head.line == n && range.head.ch < curSpaceString.length) {
- var pos$1 = Pos(n, curSpaceString.length);
- replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
- break
- }
- }
- }
- }
- // This will be set to a {lineWise: bool, text: [string]} object, so
- // that, when pasting, we know what kind of selections the copied
- // text was made out of.
- var lastCopied = null;
- function setLastCopied(newLastCopied) {
- lastCopied = newLastCopied;
- }
- function applyTextInput(cm, inserted, deleted, sel, origin) {
- var doc = cm.doc;
- cm.display.shift = false;
- if (!sel) { sel = doc.sel; }
- var recent = +new Date - 200;
- var paste = origin == "paste" || cm.state.pasteIncoming > recent;
- var textLines = splitLinesAuto(inserted), multiPaste = null;
- // When pasting N lines into N selections, insert one line per selection
- if (paste && sel.ranges.length > 1) {
- if (lastCopied && lastCopied.text.join("\n") == inserted) {
- if (sel.ranges.length % lastCopied.text.length == 0) {
- multiPaste = [];
- for (var i = 0; i < lastCopied.text.length; i++)
- { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
- }
- } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
- multiPaste = map(textLines, function (l) { return [l]; });
- }
- }
- var updateInput = cm.curOp.updateInput;
- // Normal behavior is to insert the new text into every selection
- for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
- var range$$1 = sel.ranges[i$1];
- var from = range$$1.from(), to = range$$1.to();
- if (range$$1.empty()) {
- if (deleted && deleted > 0) // Handle deletion
- { from = Pos(from.line, from.ch - deleted); }
- else if (cm.state.overwrite && !paste) // Handle overwrite
- { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
- else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
- { from = to = Pos(from.line, 0); }
- }
- var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
- origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
- makeChange(cm.doc, changeEvent);
- signalLater(cm, "inputRead", cm, changeEvent);
- }
- if (inserted && !paste)
- { triggerElectric(cm, inserted); }
- ensureCursorVisible(cm);
- if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
- cm.curOp.typing = true;
- cm.state.pasteIncoming = cm.state.cutIncoming = -1;
- }
- function handlePaste(e, cm) {
- var pasted = e.clipboardData && e.clipboardData.getData("Text");
- if (pasted) {
- e.preventDefault();
- if (!cm.isReadOnly() && !cm.options.disableInput)
- { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
- return true
- }
- }
- function triggerElectric(cm, inserted) {
- // When an 'electric' character is inserted, immediately trigger a reindent
- if (!cm.options.electricChars || !cm.options.smartIndent) { return }
- var sel = cm.doc.sel;
- for (var i = sel.ranges.length - 1; i >= 0; i--) {
- var range$$1 = sel.ranges[i];
- if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
- var mode = cm.getModeAt(range$$1.head);
- var indented = false;
- if (mode.electricChars) {
- for (var j = 0; j < mode.electricChars.length; j++)
- { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
- indented = indentLine(cm, range$$1.head.line, "smart");
- break
- } }
- } else if (mode.electricInput) {
- if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
- { indented = indentLine(cm, range$$1.head.line, "smart"); }
- }
- if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
- }
- }
- function copyableRanges(cm) {
- var text = [], ranges = [];
- for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
- var line = cm.doc.sel.ranges[i].head.line;
- var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
- ranges.push(lineRange);
- text.push(cm.getRange(lineRange.anchor, lineRange.head));
- }
- return {text: text, ranges: ranges}
- }
- function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
- field.setAttribute("autocorrect", autocorrect ? "" : "off");
- field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
- field.setAttribute("spellcheck", !!spellcheck);
- }
- function hiddenTextarea() {
- var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
- var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
- // The textarea is kept positioned near the cursor to prevent the
- // fact that it'll be scrolled into view on input from scrolling
- // our fake cursor out of view. On webkit, when wrap=off, paste is
- // very slow. So make the area wide instead.
- if (webkit) { te.style.width = "1000px"; }
- else { te.setAttribute("wrap", "off"); }
- // If border: 0; -- iOS fails to open keyboard (issue #1287)
- if (ios) { te.style.border = "1px solid black"; }
- disableBrowserMagic(te);
- return div
- }
- // The publicly visible API. Note that methodOp(f) means
- // 'wrap f in an operation, performed on its `this` parameter'.
- // This is not the complete set of editor methods. Most of the
- // methods defined on the Doc type are also injected into
- // CodeMirror.prototype, for backwards compatibility and
- // convenience.
- function addEditorMethods(CodeMirror) {
- var optionHandlers = CodeMirror.optionHandlers;
- var helpers = CodeMirror.helpers = {};
- CodeMirror.prototype = {
- constructor: CodeMirror,
- focus: function(){window.focus(); this.display.input.focus();},
- setOption: function(option, value) {
- var options = this.options, old = options[option];
- if (options[option] == value && option != "mode") { return }
- options[option] = value;
- if (optionHandlers.hasOwnProperty(option))
- { operation(this, optionHandlers[option])(this, value, old); }
- signal(this, "optionChange", this, option);
- },
- getOption: function(option) {return this.options[option]},
- getDoc: function() {return this.doc},
- addKeyMap: function(map$$1, bottom) {
- this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
- },
- removeKeyMap: function(map$$1) {
- var maps = this.state.keyMaps;
- for (var i = 0; i < maps.length; ++i)
- { if (maps[i] == map$$1 || maps[i].name == map$$1) {
- maps.splice(i, 1);
- return true
- } }
- },
- addOverlay: methodOp(function(spec, options) {
- var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
- if (mode.startState) { throw new Error("Overlays may not be stateful.") }
- insertSorted(this.state.overlays,
- {mode: mode, modeSpec: spec, opaque: options && options.opaque,
- priority: (options && options.priority) || 0},
- function (overlay) { return overlay.priority; });
- this.state.modeGen++;
- regChange(this);
- }),
- removeOverlay: methodOp(function(spec) {
- var this$1 = this;
- var overlays = this.state.overlays;
- for (var i = 0; i < overlays.length; ++i) {
- var cur = overlays[i].modeSpec;
- if (cur == spec || typeof spec == "string" && cur.name == spec) {
- overlays.splice(i, 1);
- this$1.state.modeGen++;
- regChange(this$1);
- return
- }
- }
- }),
- indentLine: methodOp(function(n, dir, aggressive) {
- if (typeof dir != "string" && typeof dir != "number") {
- if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
- else { dir = dir ? "add" : "subtract"; }
- }
- if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
- }),
- indentSelection: methodOp(function(how) {
- var this$1 = this;
- var ranges = this.doc.sel.ranges, end = -1;
- for (var i = 0; i < ranges.length; i++) {
- var range$$1 = ranges[i];
- if (!range$$1.empty()) {
- var from = range$$1.from(), to = range$$1.to();
- var start = Math.max(end, from.line);
- end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
- for (var j = start; j < end; ++j)
- { indentLine(this$1, j, how); }
- var newRanges = this$1.doc.sel.ranges;
- if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
- { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
- } else if (range$$1.head.line > end) {
- indentLine(this$1, range$$1.head.line, how, true);
- end = range$$1.head.line;
- if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
- }
- }
- }),
- // Fetch the parser token for a given character. Useful for hacks
- // that want to inspect the mode state (say, for completion).
- getTokenAt: function(pos, precise) {
- return takeToken(this, pos, precise)
- },
- getLineTokens: function(line, precise) {
- return takeToken(this, Pos(line), precise, true)
- },
- getTokenTypeAt: function(pos) {
- pos = clipPos(this.doc, pos);
- var styles = getLineStyles(this, getLine(this.doc, pos.line));
- var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
- var type;
- if (ch == 0) { type = styles[2]; }
- else { for (;;) {
- var mid = (before + after) >> 1;
- if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
- else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
- else { type = styles[mid * 2 + 2]; break }
- } }
- var cut = type ? type.indexOf("overlay ") : -1;
- return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
- },
- getModeAt: function(pos) {
- var mode = this.doc.mode;
- if (!mode.innerMode) { return mode }
- return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
- },
- getHelper: function(pos, type) {
- return this.getHelpers(pos, type)[0]
- },
- getHelpers: function(pos, type) {
- var this$1 = this;
- var found = [];
- if (!helpers.hasOwnProperty(type)) { return found }
- var help = helpers[type], mode = this.getModeAt(pos);
- if (typeof mode[type] == "string") {
- if (help[mode[type]]) { found.push(help[mode[type]]); }
- } else if (mode[type]) {
- for (var i = 0; i < mode[type].length; i++) {
- var val = help[mode[type][i]];
- if (val) { found.push(val); }
- }
- } else if (mode.helperType && help[mode.helperType]) {
- found.push(help[mode.helperType]);
- } else if (help[mode.name]) {
- found.push(help[mode.name]);
- }
- for (var i$1 = 0; i$1 < help._global.length; i$1++) {
- var cur = help._global[i$1];
- if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
- { found.push(cur.val); }
- }
- return found
- },
- getStateAfter: function(line, precise) {
- var doc = this.doc;
- line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
- return getContextBefore(this, line + 1, precise).state
- },
- cursorCoords: function(start, mode) {
- var pos, range$$1 = this.doc.sel.primary();
- if (start == null) { pos = range$$1.head; }
- else if (typeof start == "object") { pos = clipPos(this.doc, start); }
- else { pos = start ? range$$1.from() : range$$1.to(); }
- return cursorCoords(this, pos, mode || "page")
- },
- charCoords: function(pos, mode) {
- return charCoords(this, clipPos(this.doc, pos), mode || "page")
- },
- coordsChar: function(coords, mode) {
- coords = fromCoordSystem(this, coords, mode || "page");
- return coordsChar(this, coords.left, coords.top)
- },
- lineAtHeight: function(height, mode) {
- height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
- return lineAtHeight(this.doc, height + this.display.viewOffset)
- },
- heightAtLine: function(line, mode, includeWidgets) {
- var end = false, lineObj;
- if (typeof line == "number") {
- var last = this.doc.first + this.doc.size - 1;
- if (line < this.doc.first) { line = this.doc.first; }
- else if (line > last) { line = last; end = true; }
- lineObj = getLine(this.doc, line);
- } else {
- lineObj = line;
- }
- return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
- (end ? this.doc.height - heightAtLine(lineObj) : 0)
- },
- defaultTextHeight: function() { return textHeight(this.display) },
- defaultCharWidth: function() { return charWidth(this.display) },
- getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
- addWidget: function(pos, node, scroll, vert, horiz) {
- var display = this.display;
- pos = cursorCoords(this, clipPos(this.doc, pos));
- var top = pos.bottom, left = pos.left;
- node.style.position = "absolute";
- node.setAttribute("cm-ignore-events", "true");
- this.display.input.setUneditable(node);
- display.sizer.appendChild(node);
- if (vert == "over") {
- top = pos.top;
- } else if (vert == "above" || vert == "near") {
- var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
- hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
- // Default to positioning above (if specified and possible); otherwise default to positioning below
- if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
- { top = pos.top - node.offsetHeight; }
- else if (pos.bottom + node.offsetHeight <= vspace)
- { top = pos.bottom; }
- if (left + node.offsetWidth > hspace)
- { left = hspace - node.offsetWidth; }
- }
- node.style.top = top + "px";
- node.style.left = node.style.right = "";
- if (horiz == "right") {
- left = display.sizer.clientWidth - node.offsetWidth;
- node.style.right = "0px";
- } else {
- if (horiz == "left") { left = 0; }
- else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
- node.style.left = left + "px";
- }
- if (scroll)
- { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
- },
- triggerOnKeyDown: methodOp(onKeyDown),
- triggerOnKeyPress: methodOp(onKeyPress),
- triggerOnKeyUp: onKeyUp,
- triggerOnMouseDown: methodOp(onMouseDown),
- execCommand: function(cmd) {
- if (commands.hasOwnProperty(cmd))
- { return commands[cmd].call(null, this) }
- },
- triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
- findPosH: function(from, amount, unit, visually) {
- var this$1 = this;
- var dir = 1;
- if (amount < 0) { dir = -1; amount = -amount; }
- var cur = clipPos(this.doc, from);
- for (var i = 0; i < amount; ++i) {
- cur = findPosH(this$1.doc, cur, dir, unit, visually);
- if (cur.hitSide) { break }
- }
- return cur
- },
- moveH: methodOp(function(dir, unit) {
- var this$1 = this;
- this.extendSelectionsBy(function (range$$1) {
- if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
- { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
- else
- { return dir < 0 ? range$$1.from() : range$$1.to() }
- }, sel_move);
- }),
- deleteH: methodOp(function(dir, unit) {
- var sel = this.doc.sel, doc = this.doc;
- if (sel.somethingSelected())
- { doc.replaceSelection("", null, "+delete"); }
- else
- { deleteNearSelection(this, function (range$$1) {
- var other = findPosH(doc, range$$1.head, dir, unit, false);
- return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
- }); }
- }),
- findPosV: function(from, amount, unit, goalColumn) {
- var this$1 = this;
- var dir = 1, x = goalColumn;
- if (amount < 0) { dir = -1; amount = -amount; }
- var cur = clipPos(this.doc, from);
- for (var i = 0; i < amount; ++i) {
- var coords = cursorCoords(this$1, cur, "div");
- if (x == null) { x = coords.left; }
- else { coords.left = x; }
- cur = findPosV(this$1, coords, dir, unit);
- if (cur.hitSide) { break }
- }
- return cur
- },
- moveV: methodOp(function(dir, unit) {
- var this$1 = this;
- var doc = this.doc, goals = [];
- var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
- doc.extendSelectionsBy(function (range$$1) {
- if (collapse)
- { return dir < 0 ? range$$1.from() : range$$1.to() }
- var headPos = cursorCoords(this$1, range$$1.head, "div");
- if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
- goals.push(headPos.left);
- var pos = findPosV(this$1, headPos, dir, unit);
- if (unit == "page" && range$$1 == doc.sel.primary())
- { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
- return pos
- }, sel_move);
- if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
- { doc.sel.ranges[i].goalColumn = goals[i]; } }
- }),
- // Find the word at the given position (as returned by coordsChar).
- findWordAt: function(pos) {
- var doc = this.doc, line = getLine(doc, pos.line).text;
- var start = pos.ch, end = pos.ch;
- if (line) {
- var helper = this.getHelper(pos, "wordChars");
- if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
- var startChar = line.charAt(start);
- var check = isWordChar(startChar, helper)
- ? function (ch) { return isWordChar(ch, helper); }
- : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
- : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
- while (start > 0 && check(line.charAt(start - 1))) { --start; }
- while (end < line.length && check(line.charAt(end))) { ++end; }
- }
- return new Range(Pos(pos.line, start), Pos(pos.line, end))
- },
- toggleOverwrite: function(value) {
- if (value != null && value == this.state.overwrite) { return }
- if (this.state.overwrite = !this.state.overwrite)
- { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
- else
- { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
- signal(this, "overwriteToggle", this, this.state.overwrite);
- },
- hasFocus: function() { return this.display.input.getField() == activeElt() },
- isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
- scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
- getScrollInfo: function() {
- var scroller = this.display.scroller;
- return {left: scroller.scrollLeft, top: scroller.scrollTop,
- height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
- width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
- clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
- },
- scrollIntoView: methodOp(function(range$$1, margin) {
- if (range$$1 == null) {
- range$$1 = {from: this.doc.sel.primary().head, to: null};
- if (margin == null) { margin = this.options.cursorScrollMargin; }
- } else if (typeof range$$1 == "number") {
- range$$1 = {from: Pos(range$$1, 0), to: null};
- } else if (range$$1.from == null) {
- range$$1 = {from: range$$1, to: null};
- }
- if (!range$$1.to) { range$$1.to = range$$1.from; }
- range$$1.margin = margin || 0;
- if (range$$1.from.line != null) {
- scrollToRange(this, range$$1);
- } else {
- scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
- }
- }),
- setSize: methodOp(function(width, height) {
- var this$1 = this;
- var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
- if (width != null) { this.display.wrapper.style.width = interpret(width); }
- if (height != null) { this.display.wrapper.style.height = interpret(height); }
- if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
- var lineNo$$1 = this.display.viewFrom;
- this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
- if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
- { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
- ++lineNo$$1;
- });
- this.curOp.forceUpdate = true;
- signal(this, "refresh", this);
- }),
- operation: function(f){return runInOp(this, f)},
- startOperation: function(){return startOperation(this)},
- endOperation: function(){return endOperation(this)},
- refresh: methodOp(function() {
- var oldHeight = this.display.cachedTextHeight;
- regChange(this);
- this.curOp.forceUpdate = true;
- clearCaches(this);
- scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
- updateGutterSpace(this.display);
- if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
- { estimateLineHeights(this); }
- signal(this, "refresh", this);
- }),
- swapDoc: methodOp(function(doc) {
- var old = this.doc;
- old.cm = null;
- // Cancel the current text selection if any (#5821)
- if (this.state.selectingText) { this.state.selectingText(); }
- attachDoc(this, doc);
- clearCaches(this);
- this.display.input.reset();
- scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
- this.curOp.forceScroll = true;
- signalLater(this, "swapDoc", this, old);
- return old
- }),
- phrase: function(phraseText) {
- var phrases = this.options.phrases;
- return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
- },
- getInputField: function(){return this.display.input.getField()},
- getWrapperElement: function(){return this.display.wrapper},
- getScrollerElement: function(){return this.display.scroller},
- getGutterElement: function(){return this.display.gutters}
- };
- eventMixin(CodeMirror);
- CodeMirror.registerHelper = function(type, name, value) {
- if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
- helpers[type][name] = value;
- };
- CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
- CodeMirror.registerHelper(type, name, value);
- helpers[type]._global.push({pred: predicate, val: value});
- };
- }
- // Used for horizontal relative motion. Dir is -1 or 1 (left or
- // right), unit can be "char", "column" (like char, but doesn't
- // cross line boundaries), "word" (across next word), or "group" (to
- // the start of next group of word or non-word-non-whitespace
- // chars). The visually param controls whether, in right-to-left
- // text, direction 1 means to move towards the next index in the
- // string, or towards the character to the right of the current
- // position. The resulting position will have a hitSide=true
- // property if it reached the end of the document.
- function findPosH(doc, pos, dir, unit, visually) {
- var oldPos = pos;
- var origDir = dir;
- var lineObj = getLine(doc, pos.line);
- function findNextLine() {
- var l = pos.line + dir;
- if (l < doc.first || l >= doc.first + doc.size) { return false }
- pos = new Pos(l, pos.ch, pos.sticky);
- return lineObj = getLine(doc, l)
- }
- function moveOnce(boundToLine) {
- var next;
- if (visually) {
- next = moveVisually(doc.cm, lineObj, pos, dir);
- } else {
- next = moveLogically(lineObj, pos, dir);
- }
- if (next == null) {
- if (!boundToLine && findNextLine())
- { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
- else
- { return false }
- } else {
- pos = next;
- }
- return true
- }
- if (unit == "char") {
- moveOnce();
- } else if (unit == "column") {
- moveOnce(true);
- } else if (unit == "word" || unit == "group") {
- var sawType = null, group = unit == "group";
- var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
- for (var first = true;; first = false) {
- if (dir < 0 && !moveOnce(!first)) { break }
- var cur = lineObj.text.charAt(pos.ch) || "\n";
- var type = isWordChar(cur, helper) ? "w"
- : group && cur == "\n" ? "n"
- : !group || /\s/.test(cur) ? null
- : "p";
- if (group && !first && !type) { type = "s"; }
- if (sawType && sawType != type) {
- if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
- break
- }
- if (type) { sawType = type; }
- if (dir > 0 && !moveOnce(!first)) { break }
- }
- }
- var result = skipAtomic(doc, pos, oldPos, origDir, true);
- if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
- return result
- }
- // For relative vertical movement. Dir may be -1 or 1. Unit can be
- // "page" or "line". The resulting position will have a hitSide=true
- // property if it reached the end of the document.
- function findPosV(cm, pos, dir, unit) {
- var doc = cm.doc, x = pos.left, y;
- if (unit == "page") {
- var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
- var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
- y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
- } else if (unit == "line") {
- y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
- }
- var target;
- for (;;) {
- target = coordsChar(cm, x, y);
- if (!target.outside) { break }
- if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
- y += dir * 5;
- }
- return target
- }
- // CONTENTEDITABLE INPUT STYLE
- var ContentEditableInput = function(cm) {
- this.cm = cm;
- this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
- this.polling = new Delayed();
- this.composing = null;
- this.gracePeriod = false;
- this.readDOMTimeout = null;
- };
- ContentEditableInput.prototype.init = function (display) {
- var this$1 = this;
- var input = this, cm = input.cm;
- var div = input.div = display.lineDiv;
- disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
- on(div, "paste", function (e) {
- if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
- // IE doesn't fire input events, so we schedule a read for the pasted content in this way
- if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
- });
- on(div, "compositionstart", function (e) {
- this$1.composing = {data: e.data, done: false};
- });
- on(div, "compositionupdate", function (e) {
- if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
- });
- on(div, "compositionend", function (e) {
- if (this$1.composing) {
- if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
- this$1.composing.done = true;
- }
- });
- on(div, "touchstart", function () { return input.forceCompositionEnd(); });
- on(div, "input", function () {
- if (!this$1.composing) { this$1.readFromDOMSoon(); }
- });
- function onCopyCut(e) {
- if (signalDOMEvent(cm, e)) { return }
- if (cm.somethingSelected()) {
- setLastCopied({lineWise: false, text: cm.getSelections()});
- if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
- } else if (!cm.options.lineWiseCopyCut) {
- return
- } else {
- var ranges = copyableRanges(cm);
- setLastCopied({lineWise: true, text: ranges.text});
- if (e.type == "cut") {
- cm.operation(function () {
- cm.setSelections(ranges.ranges, 0, sel_dontScroll);
- cm.replaceSelection("", null, "cut");
- });
- }
- }
- if (e.clipboardData) {
- e.clipboardData.clearData();
- var content = lastCopied.text.join("\n");
- // iOS exposes the clipboard API, but seems to discard content inserted into it
- e.clipboardData.setData("Text", content);
- if (e.clipboardData.getData("Text") == content) {
- e.preventDefault();
- return
- }
- }
- // Old-fashioned briefly-focus-a-textarea hack
- var kludge = hiddenTextarea(), te = kludge.firstChild;
- cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
- te.value = lastCopied.text.join("\n");
- var hadFocus = document.activeElement;
- selectInput(te);
- setTimeout(function () {
- cm.display.lineSpace.removeChild(kludge);
- hadFocus.focus();
- if (hadFocus == div) { input.showPrimarySelection(); }
- }, 50);
- }
- on(div, "copy", onCopyCut);
- on(div, "cut", onCopyCut);
- };
- ContentEditableInput.prototype.prepareSelection = function () {
- var result = prepareSelection(this.cm, false);
- result.focus = this.cm.state.focused;
- return result
- };
- ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
- if (!info || !this.cm.display.view.length) { return }
- if (info.focus || takeFocus) { this.showPrimarySelection(); }
- this.showMultipleSelections(info);
- };
- ContentEditableInput.prototype.getSelection = function () {
- return this.cm.display.wrapper.ownerDocument.getSelection()
- };
- ContentEditableInput.prototype.showPrimarySelection = function () {
- var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
- var from = prim.from(), to = prim.to();
- if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
- sel.removeAllRanges();
- return
- }
- var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
- var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
- if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
- cmp(minPos(curAnchor, curFocus), from) == 0 &&
- cmp(maxPos(curAnchor, curFocus), to) == 0)
- { return }
- var view = cm.display.view;
- var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
- {node: view[0].measure.map[2], offset: 0};
- var end = to.line < cm.display.viewTo && posToDOM(cm, to);
- if (!end) {
- var measure = view[view.length - 1].measure;
- var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
- end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
- }
- if (!start || !end) {
- sel.removeAllRanges();
- return
- }
- var old = sel.rangeCount && sel.getRangeAt(0), rng;
- try { rng = range(start.node, start.offset, end.offset, end.node); }
- catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
- if (rng) {
- if (!gecko && cm.state.focused) {
- sel.collapse(start.node, start.offset);
- if (!rng.collapsed) {
- sel.removeAllRanges();
- sel.addRange(rng);
- }
- } else {
- sel.removeAllRanges();
- sel.addRange(rng);
- }
- if (old && sel.anchorNode == null) { sel.addRange(old); }
- else if (gecko) { this.startGracePeriod(); }
- }
- this.rememberSelection();
- };
- ContentEditableInput.prototype.startGracePeriod = function () {
- var this$1 = this;
- clearTimeout(this.gracePeriod);
- this.gracePeriod = setTimeout(function () {
- this$1.gracePeriod = false;
- if (this$1.selectionChanged())
- { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
- }, 20);
- };
- ContentEditableInput.prototype.showMultipleSelections = function (info) {
- removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
- removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
- };
- ContentEditableInput.prototype.rememberSelection = function () {
- var sel = this.getSelection();
- this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
- this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
- };
- ContentEditableInput.prototype.selectionInEditor = function () {
- var sel = this.getSelection();
- if (!sel.rangeCount) { return false }
- var node = sel.getRangeAt(0).commonAncestorContainer;
- return contains(this.div, node)
- };
- ContentEditableInput.prototype.focus = function () {
- if (this.cm.options.readOnly != "nocursor") {
- if (!this.selectionInEditor())
- { this.showSelection(this.prepareSelection(), true); }
- this.div.focus();
- }
- };
- ContentEditableInput.prototype.blur = function () { this.div.blur(); };
- ContentEditableInput.prototype.getField = function () { return this.div };
- ContentEditableInput.prototype.supportsTouch = function () { return true };
- ContentEditableInput.prototype.receivedFocus = function () {
- var input = this;
- if (this.selectionInEditor())
- { this.pollSelection(); }
- else
- { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
- function poll() {
- if (input.cm.state.focused) {
- input.pollSelection();
- input.polling.set(input.cm.options.pollInterval, poll);
- }
- }
- this.polling.set(this.cm.options.pollInterval, poll);
- };
- ContentEditableInput.prototype.selectionChanged = function () {
- var sel = this.getSelection();
- return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
- sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
- };
- ContentEditableInput.prototype.pollSelection = function () {
- if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
- var sel = this.getSelection(), cm = this.cm;
- // On Android Chrome (version 56, at least), backspacing into an
- // uneditable block element will put the cursor in that element,
- // and then, because it's not editable, hide the virtual keyboard.
- // Because Android doesn't allow us to actually detect backspace
- // presses in a sane way, this code checks for when that happens
- // and simulates a backspace press in this case.
- if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
- this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
- this.blur();
- this.focus();
- return
- }
- if (this.composing) { return }
- this.rememberSelection();
- var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
- var head = domToPos(cm, sel.focusNode, sel.focusOffset);
- if (anchor && head) { runInOp(cm, function () {
- setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
- if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
- }); }
- };
- ContentEditableInput.prototype.pollContent = function () {
- if (this.readDOMTimeout != null) {
- clearTimeout(this.readDOMTimeout);
- this.readDOMTimeout = null;
- }
- var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
- var from = sel.from(), to = sel.to();
- if (from.ch == 0 && from.line > cm.firstLine())
- { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
- if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
- { to = Pos(to.line + 1, 0); }
- if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
- var fromIndex, fromLine, fromNode;
- if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
- fromLine = lineNo(display.view[0].line);
- fromNode = display.view[0].node;
- } else {
- fromLine = lineNo(display.view[fromIndex].line);
- fromNode = display.view[fromIndex - 1].node.nextSibling;
- }
- var toIndex = findViewIndex(cm, to.line);
- var toLine, toNode;
- if (toIndex == display.view.length - 1) {
- toLine = display.viewTo - 1;
- toNode = display.lineDiv.lastChild;
- } else {
- toLine = lineNo(display.view[toIndex + 1].line) - 1;
- toNode = display.view[toIndex + 1].node.previousSibling;
- }
- if (!fromNode) { return false }
- var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
- var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
- while (newText.length > 1 && oldText.length > 1) {
- if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
- else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
- else { break }
- }
- var cutFront = 0, cutEnd = 0;
- var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
- while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
- { ++cutFront; }
- var newBot = lst(newText), oldBot = lst(oldText);
- var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
- oldBot.length - (oldText.length == 1 ? cutFront : 0));
- while (cutEnd < maxCutEnd &&
- newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
- { ++cutEnd; }
- // Try to move start of change to start of selection if ambiguous
- if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
- while (cutFront && cutFront > from.ch &&
- newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
- cutFront--;
- cutEnd++;
- }
- }
- newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
- newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
- var chFrom = Pos(fromLine, cutFront);
- var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
- if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
- replaceRange(cm.doc, newText, chFrom, chTo, "+input");
- return true
- }
- };
- ContentEditableInput.prototype.ensurePolled = function () {
- this.forceCompositionEnd();
- };
- ContentEditableInput.prototype.reset = function () {
- this.forceCompositionEnd();
- };
- ContentEditableInput.prototype.forceCompositionEnd = function () {
- if (!this.composing) { return }
- clearTimeout(this.readDOMTimeout);
- this.composing = null;
- this.updateFromDOM();
- this.div.blur();
- this.div.focus();
- };
- ContentEditableInput.prototype.readFromDOMSoon = function () {
- var this$1 = this;
- if (this.readDOMTimeout != null) { return }
- this.readDOMTimeout = setTimeout(function () {
- this$1.readDOMTimeout = null;
- if (this$1.composing) {
- if (this$1.composing.done) { this$1.composing = null; }
- else { return }
- }
- this$1.updateFromDOM();
- }, 80);
- };
- ContentEditableInput.prototype.updateFromDOM = function () {
- var this$1 = this;
- if (this.cm.isReadOnly() || !this.pollContent())
- { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
- };
- ContentEditableInput.prototype.setUneditable = function (node) {
- node.contentEditable = "false";
- };
- ContentEditableInput.prototype.onKeyPress = function (e) {
- if (e.charCode == 0 || this.composing) { return }
- e.preventDefault();
- if (!this.cm.isReadOnly())
- { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
- };
- ContentEditableInput.prototype.readOnlyChanged = function (val) {
- this.div.contentEditable = String(val != "nocursor");
- };
- ContentEditableInput.prototype.onContextMenu = function () {};
- ContentEditableInput.prototype.resetPosition = function () {};
- ContentEditableInput.prototype.needsContentAttribute = true;
- function posToDOM(cm, pos) {
- var view = findViewForLine(cm, pos.line);
- if (!view || view.hidden) { return null }
- var line = getLine(cm.doc, pos.line);
- var info = mapFromLineView(view, line, pos.line);
- var order = getOrder(line, cm.doc.direction), side = "left";
- if (order) {
- var partPos = getBidiPartAt(order, pos.ch);
- side = partPos % 2 ? "right" : "left";
- }
- var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
- result.offset = result.collapse == "right" ? result.end : result.start;
- return result
- }
- function isInGutter(node) {
- for (var scan = node; scan; scan = scan.parentNode)
- { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
- return false
- }
- function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
- function domTextBetween(cm, from, to, fromLine, toLine) {
- var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
- function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
- function close() {
- if (closing) {
- text += lineSep;
- if (extraLinebreak) { text += lineSep; }
- closing = extraLinebreak = false;
- }
- }
- function addText(str) {
- if (str) {
- close();
- text += str;
- }
- }
- function walk(node) {
- if (node.nodeType == 1) {
- var cmText = node.getAttribute("cm-text");
- if (cmText) {
- addText(cmText);
- return
- }
- var markerID = node.getAttribute("cm-marker"), range$$1;
- if (markerID) {
- var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
- if (found.length && (range$$1 = found[0].find(0)))
- { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
- return
- }
- if (node.getAttribute("contenteditable") == "false") { return }
- var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
- if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
- if (isBlock) { close(); }
- for (var i = 0; i < node.childNodes.length; i++)
- { walk(node.childNodes[i]); }
- if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
- if (isBlock) { closing = true; }
- } else if (node.nodeType == 3) {
- addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
- }
- }
- for (;;) {
- walk(from);
- if (from == to) { break }
- from = from.nextSibling;
- extraLinebreak = false;
- }
- return text
- }
- function domToPos(cm, node, offset) {
- var lineNode;
- if (node == cm.display.lineDiv) {
- lineNode = cm.display.lineDiv.childNodes[offset];
- if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
- node = null; offset = 0;
- } else {
- for (lineNode = node;; lineNode = lineNode.parentNode) {
- if (!lineNode || lineNode == cm.display.lineDiv) { return null }
- if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
- }
- }
- for (var i = 0; i < cm.display.view.length; i++) {
- var lineView = cm.display.view[i];
- if (lineView.node == lineNode)
- { return locateNodeInLineView(lineView, node, offset) }
- }
- }
- function locateNodeInLineView(lineView, node, offset) {
- var wrapper = lineView.text.firstChild, bad = false;
- if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
- if (node == wrapper) {
- bad = true;
- node = wrapper.childNodes[offset];
- offset = 0;
- if (!node) {
- var line = lineView.rest ? lst(lineView.rest) : lineView.line;
- return badPos(Pos(lineNo(line), line.text.length), bad)
- }
- }
- var textNode = node.nodeType == 3 ? node : null, topNode = node;
- if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
- textNode = node.firstChild;
- if (offset) { offset = textNode.nodeValue.length; }
- }
- while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
- var measure = lineView.measure, maps = measure.maps;
- function find(textNode, topNode, offset) {
- for (var i = -1; i < (maps ? maps.length : 0); i++) {
- var map$$1 = i < 0 ? measure.map : maps[i];
- for (var j = 0; j < map$$1.length; j += 3) {
- var curNode = map$$1[j + 2];
- if (curNode == textNode || curNode == topNode) {
- var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
- var ch = map$$1[j] + offset;
- if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
- return Pos(line, ch)
- }
- }
- }
- }
- var found = find(textNode, topNode, offset);
- if (found) { return badPos(found, bad) }
- // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
- for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
- found = find(after, after.firstChild, 0);
- if (found)
- { return badPos(Pos(found.line, found.ch - dist), bad) }
- else
- { dist += after.textContent.length; }
- }
- for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
- found = find(before, before.firstChild, -1);
- if (found)
- { return badPos(Pos(found.line, found.ch + dist$1), bad) }
- else
- { dist$1 += before.textContent.length; }
- }
- }
- // TEXTAREA INPUT STYLE
- var TextareaInput = function(cm) {
- this.cm = cm;
- // See input.poll and input.reset
- this.prevInput = "";
- // Flag that indicates whether we expect input to appear real soon
- // now (after some event like 'keypress' or 'input') and are
- // polling intensively.
- this.pollingFast = false;
- // Self-resetting timeout for the poller
- this.polling = new Delayed();
- // Used to work around IE issue with selection being forgotten when focus moves away from textarea
- this.hasSelection = false;
- this.composing = null;
- };
- TextareaInput.prototype.init = function (display) {
- var this$1 = this;
- var input = this, cm = this.cm;
- this.createField(display);
- var te = this.textarea;
- display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
- // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
- if (ios) { te.style.width = "0px"; }
- on(te, "input", function () {
- if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
- input.poll();
- });
- on(te, "paste", function (e) {
- if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
- cm.state.pasteIncoming = +new Date;
- input.fastPoll();
- });
- function prepareCopyCut(e) {
- if (signalDOMEvent(cm, e)) { return }
- if (cm.somethingSelected()) {
- setLastCopied({lineWise: false, text: cm.getSelections()});
- } else if (!cm.options.lineWiseCopyCut) {
- return
- } else {
- var ranges = copyableRanges(cm);
- setLastCopied({lineWise: true, text: ranges.text});
- if (e.type == "cut") {
- cm.setSelections(ranges.ranges, null, sel_dontScroll);
- } else {
- input.prevInput = "";
- te.value = ranges.text.join("\n");
- selectInput(te);
- }
- }
- if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
- }
- on(te, "cut", prepareCopyCut);
- on(te, "copy", prepareCopyCut);
- on(display.scroller, "paste", function (e) {
- if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
- if (!te.dispatchEvent) {
- cm.state.pasteIncoming = +new Date;
- input.focus();
- return
- }
- // Pass the `paste` event to the textarea so it's handled by its event listener.
- var event = new Event("paste");
- event.clipboardData = e.clipboardData;
- te.dispatchEvent(event);
- });
- // Prevent normal selection in the editor (we handle our own)
- on(display.lineSpace, "selectstart", function (e) {
- if (!eventInWidget(display, e)) { e_preventDefault(e); }
- });
- on(te, "compositionstart", function () {
- var start = cm.getCursor("from");
- if (input.composing) { input.composing.range.clear(); }
- input.composing = {
- start: start,
- range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
- };
- });
- on(te, "compositionend", function () {
- if (input.composing) {
- input.poll();
- input.composing.range.clear();
- input.composing = null;
- }
- });
- };
- TextareaInput.prototype.createField = function (_display) {
- // Wraps and hides input textarea
- this.wrapper = hiddenTextarea();
- // The semihidden textarea that is focused when the editor is
- // focused, and receives input.
- this.textarea = this.wrapper.firstChild;
- };
- TextareaInput.prototype.prepareSelection = function () {
- // Redraw the selection and/or cursor
- var cm = this.cm, display = cm.display, doc = cm.doc;
- var result = prepareSelection(cm);
- // Move the hidden textarea near the cursor to prevent scrolling artifacts
- if (cm.options.moveInputWithCursor) {
- var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
- var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
- result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
- headPos.top + lineOff.top - wrapOff.top));
- result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
- headPos.left + lineOff.left - wrapOff.left));
- }
- return result
- };
- TextareaInput.prototype.showSelection = function (drawn) {
- var cm = this.cm, display = cm.display;
- removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
- removeChildrenAndAdd(display.selectionDiv, drawn.selection);
- if (drawn.teTop != null) {
- this.wrapper.style.top = drawn.teTop + "px";
- this.wrapper.style.left = drawn.teLeft + "px";
- }
- };
- // Reset the input to correspond to the selection (or to be empty,
- // when not typing and nothing is selected)
- TextareaInput.prototype.reset = function (typing) {
- if (this.contextMenuPending || this.composing) { return }
- var cm = this.cm;
- if (cm.somethingSelected()) {
- this.prevInput = "";
- var content = cm.getSelection();
- this.textarea.value = content;
- if (cm.state.focused) { selectInput(this.textarea); }
- if (ie && ie_version >= 9) { this.hasSelection = content; }
- } else if (!typing) {
- this.prevInput = this.textarea.value = "";
- if (ie && ie_version >= 9) { this.hasSelection = null; }
- }
- };
- TextareaInput.prototype.getField = function () { return this.textarea };
- TextareaInput.prototype.supportsTouch = function () { return false };
- TextareaInput.prototype.focus = function () {
- if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
- try { this.textarea.focus(); }
- catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
- }
- };
- TextareaInput.prototype.blur = function () { this.textarea.blur(); };
- TextareaInput.prototype.resetPosition = function () {
- this.wrapper.style.top = this.wrapper.style.left = 0;
- };
- TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
- // Poll for input changes, using the normal rate of polling. This
- // runs as long as the editor is focused.
- TextareaInput.prototype.slowPoll = function () {
- var this$1 = this;
- if (this.pollingFast) { return }
- this.polling.set(this.cm.options.pollInterval, function () {
- this$1.poll();
- if (this$1.cm.state.focused) { this$1.slowPoll(); }
- });
- };
- // When an event has just come in that is likely to add or change
- // something in the input textarea, we poll faster, to ensure that
- // the change appears on the screen quickly.
- TextareaInput.prototype.fastPoll = function () {
- var missed = false, input = this;
- input.pollingFast = true;
- function p() {
- var changed = input.poll();
- if (!changed && !missed) {missed = true; input.polling.set(60, p);}
- else {input.pollingFast = false; input.slowPoll();}
- }
- input.polling.set(20, p);
- };
- // Read input from the textarea, and update the document to match.
- // When something is selected, it is present in the textarea, and
- // selected (unless it is huge, in which case a placeholder is
- // used). When nothing is selected, the cursor sits after previously
- // seen text (can be empty), which is stored in prevInput (we must
- // not reset the textarea when typing, because that breaks IME).
- TextareaInput.prototype.poll = function () {
- var this$1 = this;
- var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
- // Since this is called a *lot*, try to bail out as cheaply as
- // possible when it is clear that nothing happened. hasSelection
- // will be the case when there is a lot of text in the textarea,
- // in which case reading its value would be expensive.
- if (this.contextMenuPending || !cm.state.focused ||
- (hasSelection(input) && !prevInput && !this.composing) ||
- cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
- { return false }
- var text = input.value;
- // If nothing changed, bail.
- if (text == prevInput && !cm.somethingSelected()) { return false }
- // Work around nonsensical selection resetting in IE9/10, and
- // inexplicable appearance of private area unicode characters on
- // some key combos in Mac (#2689).
- if (ie && ie_version >= 9 && this.hasSelection === text ||
- mac && /[\uf700-\uf7ff]/.test(text)) {
- cm.display.input.reset();
- return false
- }
- if (cm.doc.sel == cm.display.selForContextMenu) {
- var first = text.charCodeAt(0);
- if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
- if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
- }
- // Find the part of the input that is actually new
- var same = 0, l = Math.min(prevInput.length, text.length);
- while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
- runInOp(cm, function () {
- applyTextInput(cm, text.slice(same), prevInput.length - same,
- null, this$1.composing ? "*compose" : null);
- // Don't leave long text in the textarea, since it makes further polling slow
- if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
- else { this$1.prevInput = text; }
- if (this$1.composing) {
- this$1.composing.range.clear();
- this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
- {className: "CodeMirror-composing"});
- }
- });
- return true
- };
- TextareaInput.prototype.ensurePolled = function () {
- if (this.pollingFast && this.poll()) { this.pollingFast = false; }
- };
- TextareaInput.prototype.onKeyPress = function () {
- if (ie && ie_version >= 9) { this.hasSelection = null; }
- this.fastPoll();
- };
- TextareaInput.prototype.onContextMenu = function (e) {
- var input = this, cm = input.cm, display = cm.display, te = input.textarea;
- if (input.contextMenuPending) { input.contextMenuPending(); }
- var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
- if (!pos || presto) { return } // Opera is difficult.
- // Reset the current text selection only if the click is done outside of the selection
- // and 'resetSelectionOnContextMenu' option is true.
- var reset = cm.options.resetSelectionOnContextMenu;
- if (reset && cm.doc.sel.contains(pos) == -1)
- { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
- var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
- var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
- input.wrapper.style.cssText = "position: static";
- te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
- var oldScrollY;
- if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
- display.input.focus();
- if (webkit) { window.scrollTo(null, oldScrollY); }
- display.input.reset();
- // Adds "Select all" to context menu in FF
- if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
- input.contextMenuPending = rehide;
- display.selForContextMenu = cm.doc.sel;
- clearTimeout(display.detectingSelectAll);
- // Select-all will be greyed out if there's nothing to select, so
- // this adds a zero-width space so that we can later check whether
- // it got selected.
- function prepareSelectAllHack() {
- if (te.selectionStart != null) {
- var selected = cm.somethingSelected();
- var extval = "\u200b" + (selected ? te.value : "");
- te.value = "\u21da"; // Used to catch context-menu undo
- te.value = extval;
- input.prevInput = selected ? "" : "\u200b";
- te.selectionStart = 1; te.selectionEnd = extval.length;
- // Re-set this, in case some other handler touched the
- // selection in the meantime.
- display.selForContextMenu = cm.doc.sel;
- }
- }
- function rehide() {
- if (input.contextMenuPending != rehide) { return }
- input.contextMenuPending = false;
- input.wrapper.style.cssText = oldWrapperCSS;
- te.style.cssText = oldCSS;
- if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
- // Try to detect the user choosing select-all
- if (te.selectionStart != null) {
- if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
- var i = 0, poll = function () {
- if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
- te.selectionEnd > 0 && input.prevInput == "\u200b") {
- operation(cm, selectAll)(cm);
- } else if (i++ < 10) {
- display.detectingSelectAll = setTimeout(poll, 500);
- } else {
- display.selForContextMenu = null;
- display.input.reset();
- }
- };
- display.detectingSelectAll = setTimeout(poll, 200);
- }
- }
- if (ie && ie_version >= 9) { prepareSelectAllHack(); }
- if (captureRightClick) {
- e_stop(e);
- var mouseup = function () {
- off(window, "mouseup", mouseup);
- setTimeout(rehide, 20);
- };
- on(window, "mouseup", mouseup);
- } else {
- setTimeout(rehide, 50);
- }
- };
- TextareaInput.prototype.readOnlyChanged = function (val) {
- if (!val) { this.reset(); }
- this.textarea.disabled = val == "nocursor";
- };
- TextareaInput.prototype.setUneditable = function () {};
- TextareaInput.prototype.needsContentAttribute = false;
- function fromTextArea(textarea, options) {
- options = options ? copyObj(options) : {};
- options.value = textarea.value;
- if (!options.tabindex && textarea.tabIndex)
- { options.tabindex = textarea.tabIndex; }
- if (!options.placeholder && textarea.placeholder)
- { options.placeholder = textarea.placeholder; }
- // Set autofocus to true if this textarea is focused, or if it has
- // autofocus and no other element is focused.
- if (options.autofocus == null) {
- var hasFocus = activeElt();
- options.autofocus = hasFocus == textarea ||
- textarea.getAttribute("autofocus") != null && hasFocus == document.body;
- }
- function save() {textarea.value = cm.getValue();}
- var realSubmit;
- if (textarea.form) {
- on(textarea.form, "submit", save);
- // Deplorable hack to make the submit method do the right thing.
- if (!options.leaveSubmitMethodAlone) {
- var form = textarea.form;
- realSubmit = form.submit;
- try {
- var wrappedSubmit = form.submit = function () {
- save();
- form.submit = realSubmit;
- form.submit();
- form.submit = wrappedSubmit;
- };
- } catch(e) {}
- }
- }
- options.finishInit = function (cm) {
- cm.save = save;
- cm.getTextArea = function () { return textarea; };
- cm.toTextArea = function () {
- cm.toTextArea = isNaN; // Prevent this from being ran twice
- save();
- textarea.parentNode.removeChild(cm.getWrapperElement());
- textarea.style.display = "";
- if (textarea.form) {
- off(textarea.form, "submit", save);
- if (typeof textarea.form.submit == "function")
- { textarea.form.submit = realSubmit; }
- }
- };
- };
- textarea.style.display = "none";
- var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
- options);
- return cm
- }
- function addLegacyProps(CodeMirror) {
- CodeMirror.off = off;
- CodeMirror.on = on;
- CodeMirror.wheelEventPixels = wheelEventPixels;
- CodeMirror.Doc = Doc;
- CodeMirror.splitLines = splitLinesAuto;
- CodeMirror.countColumn = countColumn;
- CodeMirror.findColumn = findColumn;
- CodeMirror.isWordChar = isWordCharBasic;
- CodeMirror.Pass = Pass;
- CodeMirror.signal = signal;
- CodeMirror.Line = Line;
- CodeMirror.changeEnd = changeEnd;
- CodeMirror.scrollbarModel = scrollbarModel;
- CodeMirror.Pos = Pos;
- CodeMirror.cmpPos = cmp;
- CodeMirror.modes = modes;
- CodeMirror.mimeModes = mimeModes;
- CodeMirror.resolveMode = resolveMode;
- CodeMirror.getMode = getMode;
- CodeMirror.modeExtensions = modeExtensions;
- CodeMirror.extendMode = extendMode;
- CodeMirror.copyState = copyState;
- CodeMirror.startState = startState;
- CodeMirror.innerMode = innerMode;
- CodeMirror.commands = commands;
- CodeMirror.keyMap = keyMap;
- CodeMirror.keyName = keyName;
- CodeMirror.isModifierKey = isModifierKey;
- CodeMirror.lookupKey = lookupKey;
- CodeMirror.normalizeKeyMap = normalizeKeyMap;
- CodeMirror.StringStream = StringStream;
- CodeMirror.SharedTextMarker = SharedTextMarker;
- CodeMirror.TextMarker = TextMarker;
- CodeMirror.LineWidget = LineWidget;
- CodeMirror.e_preventDefault = e_preventDefault;
- CodeMirror.e_stopPropagation = e_stopPropagation;
- CodeMirror.e_stop = e_stop;
- CodeMirror.addClass = addClass;
- CodeMirror.contains = contains;
- CodeMirror.rmClass = rmClass;
- CodeMirror.keyNames = keyNames;
- }
- // EDITOR CONSTRUCTOR
- defineOptions(CodeMirror);
- addEditorMethods(CodeMirror);
- // Set up methods on CodeMirror's prototype to redirect to the editor's document.
- var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
- for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
- { CodeMirror.prototype[prop] = (function(method) {
- return function() {return method.apply(this.doc, arguments)}
- })(Doc.prototype[prop]); } }
- eventMixin(Doc);
- CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
- // Extra arguments are stored as the mode's dependencies, which is
- // used by (legacy) mechanisms like loadmode.js to automatically
- // load a mode. (Preferred mechanism is the require/define calls.)
- CodeMirror.defineMode = function(name/*, mode, …*/) {
- if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
- defineMode.apply(this, arguments);
- };
- CodeMirror.defineMIME = defineMIME;
- // Minimal default mode.
- CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
- CodeMirror.defineMIME("text/plain", "null");
- // EXTENSIONS
- CodeMirror.defineExtension = function (name, func) {
- CodeMirror.prototype[name] = func;
- };
- CodeMirror.defineDocExtension = function (name, func) {
- Doc.prototype[name] = func;
- };
- CodeMirror.fromTextArea = fromTextArea;
- addLegacyProps(CodeMirror);
- CodeMirror.version = "5.47.0";
- return CodeMirror;
- })));
- },{}],17:[function(require,module,exports){
- "use strict";
- var deselectCurrent = require("toggle-selection");
- var defaultMessage = "Copy to clipboard: #{key}, Enter";
- function format(message) {
- var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C";
- return message.replace(/#{\s*key\s*}/g, copyKey);
- }
- function copy(text, options) {
- var debug,
- message,
- reselectPrevious,
- range,
- selection,
- mark,
- success = false;
- if (!options) {
- options = {};
- }
- debug = options.debug || false;
- try {
- reselectPrevious = deselectCurrent();
- range = document.createRange();
- selection = document.getSelection();
- mark = document.createElement("span");
- mark.textContent = text;
- // reset user styles for span element
- mark.style.all = "unset";
- // prevents scrolling to the end of the page
- mark.style.position = "fixed";
- mark.style.top = 0;
- mark.style.clip = "rect(0, 0, 0, 0)";
- // used to preserve spaces and line breaks
- mark.style.whiteSpace = "pre";
- // do not inherit user-select (it may be `none`)
- mark.style.webkitUserSelect = "text";
- mark.style.MozUserSelect = "text";
- mark.style.msUserSelect = "text";
- mark.style.userSelect = "text";
- mark.addEventListener("copy", function(e) {
- e.stopPropagation();
- if (options.format) {
- e.preventDefault();
- e.clipboardData.clearData();
- e.clipboardData.setData(options.format, text);
- }
- });
- document.body.appendChild(mark);
- range.selectNodeContents(mark);
- selection.addRange(range);
- var successful = document.execCommand("copy");
- if (!successful) {
- throw new Error("copy command was unsuccessful");
- }
- success = true;
- } catch (err) {
- debug && console.error("unable to copy using execCommand: ", err);
- debug && console.warn("trying IE specific stuff");
- try {
- window.clipboardData.setData(options.format || "text", text);
- success = true;
- } catch (err) {
- debug && console.error("unable to copy using clipboardData: ", err);
- debug && console.error("falling back to prompt");
- message = format("message" in options ? options.message : defaultMessage);
- window.prompt(message, text);
- }
- } finally {
- if (selection) {
- if (typeof selection.removeRange == "function") {
- selection.removeRange(range);
- } else {
- selection.removeAllRanges();
- }
- }
- if (mark) {
- document.body.removeChild(mark);
- }
- reselectPrevious();
- }
- return success;
- }
- module.exports = copy;
- },{"toggle-selection":207}],18:[function(require,module,exports){
- module.exports={"Aacute":"\u00C1","aacute":"\u00E1","Abreve":"\u0102","abreve":"\u0103","ac":"\u223E","acd":"\u223F","acE":"\u223E\u0333","Acirc":"\u00C2","acirc":"\u00E2","acute":"\u00B4","Acy":"\u0410","acy":"\u0430","AElig":"\u00C6","aelig":"\u00E6","af":"\u2061","Afr":"\uD835\uDD04","afr":"\uD835\uDD1E","Agrave":"\u00C0","agrave":"\u00E0","alefsym":"\u2135","aleph":"\u2135","Alpha":"\u0391","alpha":"\u03B1","Amacr":"\u0100","amacr":"\u0101","amalg":"\u2A3F","amp":"&","AMP":"&","andand":"\u2A55","And":"\u2A53","and":"\u2227","andd":"\u2A5C","andslope":"\u2A58","andv":"\u2A5A","ang":"\u2220","ange":"\u29A4","angle":"\u2220","angmsdaa":"\u29A8","angmsdab":"\u29A9","angmsdac":"\u29AA","angmsdad":"\u29AB","angmsdae":"\u29AC","angmsdaf":"\u29AD","angmsdag":"\u29AE","angmsdah":"\u29AF","angmsd":"\u2221","angrt":"\u221F","angrtvb":"\u22BE","angrtvbd":"\u299D","angsph":"\u2222","angst":"\u00C5","angzarr":"\u237C","Aogon":"\u0104","aogon":"\u0105","Aopf":"\uD835\uDD38","aopf":"\uD835\uDD52","apacir":"\u2A6F","ap":"\u2248","apE":"\u2A70","ape":"\u224A","apid":"\u224B","apos":"'","ApplyFunction":"\u2061","approx":"\u2248","approxeq":"\u224A","Aring":"\u00C5","aring":"\u00E5","Ascr":"\uD835\uDC9C","ascr":"\uD835\uDCB6","Assign":"\u2254","ast":"*","asymp":"\u2248","asympeq":"\u224D","Atilde":"\u00C3","atilde":"\u00E3","Auml":"\u00C4","auml":"\u00E4","awconint":"\u2233","awint":"\u2A11","backcong":"\u224C","backepsilon":"\u03F6","backprime":"\u2035","backsim":"\u223D","backsimeq":"\u22CD","Backslash":"\u2216","Barv":"\u2AE7","barvee":"\u22BD","barwed":"\u2305","Barwed":"\u2306","barwedge":"\u2305","bbrk":"\u23B5","bbrktbrk":"\u23B6","bcong":"\u224C","Bcy":"\u0411","bcy":"\u0431","bdquo":"\u201E","becaus":"\u2235","because":"\u2235","Because":"\u2235","bemptyv":"\u29B0","bepsi":"\u03F6","bernou":"\u212C","Bernoullis":"\u212C","Beta":"\u0392","beta":"\u03B2","beth":"\u2136","between":"\u226C","Bfr":"\uD835\uDD05","bfr":"\uD835\uDD1F","bigcap":"\u22C2","bigcirc":"\u25EF","bigcup":"\u22C3","bigodot":"\u2A00","bigoplus":"\u2A01","bigotimes":"\u2A02","bigsqcup":"\u2A06","bigstar":"\u2605","bigtriangledown":"\u25BD","bigtriangleup":"\u25B3","biguplus":"\u2A04","bigvee":"\u22C1","bigwedge":"\u22C0","bkarow":"\u290D","blacklozenge":"\u29EB","blacksquare":"\u25AA","blacktriangle":"\u25B4","blacktriangledown":"\u25BE","blacktriangleleft":"\u25C2","blacktriangleright":"\u25B8","blank":"\u2423","blk12":"\u2592","blk14":"\u2591","blk34":"\u2593","block":"\u2588","bne":"=\u20E5","bnequiv":"\u2261\u20E5","bNot":"\u2AED","bnot":"\u2310","Bopf":"\uD835\uDD39","bopf":"\uD835\uDD53","bot":"\u22A5","bottom":"\u22A5","bowtie":"\u22C8","boxbox":"\u29C9","boxdl":"\u2510","boxdL":"\u2555","boxDl":"\u2556","boxDL":"\u2557","boxdr":"\u250C","boxdR":"\u2552","boxDr":"\u2553","boxDR":"\u2554","boxh":"\u2500","boxH":"\u2550","boxhd":"\u252C","boxHd":"\u2564","boxhD":"\u2565","boxHD":"\u2566","boxhu":"\u2534","boxHu":"\u2567","boxhU":"\u2568","boxHU":"\u2569","boxminus":"\u229F","boxplus":"\u229E","boxtimes":"\u22A0","boxul":"\u2518","boxuL":"\u255B","boxUl":"\u255C","boxUL":"\u255D","boxur":"\u2514","boxuR":"\u2558","boxUr":"\u2559","boxUR":"\u255A","boxv":"\u2502","boxV":"\u2551","boxvh":"\u253C","boxvH":"\u256A","boxVh":"\u256B","boxVH":"\u256C","boxvl":"\u2524","boxvL":"\u2561","boxVl":"\u2562","boxVL":"\u2563","boxvr":"\u251C","boxvR":"\u255E","boxVr":"\u255F","boxVR":"\u2560","bprime":"\u2035","breve":"\u02D8","Breve":"\u02D8","brvbar":"\u00A6","bscr":"\uD835\uDCB7","Bscr":"\u212C","bsemi":"\u204F","bsim":"\u223D","bsime":"\u22CD","bsolb":"\u29C5","bsol":"\\","bsolhsub":"\u27C8","bull":"\u2022","bullet":"\u2022","bump":"\u224E","bumpE":"\u2AAE","bumpe":"\u224F","Bumpeq":"\u224E","bumpeq":"\u224F","Cacute":"\u0106","cacute":"\u0107","capand":"\u2A44","capbrcup":"\u2A49","capcap":"\u2A4B","cap":"\u2229","Cap":"\u22D2","capcup":"\u2A47","capdot":"\u2A40","CapitalDifferentialD":"\u2145","caps":"\u2229\uFE00","caret":"\u2041","caron":"\u02C7","Cayleys":"\u212D","ccaps":"\u2A4D","Ccaron":"\u010C","ccaron":"\u010D","Ccedil":"\u00C7","ccedil":"\u00E7","Ccirc":"\u0108","ccirc":"\u0109","Cconint":"\u2230","ccups":"\u2A4C","ccupssm":"\u2A50","Cdot":"\u010A","cdot":"\u010B","cedil":"\u00B8","Cedilla":"\u00B8","cemptyv":"\u29B2","cent":"\u00A2","centerdot":"\u00B7","CenterDot":"\u00B7","cfr":"\uD835\uDD20","Cfr":"\u212D","CHcy":"\u0427","chcy":"\u0447","check":"\u2713","checkmark":"\u2713","Chi":"\u03A7","chi":"\u03C7","circ":"\u02C6","circeq":"\u2257","circlearrowleft":"\u21BA","circlearrowright":"\u21BB","circledast":"\u229B","circledcirc":"\u229A","circleddash":"\u229D","CircleDot":"\u2299","circledR":"\u00AE","circledS":"\u24C8","CircleMinus":"\u2296","CirclePlus":"\u2295","CircleTimes":"\u2297","cir":"\u25CB","cirE":"\u29C3","cire":"\u2257","cirfnint":"\u2A10","cirmid":"\u2AEF","cirscir":"\u29C2","ClockwiseContourIntegral":"\u2232","CloseCurlyDoubleQuote":"\u201D","CloseCurlyQuote":"\u2019","clubs":"\u2663","clubsuit":"\u2663","colon":":","Colon":"\u2237","Colone":"\u2A74","colone":"\u2254","coloneq":"\u2254","comma":",","commat":"@","comp":"\u2201","compfn":"\u2218","complement":"\u2201","complexes":"\u2102","cong":"\u2245","congdot":"\u2A6D","Congruent":"\u2261","conint":"\u222E","Conint":"\u222F","ContourIntegral":"\u222E","copf":"\uD835\uDD54","Copf":"\u2102","coprod":"\u2210","Coproduct":"\u2210","copy":"\u00A9","COPY":"\u00A9","copysr":"\u2117","CounterClockwiseContourIntegral":"\u2233","crarr":"\u21B5","cross":"\u2717","Cross":"\u2A2F","Cscr":"\uD835\uDC9E","cscr":"\uD835\uDCB8","csub":"\u2ACF","csube":"\u2AD1","csup":"\u2AD0","csupe":"\u2AD2","ctdot":"\u22EF","cudarrl":"\u2938","cudarrr":"\u2935","cuepr":"\u22DE","cuesc":"\u22DF","cularr":"\u21B6","cularrp":"\u293D","cupbrcap":"\u2A48","cupcap":"\u2A46","CupCap":"\u224D","cup":"\u222A","Cup":"\u22D3","cupcup":"\u2A4A","cupdot":"\u228D","cupor":"\u2A45","cups":"\u222A\uFE00","curarr":"\u21B7","curarrm":"\u293C","curlyeqprec":"\u22DE","curlyeqsucc":"\u22DF","curlyvee":"\u22CE","curlywedge":"\u22CF","curren":"\u00A4","curvearrowleft":"\u21B6","curvearrowright":"\u21B7","cuvee":"\u22CE","cuwed":"\u22CF","cwconint":"\u2232","cwint":"\u2231","cylcty":"\u232D","dagger":"\u2020","Dagger":"\u2021","daleth":"\u2138","darr":"\u2193","Darr":"\u21A1","dArr":"\u21D3","dash":"\u2010","Dashv":"\u2AE4","dashv":"\u22A3","dbkarow":"\u290F","dblac":"\u02DD","Dcaron":"\u010E","dcaron":"\u010F","Dcy":"\u0414","dcy":"\u0434","ddagger":"\u2021","ddarr":"\u21CA","DD":"\u2145","dd":"\u2146","DDotrahd":"\u2911","ddotseq":"\u2A77","deg":"\u00B0","Del":"\u2207","Delta":"\u0394","delta":"\u03B4","demptyv":"\u29B1","dfisht":"\u297F","Dfr":"\uD835\uDD07","dfr":"\uD835\uDD21","dHar":"\u2965","dharl":"\u21C3","dharr":"\u21C2","DiacriticalAcute":"\u00B4","DiacriticalDot":"\u02D9","DiacriticalDoubleAcute":"\u02DD","DiacriticalGrave":"`","DiacriticalTilde":"\u02DC","diam":"\u22C4","diamond":"\u22C4","Diamond":"\u22C4","diamondsuit":"\u2666","diams":"\u2666","die":"\u00A8","DifferentialD":"\u2146","digamma":"\u03DD","disin":"\u22F2","div":"\u00F7","divide":"\u00F7","divideontimes":"\u22C7","divonx":"\u22C7","DJcy":"\u0402","djcy":"\u0452","dlcorn":"\u231E","dlcrop":"\u230D","dollar":"$","Dopf":"\uD835\uDD3B","dopf":"\uD835\uDD55","Dot":"\u00A8","dot":"\u02D9","DotDot":"\u20DC","doteq":"\u2250","doteqdot":"\u2251","DotEqual":"\u2250","dotminus":"\u2238","dotplus":"\u2214","dotsquare":"\u22A1","doublebarwedge":"\u2306","DoubleContourIntegral":"\u222F","DoubleDot":"\u00A8","DoubleDownArrow":"\u21D3","DoubleLeftArrow":"\u21D0","DoubleLeftRightArrow":"\u21D4","DoubleLeftTee":"\u2AE4","DoubleLongLeftArrow":"\u27F8","DoubleLongLeftRightArrow":"\u27FA","DoubleLongRightArrow":"\u27F9","DoubleRightArrow":"\u21D2","DoubleRightTee":"\u22A8","DoubleUpArrow":"\u21D1","DoubleUpDownArrow":"\u21D5","DoubleVerticalBar":"\u2225","DownArrowBar":"\u2913","downarrow":"\u2193","DownArrow":"\u2193","Downarrow":"\u21D3","DownArrowUpArrow":"\u21F5","DownBreve":"\u0311","downdownarrows":"\u21CA","downharpoonleft":"\u21C3","downharpoonright":"\u21C2","DownLeftRightVector":"\u2950","DownLeftTeeVector":"\u295E","DownLeftVectorBar":"\u2956","DownLeftVector":"\u21BD","DownRightTeeVector":"\u295F","DownRightVectorBar":"\u2957","DownRightVector":"\u21C1","DownTeeArrow":"\u21A7","DownTee":"\u22A4","drbkarow":"\u2910","drcorn":"\u231F","drcrop":"\u230C","Dscr":"\uD835\uDC9F","dscr":"\uD835\uDCB9","DScy":"\u0405","dscy":"\u0455","dsol":"\u29F6","Dstrok":"\u0110","dstrok":"\u0111","dtdot":"\u22F1","dtri":"\u25BF","dtrif":"\u25BE","duarr":"\u21F5","duhar":"\u296F","dwangle":"\u29A6","DZcy":"\u040F","dzcy":"\u045F","dzigrarr":"\u27FF","Eacute":"\u00C9","eacute":"\u00E9","easter":"\u2A6E","Ecaron":"\u011A","ecaron":"\u011B","Ecirc":"\u00CA","ecirc":"\u00EA","ecir":"\u2256","ecolon":"\u2255","Ecy":"\u042D","ecy":"\u044D","eDDot":"\u2A77","Edot":"\u0116","edot":"\u0117","eDot":"\u2251","ee":"\u2147","efDot":"\u2252","Efr":"\uD835\uDD08","efr":"\uD835\uDD22","eg":"\u2A9A","Egrave":"\u00C8","egrave":"\u00E8","egs":"\u2A96","egsdot":"\u2A98","el":"\u2A99","Element":"\u2208","elinters":"\u23E7","ell":"\u2113","els":"\u2A95","elsdot":"\u2A97","Emacr":"\u0112","emacr":"\u0113","empty":"\u2205","emptyset":"\u2205","EmptySmallSquare":"\u25FB","emptyv":"\u2205","EmptyVerySmallSquare":"\u25AB","emsp13":"\u2004","emsp14":"\u2005","emsp":"\u2003","ENG":"\u014A","eng":"\u014B","ensp":"\u2002","Eogon":"\u0118","eogon":"\u0119","Eopf":"\uD835\uDD3C","eopf":"\uD835\uDD56","epar":"\u22D5","eparsl":"\u29E3","eplus":"\u2A71","epsi":"\u03B5","Epsilon":"\u0395","epsilon":"\u03B5","epsiv":"\u03F5","eqcirc":"\u2256","eqcolon":"\u2255","eqsim":"\u2242","eqslantgtr":"\u2A96","eqslantless":"\u2A95","Equal":"\u2A75","equals":"=","EqualTilde":"\u2242","equest":"\u225F","Equilibrium":"\u21CC","equiv":"\u2261","equivDD":"\u2A78","eqvparsl":"\u29E5","erarr":"\u2971","erDot":"\u2253","escr":"\u212F","Escr":"\u2130","esdot":"\u2250","Esim":"\u2A73","esim":"\u2242","Eta":"\u0397","eta":"\u03B7","ETH":"\u00D0","eth":"\u00F0","Euml":"\u00CB","euml":"\u00EB","euro":"\u20AC","excl":"!","exist":"\u2203","Exists":"\u2203","expectation":"\u2130","exponentiale":"\u2147","ExponentialE":"\u2147","fallingdotseq":"\u2252","Fcy":"\u0424","fcy":"\u0444","female":"\u2640","ffilig":"\uFB03","fflig":"\uFB00","ffllig":"\uFB04","Ffr":"\uD835\uDD09","ffr":"\uD835\uDD23","filig":"\uFB01","FilledSmallSquare":"\u25FC","FilledVerySmallSquare":"\u25AA","fjlig":"fj","flat":"\u266D","fllig":"\uFB02","fltns":"\u25B1","fnof":"\u0192","Fopf":"\uD835\uDD3D","fopf":"\uD835\uDD57","forall":"\u2200","ForAll":"\u2200","fork":"\u22D4","forkv":"\u2AD9","Fouriertrf":"\u2131","fpartint":"\u2A0D","frac12":"\u00BD","frac13":"\u2153","frac14":"\u00BC","frac15":"\u2155","frac16":"\u2159","frac18":"\u215B","frac23":"\u2154","frac25":"\u2156","frac34":"\u00BE","frac35":"\u2157","frac38":"\u215C","frac45":"\u2158","frac56":"\u215A","frac58":"\u215D","frac78":"\u215E","frasl":"\u2044","frown":"\u2322","fscr":"\uD835\uDCBB","Fscr":"\u2131","gacute":"\u01F5","Gamma":"\u0393","gamma":"\u03B3","Gammad":"\u03DC","gammad":"\u03DD","gap":"\u2A86","Gbreve":"\u011E","gbreve":"\u011F","Gcedil":"\u0122","Gcirc":"\u011C","gcirc":"\u011D","Gcy":"\u0413","gcy":"\u0433","Gdot":"\u0120","gdot":"\u0121","ge":"\u2265","gE":"\u2267","gEl":"\u2A8C","gel":"\u22DB","geq":"\u2265","geqq":"\u2267","geqslant":"\u2A7E","gescc":"\u2AA9","ges":"\u2A7E","gesdot":"\u2A80","gesdoto":"\u2A82","gesdotol":"\u2A84","gesl":"\u22DB\uFE00","gesles":"\u2A94","Gfr":"\uD835\uDD0A","gfr":"\uD835\uDD24","gg":"\u226B","Gg":"\u22D9","ggg":"\u22D9","gimel":"\u2137","GJcy":"\u0403","gjcy":"\u0453","gla":"\u2AA5","gl":"\u2277","glE":"\u2A92","glj":"\u2AA4","gnap":"\u2A8A","gnapprox":"\u2A8A","gne":"\u2A88","gnE":"\u2269","gneq":"\u2A88","gneqq":"\u2269","gnsim":"\u22E7","Gopf":"\uD835\uDD3E","gopf":"\uD835\uDD58","grave":"`","GreaterEqual":"\u2265","GreaterEqualLess":"\u22DB","GreaterFullEqual":"\u2267","GreaterGreater":"\u2AA2","GreaterLess":"\u2277","GreaterSlantEqual":"\u2A7E","GreaterTilde":"\u2273","Gscr":"\uD835\uDCA2","gscr":"\u210A","gsim":"\u2273","gsime":"\u2A8E","gsiml":"\u2A90","gtcc":"\u2AA7","gtcir":"\u2A7A","gt":">","GT":">","Gt":"\u226B","gtdot":"\u22D7","gtlPar":"\u2995","gtquest":"\u2A7C","gtrapprox":"\u2A86","gtrarr":"\u2978","gtrdot":"\u22D7","gtreqless":"\u22DB","gtreqqless":"\u2A8C","gtrless":"\u2277","gtrsim":"\u2273","gvertneqq":"\u2269\uFE00","gvnE":"\u2269\uFE00","Hacek":"\u02C7","hairsp":"\u200A","half":"\u00BD","hamilt":"\u210B","HARDcy":"\u042A","hardcy":"\u044A","harrcir":"\u2948","harr":"\u2194","hArr":"\u21D4","harrw":"\u21AD","Hat":"^","hbar":"\u210F","Hcirc":"\u0124","hcirc":"\u0125","hearts":"\u2665","heartsuit":"\u2665","hellip":"\u2026","hercon":"\u22B9","hfr":"\uD835\uDD25","Hfr":"\u210C","HilbertSpace":"\u210B","hksearow":"\u2925","hkswarow":"\u2926","hoarr":"\u21FF","homtht":"\u223B","hookleftarrow":"\u21A9","hookrightarrow":"\u21AA","hopf":"\uD835\uDD59","Hopf":"\u210D","horbar":"\u2015","HorizontalLine":"\u2500","hscr":"\uD835\uDCBD","Hscr":"\u210B","hslash":"\u210F","Hstrok":"\u0126","hstrok":"\u0127","HumpDownHump":"\u224E","HumpEqual":"\u224F","hybull":"\u2043","hyphen":"\u2010","Iacute":"\u00CD","iacute":"\u00ED","ic":"\u2063","Icirc":"\u00CE","icirc":"\u00EE","Icy":"\u0418","icy":"\u0438","Idot":"\u0130","IEcy":"\u0415","iecy":"\u0435","iexcl":"\u00A1","iff":"\u21D4","ifr":"\uD835\uDD26","Ifr":"\u2111","Igrave":"\u00CC","igrave":"\u00EC","ii":"\u2148","iiiint":"\u2A0C","iiint":"\u222D","iinfin":"\u29DC","iiota":"\u2129","IJlig":"\u0132","ijlig":"\u0133","Imacr":"\u012A","imacr":"\u012B","image":"\u2111","ImaginaryI":"\u2148","imagline":"\u2110","imagpart":"\u2111","imath":"\u0131","Im":"\u2111","imof":"\u22B7","imped":"\u01B5","Implies":"\u21D2","incare":"\u2105","in":"\u2208","infin":"\u221E","infintie":"\u29DD","inodot":"\u0131","intcal":"\u22BA","int":"\u222B","Int":"\u222C","integers":"\u2124","Integral":"\u222B","intercal":"\u22BA","Intersection":"\u22C2","intlarhk":"\u2A17","intprod":"\u2A3C","InvisibleComma":"\u2063","InvisibleTimes":"\u2062","IOcy":"\u0401","iocy":"\u0451","Iogon":"\u012E","iogon":"\u012F","Iopf":"\uD835\uDD40","iopf":"\uD835\uDD5A","Iota":"\u0399","iota":"\u03B9","iprod":"\u2A3C","iquest":"\u00BF","iscr":"\uD835\uDCBE","Iscr":"\u2110","isin":"\u2208","isindot":"\u22F5","isinE":"\u22F9","isins":"\u22F4","isinsv":"\u22F3","isinv":"\u2208","it":"\u2062","Itilde":"\u0128","itilde":"\u0129","Iukcy":"\u0406","iukcy":"\u0456","Iuml":"\u00CF","iuml":"\u00EF","Jcirc":"\u0134","jcirc":"\u0135","Jcy":"\u0419","jcy":"\u0439","Jfr":"\uD835\uDD0D","jfr":"\uD835\uDD27","jmath":"\u0237","Jopf":"\uD835\uDD41","jopf":"\uD835\uDD5B","Jscr":"\uD835\uDCA5","jscr":"\uD835\uDCBF","Jsercy":"\u0408","jsercy":"\u0458","Jukcy":"\u0404","jukcy":"\u0454","Kappa":"\u039A","kappa":"\u03BA","kappav":"\u03F0","Kcedil":"\u0136","kcedil":"\u0137","Kcy":"\u041A","kcy":"\u043A","Kfr":"\uD835\uDD0E","kfr":"\uD835\uDD28","kgreen":"\u0138","KHcy":"\u0425","khcy":"\u0445","KJcy":"\u040C","kjcy":"\u045C","Kopf":"\uD835\uDD42","kopf":"\uD835\uDD5C","Kscr":"\uD835\uDCA6","kscr":"\uD835\uDCC0","lAarr":"\u21DA","Lacute":"\u0139","lacute":"\u013A","laemptyv":"\u29B4","lagran":"\u2112","Lambda":"\u039B","lambda":"\u03BB","lang":"\u27E8","Lang":"\u27EA","langd":"\u2991","langle":"\u27E8","lap":"\u2A85","Laplacetrf":"\u2112","laquo":"\u00AB","larrb":"\u21E4","larrbfs":"\u291F","larr":"\u2190","Larr":"\u219E","lArr":"\u21D0","larrfs":"\u291D","larrhk":"\u21A9","larrlp":"\u21AB","larrpl":"\u2939","larrsim":"\u2973","larrtl":"\u21A2","latail":"\u2919","lAtail":"\u291B","lat":"\u2AAB","late":"\u2AAD","lates":"\u2AAD\uFE00","lbarr":"\u290C","lBarr":"\u290E","lbbrk":"\u2772","lbrace":"{","lbrack":"[","lbrke":"\u298B","lbrksld":"\u298F","lbrkslu":"\u298D","Lcaron":"\u013D","lcaron":"\u013E","Lcedil":"\u013B","lcedil":"\u013C","lceil":"\u2308","lcub":"{","Lcy":"\u041B","lcy":"\u043B","ldca":"\u2936","ldquo":"\u201C","ldquor":"\u201E","ldrdhar":"\u2967","ldrushar":"\u294B","ldsh":"\u21B2","le":"\u2264","lE":"\u2266","LeftAngleBracket":"\u27E8","LeftArrowBar":"\u21E4","leftarrow":"\u2190","LeftArrow":"\u2190","Leftarrow":"\u21D0","LeftArrowRightArrow":"\u21C6","leftarrowtail":"\u21A2","LeftCeiling":"\u2308","LeftDoubleBracket":"\u27E6","LeftDownTeeVector":"\u2961","LeftDownVectorBar":"\u2959","LeftDownVector":"\u21C3","LeftFloor":"\u230A","leftharpoondown":"\u21BD","leftharpoonup":"\u21BC","leftleftarrows":"\u21C7","leftrightarrow":"\u2194","LeftRightArrow":"\u2194","Leftrightarrow":"\u21D4","leftrightarrows":"\u21C6","leftrightharpoons":"\u21CB","leftrightsquigarrow":"\u21AD","LeftRightVector":"\u294E","LeftTeeArrow":"\u21A4","LeftTee":"\u22A3","LeftTeeVector":"\u295A","leftthreetimes":"\u22CB","LeftTriangleBar":"\u29CF","LeftTriangle":"\u22B2","LeftTriangleEqual":"\u22B4","LeftUpDownVector":"\u2951","LeftUpTeeVector":"\u2960","LeftUpVectorBar":"\u2958","LeftUpVector":"\u21BF","LeftVectorBar":"\u2952","LeftVector":"\u21BC","lEg":"\u2A8B","leg":"\u22DA","leq":"\u2264","leqq":"\u2266","leqslant":"\u2A7D","lescc":"\u2AA8","les":"\u2A7D","lesdot":"\u2A7F","lesdoto":"\u2A81","lesdotor":"\u2A83","lesg":"\u22DA\uFE00","lesges":"\u2A93","lessapprox":"\u2A85","lessdot":"\u22D6","lesseqgtr":"\u22DA","lesseqqgtr":"\u2A8B","LessEqualGreater":"\u22DA","LessFullEqual":"\u2266","LessGreater":"\u2276","lessgtr":"\u2276","LessLess":"\u2AA1","lesssim":"\u2272","LessSlantEqual":"\u2A7D","LessTilde":"\u2272","lfisht":"\u297C","lfloor":"\u230A","Lfr":"\uD835\uDD0F","lfr":"\uD835\uDD29","lg":"\u2276","lgE":"\u2A91","lHar":"\u2962","lhard":"\u21BD","lharu":"\u21BC","lharul":"\u296A","lhblk":"\u2584","LJcy":"\u0409","ljcy":"\u0459","llarr":"\u21C7","ll":"\u226A","Ll":"\u22D8","llcorner":"\u231E","Lleftarrow":"\u21DA","llhard":"\u296B","lltri":"\u25FA","Lmidot":"\u013F","lmidot":"\u0140","lmoustache":"\u23B0","lmoust":"\u23B0","lnap":"\u2A89","lnapprox":"\u2A89","lne":"\u2A87","lnE":"\u2268","lneq":"\u2A87","lneqq":"\u2268","lnsim":"\u22E6","loang":"\u27EC","loarr":"\u21FD","lobrk":"\u27E6","longleftarrow":"\u27F5","LongLeftArrow":"\u27F5","Longleftarrow":"\u27F8","longleftrightarrow":"\u27F7","LongLeftRightArrow":"\u27F7","Longleftrightarrow":"\u27FA","longmapsto":"\u27FC","longrightarrow":"\u27F6","LongRightArrow":"\u27F6","Longrightarrow":"\u27F9","looparrowleft":"\u21AB","looparrowright":"\u21AC","lopar":"\u2985","Lopf":"\uD835\uDD43","lopf":"\uD835\uDD5D","loplus":"\u2A2D","lotimes":"\u2A34","lowast":"\u2217","lowbar":"_","LowerLeftArrow":"\u2199","LowerRightArrow":"\u2198","loz":"\u25CA","lozenge":"\u25CA","lozf":"\u29EB","lpar":"(","lparlt":"\u2993","lrarr":"\u21C6","lrcorner":"\u231F","lrhar":"\u21CB","lrhard":"\u296D","lrm":"\u200E","lrtri":"\u22BF","lsaquo":"\u2039","lscr":"\uD835\uDCC1","Lscr":"\u2112","lsh":"\u21B0","Lsh":"\u21B0","lsim":"\u2272","lsime":"\u2A8D","lsimg":"\u2A8F","lsqb":"[","lsquo":"\u2018","lsquor":"\u201A","Lstrok":"\u0141","lstrok":"\u0142","ltcc":"\u2AA6","ltcir":"\u2A79","lt":"<","LT":"<","Lt":"\u226A","ltdot":"\u22D6","lthree":"\u22CB","ltimes":"\u22C9","ltlarr":"\u2976","ltquest":"\u2A7B","ltri":"\u25C3","ltrie":"\u22B4","ltrif":"\u25C2","ltrPar":"\u2996","lurdshar":"\u294A","luruhar":"\u2966","lvertneqq":"\u2268\uFE00","lvnE":"\u2268\uFE00","macr":"\u00AF","male":"\u2642","malt":"\u2720","maltese":"\u2720","Map":"\u2905","map":"\u21A6","mapsto":"\u21A6","mapstodown":"\u21A7","mapstoleft":"\u21A4","mapstoup":"\u21A5","marker":"\u25AE","mcomma":"\u2A29","Mcy":"\u041C","mcy":"\u043C","mdash":"\u2014","mDDot":"\u223A","measuredangle":"\u2221","MediumSpace":"\u205F","Mellintrf":"\u2133","Mfr":"\uD835\uDD10","mfr":"\uD835\uDD2A","mho":"\u2127","micro":"\u00B5","midast":"*","midcir":"\u2AF0","mid":"\u2223","middot":"\u00B7","minusb":"\u229F","minus":"\u2212","minusd":"\u2238","minusdu":"\u2A2A","MinusPlus":"\u2213","mlcp":"\u2ADB","mldr":"\u2026","mnplus":"\u2213","models":"\u22A7","Mopf":"\uD835\uDD44","mopf":"\uD835\uDD5E","mp":"\u2213","mscr":"\uD835\uDCC2","Mscr":"\u2133","mstpos":"\u223E","Mu":"\u039C","mu":"\u03BC","multimap":"\u22B8","mumap":"\u22B8","nabla":"\u2207","Nacute":"\u0143","nacute":"\u0144","nang":"\u2220\u20D2","nap":"\u2249","napE":"\u2A70\u0338","napid":"\u224B\u0338","napos":"\u0149","napprox":"\u2249","natural":"\u266E","naturals":"\u2115","natur":"\u266E","nbsp":"\u00A0","nbump":"\u224E\u0338","nbumpe":"\u224F\u0338","ncap":"\u2A43","Ncaron":"\u0147","ncaron":"\u0148","Ncedil":"\u0145","ncedil":"\u0146","ncong":"\u2247","ncongdot":"\u2A6D\u0338","ncup":"\u2A42","Ncy":"\u041D","ncy":"\u043D","ndash":"\u2013","nearhk":"\u2924","nearr":"\u2197","neArr":"\u21D7","nearrow":"\u2197","ne":"\u2260","nedot":"\u2250\u0338","NegativeMediumSpace":"\u200B","NegativeThickSpace":"\u200B","NegativeThinSpace":"\u200B","NegativeVeryThinSpace":"\u200B","nequiv":"\u2262","nesear":"\u2928","nesim":"\u2242\u0338","NestedGreaterGreater":"\u226B","NestedLessLess":"\u226A","NewLine":"\n","nexist":"\u2204","nexists":"\u2204","Nfr":"\uD835\uDD11","nfr":"\uD835\uDD2B","ngE":"\u2267\u0338","nge":"\u2271","ngeq":"\u2271","ngeqq":"\u2267\u0338","ngeqslant":"\u2A7E\u0338","nges":"\u2A7E\u0338","nGg":"\u22D9\u0338","ngsim":"\u2275","nGt":"\u226B\u20D2","ngt":"\u226F","ngtr":"\u226F","nGtv":"\u226B\u0338","nharr":"\u21AE","nhArr":"\u21CE","nhpar":"\u2AF2","ni":"\u220B","nis":"\u22FC","nisd":"\u22FA","niv":"\u220B","NJcy":"\u040A","njcy":"\u045A","nlarr":"\u219A","nlArr":"\u21CD","nldr":"\u2025","nlE":"\u2266\u0338","nle":"\u2270","nleftarrow":"\u219A","nLeftarrow":"\u21CD","nleftrightarrow":"\u21AE","nLeftrightarrow":"\u21CE","nleq":"\u2270","nleqq":"\u2266\u0338","nleqslant":"\u2A7D\u0338","nles":"\u2A7D\u0338","nless":"\u226E","nLl":"\u22D8\u0338","nlsim":"\u2274","nLt":"\u226A\u20D2","nlt":"\u226E","nltri":"\u22EA","nltrie":"\u22EC","nLtv":"\u226A\u0338","nmid":"\u2224","NoBreak":"\u2060","NonBreakingSpace":"\u00A0","nopf":"\uD835\uDD5F","Nopf":"\u2115","Not":"\u2AEC","not":"\u00AC","NotCongruent":"\u2262","NotCupCap":"\u226D","NotDoubleVerticalBar":"\u2226","NotElement":"\u2209","NotEqual":"\u2260","NotEqualTilde":"\u2242\u0338","NotExists":"\u2204","NotGreater":"\u226F","NotGreaterEqual":"\u2271","NotGreaterFullEqual":"\u2267\u0338","NotGreaterGreater":"\u226B\u0338","NotGreaterLess":"\u2279","NotGreaterSlantEqual":"\u2A7E\u0338","NotGreaterTilde":"\u2275","NotHumpDownHump":"\u224E\u0338","NotHumpEqual":"\u224F\u0338","notin":"\u2209","notindot":"\u22F5\u0338","notinE":"\u22F9\u0338","notinva":"\u2209","notinvb":"\u22F7","notinvc":"\u22F6","NotLeftTriangleBar":"\u29CF\u0338","NotLeftTriangle":"\u22EA","NotLeftTriangleEqual":"\u22EC","NotLess":"\u226E","NotLessEqual":"\u2270","NotLessGreater":"\u2278","NotLessLess":"\u226A\u0338","NotLessSlantEqual":"\u2A7D\u0338","NotLessTilde":"\u2274","NotNestedGreaterGreater":"\u2AA2\u0338","NotNestedLessLess":"\u2AA1\u0338","notni":"\u220C","notniva":"\u220C","notnivb":"\u22FE","notnivc":"\u22FD","NotPrecedes":"\u2280","NotPrecedesEqual":"\u2AAF\u0338","NotPrecedesSlantEqual":"\u22E0","NotReverseElement":"\u220C","NotRightTriangleBar":"\u29D0\u0338","NotRightTriangle":"\u22EB","NotRightTriangleEqual":"\u22ED","NotSquareSubset":"\u228F\u0338","NotSquareSubsetEqual":"\u22E2","NotSquareSuperset":"\u2290\u0338","NotSquareSupersetEqual":"\u22E3","NotSubset":"\u2282\u20D2","NotSubsetEqual":"\u2288","NotSucceeds":"\u2281","NotSucceedsEqual":"\u2AB0\u0338","NotSucceedsSlantEqual":"\u22E1","NotSucceedsTilde":"\u227F\u0338","NotSuperset":"\u2283\u20D2","NotSupersetEqual":"\u2289","NotTilde":"\u2241","NotTildeEqual":"\u2244","NotTildeFullEqual":"\u2247","NotTildeTilde":"\u2249","NotVerticalBar":"\u2224","nparallel":"\u2226","npar":"\u2226","nparsl":"\u2AFD\u20E5","npart":"\u2202\u0338","npolint":"\u2A14","npr":"\u2280","nprcue":"\u22E0","nprec":"\u2280","npreceq":"\u2AAF\u0338","npre":"\u2AAF\u0338","nrarrc":"\u2933\u0338","nrarr":"\u219B","nrArr":"\u21CF","nrarrw":"\u219D\u0338","nrightarrow":"\u219B","nRightarrow":"\u21CF","nrtri":"\u22EB","nrtrie":"\u22ED","nsc":"\u2281","nsccue":"\u22E1","nsce":"\u2AB0\u0338","Nscr":"\uD835\uDCA9","nscr":"\uD835\uDCC3","nshortmid":"\u2224","nshortparallel":"\u2226","nsim":"\u2241","nsime":"\u2244","nsimeq":"\u2244","nsmid":"\u2224","nspar":"\u2226","nsqsube":"\u22E2","nsqsupe":"\u22E3","nsub":"\u2284","nsubE":"\u2AC5\u0338","nsube":"\u2288","nsubset":"\u2282\u20D2","nsubseteq":"\u2288","nsubseteqq":"\u2AC5\u0338","nsucc":"\u2281","nsucceq":"\u2AB0\u0338","nsup":"\u2285","nsupE":"\u2AC6\u0338","nsupe":"\u2289","nsupset":"\u2283\u20D2","nsupseteq":"\u2289","nsupseteqq":"\u2AC6\u0338","ntgl":"\u2279","Ntilde":"\u00D1","ntilde":"\u00F1","ntlg":"\u2278","ntriangleleft":"\u22EA","ntrianglelefteq":"\u22EC","ntriangleright":"\u22EB","ntrianglerighteq":"\u22ED","Nu":"\u039D","nu":"\u03BD","num":"#","numero":"\u2116","numsp":"\u2007","nvap":"\u224D\u20D2","nvdash":"\u22AC","nvDash":"\u22AD","nVdash":"\u22AE","nVDash":"\u22AF","nvge":"\u2265\u20D2","nvgt":">\u20D2","nvHarr":"\u2904","nvinfin":"\u29DE","nvlArr":"\u2902","nvle":"\u2264\u20D2","nvlt":"<\u20D2","nvltrie":"\u22B4\u20D2","nvrArr":"\u2903","nvrtrie":"\u22B5\u20D2","nvsim":"\u223C\u20D2","nwarhk":"\u2923","nwarr":"\u2196","nwArr":"\u21D6","nwarrow":"\u2196","nwnear":"\u2927","Oacute":"\u00D3","oacute":"\u00F3","oast":"\u229B","Ocirc":"\u00D4","ocirc":"\u00F4","ocir":"\u229A","Ocy":"\u041E","ocy":"\u043E","odash":"\u229D","Odblac":"\u0150","odblac":"\u0151","odiv":"\u2A38","odot":"\u2299","odsold":"\u29BC","OElig":"\u0152","oelig":"\u0153","ofcir":"\u29BF","Ofr":"\uD835\uDD12","ofr":"\uD835\uDD2C","ogon":"\u02DB","Ograve":"\u00D2","ograve":"\u00F2","ogt":"\u29C1","ohbar":"\u29B5","ohm":"\u03A9","oint":"\u222E","olarr":"\u21BA","olcir":"\u29BE","olcross":"\u29BB","oline":"\u203E","olt":"\u29C0","Omacr":"\u014C","omacr":"\u014D","Omega":"\u03A9","omega":"\u03C9","Omicron":"\u039F","omicron":"\u03BF","omid":"\u29B6","ominus":"\u2296","Oopf":"\uD835\uDD46","oopf":"\uD835\uDD60","opar":"\u29B7","OpenCurlyDoubleQuote":"\u201C","OpenCurlyQuote":"\u2018","operp":"\u29B9","oplus":"\u2295","orarr":"\u21BB","Or":"\u2A54","or":"\u2228","ord":"\u2A5D","order":"\u2134","orderof":"\u2134","ordf":"\u00AA","ordm":"\u00BA","origof":"\u22B6","oror":"\u2A56","orslope":"\u2A57","orv":"\u2A5B","oS":"\u24C8","Oscr":"\uD835\uDCAA","oscr":"\u2134","Oslash":"\u00D8","oslash":"\u00F8","osol":"\u2298","Otilde":"\u00D5","otilde":"\u00F5","otimesas":"\u2A36","Otimes":"\u2A37","otimes":"\u2297","Ouml":"\u00D6","ouml":"\u00F6","ovbar":"\u233D","OverBar":"\u203E","OverBrace":"\u23DE","OverBracket":"\u23B4","OverParenthesis":"\u23DC","para":"\u00B6","parallel":"\u2225","par":"\u2225","parsim":"\u2AF3","parsl":"\u2AFD","part":"\u2202","PartialD":"\u2202","Pcy":"\u041F","pcy":"\u043F","percnt":"%","period":".","permil":"\u2030","perp":"\u22A5","pertenk":"\u2031","Pfr":"\uD835\uDD13","pfr":"\uD835\uDD2D","Phi":"\u03A6","phi":"\u03C6","phiv":"\u03D5","phmmat":"\u2133","phone":"\u260E","Pi":"\u03A0","pi":"\u03C0","pitchfork":"\u22D4","piv":"\u03D6","planck":"\u210F","planckh":"\u210E","plankv":"\u210F","plusacir":"\u2A23","plusb":"\u229E","pluscir":"\u2A22","plus":"+","plusdo":"\u2214","plusdu":"\u2A25","pluse":"\u2A72","PlusMinus":"\u00B1","plusmn":"\u00B1","plussim":"\u2A26","plustwo":"\u2A27","pm":"\u00B1","Poincareplane":"\u210C","pointint":"\u2A15","popf":"\uD835\uDD61","Popf":"\u2119","pound":"\u00A3","prap":"\u2AB7","Pr":"\u2ABB","pr":"\u227A","prcue":"\u227C","precapprox":"\u2AB7","prec":"\u227A","preccurlyeq":"\u227C","Precedes":"\u227A","PrecedesEqual":"\u2AAF","PrecedesSlantEqual":"\u227C","PrecedesTilde":"\u227E","preceq":"\u2AAF","precnapprox":"\u2AB9","precneqq":"\u2AB5","precnsim":"\u22E8","pre":"\u2AAF","prE":"\u2AB3","precsim":"\u227E","prime":"\u2032","Prime":"\u2033","primes":"\u2119","prnap":"\u2AB9","prnE":"\u2AB5","prnsim":"\u22E8","prod":"\u220F","Product":"\u220F","profalar":"\u232E","profline":"\u2312","profsurf":"\u2313","prop":"\u221D","Proportional":"\u221D","Proportion":"\u2237","propto":"\u221D","prsim":"\u227E","prurel":"\u22B0","Pscr":"\uD835\uDCAB","pscr":"\uD835\uDCC5","Psi":"\u03A8","psi":"\u03C8","puncsp":"\u2008","Qfr":"\uD835\uDD14","qfr":"\uD835\uDD2E","qint":"\u2A0C","qopf":"\uD835\uDD62","Qopf":"\u211A","qprime":"\u2057","Qscr":"\uD835\uDCAC","qscr":"\uD835\uDCC6","quaternions":"\u210D","quatint":"\u2A16","quest":"?","questeq":"\u225F","quot":"\"","QUOT":"\"","rAarr":"\u21DB","race":"\u223D\u0331","Racute":"\u0154","racute":"\u0155","radic":"\u221A","raemptyv":"\u29B3","rang":"\u27E9","Rang":"\u27EB","rangd":"\u2992","range":"\u29A5","rangle":"\u27E9","raquo":"\u00BB","rarrap":"\u2975","rarrb":"\u21E5","rarrbfs":"\u2920","rarrc":"\u2933","rarr":"\u2192","Rarr":"\u21A0","rArr":"\u21D2","rarrfs":"\u291E","rarrhk":"\u21AA","rarrlp":"\u21AC","rarrpl":"\u2945","rarrsim":"\u2974","Rarrtl":"\u2916","rarrtl":"\u21A3","rarrw":"\u219D","ratail":"\u291A","rAtail":"\u291C","ratio":"\u2236","rationals":"\u211A","rbarr":"\u290D","rBarr":"\u290F","RBarr":"\u2910","rbbrk":"\u2773","rbrace":"}","rbrack":"]","rbrke":"\u298C","rbrksld":"\u298E","rbrkslu":"\u2990","Rcaron":"\u0158","rcaron":"\u0159","Rcedil":"\u0156","rcedil":"\u0157","rceil":"\u2309","rcub":"}","Rcy":"\u0420","rcy":"\u0440","rdca":"\u2937","rdldhar":"\u2969","rdquo":"\u201D","rdquor":"\u201D","rdsh":"\u21B3","real":"\u211C","realine":"\u211B","realpart":"\u211C","reals":"\u211D","Re":"\u211C","rect":"\u25AD","reg":"\u00AE","REG":"\u00AE","ReverseElement":"\u220B","ReverseEquilibrium":"\u21CB","ReverseUpEquilibrium":"\u296F","rfisht":"\u297D","rfloor":"\u230B","rfr":"\uD835\uDD2F","Rfr":"\u211C","rHar":"\u2964","rhard":"\u21C1","rharu":"\u21C0","rharul":"\u296C","Rho":"\u03A1","rho":"\u03C1","rhov":"\u03F1","RightAngleBracket":"\u27E9","RightArrowBar":"\u21E5","rightarrow":"\u2192","RightArrow":"\u2192","Rightarrow":"\u21D2","RightArrowLeftArrow":"\u21C4","rightarrowtail":"\u21A3","RightCeiling":"\u2309","RightDoubleBracket":"\u27E7","RightDownTeeVector":"\u295D","RightDownVectorBar":"\u2955","RightDownVector":"\u21C2","RightFloor":"\u230B","rightharpoondown":"\u21C1","rightharpoonup":"\u21C0","rightleftarrows":"\u21C4","rightleftharpoons":"\u21CC","rightrightarrows":"\u21C9","rightsquigarrow":"\u219D","RightTeeArrow":"\u21A6","RightTee":"\u22A2","RightTeeVector":"\u295B","rightthreetimes":"\u22CC","RightTriangleBar":"\u29D0","RightTriangle":"\u22B3","RightTriangleEqual":"\u22B5","RightUpDownVector":"\u294F","RightUpTeeVector":"\u295C","RightUpVectorBar":"\u2954","RightUpVector":"\u21BE","RightVectorBar":"\u2953","RightVector":"\u21C0","ring":"\u02DA","risingdotseq":"\u2253","rlarr":"\u21C4","rlhar":"\u21CC","rlm":"\u200F","rmoustache":"\u23B1","rmoust":"\u23B1","rnmid":"\u2AEE","roang":"\u27ED","roarr":"\u21FE","robrk":"\u27E7","ropar":"\u2986","ropf":"\uD835\uDD63","Ropf":"\u211D","roplus":"\u2A2E","rotimes":"\u2A35","RoundImplies":"\u2970","rpar":")","rpargt":"\u2994","rppolint":"\u2A12","rrarr":"\u21C9","Rrightarrow":"\u21DB","rsaquo":"\u203A","rscr":"\uD835\uDCC7","Rscr":"\u211B","rsh":"\u21B1","Rsh":"\u21B1","rsqb":"]","rsquo":"\u2019","rsquor":"\u2019","rthree":"\u22CC","rtimes":"\u22CA","rtri":"\u25B9","rtrie":"\u22B5","rtrif":"\u25B8","rtriltri":"\u29CE","RuleDelayed":"\u29F4","ruluhar":"\u2968","rx":"\u211E","Sacute":"\u015A","sacute":"\u015B","sbquo":"\u201A","scap":"\u2AB8","Scaron":"\u0160","scaron":"\u0161","Sc":"\u2ABC","sc":"\u227B","sccue":"\u227D","sce":"\u2AB0","scE":"\u2AB4","Scedil":"\u015E","scedil":"\u015F","Scirc":"\u015C","scirc":"\u015D","scnap":"\u2ABA","scnE":"\u2AB6","scnsim":"\u22E9","scpolint":"\u2A13","scsim":"\u227F","Scy":"\u0421","scy":"\u0441","sdotb":"\u22A1","sdot":"\u22C5","sdote":"\u2A66","searhk":"\u2925","searr":"\u2198","seArr":"\u21D8","searrow":"\u2198","sect":"\u00A7","semi":";","seswar":"\u2929","setminus":"\u2216","setmn":"\u2216","sext":"\u2736","Sfr":"\uD835\uDD16","sfr":"\uD835\uDD30","sfrown":"\u2322","sharp":"\u266F","SHCHcy":"\u0429","shchcy":"\u0449","SHcy":"\u0428","shcy":"\u0448","ShortDownArrow":"\u2193","ShortLeftArrow":"\u2190","shortmid":"\u2223","shortparallel":"\u2225","ShortRightArrow":"\u2192","ShortUpArrow":"\u2191","shy":"\u00AD","Sigma":"\u03A3","sigma":"\u03C3","sigmaf":"\u03C2","sigmav":"\u03C2","sim":"\u223C","simdot":"\u2A6A","sime":"\u2243","simeq":"\u2243","simg":"\u2A9E","simgE":"\u2AA0","siml":"\u2A9D","simlE":"\u2A9F","simne":"\u2246","simplus":"\u2A24","simrarr":"\u2972","slarr":"\u2190","SmallCircle":"\u2218","smallsetminus":"\u2216","smashp":"\u2A33","smeparsl":"\u29E4","smid":"\u2223","smile":"\u2323","smt":"\u2AAA","smte":"\u2AAC","smtes":"\u2AAC\uFE00","SOFTcy":"\u042C","softcy":"\u044C","solbar":"\u233F","solb":"\u29C4","sol":"/","Sopf":"\uD835\uDD4A","sopf":"\uD835\uDD64","spades":"\u2660","spadesuit":"\u2660","spar":"\u2225","sqcap":"\u2293","sqcaps":"\u2293\uFE00","sqcup":"\u2294","sqcups":"\u2294\uFE00","Sqrt":"\u221A","sqsub":"\u228F","sqsube":"\u2291","sqsubset":"\u228F","sqsubseteq":"\u2291","sqsup":"\u2290","sqsupe":"\u2292","sqsupset":"\u2290","sqsupseteq":"\u2292","square":"\u25A1","Square":"\u25A1","SquareIntersection":"\u2293","SquareSubset":"\u228F","SquareSubsetEqual":"\u2291","SquareSuperset":"\u2290","SquareSupersetEqual":"\u2292","SquareUnion":"\u2294","squarf":"\u25AA","squ":"\u25A1","squf":"\u25AA","srarr":"\u2192","Sscr":"\uD835\uDCAE","sscr":"\uD835\uDCC8","ssetmn":"\u2216","ssmile":"\u2323","sstarf":"\u22C6","Star":"\u22C6","star":"\u2606","starf":"\u2605","straightepsilon":"\u03F5","straightphi":"\u03D5","strns":"\u00AF","sub":"\u2282","Sub":"\u22D0","subdot":"\u2ABD","subE":"\u2AC5","sube":"\u2286","subedot":"\u2AC3","submult":"\u2AC1","subnE":"\u2ACB","subne":"\u228A","subplus":"\u2ABF","subrarr":"\u2979","subset":"\u2282","Subset":"\u22D0","subseteq":"\u2286","subseteqq":"\u2AC5","SubsetEqual":"\u2286","subsetneq":"\u228A","subsetneqq":"\u2ACB","subsim":"\u2AC7","subsub":"\u2AD5","subsup":"\u2AD3","succapprox":"\u2AB8","succ":"\u227B","succcurlyeq":"\u227D","Succeeds":"\u227B","SucceedsEqual":"\u2AB0","SucceedsSlantEqual":"\u227D","SucceedsTilde":"\u227F","succeq":"\u2AB0","succnapprox":"\u2ABA","succneqq":"\u2AB6","succnsim":"\u22E9","succsim":"\u227F","SuchThat":"\u220B","sum":"\u2211","Sum":"\u2211","sung":"\u266A","sup1":"\u00B9","sup2":"\u00B2","sup3":"\u00B3","sup":"\u2283","Sup":"\u22D1","supdot":"\u2ABE","supdsub":"\u2AD8","supE":"\u2AC6","supe":"\u2287","supedot":"\u2AC4","Superset":"\u2283","SupersetEqual":"\u2287","suphsol":"\u27C9","suphsub":"\u2AD7","suplarr":"\u297B","supmult":"\u2AC2","supnE":"\u2ACC","supne":"\u228B","supplus":"\u2AC0","supset":"\u2283","Supset":"\u22D1","supseteq":"\u2287","supseteqq":"\u2AC6","supsetneq":"\u228B","supsetneqq":"\u2ACC","supsim":"\u2AC8","supsub":"\u2AD4","supsup":"\u2AD6","swarhk":"\u2926","swarr":"\u2199","swArr":"\u21D9","swarrow":"\u2199","swnwar":"\u292A","szlig":"\u00DF","Tab":"\t","target":"\u2316","Tau":"\u03A4","tau":"\u03C4","tbrk":"\u23B4","Tcaron":"\u0164","tcaron":"\u0165","Tcedil":"\u0162","tcedil":"\u0163","Tcy":"\u0422","tcy":"\u0442","tdot":"\u20DB","telrec":"\u2315","Tfr":"\uD835\uDD17","tfr":"\uD835\uDD31","there4":"\u2234","therefore":"\u2234","Therefore":"\u2234","Theta":"\u0398","theta":"\u03B8","thetasym":"\u03D1","thetav":"\u03D1","thickapprox":"\u2248","thicksim":"\u223C","ThickSpace":"\u205F\u200A","ThinSpace":"\u2009","thinsp":"\u2009","thkap":"\u2248","thksim":"\u223C","THORN":"\u00DE","thorn":"\u00FE","tilde":"\u02DC","Tilde":"\u223C","TildeEqual":"\u2243","TildeFullEqual":"\u2245","TildeTilde":"\u2248","timesbar":"\u2A31","timesb":"\u22A0","times":"\u00D7","timesd":"\u2A30","tint":"\u222D","toea":"\u2928","topbot":"\u2336","topcir":"\u2AF1","top":"\u22A4","Topf":"\uD835\uDD4B","topf":"\uD835\uDD65","topfork":"\u2ADA","tosa":"\u2929","tprime":"\u2034","trade":"\u2122","TRADE":"\u2122","triangle":"\u25B5","triangledown":"\u25BF","triangleleft":"\u25C3","trianglelefteq":"\u22B4","triangleq":"\u225C","triangleright":"\u25B9","trianglerighteq":"\u22B5","tridot":"\u25EC","trie":"\u225C","triminus":"\u2A3A","TripleDot":"\u20DB","triplus":"\u2A39","trisb":"\u29CD","tritime":"\u2A3B","trpezium":"\u23E2","Tscr":"\uD835\uDCAF","tscr":"\uD835\uDCC9","TScy":"\u0426","tscy":"\u0446","TSHcy":"\u040B","tshcy":"\u045B","Tstrok":"\u0166","tstrok":"\u0167","twixt":"\u226C","twoheadleftarrow":"\u219E","twoheadrightarrow":"\u21A0","Uacute":"\u00DA","uacute":"\u00FA","uarr":"\u2191","Uarr":"\u219F","uArr":"\u21D1","Uarrocir":"\u2949","Ubrcy":"\u040E","ubrcy":"\u045E","Ubreve":"\u016C","ubreve":"\u016D","Ucirc":"\u00DB","ucirc":"\u00FB","Ucy":"\u0423","ucy":"\u0443","udarr":"\u21C5","Udblac":"\u0170","udblac":"\u0171","udhar":"\u296E","ufisht":"\u297E","Ufr":"\uD835\uDD18","ufr":"\uD835\uDD32","Ugrave":"\u00D9","ugrave":"\u00F9","uHar":"\u2963","uharl":"\u21BF","uharr":"\u21BE","uhblk":"\u2580","ulcorn":"\u231C","ulcorner":"\u231C","ulcrop":"\u230F","ultri":"\u25F8","Umacr":"\u016A","umacr":"\u016B","uml":"\u00A8","UnderBar":"_","UnderBrace":"\u23DF","UnderBracket":"\u23B5","UnderParenthesis":"\u23DD","Union":"\u22C3","UnionPlus":"\u228E","Uogon":"\u0172","uogon":"\u0173","Uopf":"\uD835\uDD4C","uopf":"\uD835\uDD66","UpArrowBar":"\u2912","uparrow":"\u2191","UpArrow":"\u2191","Uparrow":"\u21D1","UpArrowDownArrow":"\u21C5","updownarrow":"\u2195","UpDownArrow":"\u2195","Updownarrow":"\u21D5","UpEquilibrium":"\u296E","upharpoonleft":"\u21BF","upharpoonright":"\u21BE","uplus":"\u228E","UpperLeftArrow":"\u2196","UpperRightArrow":"\u2197","upsi":"\u03C5","Upsi":"\u03D2","upsih":"\u03D2","Upsilon":"\u03A5","upsilon":"\u03C5","UpTeeArrow":"\u21A5","UpTee":"\u22A5","upuparrows":"\u21C8","urcorn":"\u231D","urcorner":"\u231D","urcrop":"\u230E","Uring":"\u016E","uring":"\u016F","urtri":"\u25F9","Uscr":"\uD835\uDCB0","uscr":"\uD835\uDCCA","utdot":"\u22F0","Utilde":"\u0168","utilde":"\u0169","utri":"\u25B5","utrif":"\u25B4","uuarr":"\u21C8","Uuml":"\u00DC","uuml":"\u00FC","uwangle":"\u29A7","vangrt":"\u299C","varepsilon":"\u03F5","varkappa":"\u03F0","varnothing":"\u2205","varphi":"\u03D5","varpi":"\u03D6","varpropto":"\u221D","varr":"\u2195","vArr":"\u21D5","varrho":"\u03F1","varsigma":"\u03C2","varsubsetneq":"\u228A\uFE00","varsubsetneqq":"\u2ACB\uFE00","varsupsetneq":"\u228B\uFE00","varsupsetneqq":"\u2ACC\uFE00","vartheta":"\u03D1","vartriangleleft":"\u22B2","vartriangleright":"\u22B3","vBar":"\u2AE8","Vbar":"\u2AEB","vBarv":"\u2AE9","Vcy":"\u0412","vcy":"\u0432","vdash":"\u22A2","vDash":"\u22A8","Vdash":"\u22A9","VDash":"\u22AB","Vdashl":"\u2AE6","veebar":"\u22BB","vee":"\u2228","Vee":"\u22C1","veeeq":"\u225A","vellip":"\u22EE","verbar":"|","Verbar":"\u2016","vert":"|","Vert":"\u2016","VerticalBar":"\u2223","VerticalLine":"|","VerticalSeparator":"\u2758","VerticalTilde":"\u2240","VeryThinSpace":"\u200A","Vfr":"\uD835\uDD19","vfr":"\uD835\uDD33","vltri":"\u22B2","vnsub":"\u2282\u20D2","vnsup":"\u2283\u20D2","Vopf":"\uD835\uDD4D","vopf":"\uD835\uDD67","vprop":"\u221D","vrtri":"\u22B3","Vscr":"\uD835\uDCB1","vscr":"\uD835\uDCCB","vsubnE":"\u2ACB\uFE00","vsubne":"\u228A\uFE00","vsupnE":"\u2ACC\uFE00","vsupne":"\u228B\uFE00","Vvdash":"\u22AA","vzigzag":"\u299A","Wcirc":"\u0174","wcirc":"\u0175","wedbar":"\u2A5F","wedge":"\u2227","Wedge":"\u22C0","wedgeq":"\u2259","weierp":"\u2118","Wfr":"\uD835\uDD1A","wfr":"\uD835\uDD34","Wopf":"\uD835\uDD4E","wopf":"\uD835\uDD68","wp":"\u2118","wr":"\u2240","wreath":"\u2240","Wscr":"\uD835\uDCB2","wscr":"\uD835\uDCCC","xcap":"\u22C2","xcirc":"\u25EF","xcup":"\u22C3","xdtri":"\u25BD","Xfr":"\uD835\uDD1B","xfr":"\uD835\uDD35","xharr":"\u27F7","xhArr":"\u27FA","Xi":"\u039E","xi":"\u03BE","xlarr":"\u27F5","xlArr":"\u27F8","xmap":"\u27FC","xnis":"\u22FB","xodot":"\u2A00","Xopf":"\uD835\uDD4F","xopf":"\uD835\uDD69","xoplus":"\u2A01","xotime":"\u2A02","xrarr":"\u27F6","xrArr":"\u27F9","Xscr":"\uD835\uDCB3","xscr":"\uD835\uDCCD","xsqcup":"\u2A06","xuplus":"\u2A04","xutri":"\u25B3","xvee":"\u22C1","xwedge":"\u22C0","Yacute":"\u00DD","yacute":"\u00FD","YAcy":"\u042F","yacy":"\u044F","Ycirc":"\u0176","ycirc":"\u0177","Ycy":"\u042B","ycy":"\u044B","yen":"\u00A5","Yfr":"\uD835\uDD1C","yfr":"\uD835\uDD36","YIcy":"\u0407","yicy":"\u0457","Yopf":"\uD835\uDD50","yopf":"\uD835\uDD6A","Yscr":"\uD835\uDCB4","yscr":"\uD835\uDCCE","YUcy":"\u042E","yucy":"\u044E","yuml":"\u00FF","Yuml":"\u0178","Zacute":"\u0179","zacute":"\u017A","Zcaron":"\u017D","zcaron":"\u017E","Zcy":"\u0417","zcy":"\u0437","Zdot":"\u017B","zdot":"\u017C","zeetrf":"\u2128","ZeroWidthSpace":"\u200B","Zeta":"\u0396","zeta":"\u03B6","zfr":"\uD835\uDD37","Zfr":"\u2128","ZHcy":"\u0416","zhcy":"\u0436","zigrarr":"\u21DD","zopf":"\uD835\uDD6B","Zopf":"\u2124","Zscr":"\uD835\uDCB5","zscr":"\uD835\uDCCF","zwj":"\u200D","zwnj":"\u200C"}
- },{}],19:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.GraphQLError = GraphQLError;
- var _printError = require("./printError");
- var _location = require("../language/location");
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function GraphQLError( // eslint-disable-line no-redeclare
- message, nodes, source, positions, path, originalError, extensions) {
- // Compute list of blame nodes.
- var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.
- var _source = source;
- if (!_source && _nodes) {
- var node = _nodes[0];
- _source = node && node.loc && node.loc.source;
- }
- var _positions = positions;
- if (!_positions && _nodes) {
- _positions = _nodes.reduce(function (list, node) {
- if (node.loc) {
- list.push(node.loc.start);
- }
- return list;
- }, []);
- }
- if (_positions && _positions.length === 0) {
- _positions = undefined;
- }
- var _locations;
- if (positions && source) {
- _locations = positions.map(function (pos) {
- return (0, _location.getLocation)(source, pos);
- });
- } else if (_nodes) {
- _locations = _nodes.reduce(function (list, node) {
- if (node.loc) {
- list.push((0, _location.getLocation)(node.loc.source, node.loc.start));
- }
- return list;
- }, []);
- }
- var _extensions = extensions;
- if (_extensions == null && originalError != null) {
- var originalExtensions = originalError.extensions;
- if (originalExtensions != null && _typeof(originalExtensions) === 'object') {
- _extensions = originalExtensions;
- }
- }
- Object.defineProperties(this, {
- message: {
- value: message,
- // By being enumerable, JSON.stringify will include `message` in the
- // resulting output. This ensures that the simplest possible GraphQL
- // service adheres to the spec.
- enumerable: true,
- writable: true
- },
- locations: {
- // Coercing falsey values to undefined ensures they will not be included
- // in JSON.stringify() when not provided.
- value: _locations || undefined,
- // By being enumerable, JSON.stringify will include `locations` in the
- // resulting output. This ensures that the simplest possible GraphQL
- // service adheres to the spec.
- enumerable: Boolean(_locations)
- },
- path: {
- // Coercing falsey values to undefined ensures they will not be included
- // in JSON.stringify() when not provided.
- value: path || undefined,
- // By being enumerable, JSON.stringify will include `path` in the
- // resulting output. This ensures that the simplest possible GraphQL
- // service adheres to the spec.
- enumerable: Boolean(path)
- },
- nodes: {
- value: _nodes || undefined
- },
- source: {
- value: _source || undefined
- },
- positions: {
- value: _positions || undefined
- },
- originalError: {
- value: originalError
- },
- extensions: {
- // Coercing falsey values to undefined ensures they will not be included
- // in JSON.stringify() when not provided.
- value: _extensions || undefined,
- // By being enumerable, JSON.stringify will include `path` in the
- // resulting output. This ensures that the simplest possible GraphQL
- // service adheres to the spec.
- enumerable: Boolean(_extensions)
- }
- }); // Include (non-enumerable) stack trace.
- if (originalError && originalError.stack) {
- Object.defineProperty(this, 'stack', {
- value: originalError.stack,
- writable: true,
- configurable: true
- });
- } else if (Error.captureStackTrace) {
- Error.captureStackTrace(this, GraphQLError);
- } else {
- Object.defineProperty(this, 'stack', {
- value: Error().stack,
- writable: true,
- configurable: true
- });
- }
- }
- GraphQLError.prototype = Object.create(Error.prototype, {
- constructor: {
- value: GraphQLError
- },
- name: {
- value: 'GraphQLError'
- },
- toString: {
- value: function toString() {
- return (0, _printError.printError)(this);
- }
- }
- });
- },{"../language/location":53,"./printError":23}],20:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.formatError = formatError;
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given a GraphQLError, format it according to the rules described by the
- * Response Format, Errors section of the GraphQL Specification.
- */
- function formatError(error) {
- !error ? (0, _invariant.default)(0, 'Received null or undefined error.') : void 0;
- var message = error.message || 'An unknown error occurred.';
- var locations = error.locations;
- var path = error.path;
- var extensions = error.extensions;
- return extensions ? {
- message: message,
- locations: locations,
- path: path,
- extensions: extensions
- } : {
- message: message,
- locations: locations,
- path: path
- };
- }
- },{"../jsutils/invariant":34}],21:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "GraphQLError", {
- enumerable: true,
- get: function get() {
- return _GraphQLError.GraphQLError;
- }
- });
- Object.defineProperty(exports, "syntaxError", {
- enumerable: true,
- get: function get() {
- return _syntaxError.syntaxError;
- }
- });
- Object.defineProperty(exports, "locatedError", {
- enumerable: true,
- get: function get() {
- return _locatedError.locatedError;
- }
- });
- Object.defineProperty(exports, "printError", {
- enumerable: true,
- get: function get() {
- return _printError.printError;
- }
- });
- Object.defineProperty(exports, "formatError", {
- enumerable: true,
- get: function get() {
- return _formatError.formatError;
- }
- });
- var _GraphQLError = require("./GraphQLError");
- var _syntaxError = require("./syntaxError");
- var _locatedError = require("./locatedError");
- var _printError = require("./printError");
- var _formatError = require("./formatError");
- },{"./GraphQLError":19,"./formatError":20,"./locatedError":22,"./printError":23,"./syntaxError":24}],22:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.locatedError = locatedError;
- var _GraphQLError = require("./GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given an arbitrary Error, presumably thrown while attempting to execute a
- * GraphQL operation, produce a new GraphQLError aware of the location in the
- * document responsible for the original Error.
- */
- function locatedError(originalError, nodes, path) {
- // Note: this uses a brand-check to support GraphQL errors originating from
- // other contexts.
- if (originalError && Array.isArray(originalError.path)) {
- return originalError;
- }
- return new _GraphQLError.GraphQLError(originalError && originalError.message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError);
- }
- },{"./GraphQLError":19}],23:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.printError = printError;
- var _location = require("../language/location");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Prints a GraphQLError to a string, representing useful location information
- * about the error's position in the source.
- */
- function printError(error) {
- var printedLocations = [];
- if (error.nodes) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = error.nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var node = _step.value;
- if (node.loc) {
- printedLocations.push(highlightSourceAtLocation(node.loc.source, (0, _location.getLocation)(node.loc.source, node.loc.start)));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- } else if (error.source && error.locations) {
- var source = error.source;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = error.locations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var location = _step2.value;
- printedLocations.push(highlightSourceAtLocation(source, location));
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- }
- return printedLocations.length === 0 ? error.message : [error.message].concat(printedLocations).join('\n\n') + '\n';
- }
- /**
- * Render a helpful description of the location of the error in the GraphQL
- * Source document.
- */
- function highlightSourceAtLocation(source, location) {
- var firstLineColumnOffset = source.locationOffset.column - 1;
- var body = whitespace(firstLineColumnOffset) + source.body;
- var lineIndex = location.line - 1;
- var lineOffset = source.locationOffset.line - 1;
- var lineNum = location.line + lineOffset;
- var columnOffset = location.line === 1 ? firstLineColumnOffset : 0;
- var columnNum = location.column + columnOffset;
- var lines = body.split(/\r\n|[\n\r]/g);
- return "".concat(source.name, " (").concat(lineNum, ":").concat(columnNum, ")\n") + printPrefixedLines([// Lines specified like this: ["prefix", "string"],
- ["".concat(lineNum - 1, ": "), lines[lineIndex - 1]], ["".concat(lineNum, ": "), lines[lineIndex]], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1, ": "), lines[lineIndex + 1]]]);
- }
- function printPrefixedLines(lines) {
- var existingLines = lines.filter(function (_ref) {
- var _ = _ref[0],
- line = _ref[1];
- return line !== undefined;
- });
- var padLen = 0;
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = existingLines[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var _ref4 = _step3.value;
- var prefix = _ref4[0];
- padLen = Math.max(padLen, prefix.length);
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- return existingLines.map(function (_ref3) {
- var prefix = _ref3[0],
- line = _ref3[1];
- return lpad(padLen, prefix) + line;
- }).join('\n');
- }
- function whitespace(len) {
- return Array(len + 1).join(' ');
- }
- function lpad(len, str) {
- return whitespace(len - str.length) + str;
- }
- },{"../language/location":53}],24:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.syntaxError = syntaxError;
- var _GraphQLError = require("./GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Produces a GraphQLError representing a syntax error, containing useful
- * descriptive information about the syntax error's position in the source.
- */
- function syntaxError(source, position, description) {
- return new _GraphQLError.GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]);
- }
- },{"./GraphQLError":19}],25:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.execute = execute;
- exports.responsePathAsArray = responsePathAsArray;
- exports.addPath = addPath;
- exports.assertValidExecutionArguments = assertValidExecutionArguments;
- exports.buildExecutionContext = buildExecutionContext;
- exports.collectFields = collectFields;
- exports.buildResolveInfo = buildResolveInfo;
- exports.resolveFieldValueOrError = resolveFieldValueOrError;
- exports.getFieldDef = getFieldDef;
- exports.defaultFieldResolver = exports.defaultTypeResolver = void 0;
- var _iterall = require("iterall");
- var _GraphQLError = require("../error/GraphQLError");
- var _locatedError = require("../error/locatedError");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _isNullish = _interopRequireDefault(require("../jsutils/isNullish"));
- var _isPromise = _interopRequireDefault(require("../jsutils/isPromise"));
- var _memoize = _interopRequireDefault(require("../jsutils/memoize3"));
- var _promiseForObject = _interopRequireDefault(require("../jsutils/promiseForObject"));
- var _promiseReduce = _interopRequireDefault(require("../jsutils/promiseReduce"));
- var _getOperationRootType = require("../utilities/getOperationRootType");
- var _typeFromAST = require("../utilities/typeFromAST");
- var _kinds = require("../language/kinds");
- var _values = require("./values");
- var _definition = require("../type/definition");
- var _introspection = require("../type/introspection");
- var _directives = require("../type/directives");
- var _validate = require("../type/validate");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {
- /* eslint-enable no-redeclare */
- // Extract arguments from object args if provided.
- return arguments.length === 1 ? executeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, argsOrSchema.typeResolver) : executeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver);
- }
- function executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {
- // If arguments are missing or incorrect, throw an error.
- assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,
- // a "Response" with only errors is returned.
- var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver); // Return early errors if execution context failed.
- if (Array.isArray(exeContext)) {
- return {
- errors: exeContext
- };
- } // Return a Promise that will eventually resolve to the data described by
- // The "Response" section of the GraphQL specification.
- //
- // If errors are encountered while executing a GraphQL field, only that
- // field and its descendants will be omitted, and sibling fields will still
- // be executed. An execution which encounters errors will still result in a
- // resolved Promise.
- var data = executeOperation(exeContext, exeContext.operation, rootValue);
- return buildResponse(exeContext, data);
- }
- /**
- * Given a completed execution context and data, build the { errors, data }
- * response defined by the "Response" section of the GraphQL specification.
- */
- function buildResponse(exeContext, data) {
- if ((0, _isPromise.default)(data)) {
- return data.then(function (resolved) {
- return buildResponse(exeContext, resolved);
- });
- }
- return exeContext.errors.length === 0 ? {
- data: data
- } : {
- errors: exeContext.errors,
- data: data
- };
- }
- /**
- * Given a ResponsePath (found in the `path` entry in the information provided
- * as the last argument to a field resolver), return an Array of the path keys.
- */
- function responsePathAsArray(path) {
- var flattened = [];
- var curr = path;
- while (curr) {
- flattened.push(curr.key);
- curr = curr.prev;
- }
- return flattened.reverse();
- }
- /**
- * Given a ResponsePath and a key, return a new ResponsePath containing the
- * new key.
- */
- function addPath(prev, key) {
- return {
- prev: prev,
- key: key
- };
- }
- /**
- * Essential assertions before executing to provide developer feedback for
- * improper use of the GraphQL library.
- */
- function assertValidExecutionArguments(schema, document, rawVariableValues) {
- !document ? (0, _invariant.default)(0, 'Must provide document') : void 0; // If the schema used for execution is invalid, throw an error.
- (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object.
- !(!rawVariableValues || _typeof(rawVariableValues) === 'object') ? (0, _invariant.default)(0, 'Variables must be provided as an Object where each property is a ' + 'variable value. Perhaps look to see if an unparsed JSON string ' + 'was provided.') : void 0;
- }
- /**
- * Constructs a ExecutionContext object from the arguments passed to
- * execute, which we will pass throughout the other execution methods.
- *
- * Throws a GraphQLError if a valid execution context cannot be created.
- */
- function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver, typeResolver) {
- var errors = [];
- var operation;
- var hasMultipleAssumedOperations = false;
- var fragments = Object.create(null);
- for (var i = 0; i < document.definitions.length; i++) {
- var definition = document.definitions[i];
- switch (definition.kind) {
- case _kinds.Kind.OPERATION_DEFINITION:
- if (!operationName && operation) {
- hasMultipleAssumedOperations = true;
- } else if (!operationName || definition.name && definition.name.value === operationName) {
- operation = definition;
- }
- break;
- case _kinds.Kind.FRAGMENT_DEFINITION:
- fragments[definition.name.value] = definition;
- break;
- }
- }
- if (!operation) {
- if (operationName) {
- errors.push(new _GraphQLError.GraphQLError("Unknown operation named \"".concat(operationName, "\".")));
- } else {
- errors.push(new _GraphQLError.GraphQLError('Must provide an operation.'));
- }
- } else if (hasMultipleAssumedOperations) {
- errors.push(new _GraphQLError.GraphQLError('Must provide operation name if query contains multiple operations.'));
- }
- var variableValues;
- if (operation) {
- var coercedVariableValues = (0, _values.getVariableValues)(schema, operation.variableDefinitions || [], rawVariableValues || {});
- if (coercedVariableValues.errors) {
- errors.push.apply(errors, coercedVariableValues.errors);
- } else {
- variableValues = coercedVariableValues.coerced;
- }
- }
- if (errors.length !== 0) {
- return errors;
- }
- !operation ? (0, _invariant.default)(0, 'Has operation if no errors.') : void 0;
- !variableValues ? (0, _invariant.default)(0, 'Has variables if no errors.') : void 0;
- return {
- schema: schema,
- fragments: fragments,
- rootValue: rootValue,
- contextValue: contextValue,
- operation: operation,
- variableValues: variableValues,
- fieldResolver: fieldResolver || defaultFieldResolver,
- typeResolver: typeResolver || defaultTypeResolver,
- errors: errors
- };
- }
- /**
- * Implements the "Evaluating operations" section of the spec.
- */
- function executeOperation(exeContext, operation, rootValue) {
- var type = (0, _getOperationRootType.getOperationRootType)(exeContext.schema, operation);
- var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null));
- var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level,
- // at which point we still log the error and null the parent field, which
- // in this case is the entire response.
- //
- // Similar to completeValueCatchingError.
- try {
- var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields);
- if ((0, _isPromise.default)(result)) {
- return result.then(undefined, function (error) {
- exeContext.errors.push(error);
- return Promise.resolve(null);
- });
- }
- return result;
- } catch (error) {
- exeContext.errors.push(error);
- return null;
- }
- }
- /**
- * Implements the "Evaluating selection sets" section of the spec
- * for "write" mode.
- */
- function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {
- return (0, _promiseReduce.default)(Object.keys(fields), function (results, responseName) {
- var fieldNodes = fields[responseName];
- var fieldPath = addPath(path, responseName);
- var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
- if (result === undefined) {
- return results;
- }
- if ((0, _isPromise.default)(result)) {
- return result.then(function (resolvedResult) {
- results[responseName] = resolvedResult;
- return results;
- });
- }
- results[responseName] = result;
- return results;
- }, Object.create(null));
- }
- /**
- * Implements the "Evaluating selection sets" section of the spec
- * for "read" mode.
- */
- function executeFields(exeContext, parentType, sourceValue, path, fields) {
- var results = Object.create(null);
- var containsPromise = false;
- for (var i = 0, keys = Object.keys(fields); i < keys.length; ++i) {
- var responseName = keys[i];
- var fieldNodes = fields[responseName];
- var fieldPath = addPath(path, responseName);
- var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
- if (result !== undefined) {
- results[responseName] = result;
- if (!containsPromise && (0, _isPromise.default)(result)) {
- containsPromise = true;
- }
- }
- } // If there are no promises, we can just return the object
- if (!containsPromise) {
- return results;
- } // Otherwise, results is a map from field name to the result of resolving that
- // field, which is possibly a promise. Return a promise that will return this
- // same map, but with any promises replaced with the values they resolved to.
- return (0, _promiseForObject.default)(results);
- }
- /**
- * Given a selectionSet, adds all of the fields in that selection to
- * the passed in map of fields, and returns it at the end.
- *
- * CollectFields requires the "runtime type" of an object. For a field which
- * returns an Interface or Union type, the "runtime type" will be the actual
- * Object type returned by that field.
- */
- function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {
- for (var i = 0; i < selectionSet.selections.length; i++) {
- var selection = selectionSet.selections[i];
- switch (selection.kind) {
- case _kinds.Kind.FIELD:
- {
- if (!shouldIncludeNode(exeContext, selection)) {
- continue;
- }
- var name = getFieldEntryKey(selection);
- if (!fields[name]) {
- fields[name] = [];
- }
- fields[name].push(selection);
- break;
- }
- case _kinds.Kind.INLINE_FRAGMENT:
- {
- if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {
- continue;
- }
- collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);
- break;
- }
- case _kinds.Kind.FRAGMENT_SPREAD:
- {
- var fragName = selection.name.value;
- if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) {
- continue;
- }
- visitedFragmentNames[fragName] = true;
- var fragment = exeContext.fragments[fragName];
- if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {
- continue;
- }
- collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);
- break;
- }
- }
- }
- return fields;
- }
- /**
- * Determines if a field should be included based on the @include and @skip
- * directives, where @skip has higher precedence than @include.
- */
- function shouldIncludeNode(exeContext, node) {
- var skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, exeContext.variableValues);
- if (skip && skip.if === true) {
- return false;
- }
- var include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, exeContext.variableValues);
- if (include && include.if === false) {
- return false;
- }
- return true;
- }
- /**
- * Determines if a fragment is applicable to the given type.
- */
- function doesFragmentConditionMatch(exeContext, fragment, type) {
- var typeConditionNode = fragment.typeCondition;
- if (!typeConditionNode) {
- return true;
- }
- var conditionalType = (0, _typeFromAST.typeFromAST)(exeContext.schema, typeConditionNode);
- if (conditionalType === type) {
- return true;
- }
- if ((0, _definition.isAbstractType)(conditionalType)) {
- return exeContext.schema.isPossibleType(conditionalType, type);
- }
- return false;
- }
- /**
- * Implements the logic to compute the key of a given field's entry
- */
- function getFieldEntryKey(node) {
- return node.alias ? node.alias.value : node.name.value;
- }
- /**
- * Resolves the field on the given source object. In particular, this
- * figures out the value that the field returns by calling its resolve function,
- * then calls completeValue to complete promises, serialize scalars, or execute
- * the sub-selection-set for objects.
- */
- function resolveField(exeContext, parentType, source, fieldNodes, path) {
- var fieldNode = fieldNodes[0];
- var fieldName = fieldNode.name.value;
- var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName);
- if (!fieldDef) {
- return;
- }
- var resolveFn = fieldDef.resolve || exeContext.fieldResolver;
- var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal
- // or abrupt (error).
- var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info);
- return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result);
- }
- function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) {
- // The resolve function's optional fourth argument is a collection of
- // information about the current execution state.
- return {
- fieldName: fieldDef.name,
- fieldNodes: fieldNodes,
- returnType: fieldDef.type,
- parentType: parentType,
- path: path,
- schema: exeContext.schema,
- fragments: exeContext.fragments,
- rootValue: exeContext.rootValue,
- operation: exeContext.operation,
- variableValues: exeContext.variableValues
- };
- } // Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`
- // function. Returns the result of resolveFn or the abrupt-return Error object.
- function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) {
- try {
- // Build a JS object of arguments from the field.arguments AST, using the
- // variables scope to fulfill any variable references.
- // TODO: find a way to memoize, in case this field is within a List type.
- var args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that
- // is provided to every resolve function within an execution. It is commonly
- // used to represent an authenticated user, or request-specific caches.
- var _contextValue = exeContext.contextValue;
- var result = resolveFn(source, args, _contextValue, info);
- return (0, _isPromise.default)(result) ? result.then(undefined, asErrorInstance) : result;
- } catch (error) {
- return asErrorInstance(error);
- }
- } // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a
- // consistent Error interface.
- function asErrorInstance(error) {
- if (error instanceof Error) {
- return error;
- }
- return new Error('Unexpected error value: ' + (0, _inspect.default)(error));
- } // This is a small wrapper around completeValue which detects and logs errors
- // in the execution context.
- function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) {
- try {
- var completed;
- if ((0, _isPromise.default)(result)) {
- completed = result.then(function (resolved) {
- return completeValue(exeContext, returnType, fieldNodes, info, path, resolved);
- });
- } else {
- completed = completeValue(exeContext, returnType, fieldNodes, info, path, result);
- }
- if ((0, _isPromise.default)(completed)) {
- // Note: we don't rely on a `catch` method, but we do expect "thenable"
- // to take a second callback for the error case.
- return completed.then(undefined, function (error) {
- return handleFieldError(error, fieldNodes, path, returnType, exeContext);
- });
- }
- return completed;
- } catch (error) {
- return handleFieldError(error, fieldNodes, path, returnType, exeContext);
- }
- }
- function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) {
- var error = (0, _locatedError.locatedError)(asErrorInstance(rawError), fieldNodes, responsePathAsArray(path)); // If the field type is non-nullable, then it is resolved without any
- // protection from errors, however it still properly locates the error.
- if ((0, _definition.isNonNullType)(returnType)) {
- throw error;
- } // Otherwise, error protection is applied, logging the error and resolving
- // a null value for this field if one is encountered.
- exeContext.errors.push(error);
- return null;
- }
- /**
- * Implements the instructions for completeValue as defined in the
- * "Field entries" section of the spec.
- *
- * If the field type is Non-Null, then this recursively completes the value
- * for the inner type. It throws a field error if that completion returns null,
- * as per the "Nullability" section of the spec.
- *
- * If the field type is a List, then this recursively completes the value
- * for the inner type on each item in the list.
- *
- * If the field type is a Scalar or Enum, ensures the completed value is a legal
- * value of the type by calling the `serialize` method of GraphQL type
- * definition.
- *
- * If the field is an abstract type, determine the runtime type of the value
- * and then complete based on that type
- *
- * Otherwise, the field type expects a sub-selection set, and will complete the
- * value by evaluating all sub-selections.
- */
- function completeValue(exeContext, returnType, fieldNodes, info, path, result) {
- // If result is an Error, throw a located error.
- if (result instanceof Error) {
- throw result;
- } // If field type is NonNull, complete for inner type, and throw field error
- // if result is null.
- if ((0, _definition.isNonNullType)(returnType)) {
- var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result);
- if (completed === null) {
- throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, "."));
- }
- return completed;
- } // If result value is null-ish (null, undefined, or NaN) then return null.
- if ((0, _isNullish.default)(result)) {
- return null;
- } // If field type is List, complete each item in the list with the inner type
- if ((0, _definition.isListType)(returnType)) {
- return completeListValue(exeContext, returnType, fieldNodes, info, path, result);
- } // If field type is a leaf type, Scalar or Enum, serialize to a valid value,
- // returning null if serialization is not possible.
- if ((0, _definition.isLeafType)(returnType)) {
- return completeLeafValue(returnType, result);
- } // If field type is an abstract type, Interface or Union, determine the
- // runtime Object type and complete for that type.
- if ((0, _definition.isAbstractType)(returnType)) {
- return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result);
- } // If field type is Object, execute and complete all sub-selections.
- if ((0, _definition.isObjectType)(returnType)) {
- return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result);
- } // Not reachable. All possible output types have been considered.
- /* istanbul ignore next */
- throw new Error("Cannot complete value of unexpected output type: \"".concat((0, _inspect.default)(returnType), "\"."));
- }
- /**
- * Complete a list value by completing each item in the list with the
- * inner type
- */
- function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {
- !(0, _iterall.isCollection)(result) ? (0, _invariant.default)(0, "Expected Iterable, but did not find one for field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")) : void 0; // This is specified as a simple map, however we're optimizing the path
- // where the list contains no Promises by avoiding creating another Promise.
- var itemType = returnType.ofType;
- var containsPromise = false;
- var completedResults = [];
- (0, _iterall.forEach)(result, function (item, index) {
- // No need to modify the info object containing the path,
- // since from here on it is not ever accessed by resolver functions.
- var fieldPath = addPath(path, index);
- var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item);
- if (!containsPromise && (0, _isPromise.default)(completedItem)) {
- containsPromise = true;
- }
- completedResults.push(completedItem);
- });
- return containsPromise ? Promise.all(completedResults) : completedResults;
- }
- /**
- * Complete a Scalar or Enum by serializing to a valid value, returning
- * null if serialization is not possible.
- */
- function completeLeafValue(returnType, result) {
- !returnType.serialize ? (0, _invariant.default)(0, 'Missing serialize method on type') : void 0;
- var serializedResult = returnType.serialize(result);
- if ((0, _isInvalid.default)(serializedResult)) {
- throw new Error("Expected a value of type \"".concat((0, _inspect.default)(returnType), "\" but ") + "received: ".concat((0, _inspect.default)(result)));
- }
- return serializedResult;
- }
- /**
- * Complete a value of an abstract type by determining the runtime object type
- * of that value, then complete the value for that type.
- */
- function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {
- var resolveTypeFn = returnType.resolveType || exeContext.typeResolver;
- var contextValue = exeContext.contextValue;
- var runtimeType = resolveTypeFn(result, contextValue, info, returnType);
- if ((0, _isPromise.default)(runtimeType)) {
- return runtimeType.then(function (resolvedRuntimeType) {
- return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
- });
- }
- return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
- }
- function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) {
- var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName;
- if (!(0, _definition.isObjectType)(runtimeType)) {
- throw new _GraphQLError.GraphQLError("Abstract type ".concat(returnType.name, " must resolve to an Object type at ") + "runtime for field ".concat(info.parentType.name, ".").concat(info.fieldName, " with ") + "value ".concat((0, _inspect.default)(result), ", received \"").concat((0, _inspect.default)(runtimeType), "\". ") + "Either the ".concat(returnType.name, " type should provide a \"resolveType\" ") + 'function or each possible type should provide an "isTypeOf" function.', fieldNodes);
- }
- if (!exeContext.schema.isPossibleType(returnType, runtimeType)) {
- throw new _GraphQLError.GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type ") + "for \"".concat(returnType.name, "\"."), fieldNodes);
- }
- return runtimeType;
- }
- /**
- * Complete an Object value by executing all sub-selections.
- */
- function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {
- // If there is an isTypeOf predicate function, call it with the
- // current result. If isTypeOf returns false, then raise an error rather
- // than continuing execution.
- if (returnType.isTypeOf) {
- var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
- if ((0, _isPromise.default)(isTypeOf)) {
- return isTypeOf.then(function (resolvedIsTypeOf) {
- if (!resolvedIsTypeOf) {
- throw invalidReturnTypeError(returnType, result, fieldNodes);
- }
- return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
- });
- }
- if (!isTypeOf) {
- throw invalidReturnTypeError(returnType, result, fieldNodes);
- }
- }
- return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
- }
- function invalidReturnTypeError(returnType, result, fieldNodes) {
- return new _GraphQLError.GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat((0, _inspect.default)(result), "."), fieldNodes);
- }
- function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) {
- // Collect sub-fields to execute to complete this value.
- var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);
- return executeFields(exeContext, returnType, result, path, subFieldNodes);
- }
- /**
- * A memoized collection of relevant subfields with regard to the return
- * type. Memoizing ensures the subfields are not repeatedly calculated, which
- * saves overhead when resolving lists of values.
- */
- var collectSubfields = (0, _memoize.default)(_collectSubfields);
- function _collectSubfields(exeContext, returnType, fieldNodes) {
- var subFieldNodes = Object.create(null);
- var visitedFragmentNames = Object.create(null);
- for (var i = 0; i < fieldNodes.length; i++) {
- var selectionSet = fieldNodes[i].selectionSet;
- if (selectionSet) {
- subFieldNodes = collectFields(exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames);
- }
- }
- return subFieldNodes;
- }
- /**
- * If a resolveType function is not given, then a default resolve behavior is
- * used which attempts two strategies:
- *
- * First, See if the provided value has a `__typename` field defined, if so, use
- * that value as name of the resolved type.
- *
- * Otherwise, test each possible type for the abstract type by calling
- * isTypeOf for the object being coerced, returning the first type that matches.
- */
- var defaultTypeResolver = function defaultTypeResolver(value, contextValue, info, abstractType) {
- // First, look for `__typename`.
- if (value !== null && _typeof(value) === 'object' && typeof value.__typename === 'string') {
- return value.__typename;
- } // Otherwise, test each possible type.
- var possibleTypes = info.schema.getPossibleTypes(abstractType);
- var promisedIsTypeOfResults = [];
- for (var i = 0; i < possibleTypes.length; i++) {
- var type = possibleTypes[i];
- if (type.isTypeOf) {
- var isTypeOfResult = type.isTypeOf(value, contextValue, info);
- if ((0, _isPromise.default)(isTypeOfResult)) {
- promisedIsTypeOfResults[i] = isTypeOfResult;
- } else if (isTypeOfResult) {
- return type;
- }
- }
- }
- if (promisedIsTypeOfResults.length) {
- return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) {
- for (var _i = 0; _i < isTypeOfResults.length; _i++) {
- if (isTypeOfResults[_i]) {
- return possibleTypes[_i];
- }
- }
- });
- }
- };
- /**
- * If a resolve function is not given, then a default resolve behavior is used
- * which takes the property of the source object of the same name as the field
- * and returns it as the result, or if it's a function, returns the result
- * of calling that function while passing along args and context value.
- */
- exports.defaultTypeResolver = defaultTypeResolver;
- var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) {
- // ensure source is a value for which property access is acceptable.
- if (_typeof(source) === 'object' || typeof source === 'function') {
- var property = source[info.fieldName];
- if (typeof property === 'function') {
- return source[info.fieldName](args, contextValue, info);
- }
- return property;
- }
- };
- /**
- * This method looks up the field on the given type definition.
- * It has special casing for the two introspection fields, __schema
- * and __typename. __typename is special because it can always be
- * queried as a field, even in situations where no other fields
- * are allowed, like on a Union. __schema could get automatically
- * added to the query type, but that would require mutating type
- * definitions, which would cause issues.
- */
- exports.defaultFieldResolver = defaultFieldResolver;
- function getFieldDef(schema, parentType, fieldName) {
- if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
- return _introspection.SchemaMetaFieldDef;
- } else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
- return _introspection.TypeMetaFieldDef;
- } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) {
- return _introspection.TypeNameMetaFieldDef;
- }
- return parentType.getFields()[fieldName];
- }
- },{"../error/GraphQLError":19,"../error/locatedError":22,"../jsutils/inspect":32,"../jsutils/invariant":34,"../jsutils/isInvalid":35,"../jsutils/isNullish":36,"../jsutils/isPromise":37,"../jsutils/memoize3":41,"../jsutils/promiseForObject":44,"../jsutils/promiseReduce":45,"../language/kinds":51,"../type/definition":68,"../type/directives":69,"../type/introspection":71,"../type/validate":74,"../utilities/getOperationRootType":86,"../utilities/typeFromAST":97,"./values":27,"iterall":137}],26:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "execute", {
- enumerable: true,
- get: function get() {
- return _execute.execute;
- }
- });
- Object.defineProperty(exports, "defaultFieldResolver", {
- enumerable: true,
- get: function get() {
- return _execute.defaultFieldResolver;
- }
- });
- Object.defineProperty(exports, "defaultTypeResolver", {
- enumerable: true,
- get: function get() {
- return _execute.defaultTypeResolver;
- }
- });
- Object.defineProperty(exports, "responsePathAsArray", {
- enumerable: true,
- get: function get() {
- return _execute.responsePathAsArray;
- }
- });
- Object.defineProperty(exports, "getDirectiveValues", {
- enumerable: true,
- get: function get() {
- return _values.getDirectiveValues;
- }
- });
- var _execute = require("./execute");
- var _values = require("./values");
- },{"./execute":25,"./values":27}],27:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getVariableValues = getVariableValues;
- exports.getArgumentValues = getArgumentValues;
- exports.getDirectiveValues = getDirectiveValues;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _GraphQLError = require("../error/GraphQLError");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- var _coerceValue = require("../utilities/coerceValue");
- var _typeFromAST = require("../utilities/typeFromAST");
- var _valueFromAST = require("../utilities/valueFromAST");
- var _kinds = require("../language/kinds");
- var _printer = require("../language/printer");
- var _definition = require("../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Prepares an object map of variableValues of the correct type based on the
- * provided variable definitions and arbitrary input. If the input cannot be
- * parsed to match the variable definitions, a GraphQLError will be thrown.
- *
- * Note: The returned value is a plain Object with a prototype, since it is
- * exposed to user code. Care should be taken to not pull values from the
- * Object prototype.
- */
- function getVariableValues(schema, varDefNodes, inputs) {
- var errors = [];
- var coercedValues = {};
- for (var i = 0; i < varDefNodes.length; i++) {
- var varDefNode = varDefNodes[i];
- var varName = varDefNode.variable.name.value;
- var varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type);
- if (!(0, _definition.isInputType)(varType)) {
- // Must use input types for variables. This should be caught during
- // validation, however is checked again here for safety.
- errors.push(new _GraphQLError.GraphQLError("Variable \"$".concat(varName, "\" expected value of type ") + "\"".concat((0, _printer.print)(varDefNode.type), "\" which cannot be used as an input type."), varDefNode.type));
- } else {
- var hasValue = hasOwnProperty(inputs, varName);
- var value = hasValue ? inputs[varName] : undefined;
- if (!hasValue && varDefNode.defaultValue) {
- // If no value was provided to a variable with a default value,
- // use the default value.
- coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType);
- } else if ((!hasValue || value === null) && (0, _definition.isNonNullType)(varType)) {
- // If no value or a nullish value was provided to a variable with a
- // non-null type (required), produce an error.
- errors.push(new _GraphQLError.GraphQLError(hasValue ? "Variable \"$".concat(varName, "\" of non-null type ") + "\"".concat((0, _inspect.default)(varType), "\" must not be null.") : "Variable \"$".concat(varName, "\" of required type ") + "\"".concat((0, _inspect.default)(varType), "\" was not provided."), varDefNode));
- } else if (hasValue) {
- if (value === null) {
- // If the explicit value `null` was provided, an entry in the coerced
- // values must exist as the value `null`.
- coercedValues[varName] = null;
- } else {
- // Otherwise, a non-null value was provided, coerce it to the expected
- // type or report an error if coercion fails.
- var coerced = (0, _coerceValue.coerceValue)(value, varType, varDefNode);
- var coercionErrors = coerced.errors;
- if (coercionErrors) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = coercionErrors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var error = _step.value;
- error.message = "Variable \"$".concat(varName, "\" got invalid value ").concat((0, _inspect.default)(value), "; ") + error.message;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- errors.push.apply(errors, coercionErrors);
- } else {
- coercedValues[varName] = coerced.value;
- }
- }
- }
- }
- }
- return errors.length === 0 ? {
- errors: undefined,
- coerced: coercedValues
- } : {
- errors: errors,
- coerced: undefined
- };
- }
- /**
- * Prepares an object map of argument values given a list of argument
- * definitions and list of argument AST nodes.
- *
- * Note: The returned value is a plain Object with a prototype, since it is
- * exposed to user code. Care should be taken to not pull values from the
- * Object prototype.
- */
- function getArgumentValues(def, node, variableValues) {
- var coercedValues = {};
- var argDefs = def.args;
- var argNodes = node.arguments;
- if (!argDefs || !argNodes) {
- return coercedValues;
- }
- var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) {
- return arg.name.value;
- });
- for (var i = 0; i < argDefs.length; i++) {
- var argDef = argDefs[i];
- var name = argDef.name;
- var argType = argDef.type;
- var argumentNode = argNodeMap[name];
- var hasValue = void 0;
- var isNull = void 0;
- if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) {
- var variableName = argumentNode.value.name.value;
- hasValue = variableValues != null && hasOwnProperty(variableValues, variableName);
- isNull = variableValues != null && variableValues[variableName] === null;
- } else {
- hasValue = argumentNode != null;
- isNull = argumentNode != null && argumentNode.value.kind === _kinds.Kind.NULL;
- }
- if (!hasValue && argDef.defaultValue !== undefined) {
- // If no argument was provided where the definition has a default value,
- // use the default value.
- coercedValues[name] = argDef.defaultValue;
- } else if ((!hasValue || isNull) && (0, _definition.isNonNullType)(argType)) {
- // If no argument or a null value was provided to an argument with a
- // non-null type (required), produce a field error.
- if (isNull) {
- throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat((0, _inspect.default)(argType), "\" ") + 'must not be null.', argumentNode.value);
- } else if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) {
- var _variableName = argumentNode.value.name.value;
- throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + "was provided the variable \"$".concat(_variableName, "\" ") + 'which was not provided a runtime value.', argumentNode.value);
- } else {
- throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + 'was not provided.', node);
- }
- } else if (hasValue) {
- if (argumentNode.value.kind === _kinds.Kind.NULL) {
- // If the explicit value `null` was provided, an entry in the coerced
- // values must exist as the value `null`.
- coercedValues[name] = null;
- } else if (argumentNode.value.kind === _kinds.Kind.VARIABLE) {
- var _variableName2 = argumentNode.value.name.value;
- !variableValues ? (0, _invariant.default)(0, 'Must exist for hasValue to be true.') : void 0; // Note: This does no further checking that this variable is correct.
- // This assumes that this query has been validated and the variable
- // usage here is of the correct type.
- coercedValues[name] = variableValues[_variableName2];
- } else {
- var valueNode = argumentNode.value;
- var coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues);
- if (coercedValue === undefined) {
- // Note: ValuesOfCorrectType validation should catch this before
- // execution. This is a runtime check to ensure execution does not
- // continue with an invalid argument value.
- throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat((0, _printer.print)(valueNode), "."), argumentNode.value);
- }
- coercedValues[name] = coercedValue;
- }
- }
- }
- return coercedValues;
- }
- /**
- * Prepares an object map of argument values given a directive definition
- * and a AST node which may contain directives. Optionally also accepts a map
- * of variable values.
- *
- * If the directive does not exist on the node, returns undefined.
- *
- * Note: The returned value is a plain Object with a prototype, since it is
- * exposed to user code. Care should be taken to not pull values from the
- * Object prototype.
- */
- function getDirectiveValues(directiveDef, node, variableValues) {
- var directiveNode = node.directives && (0, _find.default)(node.directives, function (directive) {
- return directive.name.value === directiveDef.name;
- });
- if (directiveNode) {
- return getArgumentValues(directiveDef, directiveNode, variableValues);
- }
- }
- function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
- },{"../error/GraphQLError":19,"../jsutils/inspect":32,"../jsutils/invariant":34,"../jsutils/keyMap":38,"../language/kinds":51,"../language/printer":56,"../polyfills/find":59,"../type/definition":68,"../utilities/coerceValue":80,"../utilities/typeFromAST":97,"../utilities/valueFromAST":98}],28:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.graphql = graphql;
- exports.graphqlSync = graphqlSync;
- var _isPromise = _interopRequireDefault(require("./jsutils/isPromise"));
- var _validate = require("./type/validate");
- var _parser = require("./language/parser");
- var _validate2 = require("./validation/validate");
- var _execute = require("./execution/execute");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {
- var _arguments = arguments;
- /* eslint-enable no-redeclare */
- // Always return a Promise for a consistent API.
- return new Promise(function (resolve) {
- return resolve( // Extract arguments from object args if provided.
- _arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, argsOrSchema.typeResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver));
- });
- }
- /**
- * The graphqlSync function also fulfills GraphQL operations by parsing,
- * validating, and executing a GraphQL document along side a GraphQL schema.
- * However, it guarantees to complete synchronously (or throw an error) assuming
- * that all field resolvers are also synchronous.
- */
- function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {
- /* eslint-enable no-redeclare */
- // Extract arguments from object args if provided.
- var result = arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, argsOrSchema.typeResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver); // Assert that the execution was synchronous.
- if ((0, _isPromise.default)(result)) {
- throw new Error('GraphQL execution failed to complete synchronously.');
- }
- return result;
- }
- function graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {
- // Validate Schema
- var schemaValidationErrors = (0, _validate.validateSchema)(schema);
- if (schemaValidationErrors.length > 0) {
- return {
- errors: schemaValidationErrors
- };
- } // Parse
- var document;
- try {
- document = (0, _parser.parse)(source);
- } catch (syntaxError) {
- return {
- errors: [syntaxError]
- };
- } // Validate
- var validationErrors = (0, _validate2.validate)(schema, document);
- if (validationErrors.length > 0) {
- return {
- errors: validationErrors
- };
- } // Execute
- return (0, _execute.execute)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver);
- }
- },{"./execution/execute":25,"./jsutils/isPromise":37,"./language/parser":54,"./type/validate":74,"./validation/validate":136}],29:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "graphql", {
- enumerable: true,
- get: function get() {
- return _graphql.graphql;
- }
- });
- Object.defineProperty(exports, "graphqlSync", {
- enumerable: true,
- get: function get() {
- return _graphql.graphqlSync;
- }
- });
- Object.defineProperty(exports, "GraphQLSchema", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLSchema;
- }
- });
- Object.defineProperty(exports, "GraphQLDirective", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLScalarType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLScalarType;
- }
- });
- Object.defineProperty(exports, "GraphQLObjectType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLObjectType;
- }
- });
- Object.defineProperty(exports, "GraphQLInterfaceType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLInterfaceType;
- }
- });
- Object.defineProperty(exports, "GraphQLUnionType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLUnionType;
- }
- });
- Object.defineProperty(exports, "GraphQLEnumType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLEnumType;
- }
- });
- Object.defineProperty(exports, "GraphQLInputObjectType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLInputObjectType;
- }
- });
- Object.defineProperty(exports, "GraphQLList", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLList;
- }
- });
- Object.defineProperty(exports, "GraphQLNonNull", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLNonNull;
- }
- });
- Object.defineProperty(exports, "specifiedScalarTypes", {
- enumerable: true,
- get: function get() {
- return _type.specifiedScalarTypes;
- }
- });
- Object.defineProperty(exports, "GraphQLInt", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLInt;
- }
- });
- Object.defineProperty(exports, "GraphQLFloat", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLFloat;
- }
- });
- Object.defineProperty(exports, "GraphQLString", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLString;
- }
- });
- Object.defineProperty(exports, "GraphQLBoolean", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLBoolean;
- }
- });
- Object.defineProperty(exports, "GraphQLID", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLID;
- }
- });
- Object.defineProperty(exports, "specifiedDirectives", {
- enumerable: true,
- get: function get() {
- return _type.specifiedDirectives;
- }
- });
- Object.defineProperty(exports, "GraphQLIncludeDirective", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLIncludeDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLSkipDirective", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLSkipDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLDeprecatedDirective", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLDeprecatedDirective;
- }
- });
- Object.defineProperty(exports, "TypeKind", {
- enumerable: true,
- get: function get() {
- return _type.TypeKind;
- }
- });
- Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", {
- enumerable: true,
- get: function get() {
- return _type.DEFAULT_DEPRECATION_REASON;
- }
- });
- Object.defineProperty(exports, "introspectionTypes", {
- enumerable: true,
- get: function get() {
- return _type.introspectionTypes;
- }
- });
- Object.defineProperty(exports, "__Schema", {
- enumerable: true,
- get: function get() {
- return _type.__Schema;
- }
- });
- Object.defineProperty(exports, "__Directive", {
- enumerable: true,
- get: function get() {
- return _type.__Directive;
- }
- });
- Object.defineProperty(exports, "__DirectiveLocation", {
- enumerable: true,
- get: function get() {
- return _type.__DirectiveLocation;
- }
- });
- Object.defineProperty(exports, "__Type", {
- enumerable: true,
- get: function get() {
- return _type.__Type;
- }
- });
- Object.defineProperty(exports, "__Field", {
- enumerable: true,
- get: function get() {
- return _type.__Field;
- }
- });
- Object.defineProperty(exports, "__InputValue", {
- enumerable: true,
- get: function get() {
- return _type.__InputValue;
- }
- });
- Object.defineProperty(exports, "__EnumValue", {
- enumerable: true,
- get: function get() {
- return _type.__EnumValue;
- }
- });
- Object.defineProperty(exports, "__TypeKind", {
- enumerable: true,
- get: function get() {
- return _type.__TypeKind;
- }
- });
- Object.defineProperty(exports, "SchemaMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _type.SchemaMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "TypeMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _type.TypeMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "TypeNameMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _type.TypeNameMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "isSchema", {
- enumerable: true,
- get: function get() {
- return _type.isSchema;
- }
- });
- Object.defineProperty(exports, "isDirective", {
- enumerable: true,
- get: function get() {
- return _type.isDirective;
- }
- });
- Object.defineProperty(exports, "isType", {
- enumerable: true,
- get: function get() {
- return _type.isType;
- }
- });
- Object.defineProperty(exports, "isScalarType", {
- enumerable: true,
- get: function get() {
- return _type.isScalarType;
- }
- });
- Object.defineProperty(exports, "isObjectType", {
- enumerable: true,
- get: function get() {
- return _type.isObjectType;
- }
- });
- Object.defineProperty(exports, "isInterfaceType", {
- enumerable: true,
- get: function get() {
- return _type.isInterfaceType;
- }
- });
- Object.defineProperty(exports, "isUnionType", {
- enumerable: true,
- get: function get() {
- return _type.isUnionType;
- }
- });
- Object.defineProperty(exports, "isEnumType", {
- enumerable: true,
- get: function get() {
- return _type.isEnumType;
- }
- });
- Object.defineProperty(exports, "isInputObjectType", {
- enumerable: true,
- get: function get() {
- return _type.isInputObjectType;
- }
- });
- Object.defineProperty(exports, "isListType", {
- enumerable: true,
- get: function get() {
- return _type.isListType;
- }
- });
- Object.defineProperty(exports, "isNonNullType", {
- enumerable: true,
- get: function get() {
- return _type.isNonNullType;
- }
- });
- Object.defineProperty(exports, "isInputType", {
- enumerable: true,
- get: function get() {
- return _type.isInputType;
- }
- });
- Object.defineProperty(exports, "isOutputType", {
- enumerable: true,
- get: function get() {
- return _type.isOutputType;
- }
- });
- Object.defineProperty(exports, "isLeafType", {
- enumerable: true,
- get: function get() {
- return _type.isLeafType;
- }
- });
- Object.defineProperty(exports, "isCompositeType", {
- enumerable: true,
- get: function get() {
- return _type.isCompositeType;
- }
- });
- Object.defineProperty(exports, "isAbstractType", {
- enumerable: true,
- get: function get() {
- return _type.isAbstractType;
- }
- });
- Object.defineProperty(exports, "isWrappingType", {
- enumerable: true,
- get: function get() {
- return _type.isWrappingType;
- }
- });
- Object.defineProperty(exports, "isNullableType", {
- enumerable: true,
- get: function get() {
- return _type.isNullableType;
- }
- });
- Object.defineProperty(exports, "isNamedType", {
- enumerable: true,
- get: function get() {
- return _type.isNamedType;
- }
- });
- Object.defineProperty(exports, "isRequiredArgument", {
- enumerable: true,
- get: function get() {
- return _type.isRequiredArgument;
- }
- });
- Object.defineProperty(exports, "isRequiredInputField", {
- enumerable: true,
- get: function get() {
- return _type.isRequiredInputField;
- }
- });
- Object.defineProperty(exports, "isSpecifiedScalarType", {
- enumerable: true,
- get: function get() {
- return _type.isSpecifiedScalarType;
- }
- });
- Object.defineProperty(exports, "isIntrospectionType", {
- enumerable: true,
- get: function get() {
- return _type.isIntrospectionType;
- }
- });
- Object.defineProperty(exports, "isSpecifiedDirective", {
- enumerable: true,
- get: function get() {
- return _type.isSpecifiedDirective;
- }
- });
- Object.defineProperty(exports, "assertSchema", {
- enumerable: true,
- get: function get() {
- return _type.assertSchema;
- }
- });
- Object.defineProperty(exports, "assertDirective", {
- enumerable: true,
- get: function get() {
- return _type.assertDirective;
- }
- });
- Object.defineProperty(exports, "assertType", {
- enumerable: true,
- get: function get() {
- return _type.assertType;
- }
- });
- Object.defineProperty(exports, "assertScalarType", {
- enumerable: true,
- get: function get() {
- return _type.assertScalarType;
- }
- });
- Object.defineProperty(exports, "assertObjectType", {
- enumerable: true,
- get: function get() {
- return _type.assertObjectType;
- }
- });
- Object.defineProperty(exports, "assertInterfaceType", {
- enumerable: true,
- get: function get() {
- return _type.assertInterfaceType;
- }
- });
- Object.defineProperty(exports, "assertUnionType", {
- enumerable: true,
- get: function get() {
- return _type.assertUnionType;
- }
- });
- Object.defineProperty(exports, "assertEnumType", {
- enumerable: true,
- get: function get() {
- return _type.assertEnumType;
- }
- });
- Object.defineProperty(exports, "assertInputObjectType", {
- enumerable: true,
- get: function get() {
- return _type.assertInputObjectType;
- }
- });
- Object.defineProperty(exports, "assertListType", {
- enumerable: true,
- get: function get() {
- return _type.assertListType;
- }
- });
- Object.defineProperty(exports, "assertNonNullType", {
- enumerable: true,
- get: function get() {
- return _type.assertNonNullType;
- }
- });
- Object.defineProperty(exports, "assertInputType", {
- enumerable: true,
- get: function get() {
- return _type.assertInputType;
- }
- });
- Object.defineProperty(exports, "assertOutputType", {
- enumerable: true,
- get: function get() {
- return _type.assertOutputType;
- }
- });
- Object.defineProperty(exports, "assertLeafType", {
- enumerable: true,
- get: function get() {
- return _type.assertLeafType;
- }
- });
- Object.defineProperty(exports, "assertCompositeType", {
- enumerable: true,
- get: function get() {
- return _type.assertCompositeType;
- }
- });
- Object.defineProperty(exports, "assertAbstractType", {
- enumerable: true,
- get: function get() {
- return _type.assertAbstractType;
- }
- });
- Object.defineProperty(exports, "assertWrappingType", {
- enumerable: true,
- get: function get() {
- return _type.assertWrappingType;
- }
- });
- Object.defineProperty(exports, "assertNullableType", {
- enumerable: true,
- get: function get() {
- return _type.assertNullableType;
- }
- });
- Object.defineProperty(exports, "assertNamedType", {
- enumerable: true,
- get: function get() {
- return _type.assertNamedType;
- }
- });
- Object.defineProperty(exports, "getNullableType", {
- enumerable: true,
- get: function get() {
- return _type.getNullableType;
- }
- });
- Object.defineProperty(exports, "getNamedType", {
- enumerable: true,
- get: function get() {
- return _type.getNamedType;
- }
- });
- Object.defineProperty(exports, "validateSchema", {
- enumerable: true,
- get: function get() {
- return _type.validateSchema;
- }
- });
- Object.defineProperty(exports, "assertValidSchema", {
- enumerable: true,
- get: function get() {
- return _type.assertValidSchema;
- }
- });
- Object.defineProperty(exports, "Source", {
- enumerable: true,
- get: function get() {
- return _language.Source;
- }
- });
- Object.defineProperty(exports, "getLocation", {
- enumerable: true,
- get: function get() {
- return _language.getLocation;
- }
- });
- Object.defineProperty(exports, "createLexer", {
- enumerable: true,
- get: function get() {
- return _language.createLexer;
- }
- });
- Object.defineProperty(exports, "TokenKind", {
- enumerable: true,
- get: function get() {
- return _language.TokenKind;
- }
- });
- Object.defineProperty(exports, "parse", {
- enumerable: true,
- get: function get() {
- return _language.parse;
- }
- });
- Object.defineProperty(exports, "parseValue", {
- enumerable: true,
- get: function get() {
- return _language.parseValue;
- }
- });
- Object.defineProperty(exports, "parseType", {
- enumerable: true,
- get: function get() {
- return _language.parseType;
- }
- });
- Object.defineProperty(exports, "print", {
- enumerable: true,
- get: function get() {
- return _language.print;
- }
- });
- Object.defineProperty(exports, "visit", {
- enumerable: true,
- get: function get() {
- return _language.visit;
- }
- });
- Object.defineProperty(exports, "visitInParallel", {
- enumerable: true,
- get: function get() {
- return _language.visitInParallel;
- }
- });
- Object.defineProperty(exports, "visitWithTypeInfo", {
- enumerable: true,
- get: function get() {
- return _language.visitWithTypeInfo;
- }
- });
- Object.defineProperty(exports, "getVisitFn", {
- enumerable: true,
- get: function get() {
- return _language.getVisitFn;
- }
- });
- Object.defineProperty(exports, "BREAK", {
- enumerable: true,
- get: function get() {
- return _language.BREAK;
- }
- });
- Object.defineProperty(exports, "Kind", {
- enumerable: true,
- get: function get() {
- return _language.Kind;
- }
- });
- Object.defineProperty(exports, "DirectiveLocation", {
- enumerable: true,
- get: function get() {
- return _language.DirectiveLocation;
- }
- });
- Object.defineProperty(exports, "isDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _language.isDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isExecutableDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _language.isExecutableDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isSelectionNode", {
- enumerable: true,
- get: function get() {
- return _language.isSelectionNode;
- }
- });
- Object.defineProperty(exports, "isValueNode", {
- enumerable: true,
- get: function get() {
- return _language.isValueNode;
- }
- });
- Object.defineProperty(exports, "isTypeNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeNode;
- }
- });
- Object.defineProperty(exports, "isTypeSystemDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeSystemDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isTypeDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isTypeSystemExtensionNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeSystemExtensionNode;
- }
- });
- Object.defineProperty(exports, "isTypeExtensionNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeExtensionNode;
- }
- });
- Object.defineProperty(exports, "execute", {
- enumerable: true,
- get: function get() {
- return _execution.execute;
- }
- });
- Object.defineProperty(exports, "defaultFieldResolver", {
- enumerable: true,
- get: function get() {
- return _execution.defaultFieldResolver;
- }
- });
- Object.defineProperty(exports, "defaultTypeResolver", {
- enumerable: true,
- get: function get() {
- return _execution.defaultTypeResolver;
- }
- });
- Object.defineProperty(exports, "responsePathAsArray", {
- enumerable: true,
- get: function get() {
- return _execution.responsePathAsArray;
- }
- });
- Object.defineProperty(exports, "getDirectiveValues", {
- enumerable: true,
- get: function get() {
- return _execution.getDirectiveValues;
- }
- });
- Object.defineProperty(exports, "subscribe", {
- enumerable: true,
- get: function get() {
- return _subscription.subscribe;
- }
- });
- Object.defineProperty(exports, "createSourceEventStream", {
- enumerable: true,
- get: function get() {
- return _subscription.createSourceEventStream;
- }
- });
- Object.defineProperty(exports, "validate", {
- enumerable: true,
- get: function get() {
- return _validation.validate;
- }
- });
- Object.defineProperty(exports, "ValidationContext", {
- enumerable: true,
- get: function get() {
- return _validation.ValidationContext;
- }
- });
- Object.defineProperty(exports, "specifiedRules", {
- enumerable: true,
- get: function get() {
- return _validation.specifiedRules;
- }
- });
- Object.defineProperty(exports, "FieldsOnCorrectTypeRule", {
- enumerable: true,
- get: function get() {
- return _validation.FieldsOnCorrectTypeRule;
- }
- });
- Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", {
- enumerable: true,
- get: function get() {
- return _validation.FragmentsOnCompositeTypesRule;
- }
- });
- Object.defineProperty(exports, "KnownArgumentNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.KnownArgumentNamesRule;
- }
- });
- Object.defineProperty(exports, "KnownDirectivesRule", {
- enumerable: true,
- get: function get() {
- return _validation.KnownDirectivesRule;
- }
- });
- Object.defineProperty(exports, "KnownFragmentNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.KnownFragmentNamesRule;
- }
- });
- Object.defineProperty(exports, "KnownTypeNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.KnownTypeNamesRule;
- }
- });
- Object.defineProperty(exports, "LoneAnonymousOperationRule", {
- enumerable: true,
- get: function get() {
- return _validation.LoneAnonymousOperationRule;
- }
- });
- Object.defineProperty(exports, "NoFragmentCyclesRule", {
- enumerable: true,
- get: function get() {
- return _validation.NoFragmentCyclesRule;
- }
- });
- Object.defineProperty(exports, "NoUndefinedVariablesRule", {
- enumerable: true,
- get: function get() {
- return _validation.NoUndefinedVariablesRule;
- }
- });
- Object.defineProperty(exports, "NoUnusedFragmentsRule", {
- enumerable: true,
- get: function get() {
- return _validation.NoUnusedFragmentsRule;
- }
- });
- Object.defineProperty(exports, "NoUnusedVariablesRule", {
- enumerable: true,
- get: function get() {
- return _validation.NoUnusedVariablesRule;
- }
- });
- Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", {
- enumerable: true,
- get: function get() {
- return _validation.OverlappingFieldsCanBeMergedRule;
- }
- });
- Object.defineProperty(exports, "PossibleFragmentSpreadsRule", {
- enumerable: true,
- get: function get() {
- return _validation.PossibleFragmentSpreadsRule;
- }
- });
- Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", {
- enumerable: true,
- get: function get() {
- return _validation.ProvidedRequiredArgumentsRule;
- }
- });
- Object.defineProperty(exports, "ScalarLeafsRule", {
- enumerable: true,
- get: function get() {
- return _validation.ScalarLeafsRule;
- }
- });
- Object.defineProperty(exports, "SingleFieldSubscriptionsRule", {
- enumerable: true,
- get: function get() {
- return _validation.SingleFieldSubscriptionsRule;
- }
- });
- Object.defineProperty(exports, "UniqueArgumentNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueArgumentNamesRule;
- }
- });
- Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueDirectivesPerLocationRule;
- }
- });
- Object.defineProperty(exports, "UniqueFragmentNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueFragmentNamesRule;
- }
- });
- Object.defineProperty(exports, "UniqueInputFieldNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueInputFieldNamesRule;
- }
- });
- Object.defineProperty(exports, "UniqueOperationNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueOperationNamesRule;
- }
- });
- Object.defineProperty(exports, "UniqueVariableNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueVariableNamesRule;
- }
- });
- Object.defineProperty(exports, "ValuesOfCorrectTypeRule", {
- enumerable: true,
- get: function get() {
- return _validation.ValuesOfCorrectTypeRule;
- }
- });
- Object.defineProperty(exports, "VariablesAreInputTypesRule", {
- enumerable: true,
- get: function get() {
- return _validation.VariablesAreInputTypesRule;
- }
- });
- Object.defineProperty(exports, "VariablesInAllowedPositionRule", {
- enumerable: true,
- get: function get() {
- return _validation.VariablesInAllowedPositionRule;
- }
- });
- Object.defineProperty(exports, "GraphQLError", {
- enumerable: true,
- get: function get() {
- return _error.GraphQLError;
- }
- });
- Object.defineProperty(exports, "syntaxError", {
- enumerable: true,
- get: function get() {
- return _error.syntaxError;
- }
- });
- Object.defineProperty(exports, "locatedError", {
- enumerable: true,
- get: function get() {
- return _error.locatedError;
- }
- });
- Object.defineProperty(exports, "printError", {
- enumerable: true,
- get: function get() {
- return _error.printError;
- }
- });
- Object.defineProperty(exports, "formatError", {
- enumerable: true,
- get: function get() {
- return _error.formatError;
- }
- });
- Object.defineProperty(exports, "getIntrospectionQuery", {
- enumerable: true,
- get: function get() {
- return _utilities.getIntrospectionQuery;
- }
- });
- Object.defineProperty(exports, "introspectionQuery", {
- enumerable: true,
- get: function get() {
- return _utilities.introspectionQuery;
- }
- });
- Object.defineProperty(exports, "getOperationAST", {
- enumerable: true,
- get: function get() {
- return _utilities.getOperationAST;
- }
- });
- Object.defineProperty(exports, "getOperationRootType", {
- enumerable: true,
- get: function get() {
- return _utilities.getOperationRootType;
- }
- });
- Object.defineProperty(exports, "introspectionFromSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.introspectionFromSchema;
- }
- });
- Object.defineProperty(exports, "buildClientSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.buildClientSchema;
- }
- });
- Object.defineProperty(exports, "buildASTSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.buildASTSchema;
- }
- });
- Object.defineProperty(exports, "buildSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.buildSchema;
- }
- });
- Object.defineProperty(exports, "getDescription", {
- enumerable: true,
- get: function get() {
- return _utilities.getDescription;
- }
- });
- Object.defineProperty(exports, "extendSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.extendSchema;
- }
- });
- Object.defineProperty(exports, "lexicographicSortSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.lexicographicSortSchema;
- }
- });
- Object.defineProperty(exports, "printSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.printSchema;
- }
- });
- Object.defineProperty(exports, "printType", {
- enumerable: true,
- get: function get() {
- return _utilities.printType;
- }
- });
- Object.defineProperty(exports, "printIntrospectionSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.printIntrospectionSchema;
- }
- });
- Object.defineProperty(exports, "typeFromAST", {
- enumerable: true,
- get: function get() {
- return _utilities.typeFromAST;
- }
- });
- Object.defineProperty(exports, "valueFromAST", {
- enumerable: true,
- get: function get() {
- return _utilities.valueFromAST;
- }
- });
- Object.defineProperty(exports, "valueFromASTUntyped", {
- enumerable: true,
- get: function get() {
- return _utilities.valueFromASTUntyped;
- }
- });
- Object.defineProperty(exports, "astFromValue", {
- enumerable: true,
- get: function get() {
- return _utilities.astFromValue;
- }
- });
- Object.defineProperty(exports, "TypeInfo", {
- enumerable: true,
- get: function get() {
- return _utilities.TypeInfo;
- }
- });
- Object.defineProperty(exports, "coerceValue", {
- enumerable: true,
- get: function get() {
- return _utilities.coerceValue;
- }
- });
- Object.defineProperty(exports, "isValidJSValue", {
- enumerable: true,
- get: function get() {
- return _utilities.isValidJSValue;
- }
- });
- Object.defineProperty(exports, "isValidLiteralValue", {
- enumerable: true,
- get: function get() {
- return _utilities.isValidLiteralValue;
- }
- });
- Object.defineProperty(exports, "concatAST", {
- enumerable: true,
- get: function get() {
- return _utilities.concatAST;
- }
- });
- Object.defineProperty(exports, "separateOperations", {
- enumerable: true,
- get: function get() {
- return _utilities.separateOperations;
- }
- });
- Object.defineProperty(exports, "stripIgnoredCharacters", {
- enumerable: true,
- get: function get() {
- return _utilities.stripIgnoredCharacters;
- }
- });
- Object.defineProperty(exports, "isEqualType", {
- enumerable: true,
- get: function get() {
- return _utilities.isEqualType;
- }
- });
- Object.defineProperty(exports, "isTypeSubTypeOf", {
- enumerable: true,
- get: function get() {
- return _utilities.isTypeSubTypeOf;
- }
- });
- Object.defineProperty(exports, "doTypesOverlap", {
- enumerable: true,
- get: function get() {
- return _utilities.doTypesOverlap;
- }
- });
- Object.defineProperty(exports, "assertValidName", {
- enumerable: true,
- get: function get() {
- return _utilities.assertValidName;
- }
- });
- Object.defineProperty(exports, "isValidNameError", {
- enumerable: true,
- get: function get() {
- return _utilities.isValidNameError;
- }
- });
- Object.defineProperty(exports, "BreakingChangeType", {
- enumerable: true,
- get: function get() {
- return _utilities.BreakingChangeType;
- }
- });
- Object.defineProperty(exports, "DangerousChangeType", {
- enumerable: true,
- get: function get() {
- return _utilities.DangerousChangeType;
- }
- });
- Object.defineProperty(exports, "findBreakingChanges", {
- enumerable: true,
- get: function get() {
- return _utilities.findBreakingChanges;
- }
- });
- Object.defineProperty(exports, "findDangerousChanges", {
- enumerable: true,
- get: function get() {
- return _utilities.findDangerousChanges;
- }
- });
- Object.defineProperty(exports, "findDeprecatedUsages", {
- enumerable: true,
- get: function get() {
- return _utilities.findDeprecatedUsages;
- }
- });
- var _graphql = require("./graphql");
- var _type = require("./type");
- var _language = require("./language");
- var _execution = require("./execution");
- var _subscription = require("./subscription");
- var _validation = require("./validation");
- var _error = require("./error");
- var _utilities = require("./utilities");
- },{"./error":21,"./execution":26,"./graphql":28,"./language":50,"./subscription":65,"./type":70,"./utilities":87,"./validation":101}],30:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = defineToJSON;
- var _nodejsCustomInspectSymbol = _interopRequireDefault(require("./nodejsCustomInspectSymbol"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * The `defineToJSON()` function defines toJSON() and inspect() prototype
- * methods, if no function provided they become aliases for toString().
- */
- function defineToJSON( // eslint-disable-next-line flowtype/no-weak-types
- classObject) {
- var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : classObject.prototype.toString;
- classObject.prototype.toJSON = fn;
- classObject.prototype.inspect = fn;
- if (_nodejsCustomInspectSymbol.default) {
- classObject.prototype[_nodejsCustomInspectSymbol.default] = fn;
- }
- }
- },{"./nodejsCustomInspectSymbol":42}],31:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = defineToStringTag;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * The `defineToStringTag()` function checks first to see if the runtime
- * supports the `Symbol` class and then if the `Symbol.toStringTag` constant
- * is defined as a `Symbol` instance. If both conditions are met, the
- * Symbol.toStringTag property is defined as a getter that returns the
- * supplied class constructor's name.
- *
- * @method defineToStringTag
- *
- * @param {Class<any>} classObject a class such as Object, String, Number but
- * typically one of your own creation through the class keyword; `class A {}`,
- * for example.
- */
- function defineToStringTag(classObject) {
- if (typeof Symbol === 'function' && Symbol.toStringTag) {
- Object.defineProperty(classObject.prototype, Symbol.toStringTag, {
- get: function get() {
- return this.constructor.name;
- }
- });
- }
- }
- },{}],32:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = inspect;
- var _nodejsCustomInspectSymbol = _interopRequireDefault(require("./nodejsCustomInspectSymbol"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- var MAX_ARRAY_LENGTH = 10;
- var MAX_RECURSIVE_DEPTH = 2;
- /**
- * Used to print values in error messages.
- */
- function inspect(value) {
- return formatValue(value, []);
- }
- function formatValue(value, seenValues) {
- switch (_typeof(value)) {
- case 'string':
- return JSON.stringify(value);
- case 'function':
- return value.name ? "[function ".concat(value.name, "]") : '[function]';
- case 'object':
- return formatObjectValue(value, seenValues);
- default:
- return String(value);
- }
- }
- function formatObjectValue(value, previouslySeenValues) {
- if (previouslySeenValues.indexOf(value) !== -1) {
- return '[Circular]';
- }
- var seenValues = [].concat(previouslySeenValues, [value]);
- if (value) {
- var customInspectFn = getCustomFn(value);
- if (customInspectFn !== undefined) {
- // $FlowFixMe(>=0.90.0)
- var customValue = customInspectFn.call(value); // check for infinite recursion
- if (customValue !== value) {
- return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues);
- }
- } else if (Array.isArray(value)) {
- return formatArray(value, seenValues);
- }
- return formatObject(value, seenValues);
- }
- return String(value);
- }
- function formatObject(object, seenValues) {
- var keys = Object.keys(object);
- if (keys.length === 0) {
- return '{}';
- }
- if (seenValues.length > MAX_RECURSIVE_DEPTH) {
- return '[' + getObjectTag(object) + ']';
- }
- var properties = keys.map(function (key) {
- var value = formatValue(object[key], seenValues);
- return key + ': ' + value;
- });
- return '{ ' + properties.join(', ') + ' }';
- }
- function formatArray(array, seenValues) {
- if (array.length === 0) {
- return '[]';
- }
- if (seenValues.length > MAX_RECURSIVE_DEPTH) {
- return '[Array]';
- }
- var len = Math.min(MAX_ARRAY_LENGTH, array.length);
- var remaining = array.length - len;
- var items = [];
- for (var i = 0; i < len; ++i) {
- items.push(formatValue(array[i], seenValues));
- }
- if (remaining === 1) {
- items.push('... 1 more item');
- } else if (remaining > 1) {
- items.push("... ".concat(remaining, " more items"));
- }
- return '[' + items.join(', ') + ']';
- }
- function getCustomFn(object) {
- var customInspectFn = object[String(_nodejsCustomInspectSymbol.default)];
- if (typeof customInspectFn === 'function') {
- return customInspectFn;
- }
- if (typeof object.inspect === 'function') {
- return object.inspect;
- }
- }
- function getObjectTag(object) {
- var tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, '');
- if (tag === 'Object' && typeof object.constructor === 'function') {
- var name = object.constructor.name;
- if (typeof name === 'string') {
- return name;
- }
- }
- return tag;
- }
- },{"./nodejsCustomInspectSymbol":42}],33:[function(require,module,exports){
- (function (process){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * A replacement for instanceof which includes an error warning when multi-realm
- * constructors are detected.
- */
- // See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
- // See: https://webpack.js.org/guides/production/
- var _default = process.env.NODE_ENV === 'production' ? // eslint-disable-next-line no-shadow
- function instanceOf(value, constructor) {
- return value instanceof constructor;
- } : // eslint-disable-next-line no-shadow
- function instanceOf(value, constructor) {
- if (value instanceof constructor) {
- return true;
- }
- if (value) {
- var valueClass = value.constructor;
- var className = constructor.name;
- if (className && valueClass && valueClass.name === className) {
- throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results."));
- }
- }
- return false;
- };
- exports.default = _default;
- }).call(this,require('_process'))
- },{"_process":198}],34:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = invariant;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function invariant(condition, message) {
- var booleanCondition = Boolean(condition);
- /* istanbul ignore else */
- if (!booleanCondition) {
- throw new Error(message);
- }
- }
- },{}],35:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = isInvalid;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Returns true if a value is undefined, or NaN.
- */
- function isInvalid(value) {
- return value === undefined || value !== value;
- }
- },{}],36:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = isNullish;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Returns true if a value is null, undefined, or NaN.
- */
- function isNullish(value) {
- return value === null || value === undefined || value !== value;
- }
- },{}],37:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = isPromise;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Returns true if the value acts like a Promise, i.e. has a "then" function,
- * otherwise returns false.
- */
- // eslint-disable-next-line no-redeclare
- function isPromise(value) {
- return Boolean(value && typeof value.then === 'function');
- }
- },{}],38:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = keyMap;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Creates a keyed JS object from an array, given a function to produce the keys
- * for each value in the array.
- *
- * This provides a convenient lookup for the array items if the key function
- * produces unique results.
- *
- * const phoneBook = [
- * { name: 'Jon', num: '555-1234' },
- * { name: 'Jenny', num: '867-5309' }
- * ]
- *
- * // { Jon: { name: 'Jon', num: '555-1234' },
- * // Jenny: { name: 'Jenny', num: '867-5309' } }
- * const entriesByName = keyMap(
- * phoneBook,
- * entry => entry.name
- * )
- *
- * // { name: 'Jenny', num: '857-6309' }
- * const jennyEntry = entriesByName['Jenny']
- *
- */
- function keyMap(list, keyFn) {
- return list.reduce(function (map, item) {
- map[keyFn(item)] = item;
- return map;
- }, Object.create(null));
- }
- },{}],39:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = keyValMap;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Creates a keyed JS object from an array, given a function to produce the keys
- * and a function to produce the values from each item in the array.
- *
- * const phoneBook = [
- * { name: 'Jon', num: '555-1234' },
- * { name: 'Jenny', num: '867-5309' }
- * ]
- *
- * // { Jon: '555-1234', Jenny: '867-5309' }
- * const phonesByName = keyValMap(
- * phoneBook,
- * entry => entry.name,
- * entry => entry.num
- * )
- *
- */
- function keyValMap(list, keyFn, valFn) {
- return list.reduce(function (map, item) {
- map[keyFn(item)] = valFn(item);
- return map;
- }, Object.create(null));
- }
- },{}],40:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = mapValue;
- var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Creates an object map with the same keys as `map` and values generated by
- * running each value of `map` thru `fn`.
- */
- function mapValue(map, fn) {
- var result = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectEntries.default)(map)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref2 = _step.value;
- var _key = _ref2[0];
- var _value = _ref2[1];
- result[_key] = fn(_value, _key);
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return result;
- }
- },{"../polyfills/objectEntries":63}],41:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = memoize3;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Memoizes the provided three-argument function.
- */
- function memoize3(fn) {
- var cache0;
- function memoized(a1, a2, a3) {
- if (!cache0) {
- cache0 = new WeakMap();
- }
- var cache1 = cache0.get(a1);
- var cache2;
- if (cache1) {
- cache2 = cache1.get(a2);
- if (cache2) {
- var cachedValue = cache2.get(a3);
- if (cachedValue !== undefined) {
- return cachedValue;
- }
- }
- } else {
- cache1 = new WeakMap();
- cache0.set(a1, cache1);
- }
- if (!cache2) {
- cache2 = new WeakMap();
- cache1.set(a2, cache2);
- }
- var newValue = fn(a1, a2, a3);
- cache2.set(a3, newValue);
- return newValue;
- }
- return memoized;
- }
- },{}],42:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var nodejsCustomInspectSymbol = typeof Symbol === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;
- var _default = nodejsCustomInspectSymbol;
- exports.default = _default;
- },{}],43:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = orList;
- var _invariant = _interopRequireDefault(require("./invariant"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var MAX_LENGTH = 5;
- /**
- * Given [ A, B, C ] return 'A, B, or C'.
- */
- function orList(items) {
- !(items.length !== 0) ? (0, _invariant.default)(0) : void 0;
- if (items.length === 1) {
- return items[0];
- }
- if (items.length === 2) {
- return items[0] + ' or ' + items[1];
- }
- var selected = items.slice(0, MAX_LENGTH);
- var lastItem = selected.pop();
- return selected.join(', ') + ', or ' + lastItem;
- }
- },{"./invariant":34}],44:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = promiseForObject;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * This function transforms a JS object `ObjMap<Promise<T>>` into
- * a `Promise<ObjMap<T>>`
- *
- * This is akin to bluebird's `Promise.props`, but implemented only using
- * `Promise.all` so it will work with any implementation of ES6 promises.
- */
- function promiseForObject(object) {
- var keys = Object.keys(object);
- var valuesAndPromises = keys.map(function (name) {
- return object[name];
- });
- return Promise.all(valuesAndPromises).then(function (values) {
- return values.reduce(function (resolvedObject, value, i) {
- resolvedObject[keys[i]] = value;
- return resolvedObject;
- }, Object.create(null));
- });
- }
- },{}],45:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = promiseReduce;
- var _isPromise = _interopRequireDefault(require("./isPromise"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Similar to Array.prototype.reduce(), however the reducing callback may return
- * a Promise, in which case reduction will continue after each promise resolves.
- *
- * If the callback does not return a Promise, then this function will also not
- * return a Promise.
- */
- function promiseReduce(values, callback, initialValue) {
- return values.reduce(function (previous, value) {
- return (0, _isPromise.default)(previous) ? previous.then(function (resolved) {
- return callback(resolved, value);
- }) : callback(previous, value);
- }, initialValue);
- }
- },{"./isPromise":37}],46:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = quotedOrList;
- var _orList = _interopRequireDefault(require("./orList"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given [ A, B, C ] return '"A", "B", or "C"'.
- */
- function quotedOrList(items) {
- return (0, _orList.default)(items.map(function (item) {
- return "\"".concat(item, "\"");
- }));
- }
- },{"./orList":43}],47:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = suggestionList;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given an invalid input string and a list of valid options, returns a filtered
- * list of valid options sorted based on their similarity with the input.
- */
- function suggestionList(input, options) {
- var optionsByDistance = Object.create(null);
- var oLength = options.length;
- var inputThreshold = input.length / 2;
- for (var i = 0; i < oLength; i++) {
- var distance = lexicalDistance(input, options[i]);
- var threshold = Math.max(inputThreshold, options[i].length / 2, 1);
- if (distance <= threshold) {
- optionsByDistance[options[i]] = distance;
- }
- }
- return Object.keys(optionsByDistance).sort(function (a, b) {
- return optionsByDistance[a] - optionsByDistance[b];
- });
- }
- /**
- * Computes the lexical distance between strings A and B.
- *
- * The "distance" between two strings is given by counting the minimum number
- * of edits needed to transform string A into string B. An edit can be an
- * insertion, deletion, or substitution of a single character, or a swap of two
- * adjacent characters.
- *
- * Includes a custom alteration from Damerau-Levenshtein to treat case changes
- * as a single edit which helps identify mis-cased values with an edit distance
- * of 1.
- *
- * This distance can be useful for detecting typos in input or sorting
- *
- * @param {string} a
- * @param {string} b
- * @return {int} distance in number of edits
- */
- function lexicalDistance(aStr, bStr) {
- if (aStr === bStr) {
- return 0;
- }
- var i;
- var j;
- var d = [];
- var a = aStr.toLowerCase();
- var b = bStr.toLowerCase();
- var aLength = a.length;
- var bLength = b.length; // Any case change counts as a single edit
- if (a === b) {
- return 1;
- }
- for (i = 0; i <= aLength; i++) {
- d[i] = [i];
- }
- for (j = 1; j <= bLength; j++) {
- d[0][j] = j;
- }
- for (i = 1; i <= aLength; i++) {
- for (j = 1; j <= bLength; j++) {
- var cost = a[i - 1] === b[j - 1] ? 0 : 1;
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
- }
- }
- }
- return d[aLength][bLength];
- }
- },{}],48:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.dedentBlockStringValue = dedentBlockStringValue;
- exports.getBlockStringIndentation = getBlockStringIndentation;
- exports.printBlockString = printBlockString;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Produces the value of a block string from its parsed raw value, similar to
- * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.
- *
- * This implements the GraphQL spec's BlockStringValue() static algorithm.
- */
- function dedentBlockStringValue(rawString) {
- // Expand a block string's raw value into independent lines.
- var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first.
- var commonIndent = getBlockStringIndentation(lines);
- if (commonIndent !== 0) {
- for (var i = 1; i < lines.length; i++) {
- lines[i] = lines[i].slice(commonIndent);
- }
- } // Remove leading and trailing blank lines.
- while (lines.length > 0 && isBlank(lines[0])) {
- lines.shift();
- }
- while (lines.length > 0 && isBlank(lines[lines.length - 1])) {
- lines.pop();
- } // Return a string of the lines joined with U+000A.
- return lines.join('\n');
- } // @internal
- function getBlockStringIndentation(lines) {
- var commonIndent = null;
- for (var i = 1; i < lines.length; i++) {
- var line = lines[i];
- var indent = leadingWhitespace(line);
- if (indent === line.length) {
- continue; // skip empty lines
- }
- if (commonIndent === null || indent < commonIndent) {
- commonIndent = indent;
- if (commonIndent === 0) {
- break;
- }
- }
- }
- return commonIndent === null ? 0 : commonIndent;
- }
- function leadingWhitespace(str) {
- var i = 0;
- while (i < str.length && (str[i] === ' ' || str[i] === '\t')) {
- i++;
- }
- return i;
- }
- function isBlank(str) {
- return leadingWhitespace(str) === str.length;
- }
- /**
- * Print a block string in the indented block form by adding a leading and
- * trailing blank line. However, if a block string starts with whitespace and is
- * a single-line, adding a leading blank line would strip that whitespace.
- */
- function printBlockString(value) {
- var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
- var preferMultipleLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
- var isSingleLine = value.indexOf('\n') === -1;
- var hasLeadingSpace = value[0] === ' ' || value[0] === '\t';
- var hasTrailingQuote = value[value.length - 1] === '"';
- var printAsMultipleLines = !isSingleLine || hasTrailingQuote || preferMultipleLines;
- var result = ''; // Format a multi-line block quote to account for leading space.
- if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) {
- result += '\n' + indentation;
- }
- result += indentation ? value.replace(/\n/g, '\n' + indentation) : value;
- if (printAsMultipleLines) {
- result += '\n';
- }
- return '"""' + result.replace(/"""/g, '\\"""') + '"""';
- }
- },{}],49:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.DirectiveLocation = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * The set of allowed directive location values.
- */
- var DirectiveLocation = Object.freeze({
- // Request Definitions
- QUERY: 'QUERY',
- MUTATION: 'MUTATION',
- SUBSCRIPTION: 'SUBSCRIPTION',
- FIELD: 'FIELD',
- FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION',
- FRAGMENT_SPREAD: 'FRAGMENT_SPREAD',
- INLINE_FRAGMENT: 'INLINE_FRAGMENT',
- VARIABLE_DEFINITION: 'VARIABLE_DEFINITION',
- // Type System Definitions
- SCHEMA: 'SCHEMA',
- SCALAR: 'SCALAR',
- OBJECT: 'OBJECT',
- FIELD_DEFINITION: 'FIELD_DEFINITION',
- ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION',
- INTERFACE: 'INTERFACE',
- UNION: 'UNION',
- ENUM: 'ENUM',
- ENUM_VALUE: 'ENUM_VALUE',
- INPUT_OBJECT: 'INPUT_OBJECT',
- INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'
- });
- /**
- * The enum type representing the directive location values.
- */
- exports.DirectiveLocation = DirectiveLocation;
- },{}],50:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "Source", {
- enumerable: true,
- get: function get() {
- return _source.Source;
- }
- });
- Object.defineProperty(exports, "getLocation", {
- enumerable: true,
- get: function get() {
- return _location.getLocation;
- }
- });
- Object.defineProperty(exports, "Kind", {
- enumerable: true,
- get: function get() {
- return _kinds.Kind;
- }
- });
- Object.defineProperty(exports, "createLexer", {
- enumerable: true,
- get: function get() {
- return _lexer.createLexer;
- }
- });
- Object.defineProperty(exports, "TokenKind", {
- enumerable: true,
- get: function get() {
- return _lexer.TokenKind;
- }
- });
- Object.defineProperty(exports, "parse", {
- enumerable: true,
- get: function get() {
- return _parser.parse;
- }
- });
- Object.defineProperty(exports, "parseValue", {
- enumerable: true,
- get: function get() {
- return _parser.parseValue;
- }
- });
- Object.defineProperty(exports, "parseType", {
- enumerable: true,
- get: function get() {
- return _parser.parseType;
- }
- });
- Object.defineProperty(exports, "print", {
- enumerable: true,
- get: function get() {
- return _printer.print;
- }
- });
- Object.defineProperty(exports, "visit", {
- enumerable: true,
- get: function get() {
- return _visitor.visit;
- }
- });
- Object.defineProperty(exports, "visitInParallel", {
- enumerable: true,
- get: function get() {
- return _visitor.visitInParallel;
- }
- });
- Object.defineProperty(exports, "visitWithTypeInfo", {
- enumerable: true,
- get: function get() {
- return _visitor.visitWithTypeInfo;
- }
- });
- Object.defineProperty(exports, "getVisitFn", {
- enumerable: true,
- get: function get() {
- return _visitor.getVisitFn;
- }
- });
- Object.defineProperty(exports, "BREAK", {
- enumerable: true,
- get: function get() {
- return _visitor.BREAK;
- }
- });
- Object.defineProperty(exports, "isDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isExecutableDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isExecutableDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isSelectionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isSelectionNode;
- }
- });
- Object.defineProperty(exports, "isValueNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isValueNode;
- }
- });
- Object.defineProperty(exports, "isTypeNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeNode;
- }
- });
- Object.defineProperty(exports, "isTypeSystemDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeSystemDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isTypeDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isTypeSystemExtensionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeSystemExtensionNode;
- }
- });
- Object.defineProperty(exports, "isTypeExtensionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeExtensionNode;
- }
- });
- Object.defineProperty(exports, "DirectiveLocation", {
- enumerable: true,
- get: function get() {
- return _directiveLocation.DirectiveLocation;
- }
- });
- var _source = require("./source");
- var _location = require("./location");
- var _kinds = require("./kinds");
- var _lexer = require("./lexer");
- var _parser = require("./parser");
- var _printer = require("./printer");
- var _visitor = require("./visitor");
- var _predicates = require("./predicates");
- var _directiveLocation = require("./directiveLocation");
- },{"./directiveLocation":49,"./kinds":51,"./lexer":52,"./location":53,"./parser":54,"./predicates":55,"./printer":56,"./source":57,"./visitor":58}],51:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Kind = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * The set of allowed kind values for AST nodes.
- */
- var Kind = Object.freeze({
- // Name
- NAME: 'Name',
- // Document
- DOCUMENT: 'Document',
- OPERATION_DEFINITION: 'OperationDefinition',
- VARIABLE_DEFINITION: 'VariableDefinition',
- SELECTION_SET: 'SelectionSet',
- FIELD: 'Field',
- ARGUMENT: 'Argument',
- // Fragments
- FRAGMENT_SPREAD: 'FragmentSpread',
- INLINE_FRAGMENT: 'InlineFragment',
- FRAGMENT_DEFINITION: 'FragmentDefinition',
- // Values
- VARIABLE: 'Variable',
- INT: 'IntValue',
- FLOAT: 'FloatValue',
- STRING: 'StringValue',
- BOOLEAN: 'BooleanValue',
- NULL: 'NullValue',
- ENUM: 'EnumValue',
- LIST: 'ListValue',
- OBJECT: 'ObjectValue',
- OBJECT_FIELD: 'ObjectField',
- // Directives
- DIRECTIVE: 'Directive',
- // Types
- NAMED_TYPE: 'NamedType',
- LIST_TYPE: 'ListType',
- NON_NULL_TYPE: 'NonNullType',
- // Type System Definitions
- SCHEMA_DEFINITION: 'SchemaDefinition',
- OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',
- // Type Definitions
- SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',
- OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',
- FIELD_DEFINITION: 'FieldDefinition',
- INPUT_VALUE_DEFINITION: 'InputValueDefinition',
- INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',
- UNION_TYPE_DEFINITION: 'UnionTypeDefinition',
- ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',
- ENUM_VALUE_DEFINITION: 'EnumValueDefinition',
- INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',
- // Directive Definitions
- DIRECTIVE_DEFINITION: 'DirectiveDefinition',
- // Type System Extensions
- SCHEMA_EXTENSION: 'SchemaExtension',
- // Type Extensions
- SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',
- OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',
- INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',
- UNION_TYPE_EXTENSION: 'UnionTypeExtension',
- ENUM_TYPE_EXTENSION: 'EnumTypeExtension',
- INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'
- });
- /**
- * The enum type representing the possible kind values of AST nodes.
- */
- exports.Kind = Kind;
- },{}],52:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.createLexer = createLexer;
- exports.isPunctuatorToken = isPunctuatorToken;
- exports.getTokenDesc = getTokenDesc;
- exports.TokenKind = void 0;
- var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON"));
- var _error = require("../error");
- var _blockString = require("./blockString");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given a Source object, this returns a Lexer for that source.
- * A Lexer is a stateful stream generator in that every time
- * it is advanced, it returns the next token in the Source. Assuming the
- * source lexes, the final Token emitted by the lexer will be of kind
- * EOF, after which the lexer will repeatedly return the same EOF token
- * whenever called.
- */
- function createLexer(source, options) {
- var startOfFileToken = new Tok(TokenKind.SOF, 0, 0, 0, 0, null);
- var lexer = {
- source: source,
- options: options,
- lastToken: startOfFileToken,
- token: startOfFileToken,
- line: 1,
- lineStart: 0,
- advance: advanceLexer,
- lookahead: lookahead
- };
- return lexer;
- }
- function advanceLexer() {
- this.lastToken = this.token;
- var token = this.token = this.lookahead();
- return token;
- }
- function lookahead() {
- var token = this.token;
- if (token.kind !== TokenKind.EOF) {
- do {
- // Note: next is only mutable during parsing, so we cast to allow this.
- token = token.next || (token.next = readToken(this, token));
- } while (token.kind === TokenKind.COMMENT);
- }
- return token;
- }
- /**
- * The return type of createLexer.
- */
- /**
- * An exported enum describing the different kinds of tokens that the
- * lexer emits.
- */
- var TokenKind = Object.freeze({
- SOF: '<SOF>',
- EOF: '<EOF>',
- BANG: '!',
- DOLLAR: '$',
- AMP: '&',
- PAREN_L: '(',
- PAREN_R: ')',
- SPREAD: '...',
- COLON: ':',
- EQUALS: '=',
- AT: '@',
- BRACKET_L: '[',
- BRACKET_R: ']',
- BRACE_L: '{',
- PIPE: '|',
- BRACE_R: '}',
- NAME: 'Name',
- INT: 'Int',
- FLOAT: 'Float',
- STRING: 'String',
- BLOCK_STRING: 'BlockString',
- COMMENT: 'Comment'
- });
- /**
- * The enum type representing the token kinds values.
- */
- exports.TokenKind = TokenKind;
- // @internal
- function isPunctuatorToken(token) {
- var kind = token.kind;
- return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;
- }
- /**
- * A helper function to describe a token as a string for debugging
- */
- function getTokenDesc(token) {
- var value = token.value;
- return value ? "".concat(token.kind, " \"").concat(value, "\"") : token.kind;
- }
- /**
- * Helper function for constructing the Token object.
- */
- function Tok(kind, start, end, line, column, prev, value) {
- this.kind = kind;
- this.start = start;
- this.end = end;
- this.line = line;
- this.column = column;
- this.value = value;
- this.prev = prev;
- this.next = null;
- } // Print a simplified form when appearing in JSON/util.inspect.
- (0, _defineToJSON.default)(Tok, function () {
- return {
- kind: this.kind,
- value: this.value,
- line: this.line,
- column: this.column
- };
- });
- function printCharCode(code) {
- return (// NaN/undefined represents access beyond the end of the file.
- isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII.
- code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form.
- "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"")
- );
- }
- /**
- * Gets the next token from the source starting at the given position.
- *
- * This skips over whitespace until it finds the next lexable token, then lexes
- * punctuators immediately or calls the appropriate helper function for more
- * complicated tokens.
- */
- function readToken(lexer, prev) {
- var source = lexer.source;
- var body = source.body;
- var bodyLength = body.length;
- var pos = positionAfterWhitespace(body, prev.end, lexer);
- var line = lexer.line;
- var col = 1 + pos - lexer.lineStart;
- if (pos >= bodyLength) {
- return new Tok(TokenKind.EOF, bodyLength, bodyLength, line, col, prev);
- }
- var code = body.charCodeAt(pos); // SourceCharacter
- switch (code) {
- // !
- case 33:
- return new Tok(TokenKind.BANG, pos, pos + 1, line, col, prev);
- // #
- case 35:
- return readComment(source, pos, line, col, prev);
- // $
- case 36:
- return new Tok(TokenKind.DOLLAR, pos, pos + 1, line, col, prev);
- // &
- case 38:
- return new Tok(TokenKind.AMP, pos, pos + 1, line, col, prev);
- // (
- case 40:
- return new Tok(TokenKind.PAREN_L, pos, pos + 1, line, col, prev);
- // )
- case 41:
- return new Tok(TokenKind.PAREN_R, pos, pos + 1, line, col, prev);
- // .
- case 46:
- if (body.charCodeAt(pos + 1) === 46 && body.charCodeAt(pos + 2) === 46) {
- return new Tok(TokenKind.SPREAD, pos, pos + 3, line, col, prev);
- }
- break;
- // :
- case 58:
- return new Tok(TokenKind.COLON, pos, pos + 1, line, col, prev);
- // =
- case 61:
- return new Tok(TokenKind.EQUALS, pos, pos + 1, line, col, prev);
- // @
- case 64:
- return new Tok(TokenKind.AT, pos, pos + 1, line, col, prev);
- // [
- case 91:
- return new Tok(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev);
- // ]
- case 93:
- return new Tok(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev);
- // {
- case 123:
- return new Tok(TokenKind.BRACE_L, pos, pos + 1, line, col, prev);
- // |
- case 124:
- return new Tok(TokenKind.PIPE, pos, pos + 1, line, col, prev);
- // }
- case 125:
- return new Tok(TokenKind.BRACE_R, pos, pos + 1, line, col, prev);
- // A-Z _ a-z
- case 65:
- case 66:
- case 67:
- case 68:
- case 69:
- case 70:
- case 71:
- case 72:
- case 73:
- case 74:
- case 75:
- case 76:
- case 77:
- case 78:
- case 79:
- case 80:
- case 81:
- case 82:
- case 83:
- case 84:
- case 85:
- case 86:
- case 87:
- case 88:
- case 89:
- case 90:
- case 95:
- case 97:
- case 98:
- case 99:
- case 100:
- case 101:
- case 102:
- case 103:
- case 104:
- case 105:
- case 106:
- case 107:
- case 108:
- case 109:
- case 110:
- case 111:
- case 112:
- case 113:
- case 114:
- case 115:
- case 116:
- case 117:
- case 118:
- case 119:
- case 120:
- case 121:
- case 122:
- return readName(source, pos, line, col, prev);
- // - 0-9
- case 45:
- case 48:
- case 49:
- case 50:
- case 51:
- case 52:
- case 53:
- case 54:
- case 55:
- case 56:
- case 57:
- return readNumber(source, pos, code, line, col, prev);
- // "
- case 34:
- if (body.charCodeAt(pos + 1) === 34 && body.charCodeAt(pos + 2) === 34) {
- return readBlockString(source, pos, line, col, prev, lexer);
- }
- return readString(source, pos, line, col, prev);
- }
- throw (0, _error.syntaxError)(source, pos, unexpectedCharacterMessage(code));
- }
- /**
- * Report a message that an unexpected character was encountered.
- */
- function unexpectedCharacterMessage(code) {
- if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
- return "Cannot contain the invalid character ".concat(printCharCode(code), ".");
- }
- if (code === 39) {
- // '
- return "Unexpected single quote character ('), did you mean to use " + 'a double quote (")?';
- }
- return "Cannot parse the unexpected character ".concat(printCharCode(code), ".");
- }
- /**
- * Reads from body starting at startPosition until it finds a non-whitespace
- * character, then returns the position of that character for lexing.
- */
- function positionAfterWhitespace(body, startPosition, lexer) {
- var bodyLength = body.length;
- var position = startPosition;
- while (position < bodyLength) {
- var code = body.charCodeAt(position); // tab | space | comma | BOM
- if (code === 9 || code === 32 || code === 44 || code === 0xfeff) {
- ++position;
- } else if (code === 10) {
- // new line
- ++position;
- ++lexer.line;
- lexer.lineStart = position;
- } else if (code === 13) {
- // carriage return
- if (body.charCodeAt(position + 1) === 10) {
- position += 2;
- } else {
- ++position;
- }
- ++lexer.line;
- lexer.lineStart = position;
- } else {
- break;
- }
- }
- return position;
- }
- /**
- * Reads a comment token from the source file.
- *
- * #[\u0009\u0020-\uFFFF]*
- */
- function readComment(source, start, line, col, prev) {
- var body = source.body;
- var code;
- var position = start;
- do {
- code = body.charCodeAt(++position);
- } while (!isNaN(code) && ( // SourceCharacter but not LineTerminator
- code > 0x001f || code === 0x0009));
- return new Tok(TokenKind.COMMENT, start, position, line, col, prev, body.slice(start + 1, position));
- }
- /**
- * Reads a number token from the source file, either a float
- * or an int depending on whether a decimal point appears.
- *
- * Int: -?(0|[1-9][0-9]*)
- * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?
- */
- function readNumber(source, start, firstCode, line, col, prev) {
- var body = source.body;
- var code = firstCode;
- var position = start;
- var isFloat = false;
- if (code === 45) {
- // -
- code = body.charCodeAt(++position);
- }
- if (code === 48) {
- // 0
- code = body.charCodeAt(++position);
- if (code >= 48 && code <= 57) {
- throw (0, _error.syntaxError)(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), "."));
- }
- } else {
- position = readDigits(source, position, code);
- code = body.charCodeAt(position);
- }
- if (code === 46) {
- // .
- isFloat = true;
- code = body.charCodeAt(++position);
- position = readDigits(source, position, code);
- code = body.charCodeAt(position);
- }
- if (code === 69 || code === 101) {
- // E e
- isFloat = true;
- code = body.charCodeAt(++position);
- if (code === 43 || code === 45) {
- // + -
- code = body.charCodeAt(++position);
- }
- position = readDigits(source, position, code);
- }
- return new Tok(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, body.slice(start, position));
- }
- /**
- * Returns the new position in the source after reading digits.
- */
- function readDigits(source, start, firstCode) {
- var body = source.body;
- var position = start;
- var code = firstCode;
- if (code >= 48 && code <= 57) {
- // 0 - 9
- do {
- code = body.charCodeAt(++position);
- } while (code >= 48 && code <= 57); // 0 - 9
- return position;
- }
- throw (0, _error.syntaxError)(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));
- }
- /**
- * Reads a string token from the source file.
- *
- * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
- */
- function readString(source, start, line, col, prev) {
- var body = source.body;
- var position = start + 1;
- var chunkStart = position;
- var code = 0;
- var value = '';
- while (position < body.length && !isNaN(code = body.charCodeAt(position)) && // not LineTerminator
- code !== 0x000a && code !== 0x000d) {
- // Closing Quote (")
- if (code === 34) {
- value += body.slice(chunkStart, position);
- return new Tok(TokenKind.STRING, start, position + 1, line, col, prev, value);
- } // SourceCharacter
- if (code < 0x0020 && code !== 0x0009) {
- throw (0, _error.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));
- }
- ++position;
- if (code === 92) {
- // \
- value += body.slice(chunkStart, position - 1);
- code = body.charCodeAt(position);
- switch (code) {
- case 34:
- value += '"';
- break;
- case 47:
- value += '/';
- break;
- case 92:
- value += '\\';
- break;
- case 98:
- value += '\b';
- break;
- case 102:
- value += '\f';
- break;
- case 110:
- value += '\n';
- break;
- case 114:
- value += '\r';
- break;
- case 116:
- value += '\t';
- break;
- case 117:
- {
- // uXXXX
- var charCode = uniCharCode(body.charCodeAt(position + 1), body.charCodeAt(position + 2), body.charCodeAt(position + 3), body.charCodeAt(position + 4));
- if (charCode < 0) {
- throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: ' + "\\u".concat(body.slice(position + 1, position + 5), "."));
- }
- value += String.fromCharCode(charCode);
- position += 4;
- break;
- }
- default:
- throw (0, _error.syntaxError)(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), "."));
- }
- ++position;
- chunkStart = position;
- }
- }
- throw (0, _error.syntaxError)(source, position, 'Unterminated string.');
- }
- /**
- * Reads a block string token from the source file.
- *
- * """("?"?(\\"""|\\(?!=""")|[^"\\]))*"""
- */
- function readBlockString(source, start, line, col, prev, lexer) {
- var body = source.body;
- var position = start + 3;
- var chunkStart = position;
- var code = 0;
- var rawValue = '';
- while (position < body.length && !isNaN(code = body.charCodeAt(position))) {
- // Closing Triple-Quote (""")
- if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
- rawValue += body.slice(chunkStart, position);
- return new Tok(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, (0, _blockString.dedentBlockStringValue)(rawValue));
- } // SourceCharacter
- if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
- throw (0, _error.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));
- }
- if (code === 10) {
- // new line
- ++position;
- ++lexer.line;
- lexer.lineStart = position;
- } else if (code === 13) {
- // carriage return
- if (body.charCodeAt(position + 1) === 10) {
- position += 2;
- } else {
- ++position;
- }
- ++lexer.line;
- lexer.lineStart = position;
- } else if ( // Escape Triple-Quote (\""")
- code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {
- rawValue += body.slice(chunkStart, position) + '"""';
- position += 4;
- chunkStart = position;
- } else {
- ++position;
- }
- }
- throw (0, _error.syntaxError)(source, position, 'Unterminated string.');
- }
- /**
- * Converts four hexadecimal chars to the integer that the
- * string represents. For example, uniCharCode('0','0','0','f')
- * will return 15, and uniCharCode('0','0','f','f') returns 255.
- *
- * Returns a negative number on error, if a char was invalid.
- *
- * This is implemented by noting that char2hex() returns -1 on error,
- * which means the result of ORing the char2hex() will also be negative.
- */
- function uniCharCode(a, b, c, d) {
- return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);
- }
- /**
- * Converts a hex character to its integer value.
- * '0' becomes 0, '9' becomes 9
- * 'A' becomes 10, 'F' becomes 15
- * 'a' becomes 10, 'f' becomes 15
- *
- * Returns -1 on error.
- */
- function char2hex(a) {
- return a >= 48 && a <= 57 ? a - 48 // 0-9
- : a >= 65 && a <= 70 ? a - 55 // A-F
- : a >= 97 && a <= 102 ? a - 87 // a-f
- : -1;
- }
- /**
- * Reads an alphanumeric + underscore name from the source.
- *
- * [_A-Za-z][_0-9A-Za-z]*
- */
- function readName(source, start, line, col, prev) {
- var body = source.body;
- var bodyLength = body.length;
- var position = start + 1;
- var code = 0;
- while (position !== bodyLength && !isNaN(code = body.charCodeAt(position)) && (code === 95 || // _
- code >= 48 && code <= 57 || // 0-9
- code >= 65 && code <= 90 || // A-Z
- code >= 97 && code <= 122) // a-z
- ) {
- ++position;
- }
- return new Tok(TokenKind.NAME, start, position, line, col, prev, body.slice(start, position));
- }
- },{"../error":21,"../jsutils/defineToJSON":30,"./blockString":48}],53:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getLocation = getLocation;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Represents a location in a Source.
- */
- /**
- * Takes a Source and a UTF-8 character offset, and returns the corresponding
- * line and column as a SourceLocation.
- */
- function getLocation(source, position) {
- var lineRegexp = /\r\n|[\n\r]/g;
- var line = 1;
- var column = position + 1;
- var match;
- while ((match = lineRegexp.exec(source.body)) && match.index < position) {
- line += 1;
- column = position + 1 - (match.index + match[0].length);
- }
- return {
- line: line,
- column: column
- };
- }
- },{}],54:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.parse = parse;
- exports.parseValue = parseValue;
- exports.parseType = parseType;
- exports.parseConstValue = parseConstValue;
- exports.parseTypeReference = parseTypeReference;
- exports.parseNamedType = parseNamedType;
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON"));
- var _source = require("./source");
- var _error = require("../error");
- var _lexer = require("./lexer");
- var _kinds = require("./kinds");
- var _directiveLocation = require("./directiveLocation");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given a GraphQL source, parses it into a Document.
- * Throws GraphQLError if a syntax error is encountered.
- */
- function parse(source, options) {
- var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
- if (!(sourceObj instanceof _source.Source)) {
- throw new TypeError("Must provide Source. Received: ".concat((0, _inspect.default)(sourceObj)));
- }
- var lexer = (0, _lexer.createLexer)(sourceObj, options || {});
- return parseDocument(lexer);
- }
- /**
- * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for
- * that value.
- * Throws GraphQLError if a syntax error is encountered.
- *
- * This is useful within tools that operate upon GraphQL Values directly and
- * in isolation of complete GraphQL documents.
- *
- * Consider providing the results to the utility function: valueFromAST().
- */
- function parseValue(source, options) {
- var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
- var lexer = (0, _lexer.createLexer)(sourceObj, options || {});
- expectToken(lexer, _lexer.TokenKind.SOF);
- var value = parseValueLiteral(lexer, false);
- expectToken(lexer, _lexer.TokenKind.EOF);
- return value;
- }
- /**
- * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for
- * that type.
- * Throws GraphQLError if a syntax error is encountered.
- *
- * This is useful within tools that operate upon GraphQL Types directly and
- * in isolation of complete GraphQL documents.
- *
- * Consider providing the results to the utility function: typeFromAST().
- */
- function parseType(source, options) {
- var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
- var lexer = (0, _lexer.createLexer)(sourceObj, options || {});
- expectToken(lexer, _lexer.TokenKind.SOF);
- var type = parseTypeReference(lexer);
- expectToken(lexer, _lexer.TokenKind.EOF);
- return type;
- }
- /**
- * Converts a name lex token into a name parse node.
- */
- function parseName(lexer) {
- var token = expectToken(lexer, _lexer.TokenKind.NAME);
- return {
- kind: _kinds.Kind.NAME,
- value: token.value,
- loc: loc(lexer, token)
- };
- } // Implements the parsing rules in the Document section.
- /**
- * Document : Definition+
- */
- function parseDocument(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.DOCUMENT,
- definitions: many(lexer, _lexer.TokenKind.SOF, parseDefinition, _lexer.TokenKind.EOF),
- loc: loc(lexer, start)
- };
- }
- /**
- * Definition :
- * - ExecutableDefinition
- * - TypeSystemDefinition
- * - TypeSystemExtension
- */
- function parseDefinition(lexer) {
- if (peek(lexer, _lexer.TokenKind.NAME)) {
- switch (lexer.token.value) {
- case 'query':
- case 'mutation':
- case 'subscription':
- case 'fragment':
- return parseExecutableDefinition(lexer);
- case 'schema':
- case 'scalar':
- case 'type':
- case 'interface':
- case 'union':
- case 'enum':
- case 'input':
- case 'directive':
- return parseTypeSystemDefinition(lexer);
- case 'extend':
- return parseTypeSystemExtension(lexer);
- }
- } else if (peek(lexer, _lexer.TokenKind.BRACE_L)) {
- return parseExecutableDefinition(lexer);
- } else if (peekDescription(lexer)) {
- return parseTypeSystemDefinition(lexer);
- }
- throw unexpected(lexer);
- }
- /**
- * ExecutableDefinition :
- * - OperationDefinition
- * - FragmentDefinition
- */
- function parseExecutableDefinition(lexer) {
- if (peek(lexer, _lexer.TokenKind.NAME)) {
- switch (lexer.token.value) {
- case 'query':
- case 'mutation':
- case 'subscription':
- return parseOperationDefinition(lexer);
- case 'fragment':
- return parseFragmentDefinition(lexer);
- }
- } else if (peek(lexer, _lexer.TokenKind.BRACE_L)) {
- return parseOperationDefinition(lexer);
- }
- throw unexpected(lexer);
- } // Implements the parsing rules in the Operations section.
- /**
- * OperationDefinition :
- * - SelectionSet
- * - OperationType Name? VariableDefinitions? Directives? SelectionSet
- */
- function parseOperationDefinition(lexer) {
- var start = lexer.token;
- if (peek(lexer, _lexer.TokenKind.BRACE_L)) {
- return {
- kind: _kinds.Kind.OPERATION_DEFINITION,
- operation: 'query',
- name: undefined,
- variableDefinitions: [],
- directives: [],
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- var operation = parseOperationType(lexer);
- var name;
- if (peek(lexer, _lexer.TokenKind.NAME)) {
- name = parseName(lexer);
- }
- return {
- kind: _kinds.Kind.OPERATION_DEFINITION,
- operation: operation,
- name: name,
- variableDefinitions: parseVariableDefinitions(lexer),
- directives: parseDirectives(lexer, false),
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- /**
- * OperationType : one of query mutation subscription
- */
- function parseOperationType(lexer) {
- var operationToken = expectToken(lexer, _lexer.TokenKind.NAME);
- switch (operationToken.value) {
- case 'query':
- return 'query';
- case 'mutation':
- return 'mutation';
- case 'subscription':
- return 'subscription';
- }
- throw unexpected(lexer, operationToken);
- }
- /**
- * VariableDefinitions : ( VariableDefinition+ )
- */
- function parseVariableDefinitions(lexer) {
- return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, parseVariableDefinition, _lexer.TokenKind.PAREN_R) : [];
- }
- /**
- * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
- */
- function parseVariableDefinition(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.VARIABLE_DEFINITION,
- variable: parseVariable(lexer),
- type: (expectToken(lexer, _lexer.TokenKind.COLON), parseTypeReference(lexer)),
- defaultValue: expectOptionalToken(lexer, _lexer.TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined,
- directives: parseDirectives(lexer, true),
- loc: loc(lexer, start)
- };
- }
- /**
- * Variable : $ Name
- */
- function parseVariable(lexer) {
- var start = lexer.token;
- expectToken(lexer, _lexer.TokenKind.DOLLAR);
- return {
- kind: _kinds.Kind.VARIABLE,
- name: parseName(lexer),
- loc: loc(lexer, start)
- };
- }
- /**
- * SelectionSet : { Selection+ }
- */
- function parseSelectionSet(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.SELECTION_SET,
- selections: many(lexer, _lexer.TokenKind.BRACE_L, parseSelection, _lexer.TokenKind.BRACE_R),
- loc: loc(lexer, start)
- };
- }
- /**
- * Selection :
- * - Field
- * - FragmentSpread
- * - InlineFragment
- */
- function parseSelection(lexer) {
- return peek(lexer, _lexer.TokenKind.SPREAD) ? parseFragment(lexer) : parseField(lexer);
- }
- /**
- * Field : Alias? Name Arguments? Directives? SelectionSet?
- *
- * Alias : Name :
- */
- function parseField(lexer) {
- var start = lexer.token;
- var nameOrAlias = parseName(lexer);
- var alias;
- var name;
- if (expectOptionalToken(lexer, _lexer.TokenKind.COLON)) {
- alias = nameOrAlias;
- name = parseName(lexer);
- } else {
- name = nameOrAlias;
- }
- return {
- kind: _kinds.Kind.FIELD,
- alias: alias,
- name: name,
- arguments: parseArguments(lexer, false),
- directives: parseDirectives(lexer, false),
- selectionSet: peek(lexer, _lexer.TokenKind.BRACE_L) ? parseSelectionSet(lexer) : undefined,
- loc: loc(lexer, start)
- };
- }
- /**
- * Arguments[Const] : ( Argument[?Const]+ )
- */
- function parseArguments(lexer, isConst) {
- var item = isConst ? parseConstArgument : parseArgument;
- return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, item, _lexer.TokenKind.PAREN_R) : [];
- }
- /**
- * Argument[Const] : Name : Value[?Const]
- */
- function parseArgument(lexer) {
- var start = lexer.token;
- var name = parseName(lexer);
- expectToken(lexer, _lexer.TokenKind.COLON);
- return {
- kind: _kinds.Kind.ARGUMENT,
- name: name,
- value: parseValueLiteral(lexer, false),
- loc: loc(lexer, start)
- };
- }
- function parseConstArgument(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.ARGUMENT,
- name: parseName(lexer),
- value: (expectToken(lexer, _lexer.TokenKind.COLON), parseConstValue(lexer)),
- loc: loc(lexer, start)
- };
- } // Implements the parsing rules in the Fragments section.
- /**
- * Corresponds to both FragmentSpread and InlineFragment in the spec.
- *
- * FragmentSpread : ... FragmentName Directives?
- *
- * InlineFragment : ... TypeCondition? Directives? SelectionSet
- */
- function parseFragment(lexer) {
- var start = lexer.token;
- expectToken(lexer, _lexer.TokenKind.SPREAD);
- var hasTypeCondition = expectOptionalKeyword(lexer, 'on');
- if (!hasTypeCondition && peek(lexer, _lexer.TokenKind.NAME)) {
- return {
- kind: _kinds.Kind.FRAGMENT_SPREAD,
- name: parseFragmentName(lexer),
- directives: parseDirectives(lexer, false),
- loc: loc(lexer, start)
- };
- }
- return {
- kind: _kinds.Kind.INLINE_FRAGMENT,
- typeCondition: hasTypeCondition ? parseNamedType(lexer) : undefined,
- directives: parseDirectives(lexer, false),
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- /**
- * FragmentDefinition :
- * - fragment FragmentName on TypeCondition Directives? SelectionSet
- *
- * TypeCondition : NamedType
- */
- function parseFragmentDefinition(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'fragment'); // Experimental support for defining variables within fragments changes
- // the grammar of FragmentDefinition:
- // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet
- if (lexer.options.experimentalFragmentVariables) {
- return {
- kind: _kinds.Kind.FRAGMENT_DEFINITION,
- name: parseFragmentName(lexer),
- variableDefinitions: parseVariableDefinitions(lexer),
- typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)),
- directives: parseDirectives(lexer, false),
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- return {
- kind: _kinds.Kind.FRAGMENT_DEFINITION,
- name: parseFragmentName(lexer),
- typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)),
- directives: parseDirectives(lexer, false),
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- /**
- * FragmentName : Name but not `on`
- */
- function parseFragmentName(lexer) {
- if (lexer.token.value === 'on') {
- throw unexpected(lexer);
- }
- return parseName(lexer);
- } // Implements the parsing rules in the Values section.
- /**
- * Value[Const] :
- * - [~Const] Variable
- * - IntValue
- * - FloatValue
- * - StringValue
- * - BooleanValue
- * - NullValue
- * - EnumValue
- * - ListValue[?Const]
- * - ObjectValue[?Const]
- *
- * BooleanValue : one of `true` `false`
- *
- * NullValue : `null`
- *
- * EnumValue : Name but not `true`, `false` or `null`
- */
- function parseValueLiteral(lexer, isConst) {
- var token = lexer.token;
- switch (token.kind) {
- case _lexer.TokenKind.BRACKET_L:
- return parseList(lexer, isConst);
- case _lexer.TokenKind.BRACE_L:
- return parseObject(lexer, isConst);
- case _lexer.TokenKind.INT:
- lexer.advance();
- return {
- kind: _kinds.Kind.INT,
- value: token.value,
- loc: loc(lexer, token)
- };
- case _lexer.TokenKind.FLOAT:
- lexer.advance();
- return {
- kind: _kinds.Kind.FLOAT,
- value: token.value,
- loc: loc(lexer, token)
- };
- case _lexer.TokenKind.STRING:
- case _lexer.TokenKind.BLOCK_STRING:
- return parseStringLiteral(lexer);
- case _lexer.TokenKind.NAME:
- if (token.value === 'true' || token.value === 'false') {
- lexer.advance();
- return {
- kind: _kinds.Kind.BOOLEAN,
- value: token.value === 'true',
- loc: loc(lexer, token)
- };
- } else if (token.value === 'null') {
- lexer.advance();
- return {
- kind: _kinds.Kind.NULL,
- loc: loc(lexer, token)
- };
- }
- lexer.advance();
- return {
- kind: _kinds.Kind.ENUM,
- value: token.value,
- loc: loc(lexer, token)
- };
- case _lexer.TokenKind.DOLLAR:
- if (!isConst) {
- return parseVariable(lexer);
- }
- break;
- }
- throw unexpected(lexer);
- }
- function parseStringLiteral(lexer) {
- var token = lexer.token;
- lexer.advance();
- return {
- kind: _kinds.Kind.STRING,
- value: token.value,
- block: token.kind === _lexer.TokenKind.BLOCK_STRING,
- loc: loc(lexer, token)
- };
- }
- function parseConstValue(lexer) {
- return parseValueLiteral(lexer, true);
- }
- function parseValueValue(lexer) {
- return parseValueLiteral(lexer, false);
- }
- /**
- * ListValue[Const] :
- * - [ ]
- * - [ Value[?Const]+ ]
- */
- function parseList(lexer, isConst) {
- var start = lexer.token;
- var item = isConst ? parseConstValue : parseValueValue;
- return {
- kind: _kinds.Kind.LIST,
- values: any(lexer, _lexer.TokenKind.BRACKET_L, item, _lexer.TokenKind.BRACKET_R),
- loc: loc(lexer, start)
- };
- }
- /**
- * ObjectValue[Const] :
- * - { }
- * - { ObjectField[?Const]+ }
- */
- function parseObject(lexer, isConst) {
- var start = lexer.token;
- var item = function item() {
- return parseObjectField(lexer, isConst);
- };
- return {
- kind: _kinds.Kind.OBJECT,
- fields: any(lexer, _lexer.TokenKind.BRACE_L, item, _lexer.TokenKind.BRACE_R),
- loc: loc(lexer, start)
- };
- }
- /**
- * ObjectField[Const] : Name : Value[?Const]
- */
- function parseObjectField(lexer, isConst) {
- var start = lexer.token;
- var name = parseName(lexer);
- expectToken(lexer, _lexer.TokenKind.COLON);
- return {
- kind: _kinds.Kind.OBJECT_FIELD,
- name: name,
- value: parseValueLiteral(lexer, isConst),
- loc: loc(lexer, start)
- };
- } // Implements the parsing rules in the Directives section.
- /**
- * Directives[Const] : Directive[?Const]+
- */
- function parseDirectives(lexer, isConst) {
- var directives = [];
- while (peek(lexer, _lexer.TokenKind.AT)) {
- directives.push(parseDirective(lexer, isConst));
- }
- return directives;
- }
- /**
- * Directive[Const] : @ Name Arguments[?Const]?
- */
- function parseDirective(lexer, isConst) {
- var start = lexer.token;
- expectToken(lexer, _lexer.TokenKind.AT);
- return {
- kind: _kinds.Kind.DIRECTIVE,
- name: parseName(lexer),
- arguments: parseArguments(lexer, isConst),
- loc: loc(lexer, start)
- };
- } // Implements the parsing rules in the Types section.
- /**
- * Type :
- * - NamedType
- * - ListType
- * - NonNullType
- */
- function parseTypeReference(lexer) {
- var start = lexer.token;
- var type;
- if (expectOptionalToken(lexer, _lexer.TokenKind.BRACKET_L)) {
- type = parseTypeReference(lexer);
- expectToken(lexer, _lexer.TokenKind.BRACKET_R);
- type = {
- kind: _kinds.Kind.LIST_TYPE,
- type: type,
- loc: loc(lexer, start)
- };
- } else {
- type = parseNamedType(lexer);
- }
- if (expectOptionalToken(lexer, _lexer.TokenKind.BANG)) {
- return {
- kind: _kinds.Kind.NON_NULL_TYPE,
- type: type,
- loc: loc(lexer, start)
- };
- }
- return type;
- }
- /**
- * NamedType : Name
- */
- function parseNamedType(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.NAMED_TYPE,
- name: parseName(lexer),
- loc: loc(lexer, start)
- };
- } // Implements the parsing rules in the Type Definition section.
- /**
- * TypeSystemDefinition :
- * - SchemaDefinition
- * - TypeDefinition
- * - DirectiveDefinition
- *
- * TypeDefinition :
- * - ScalarTypeDefinition
- * - ObjectTypeDefinition
- * - InterfaceTypeDefinition
- * - UnionTypeDefinition
- * - EnumTypeDefinition
- * - InputObjectTypeDefinition
- */
- function parseTypeSystemDefinition(lexer) {
- // Many definitions begin with a description and require a lookahead.
- var keywordToken = peekDescription(lexer) ? lexer.lookahead() : lexer.token;
- if (keywordToken.kind === _lexer.TokenKind.NAME) {
- switch (keywordToken.value) {
- case 'schema':
- return parseSchemaDefinition(lexer);
- case 'scalar':
- return parseScalarTypeDefinition(lexer);
- case 'type':
- return parseObjectTypeDefinition(lexer);
- case 'interface':
- return parseInterfaceTypeDefinition(lexer);
- case 'union':
- return parseUnionTypeDefinition(lexer);
- case 'enum':
- return parseEnumTypeDefinition(lexer);
- case 'input':
- return parseInputObjectTypeDefinition(lexer);
- case 'directive':
- return parseDirectiveDefinition(lexer);
- }
- }
- throw unexpected(lexer, keywordToken);
- }
- function peekDescription(lexer) {
- return peek(lexer, _lexer.TokenKind.STRING) || peek(lexer, _lexer.TokenKind.BLOCK_STRING);
- }
- /**
- * Description : StringValue
- */
- function parseDescription(lexer) {
- if (peekDescription(lexer)) {
- return parseStringLiteral(lexer);
- }
- }
- /**
- * SchemaDefinition : schema Directives[Const]? { OperationTypeDefinition+ }
- */
- function parseSchemaDefinition(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'schema');
- var directives = parseDirectives(lexer, true);
- var operationTypes = many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R);
- return {
- kind: _kinds.Kind.SCHEMA_DEFINITION,
- directives: directives,
- operationTypes: operationTypes,
- loc: loc(lexer, start)
- };
- }
- /**
- * OperationTypeDefinition : OperationType : NamedType
- */
- function parseOperationTypeDefinition(lexer) {
- var start = lexer.token;
- var operation = parseOperationType(lexer);
- expectToken(lexer, _lexer.TokenKind.COLON);
- var type = parseNamedType(lexer);
- return {
- kind: _kinds.Kind.OPERATION_TYPE_DEFINITION,
- operation: operation,
- type: type,
- loc: loc(lexer, start)
- };
- }
- /**
- * ScalarTypeDefinition : Description? scalar Name Directives[Const]?
- */
- function parseScalarTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'scalar');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- return {
- kind: _kinds.Kind.SCALAR_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * ObjectTypeDefinition :
- * Description?
- * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
- */
- function parseObjectTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'type');
- var name = parseName(lexer);
- var interfaces = parseImplementsInterfaces(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseFieldsDefinition(lexer);
- return {
- kind: _kinds.Kind.OBJECT_TYPE_DEFINITION,
- description: description,
- name: name,
- interfaces: interfaces,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * ImplementsInterfaces :
- * - implements `&`? NamedType
- * - ImplementsInterfaces & NamedType
- */
- function parseImplementsInterfaces(lexer) {
- var types = [];
- if (expectOptionalKeyword(lexer, 'implements')) {
- // Optional leading ampersand
- expectOptionalToken(lexer, _lexer.TokenKind.AMP);
- do {
- types.push(parseNamedType(lexer));
- } while (expectOptionalToken(lexer, _lexer.TokenKind.AMP) || // Legacy support for the SDL?
- lexer.options.allowLegacySDLImplementsInterfaces && peek(lexer, _lexer.TokenKind.NAME));
- }
- return types;
- }
- /**
- * FieldsDefinition : { FieldDefinition+ }
- */
- function parseFieldsDefinition(lexer) {
- // Legacy support for the SDL?
- if (lexer.options.allowLegacySDLEmptyFields && peek(lexer, _lexer.TokenKind.BRACE_L) && lexer.lookahead().kind === _lexer.TokenKind.BRACE_R) {
- lexer.advance();
- lexer.advance();
- return [];
- }
- return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R) : [];
- }
- /**
- * FieldDefinition :
- * - Description? Name ArgumentsDefinition? : Type Directives[Const]?
- */
- function parseFieldDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- var name = parseName(lexer);
- var args = parseArgumentDefs(lexer);
- expectToken(lexer, _lexer.TokenKind.COLON);
- var type = parseTypeReference(lexer);
- var directives = parseDirectives(lexer, true);
- return {
- kind: _kinds.Kind.FIELD_DEFINITION,
- description: description,
- name: name,
- arguments: args,
- type: type,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * ArgumentsDefinition : ( InputValueDefinition+ )
- */
- function parseArgumentDefs(lexer) {
- if (!peek(lexer, _lexer.TokenKind.PAREN_L)) {
- return [];
- }
- return many(lexer, _lexer.TokenKind.PAREN_L, parseInputValueDef, _lexer.TokenKind.PAREN_R);
- }
- /**
- * InputValueDefinition :
- * - Description? Name : Type DefaultValue? Directives[Const]?
- */
- function parseInputValueDef(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- var name = parseName(lexer);
- expectToken(lexer, _lexer.TokenKind.COLON);
- var type = parseTypeReference(lexer);
- var defaultValue;
- if (expectOptionalToken(lexer, _lexer.TokenKind.EQUALS)) {
- defaultValue = parseConstValue(lexer);
- }
- var directives = parseDirectives(lexer, true);
- return {
- kind: _kinds.Kind.INPUT_VALUE_DEFINITION,
- description: description,
- name: name,
- type: type,
- defaultValue: defaultValue,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * InterfaceTypeDefinition :
- * - Description? interface Name Directives[Const]? FieldsDefinition?
- */
- function parseInterfaceTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'interface');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseFieldsDefinition(lexer);
- return {
- kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * UnionTypeDefinition :
- * - Description? union Name Directives[Const]? UnionMemberTypes?
- */
- function parseUnionTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'union');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var types = parseUnionMemberTypes(lexer);
- return {
- kind: _kinds.Kind.UNION_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- types: types,
- loc: loc(lexer, start)
- };
- }
- /**
- * UnionMemberTypes :
- * - = `|`? NamedType
- * - UnionMemberTypes | NamedType
- */
- function parseUnionMemberTypes(lexer) {
- var types = [];
- if (expectOptionalToken(lexer, _lexer.TokenKind.EQUALS)) {
- // Optional leading pipe
- expectOptionalToken(lexer, _lexer.TokenKind.PIPE);
- do {
- types.push(parseNamedType(lexer));
- } while (expectOptionalToken(lexer, _lexer.TokenKind.PIPE));
- }
- return types;
- }
- /**
- * EnumTypeDefinition :
- * - Description? enum Name Directives[Const]? EnumValuesDefinition?
- */
- function parseEnumTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'enum');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var values = parseEnumValuesDefinition(lexer);
- return {
- kind: _kinds.Kind.ENUM_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- values: values,
- loc: loc(lexer, start)
- };
- }
- /**
- * EnumValuesDefinition : { EnumValueDefinition+ }
- */
- function parseEnumValuesDefinition(lexer) {
- return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseEnumValueDefinition, _lexer.TokenKind.BRACE_R) : [];
- }
- /**
- * EnumValueDefinition : Description? EnumValue Directives[Const]?
- *
- * EnumValue : Name
- */
- function parseEnumValueDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- return {
- kind: _kinds.Kind.ENUM_VALUE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * InputObjectTypeDefinition :
- * - Description? input Name Directives[Const]? InputFieldsDefinition?
- */
- function parseInputObjectTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'input');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseInputFieldsDefinition(lexer);
- return {
- kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * InputFieldsDefinition : { InputValueDefinition+ }
- */
- function parseInputFieldsDefinition(lexer) {
- return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseInputValueDef, _lexer.TokenKind.BRACE_R) : [];
- }
- /**
- * TypeSystemExtension :
- * - SchemaExtension
- * - TypeExtension
- *
- * TypeExtension :
- * - ScalarTypeExtension
- * - ObjectTypeExtension
- * - InterfaceTypeExtension
- * - UnionTypeExtension
- * - EnumTypeExtension
- * - InputObjectTypeDefinition
- */
- function parseTypeSystemExtension(lexer) {
- var keywordToken = lexer.lookahead();
- if (keywordToken.kind === _lexer.TokenKind.NAME) {
- switch (keywordToken.value) {
- case 'schema':
- return parseSchemaExtension(lexer);
- case 'scalar':
- return parseScalarTypeExtension(lexer);
- case 'type':
- return parseObjectTypeExtension(lexer);
- case 'interface':
- return parseInterfaceTypeExtension(lexer);
- case 'union':
- return parseUnionTypeExtension(lexer);
- case 'enum':
- return parseEnumTypeExtension(lexer);
- case 'input':
- return parseInputObjectTypeExtension(lexer);
- }
- }
- throw unexpected(lexer, keywordToken);
- }
- /**
- * SchemaExtension :
- * - extend schema Directives[Const]? { OperationTypeDefinition+ }
- * - extend schema Directives[Const]
- */
- function parseSchemaExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'schema');
- var directives = parseDirectives(lexer, true);
- var operationTypes = peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R) : [];
- if (directives.length === 0 && operationTypes.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.SCHEMA_EXTENSION,
- directives: directives,
- operationTypes: operationTypes,
- loc: loc(lexer, start)
- };
- }
- /**
- * ScalarTypeExtension :
- * - extend scalar Name Directives[Const]
- */
- function parseScalarTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'scalar');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- if (directives.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.SCALAR_TYPE_EXTENSION,
- name: name,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * ObjectTypeExtension :
- * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
- * - extend type Name ImplementsInterfaces? Directives[Const]
- * - extend type Name ImplementsInterfaces
- */
- function parseObjectTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'type');
- var name = parseName(lexer);
- var interfaces = parseImplementsInterfaces(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseFieldsDefinition(lexer);
- if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.OBJECT_TYPE_EXTENSION,
- name: name,
- interfaces: interfaces,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * InterfaceTypeExtension :
- * - extend interface Name Directives[Const]? FieldsDefinition
- * - extend interface Name Directives[Const]
- */
- function parseInterfaceTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'interface');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseFieldsDefinition(lexer);
- if (directives.length === 0 && fields.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION,
- name: name,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * UnionTypeExtension :
- * - extend union Name Directives[Const]? UnionMemberTypes
- * - extend union Name Directives[Const]
- */
- function parseUnionTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'union');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var types = parseUnionMemberTypes(lexer);
- if (directives.length === 0 && types.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.UNION_TYPE_EXTENSION,
- name: name,
- directives: directives,
- types: types,
- loc: loc(lexer, start)
- };
- }
- /**
- * EnumTypeExtension :
- * - extend enum Name Directives[Const]? EnumValuesDefinition
- * - extend enum Name Directives[Const]
- */
- function parseEnumTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'enum');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var values = parseEnumValuesDefinition(lexer);
- if (directives.length === 0 && values.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.ENUM_TYPE_EXTENSION,
- name: name,
- directives: directives,
- values: values,
- loc: loc(lexer, start)
- };
- }
- /**
- * InputObjectTypeExtension :
- * - extend input Name Directives[Const]? InputFieldsDefinition
- * - extend input Name Directives[Const]
- */
- function parseInputObjectTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'input');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseInputFieldsDefinition(lexer);
- if (directives.length === 0 && fields.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION,
- name: name,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * DirectiveDefinition :
- * - Description? directive @ Name ArgumentsDefinition? on DirectiveLocations
- */
- function parseDirectiveDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'directive');
- expectToken(lexer, _lexer.TokenKind.AT);
- var name = parseName(lexer);
- var args = parseArgumentDefs(lexer);
- expectKeyword(lexer, 'on');
- var locations = parseDirectiveLocations(lexer);
- return {
- kind: _kinds.Kind.DIRECTIVE_DEFINITION,
- description: description,
- name: name,
- arguments: args,
- locations: locations,
- loc: loc(lexer, start)
- };
- }
- /**
- * DirectiveLocations :
- * - `|`? DirectiveLocation
- * - DirectiveLocations | DirectiveLocation
- */
- function parseDirectiveLocations(lexer) {
- // Optional leading pipe
- expectOptionalToken(lexer, _lexer.TokenKind.PIPE);
- var locations = [];
- do {
- locations.push(parseDirectiveLocation(lexer));
- } while (expectOptionalToken(lexer, _lexer.TokenKind.PIPE));
- return locations;
- }
- /*
- * DirectiveLocation :
- * - ExecutableDirectiveLocation
- * - TypeSystemDirectiveLocation
- *
- * ExecutableDirectiveLocation : one of
- * `QUERY`
- * `MUTATION`
- * `SUBSCRIPTION`
- * `FIELD`
- * `FRAGMENT_DEFINITION`
- * `FRAGMENT_SPREAD`
- * `INLINE_FRAGMENT`
- *
- * TypeSystemDirectiveLocation : one of
- * `SCHEMA`
- * `SCALAR`
- * `OBJECT`
- * `FIELD_DEFINITION`
- * `ARGUMENT_DEFINITION`
- * `INTERFACE`
- * `UNION`
- * `ENUM`
- * `ENUM_VALUE`
- * `INPUT_OBJECT`
- * `INPUT_FIELD_DEFINITION`
- */
- function parseDirectiveLocation(lexer) {
- var start = lexer.token;
- var name = parseName(lexer);
- if (_directiveLocation.DirectiveLocation[name.value] !== undefined) {
- return name;
- }
- throw unexpected(lexer, start);
- } // Core parsing utility functions
- /**
- * Returns a location object, used to identify the place in
- * the source that created a given parsed object.
- */
- function loc(lexer, startToken) {
- if (!lexer.options.noLocation) {
- return new Loc(startToken, lexer.lastToken, lexer.source);
- }
- }
- function Loc(startToken, endToken, source) {
- this.start = startToken.start;
- this.end = endToken.end;
- this.startToken = startToken;
- this.endToken = endToken;
- this.source = source;
- } // Print a simplified form when appearing in JSON/util.inspect.
- (0, _defineToJSON.default)(Loc, function () {
- return {
- start: this.start,
- end: this.end
- };
- });
- /**
- * Determines if the next token is of a given kind
- */
- function peek(lexer, kind) {
- return lexer.token.kind === kind;
- }
- /**
- * If the next token is of the given kind, return that token after advancing
- * the lexer. Otherwise, do not change the parser state and throw an error.
- */
- function expectToken(lexer, kind) {
- var token = lexer.token;
- if (token.kind === kind) {
- lexer.advance();
- return token;
- }
- throw (0, _error.syntaxError)(lexer.source, token.start, "Expected ".concat(kind, ", found ").concat((0, _lexer.getTokenDesc)(token)));
- }
- /**
- * If the next token is of the given kind, return that token after advancing
- * the lexer. Otherwise, do not change the parser state and return undefined.
- */
- function expectOptionalToken(lexer, kind) {
- var token = lexer.token;
- if (token.kind === kind) {
- lexer.advance();
- return token;
- }
- return undefined;
- }
- /**
- * If the next token is a given keyword, return that token after advancing
- * the lexer. Otherwise, do not change the parser state and throw an error.
- */
- function expectKeyword(lexer, value) {
- var token = lexer.token;
- if (token.kind === _lexer.TokenKind.NAME && token.value === value) {
- lexer.advance();
- return token;
- }
- throw (0, _error.syntaxError)(lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat((0, _lexer.getTokenDesc)(token)));
- }
- /**
- * If the next token is a given keyword, return that token after advancing
- * the lexer. Otherwise, do not change the parser state and return undefined.
- */
- function expectOptionalKeyword(lexer, value) {
- var token = lexer.token;
- if (token.kind === _lexer.TokenKind.NAME && token.value === value) {
- lexer.advance();
- return token;
- }
- return undefined;
- }
- /**
- * Helper function for creating an error when an unexpected lexed token
- * is encountered.
- */
- function unexpected(lexer, atToken) {
- var token = atToken || lexer.token;
- return (0, _error.syntaxError)(lexer.source, token.start, "Unexpected ".concat((0, _lexer.getTokenDesc)(token)));
- }
- /**
- * Returns a possibly empty list of parse nodes, determined by
- * the parseFn. This list begins with a lex token of openKind
- * and ends with a lex token of closeKind. Advances the parser
- * to the next lex token after the closing token.
- */
- function any(lexer, openKind, parseFn, closeKind) {
- expectToken(lexer, openKind);
- var nodes = [];
- while (!expectOptionalToken(lexer, closeKind)) {
- nodes.push(parseFn(lexer));
- }
- return nodes;
- }
- /**
- * Returns a non-empty list of parse nodes, determined by
- * the parseFn. This list begins with a lex token of openKind
- * and ends with a lex token of closeKind. Advances the parser
- * to the next lex token after the closing token.
- */
- function many(lexer, openKind, parseFn, closeKind) {
- expectToken(lexer, openKind);
- var nodes = [parseFn(lexer)];
- while (!expectOptionalToken(lexer, closeKind)) {
- nodes.push(parseFn(lexer));
- }
- return nodes;
- }
- },{"../error":21,"../jsutils/defineToJSON":30,"../jsutils/inspect":32,"./directiveLocation":49,"./kinds":51,"./lexer":52,"./source":57}],55:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isDefinitionNode = isDefinitionNode;
- exports.isExecutableDefinitionNode = isExecutableDefinitionNode;
- exports.isSelectionNode = isSelectionNode;
- exports.isValueNode = isValueNode;
- exports.isTypeNode = isTypeNode;
- exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode;
- exports.isTypeDefinitionNode = isTypeDefinitionNode;
- exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode;
- exports.isTypeExtensionNode = isTypeExtensionNode;
- var _kinds = require("./kinds");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function isDefinitionNode(node) {
- return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node);
- }
- function isExecutableDefinitionNode(node) {
- return node.kind === _kinds.Kind.OPERATION_DEFINITION || node.kind === _kinds.Kind.FRAGMENT_DEFINITION;
- }
- function isSelectionNode(node) {
- return node.kind === _kinds.Kind.FIELD || node.kind === _kinds.Kind.FRAGMENT_SPREAD || node.kind === _kinds.Kind.INLINE_FRAGMENT;
- }
- function isValueNode(node) {
- return node.kind === _kinds.Kind.VARIABLE || node.kind === _kinds.Kind.INT || node.kind === _kinds.Kind.FLOAT || node.kind === _kinds.Kind.STRING || node.kind === _kinds.Kind.BOOLEAN || node.kind === _kinds.Kind.NULL || node.kind === _kinds.Kind.ENUM || node.kind === _kinds.Kind.LIST || node.kind === _kinds.Kind.OBJECT;
- }
- function isTypeNode(node) {
- return node.kind === _kinds.Kind.NAMED_TYPE || node.kind === _kinds.Kind.LIST_TYPE || node.kind === _kinds.Kind.NON_NULL_TYPE;
- }
- function isTypeSystemDefinitionNode(node) {
- return node.kind === _kinds.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === _kinds.Kind.DIRECTIVE_DEFINITION;
- }
- function isTypeDefinitionNode(node) {
- return node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION;
- }
- function isTypeSystemExtensionNode(node) {
- return node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node);
- }
- function isTypeExtensionNode(node) {
- return node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION;
- }
- },{"./kinds":51}],56:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.print = print;
- var _visitor = require("./visitor");
- var _blockString = require("./blockString");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Converts an AST into a string, using one set of reasonable
- * formatting rules.
- */
- function print(ast) {
- return (0, _visitor.visit)(ast, {
- leave: printDocASTReducer
- });
- } // TODO: provide better type coverage in future
- var printDocASTReducer = {
- Name: function Name(node) {
- return node.value;
- },
- Variable: function Variable(node) {
- return '$' + node.name;
- },
- // Document
- Document: function Document(node) {
- return join(node.definitions, '\n\n') + '\n';
- },
- OperationDefinition: function OperationDefinition(node) {
- var op = node.operation;
- var name = node.name;
- var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
- var directives = join(node.directives, ' ');
- var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use
- // the query short form.
- return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' ');
- },
- VariableDefinition: function VariableDefinition(_ref) {
- var variable = _ref.variable,
- type = _ref.type,
- defaultValue = _ref.defaultValue,
- directives = _ref.directives;
- return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' '));
- },
- SelectionSet: function SelectionSet(_ref2) {
- var selections = _ref2.selections;
- return block(selections);
- },
- Field: function Field(_ref3) {
- var alias = _ref3.alias,
- name = _ref3.name,
- args = _ref3.arguments,
- directives = _ref3.directives,
- selectionSet = _ref3.selectionSet;
- return join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' ');
- },
- Argument: function Argument(_ref4) {
- var name = _ref4.name,
- value = _ref4.value;
- return name + ': ' + value;
- },
- // Fragments
- FragmentSpread: function FragmentSpread(_ref5) {
- var name = _ref5.name,
- directives = _ref5.directives;
- return '...' + name + wrap(' ', join(directives, ' '));
- },
- InlineFragment: function InlineFragment(_ref6) {
- var typeCondition = _ref6.typeCondition,
- directives = _ref6.directives,
- selectionSet = _ref6.selectionSet;
- return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ');
- },
- FragmentDefinition: function FragmentDefinition(_ref7) {
- var name = _ref7.name,
- typeCondition = _ref7.typeCondition,
- variableDefinitions = _ref7.variableDefinitions,
- directives = _ref7.directives,
- selectionSet = _ref7.selectionSet;
- return (// Note: fragment variable definitions are experimental and may be changed
- // or removed in the future.
- "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet
- );
- },
- // Value
- IntValue: function IntValue(_ref8) {
- var value = _ref8.value;
- return value;
- },
- FloatValue: function FloatValue(_ref9) {
- var value = _ref9.value;
- return value;
- },
- StringValue: function StringValue(_ref10, key) {
- var value = _ref10.value,
- isBlockString = _ref10.block;
- return isBlockString ? (0, _blockString.printBlockString)(value, key === 'description' ? '' : ' ') : JSON.stringify(value);
- },
- BooleanValue: function BooleanValue(_ref11) {
- var value = _ref11.value;
- return value ? 'true' : 'false';
- },
- NullValue: function NullValue() {
- return 'null';
- },
- EnumValue: function EnumValue(_ref12) {
- var value = _ref12.value;
- return value;
- },
- ListValue: function ListValue(_ref13) {
- var values = _ref13.values;
- return '[' + join(values, ', ') + ']';
- },
- ObjectValue: function ObjectValue(_ref14) {
- var fields = _ref14.fields;
- return '{' + join(fields, ', ') + '}';
- },
- ObjectField: function ObjectField(_ref15) {
- var name = _ref15.name,
- value = _ref15.value;
- return name + ': ' + value;
- },
- // Directive
- Directive: function Directive(_ref16) {
- var name = _ref16.name,
- args = _ref16.arguments;
- return '@' + name + wrap('(', join(args, ', '), ')');
- },
- // Type
- NamedType: function NamedType(_ref17) {
- var name = _ref17.name;
- return name;
- },
- ListType: function ListType(_ref18) {
- var type = _ref18.type;
- return '[' + type + ']';
- },
- NonNullType: function NonNullType(_ref19) {
- var type = _ref19.type;
- return type + '!';
- },
- // Type System Definitions
- SchemaDefinition: function SchemaDefinition(_ref20) {
- var directives = _ref20.directives,
- operationTypes = _ref20.operationTypes;
- return join(['schema', join(directives, ' '), block(operationTypes)], ' ');
- },
- OperationTypeDefinition: function OperationTypeDefinition(_ref21) {
- var operation = _ref21.operation,
- type = _ref21.type;
- return operation + ': ' + type;
- },
- ScalarTypeDefinition: addDescription(function (_ref22) {
- var name = _ref22.name,
- directives = _ref22.directives;
- return join(['scalar', name, join(directives, ' ')], ' ');
- }),
- ObjectTypeDefinition: addDescription(function (_ref23) {
- var name = _ref23.name,
- interfaces = _ref23.interfaces,
- directives = _ref23.directives,
- fields = _ref23.fields;
- return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
- }),
- FieldDefinition: addDescription(function (_ref24) {
- var name = _ref24.name,
- args = _ref24.arguments,
- type = _ref24.type,
- directives = _ref24.directives;
- return name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' '));
- }),
- InputValueDefinition: addDescription(function (_ref25) {
- var name = _ref25.name,
- type = _ref25.type,
- defaultValue = _ref25.defaultValue,
- directives = _ref25.directives;
- return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ');
- }),
- InterfaceTypeDefinition: addDescription(function (_ref26) {
- var name = _ref26.name,
- directives = _ref26.directives,
- fields = _ref26.fields;
- return join(['interface', name, join(directives, ' '), block(fields)], ' ');
- }),
- UnionTypeDefinition: addDescription(function (_ref27) {
- var name = _ref27.name,
- directives = _ref27.directives,
- types = _ref27.types;
- return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
- }),
- EnumTypeDefinition: addDescription(function (_ref28) {
- var name = _ref28.name,
- directives = _ref28.directives,
- values = _ref28.values;
- return join(['enum', name, join(directives, ' '), block(values)], ' ');
- }),
- EnumValueDefinition: addDescription(function (_ref29) {
- var name = _ref29.name,
- directives = _ref29.directives;
- return join([name, join(directives, ' ')], ' ');
- }),
- InputObjectTypeDefinition: addDescription(function (_ref30) {
- var name = _ref30.name,
- directives = _ref30.directives,
- fields = _ref30.fields;
- return join(['input', name, join(directives, ' '), block(fields)], ' ');
- }),
- DirectiveDefinition: addDescription(function (_ref31) {
- var name = _ref31.name,
- args = _ref31.arguments,
- locations = _ref31.locations;
- return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ' on ' + join(locations, ' | ');
- }),
- SchemaExtension: function SchemaExtension(_ref32) {
- var directives = _ref32.directives,
- operationTypes = _ref32.operationTypes;
- return join(['extend schema', join(directives, ' '), block(operationTypes)], ' ');
- },
- ScalarTypeExtension: function ScalarTypeExtension(_ref33) {
- var name = _ref33.name,
- directives = _ref33.directives;
- return join(['extend scalar', name, join(directives, ' ')], ' ');
- },
- ObjectTypeExtension: function ObjectTypeExtension(_ref34) {
- var name = _ref34.name,
- interfaces = _ref34.interfaces,
- directives = _ref34.directives,
- fields = _ref34.fields;
- return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
- },
- InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) {
- var name = _ref35.name,
- directives = _ref35.directives,
- fields = _ref35.fields;
- return join(['extend interface', name, join(directives, ' '), block(fields)], ' ');
- },
- UnionTypeExtension: function UnionTypeExtension(_ref36) {
- var name = _ref36.name,
- directives = _ref36.directives,
- types = _ref36.types;
- return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
- },
- EnumTypeExtension: function EnumTypeExtension(_ref37) {
- var name = _ref37.name,
- directives = _ref37.directives,
- values = _ref37.values;
- return join(['extend enum', name, join(directives, ' '), block(values)], ' ');
- },
- InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) {
- var name = _ref38.name,
- directives = _ref38.directives,
- fields = _ref38.fields;
- return join(['extend input', name, join(directives, ' '), block(fields)], ' ');
- }
- };
- function addDescription(cb) {
- return function (node) {
- return join([node.description, cb(node)], '\n');
- };
- }
- /**
- * Given maybeArray, print an empty string if it is null or empty, otherwise
- * print all items together separated by separator if provided
- */
- function join(maybeArray, separator) {
- return maybeArray ? maybeArray.filter(function (x) {
- return x;
- }).join(separator || '') : '';
- }
- /**
- * Given array, print each item on its own line, wrapped in an
- * indented "{ }" block.
- */
- function block(array) {
- return array && array.length !== 0 ? '{\n' + indent(join(array, '\n')) + '\n}' : '';
- }
- /**
- * If maybeString is not null or empty, then wrap with start and end, otherwise
- * print an empty string.
- */
- function wrap(start, maybeString, end) {
- return maybeString ? start + maybeString + (end || '') : '';
- }
- function indent(maybeString) {
- return maybeString && ' ' + maybeString.replace(/\n/g, '\n ');
- }
- function isMultiline(string) {
- return string.indexOf('\n') !== -1;
- }
- function hasMultilineItems(maybeArray) {
- return maybeArray && maybeArray.some(isMultiline);
- }
- },{"./blockString":48,"./visitor":58}],57:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Source = void 0;
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * A representation of source input to GraphQL.
- * `name` and `locationOffset` are optional. They are useful for clients who
- * store GraphQL documents in source files; for example, if the GraphQL input
- * starts at line 40 in a file named Foo.graphql, it might be useful for name to
- * be "Foo.graphql" and location to be `{ line: 40, column: 0 }`.
- * line and column in locationOffset are 1-indexed
- */
- var Source = function Source(body, name, locationOffset) {
- this.body = body;
- this.name = name || 'GraphQL request';
- this.locationOffset = locationOffset || {
- line: 1,
- column: 1
- };
- !(this.locationOffset.line > 0) ? (0, _invariant.default)(0, 'line in locationOffset is 1-indexed and must be positive') : void 0;
- !(this.locationOffset.column > 0) ? (0, _invariant.default)(0, 'column in locationOffset is 1-indexed and must be positive') : void 0;
- }; // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.Source = Source;
- (0, _defineToStringTag.default)(Source);
- },{"../jsutils/defineToStringTag":31,"../jsutils/invariant":34}],58:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.visit = visit;
- exports.visitInParallel = visitInParallel;
- exports.visitWithTypeInfo = visitWithTypeInfo;
- exports.getVisitFn = getVisitFn;
- exports.BREAK = exports.QueryDocumentKeys = void 0;
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var QueryDocumentKeys = {
- Name: [],
- Document: ['definitions'],
- OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
- VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],
- Variable: ['name'],
- SelectionSet: ['selections'],
- Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
- Argument: ['name', 'value'],
- FragmentSpread: ['name', 'directives'],
- InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
- FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed
- // or removed in the future.
- 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'],
- IntValue: [],
- FloatValue: [],
- StringValue: [],
- BooleanValue: [],
- NullValue: [],
- EnumValue: [],
- ListValue: ['values'],
- ObjectValue: ['fields'],
- ObjectField: ['name', 'value'],
- Directive: ['name', 'arguments'],
- NamedType: ['name'],
- ListType: ['type'],
- NonNullType: ['type'],
- SchemaDefinition: ['directives', 'operationTypes'],
- OperationTypeDefinition: ['type'],
- ScalarTypeDefinition: ['description', 'name', 'directives'],
- ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
- FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],
- InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'],
- InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'],
- UnionTypeDefinition: ['description', 'name', 'directives', 'types'],
- EnumTypeDefinition: ['description', 'name', 'directives', 'values'],
- EnumValueDefinition: ['description', 'name', 'directives'],
- InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],
- DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],
- SchemaExtension: ['directives', 'operationTypes'],
- ScalarTypeExtension: ['name', 'directives'],
- ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
- InterfaceTypeExtension: ['name', 'directives', 'fields'],
- UnionTypeExtension: ['name', 'directives', 'types'],
- EnumTypeExtension: ['name', 'directives', 'values'],
- InputObjectTypeExtension: ['name', 'directives', 'fields']
- };
- exports.QueryDocumentKeys = QueryDocumentKeys;
- var BREAK = {};
- /**
- * visit() will walk through an AST using a depth first traversal, calling
- * the visitor's enter function at each node in the traversal, and calling the
- * leave function after visiting that node and all of its child nodes.
- *
- * By returning different values from the enter and leave functions, the
- * behavior of the visitor can be altered, including skipping over a sub-tree of
- * the AST (by returning false), editing the AST by returning a value or null
- * to remove the value, or to stop the whole traversal by returning BREAK.
- *
- * When using visit() to edit an AST, the original AST will not be modified, and
- * a new version of the AST with the changes applied will be returned from the
- * visit function.
- *
- * const editedAST = visit(ast, {
- * enter(node, key, parent, path, ancestors) {
- * // @return
- * // undefined: no action
- * // false: skip visiting this node
- * // visitor.BREAK: stop visiting altogether
- * // null: delete this node
- * // any value: replace this node with the returned value
- * },
- * leave(node, key, parent, path, ancestors) {
- * // @return
- * // undefined: no action
- * // false: no action
- * // visitor.BREAK: stop visiting altogether
- * // null: delete this node
- * // any value: replace this node with the returned value
- * }
- * });
- *
- * Alternatively to providing enter() and leave() functions, a visitor can
- * instead provide functions named the same as the kinds of AST nodes, or
- * enter/leave visitors at a named key, leading to four permutations of
- * visitor API:
- *
- * 1) Named visitors triggered when entering a node a specific kind.
- *
- * visit(ast, {
- * Kind(node) {
- * // enter the "Kind" node
- * }
- * })
- *
- * 2) Named visitors that trigger upon entering and leaving a node of
- * a specific kind.
- *
- * visit(ast, {
- * Kind: {
- * enter(node) {
- * // enter the "Kind" node
- * }
- * leave(node) {
- * // leave the "Kind" node
- * }
- * }
- * })
- *
- * 3) Generic visitors that trigger upon entering and leaving any node.
- *
- * visit(ast, {
- * enter(node) {
- * // enter any node
- * },
- * leave(node) {
- * // leave any node
- * }
- * })
- *
- * 4) Parallel visitors for entering and leaving nodes of a specific kind.
- *
- * visit(ast, {
- * enter: {
- * Kind(node) {
- * // enter the "Kind" node
- * }
- * },
- * leave: {
- * Kind(node) {
- * // leave the "Kind" node
- * }
- * }
- * })
- */
- exports.BREAK = BREAK;
- function visit(root, visitor) {
- var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys;
- /* eslint-disable no-undef-init */
- var stack = undefined;
- var inArray = Array.isArray(root);
- var keys = [root];
- var index = -1;
- var edits = [];
- var node = undefined;
- var key = undefined;
- var parent = undefined;
- var path = [];
- var ancestors = [];
- var newRoot = root;
- /* eslint-enable no-undef-init */
- do {
- index++;
- var isLeaving = index === keys.length;
- var isEdited = isLeaving && edits.length !== 0;
- if (isLeaving) {
- key = ancestors.length === 0 ? undefined : path[path.length - 1];
- node = parent;
- parent = ancestors.pop();
- if (isEdited) {
- if (inArray) {
- node = node.slice();
- } else {
- var clone = {};
- for (var _i = 0, _Object$keys = Object.keys(node); _i < _Object$keys.length; _i++) {
- var k = _Object$keys[_i];
- clone[k] = node[k];
- }
- node = clone;
- }
- var editOffset = 0;
- for (var ii = 0; ii < edits.length; ii++) {
- var editKey = edits[ii][0];
- var editValue = edits[ii][1];
- if (inArray) {
- editKey -= editOffset;
- }
- if (inArray && editValue === null) {
- node.splice(editKey, 1);
- editOffset++;
- } else {
- node[editKey] = editValue;
- }
- }
- }
- index = stack.index;
- keys = stack.keys;
- edits = stack.edits;
- inArray = stack.inArray;
- stack = stack.prev;
- } else {
- key = parent ? inArray ? index : keys[index] : undefined;
- node = parent ? parent[key] : newRoot;
- if (node === null || node === undefined) {
- continue;
- }
- if (parent) {
- path.push(key);
- }
- }
- var result = void 0;
- if (!Array.isArray(node)) {
- if (!isNode(node)) {
- throw new Error('Invalid AST Node: ' + (0, _inspect.default)(node));
- }
- var visitFn = getVisitFn(visitor, node.kind, isLeaving);
- if (visitFn) {
- result = visitFn.call(visitor, node, key, parent, path, ancestors);
- if (result === BREAK) {
- break;
- }
- if (result === false) {
- if (!isLeaving) {
- path.pop();
- continue;
- }
- } else if (result !== undefined) {
- edits.push([key, result]);
- if (!isLeaving) {
- if (isNode(result)) {
- node = result;
- } else {
- path.pop();
- continue;
- }
- }
- }
- }
- }
- if (result === undefined && isEdited) {
- edits.push([key, node]);
- }
- if (isLeaving) {
- path.pop();
- } else {
- stack = {
- inArray: inArray,
- index: index,
- keys: keys,
- edits: edits,
- prev: stack
- };
- inArray = Array.isArray(node);
- keys = inArray ? node : visitorKeys[node.kind] || [];
- index = -1;
- edits = [];
- if (parent) {
- ancestors.push(parent);
- }
- parent = node;
- }
- } while (stack !== undefined);
- if (edits.length !== 0) {
- newRoot = edits[edits.length - 1][1];
- }
- return newRoot;
- }
- function isNode(maybeNode) {
- return Boolean(maybeNode && typeof maybeNode.kind === 'string');
- }
- /**
- * Creates a new visitor instance which delegates to many visitors to run in
- * parallel. Each visitor will be visited for each node before moving on.
- *
- * If a prior visitor edits a node, no following visitors will see that node.
- */
- function visitInParallel(visitors) {
- var skipping = new Array(visitors.length);
- return {
- enter: function enter(node) {
- for (var i = 0; i < visitors.length; i++) {
- if (!skipping[i]) {
- var fn = getVisitFn(visitors[i], node.kind,
- /* isLeaving */
- false);
- if (fn) {
- var result = fn.apply(visitors[i], arguments);
- if (result === false) {
- skipping[i] = node;
- } else if (result === BREAK) {
- skipping[i] = BREAK;
- } else if (result !== undefined) {
- return result;
- }
- }
- }
- }
- },
- leave: function leave(node) {
- for (var i = 0; i < visitors.length; i++) {
- if (!skipping[i]) {
- var fn = getVisitFn(visitors[i], node.kind,
- /* isLeaving */
- true);
- if (fn) {
- var result = fn.apply(visitors[i], arguments);
- if (result === BREAK) {
- skipping[i] = BREAK;
- } else if (result !== undefined && result !== false) {
- return result;
- }
- }
- } else if (skipping[i] === node) {
- skipping[i] = null;
- }
- }
- }
- };
- }
- /**
- * Creates a new visitor instance which maintains a provided TypeInfo instance
- * along with visiting visitor.
- */
- function visitWithTypeInfo(typeInfo, visitor) {
- return {
- enter: function enter(node) {
- typeInfo.enter(node);
- var fn = getVisitFn(visitor, node.kind,
- /* isLeaving */
- false);
- if (fn) {
- var result = fn.apply(visitor, arguments);
- if (result !== undefined) {
- typeInfo.leave(node);
- if (isNode(result)) {
- typeInfo.enter(result);
- }
- }
- return result;
- }
- },
- leave: function leave(node) {
- var fn = getVisitFn(visitor, node.kind,
- /* isLeaving */
- true);
- var result;
- if (fn) {
- result = fn.apply(visitor, arguments);
- }
- typeInfo.leave(node);
- return result;
- }
- };
- }
- /**
- * Given a visitor instance, if it is leaving or not, and a node kind, return
- * the function the visitor runtime should call.
- */
- function getVisitFn(visitor, kind, isLeaving) {
- var kindVisitor = visitor[kind];
- if (kindVisitor) {
- if (!isLeaving && typeof kindVisitor === 'function') {
- // { Kind() {} }
- return kindVisitor;
- }
- var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
- if (typeof kindSpecificVisitor === 'function') {
- // { Kind: { enter() {}, leave() {} } }
- return kindSpecificVisitor;
- }
- } else {
- var specificVisitor = isLeaving ? visitor.leave : visitor.enter;
- if (specificVisitor) {
- if (typeof specificVisitor === 'function') {
- // { enter() {}, leave() {} }
- return specificVisitor;
- }
- var specificKindVisitor = specificVisitor[kind];
- if (typeof specificKindVisitor === 'function') {
- // { enter: { Kind() {} }, leave: { Kind() {} } }
- return specificKindVisitor;
- }
- }
- }
- }
- },{"../jsutils/inspect":32}],59:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe
- var find = Array.prototype.find ? function (list, predicate) {
- return Array.prototype.find.call(list, predicate);
- } : function (list, predicate) {
- for (var i = 0; i < list.length; i++) {
- var value = list[i];
- if (predicate(value)) {
- return value;
- }
- }
- };
- var _default = find;
- exports.default = _default;
- },{}],60:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe
- var flatMap = Array.prototype.flatMap ? function (list, fn) {
- // $FlowFixMe
- return Array.prototype.flatMap.call(list, fn);
- } : function (list, fn) {
- var result = [];
- for (var i = 0; i < list.length; i++) {
- var value = fn(list[i]);
- if (Array.isArray(value)) {
- result = result.concat(value);
- } else {
- result.push(value);
- }
- }
- return result;
- };
- var _default = flatMap;
- exports.default = _default;
- },{}],61:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
- var isFinite = Number.isFinite || function (value) {
- return typeof value === 'number' && isFinite(value);
- };
- var _default = isFinite;
- exports.default = _default;
- },{}],62:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
- var isInteger = Number.isInteger || function (value) {
- return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
- };
- var _default = isInteger;
- exports.default = _default;
- },{}],63:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe workaround for: https://github.com/facebook/flow/issues/5838
- var objectEntries = Object.entries || function (obj) {
- return Object.keys(obj).map(function (key) {
- return [key, obj[key]];
- });
- };
- var _default = objectEntries;
- exports.default = _default;
- },{}],64:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221
- var objectValues = Object.values || function (obj) {
- return Object.keys(obj).map(function (key) {
- return obj[key];
- });
- };
- var _default = objectValues;
- exports.default = _default;
- },{}],65:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "subscribe", {
- enumerable: true,
- get: function get() {
- return _subscribe.subscribe;
- }
- });
- Object.defineProperty(exports, "createSourceEventStream", {
- enumerable: true,
- get: function get() {
- return _subscribe.createSourceEventStream;
- }
- });
- var _subscribe = require("./subscribe");
- },{"./subscribe":67}],66:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = mapAsyncIterator;
- var _iterall = require("iterall");
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * Given an AsyncIterable and a callback function, return an AsyncIterator
- * which produces values mapped via calling the callback function.
- */
- function mapAsyncIterator(iterable, callback, rejectCallback) {
- var iterator = (0, _iterall.getAsyncIterator)(iterable);
- var $return;
- var abruptClose; // $FlowFixMe(>=0.68.0)
- if (typeof iterator.return === 'function') {
- $return = iterator.return;
- abruptClose = function abruptClose(error) {
- var rethrow = function rethrow() {
- return Promise.reject(error);
- };
- return $return.call(iterator).then(rethrow, rethrow);
- };
- }
- function mapResult(result) {
- return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);
- }
- var mapReject;
- if (rejectCallback) {
- // Capture rejectCallback to ensure it cannot be null.
- var reject = rejectCallback;
- mapReject = function mapReject(error) {
- return asyncMapValue(error, reject).then(iteratorResult, abruptClose);
- };
- }
- /* TODO: Flow doesn't support symbols as keys:
- https://github.com/facebook/flow/issues/3258 */
- return _defineProperty({
- next: function next() {
- return iterator.next().then(mapResult, mapReject);
- },
- return: function _return() {
- return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({
- value: undefined,
- done: true
- });
- },
- throw: function _throw(error) {
- // $FlowFixMe(>=0.68.0)
- if (typeof iterator.throw === 'function') {
- return iterator.throw(error).then(mapResult, mapReject);
- }
- return Promise.reject(error).catch(abruptClose);
- }
- }, _iterall.$$asyncIterator, function () {
- return this;
- });
- }
- function asyncMapValue(value, callback) {
- return new Promise(function (resolve) {
- return resolve(callback(value));
- });
- }
- function iteratorResult(value) {
- return {
- value: value,
- done: false
- };
- }
- },{"iterall":137}],67:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.subscribe = subscribe;
- exports.createSourceEventStream = createSourceEventStream;
- var _iterall = require("iterall");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _GraphQLError = require("../error/GraphQLError");
- var _locatedError = require("../error/locatedError");
- var _execute = require("../execution/execute");
- var _mapAsyncIterator = _interopRequireDefault(require("./mapAsyncIterator"));
- var _getOperationRootType = require("../utilities/getOperationRootType");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) {
- /* eslint-enable no-redeclare */
- // Extract arguments from object args if provided.
- return arguments.length === 1 ? subscribeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, argsOrSchema.subscribeFieldResolver) : subscribeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver);
- }
- /**
- * This function checks if the error is a GraphQLError. If it is, report it as
- * an ExecutionResult, containing only errors and no data. Otherwise treat the
- * error as a system-class error and re-throw it.
- */
- function reportGraphQLError(error) {
- if (error instanceof _GraphQLError.GraphQLError) {
- return {
- errors: [error]
- };
- }
- throw error;
- }
- function subscribeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) {
- var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal
- // GraphQL `execute` function, with `payload` as the rootValue.
- // This implements the "MapSourceToResponseEvent" algorithm described in
- // the GraphQL specification. The `execute` function provides the
- // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
- // "ExecuteQuery" algorithm, for which `execute` is also used.
- var mapSourceToResponse = function mapSourceToResponse(payload) {
- return (0, _execute.execute)(schema, document, payload, contextValue, variableValues, operationName, fieldResolver);
- }; // Resolve the Source Stream, then map every source value to a
- // ExecutionResult value as described above.
- return sourcePromise.then(function (resultOrStream) {
- return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used.
- (0, _iterall.isAsyncIterable)(resultOrStream) ? (0, _mapAsyncIterator.default)(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream
- );
- }, reportGraphQLError);
- }
- /**
- * Implements the "CreateSourceEventStream" algorithm described in the
- * GraphQL specification, resolving the subscription source event stream.
- *
- * Returns a Promise<AsyncIterable>.
- *
- * If the client-provided invalid arguments, the source stream could not be
- * created, or the resolver did not return an AsyncIterable, this function will
- * will throw an error, which should be caught and handled by the caller.
- *
- * A Source Event Stream represents a sequence of events, each of which triggers
- * a GraphQL execution for that event.
- *
- * This may be useful when hosting the stateful subscription service in a
- * different process or machine than the stateless GraphQL execution engine,
- * or otherwise separating these two steps. For more on this, see the
- * "Supporting Subscriptions at Scale" information in the GraphQL specification.
- */
- function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {
- // If arguments are missing or incorrectly typed, this is an internal
- // developer mistake which should throw an early error.
- (0, _execute.assertValidExecutionArguments)(schema, document, variableValues);
- try {
- // If a valid context cannot be created due to incorrect arguments,
- // this will throw an error.
- var exeContext = (0, _execute.buildExecutionContext)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed.
- if (Array.isArray(exeContext)) {
- return Promise.resolve({
- errors: exeContext
- });
- }
- var type = (0, _getOperationRootType.getOperationRootType)(schema, exeContext.operation);
- var fields = (0, _execute.collectFields)(exeContext, type, exeContext.operation.selectionSet, Object.create(null), Object.create(null));
- var responseNames = Object.keys(fields);
- var responseName = responseNames[0];
- var fieldNodes = fields[responseName];
- var fieldNode = fieldNodes[0];
- var fieldName = fieldNode.name.value;
- var fieldDef = (0, _execute.getFieldDef)(schema, type, fieldName);
- if (!fieldDef) {
- throw new _GraphQLError.GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes);
- } // Call the `subscribe()` resolver or the default resolver to produce an
- // AsyncIterable yielding raw payloads.
- var resolveFn = fieldDef.subscribe || exeContext.fieldResolver;
- var path = (0, _execute.addPath)(undefined, responseName);
- var info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, type, path); // resolveFieldValueOrError implements the "ResolveFieldEventStream"
- // algorithm from GraphQL specification. It differs from
- // "ResolveFieldValue" due to providing a different `resolveFn`.
- var result = (0, _execute.resolveFieldValueOrError)(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); // Coerce to Promise for easier error handling and consistent return type.
- return Promise.resolve(result).then(function (eventStream) {
- // If eventStream is an Error, rethrow a located error.
- if (eventStream instanceof Error) {
- throw (0, _locatedError.locatedError)(eventStream, fieldNodes, (0, _execute.responsePathAsArray)(path));
- } // Assert field returned an event stream, otherwise yield an error.
- if ((0, _iterall.isAsyncIterable)(eventStream)) {
- // Note: isAsyncIterable above ensures this will be correct.
- return eventStream;
- }
- throw new Error('Subscription field must return Async Iterable. Received: ' + (0, _inspect.default)(eventStream));
- });
- } catch (error) {
- return Promise.reject(error);
- }
- }
- },{"../error/GraphQLError":19,"../error/locatedError":22,"../execution/execute":25,"../jsutils/inspect":32,"../utilities/getOperationRootType":86,"./mapAsyncIterator":66,"iterall":137}],68:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isType = isType;
- exports.assertType = assertType;
- exports.isScalarType = isScalarType;
- exports.assertScalarType = assertScalarType;
- exports.isObjectType = isObjectType;
- exports.assertObjectType = assertObjectType;
- exports.isInterfaceType = isInterfaceType;
- exports.assertInterfaceType = assertInterfaceType;
- exports.isUnionType = isUnionType;
- exports.assertUnionType = assertUnionType;
- exports.isEnumType = isEnumType;
- exports.assertEnumType = assertEnumType;
- exports.isInputObjectType = isInputObjectType;
- exports.assertInputObjectType = assertInputObjectType;
- exports.isListType = isListType;
- exports.assertListType = assertListType;
- exports.isNonNullType = isNonNullType;
- exports.assertNonNullType = assertNonNullType;
- exports.isInputType = isInputType;
- exports.assertInputType = assertInputType;
- exports.isOutputType = isOutputType;
- exports.assertOutputType = assertOutputType;
- exports.isLeafType = isLeafType;
- exports.assertLeafType = assertLeafType;
- exports.isCompositeType = isCompositeType;
- exports.assertCompositeType = assertCompositeType;
- exports.isAbstractType = isAbstractType;
- exports.assertAbstractType = assertAbstractType;
- exports.GraphQLList = GraphQLList;
- exports.GraphQLNonNull = GraphQLNonNull;
- exports.isWrappingType = isWrappingType;
- exports.assertWrappingType = assertWrappingType;
- exports.isNullableType = isNullableType;
- exports.assertNullableType = assertNullableType;
- exports.getNullableType = getNullableType;
- exports.isNamedType = isNamedType;
- exports.assertNamedType = assertNamedType;
- exports.getNamedType = getNamedType;
- exports.argsToArgsConfig = argsToArgsConfig;
- exports.isRequiredArgument = isRequiredArgument;
- exports.isRequiredInputField = isRequiredInputField;
- exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = void 0;
- var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries"));
- var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON"));
- var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag"));
- var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _mapValue = _interopRequireDefault(require("../jsutils/mapValue"));
- var _kinds = require("../language/kinds");
- var _valueFromASTUntyped = require("../utilities/valueFromASTUntyped");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function isType(type) {
- return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type);
- }
- function assertType(type) {
- !isType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL type.")) : void 0;
- return type;
- }
- /**
- * There are predicates for each kind of GraphQL type.
- */
- // eslint-disable-next-line no-redeclare
- function isScalarType(type) {
- return (0, _instanceOf.default)(type, GraphQLScalarType);
- }
- function assertScalarType(type) {
- !isScalarType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Scalar type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isObjectType(type) {
- return (0, _instanceOf.default)(type, GraphQLObjectType);
- }
- function assertObjectType(type) {
- !isObjectType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Object type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isInterfaceType(type) {
- return (0, _instanceOf.default)(type, GraphQLInterfaceType);
- }
- function assertInterfaceType(type) {
- !isInterfaceType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Interface type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isUnionType(type) {
- return (0, _instanceOf.default)(type, GraphQLUnionType);
- }
- function assertUnionType(type) {
- !isUnionType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Union type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isEnumType(type) {
- return (0, _instanceOf.default)(type, GraphQLEnumType);
- }
- function assertEnumType(type) {
- !isEnumType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Enum type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isInputObjectType(type) {
- return (0, _instanceOf.default)(type, GraphQLInputObjectType);
- }
- function assertInputObjectType(type) {
- !isInputObjectType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Input Object type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isListType(type) {
- return (0, _instanceOf.default)(type, GraphQLList);
- }
- function assertListType(type) {
- !isListType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL List type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isNonNullType(type) {
- return (0, _instanceOf.default)(type, GraphQLNonNull);
- }
- function assertNonNullType(type) {
- !isNonNullType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Non-Null type.")) : void 0;
- return type;
- }
- /**
- * These types may be used as input types for arguments and directives.
- */
- function isInputType(type) {
- return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType);
- }
- function assertInputType(type) {
- !isInputType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL input type.")) : void 0;
- return type;
- }
- /**
- * These types may be used as output types as the result of fields.
- */
- function isOutputType(type) {
- return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType);
- }
- function assertOutputType(type) {
- !isOutputType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL output type.")) : void 0;
- return type;
- }
- /**
- * These types may describe types which may be leaf values.
- */
- function isLeafType(type) {
- return isScalarType(type) || isEnumType(type);
- }
- function assertLeafType(type) {
- !isLeafType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL leaf type.")) : void 0;
- return type;
- }
- /**
- * These types may describe the parent context of a selection set.
- */
- function isCompositeType(type) {
- return isObjectType(type) || isInterfaceType(type) || isUnionType(type);
- }
- function assertCompositeType(type) {
- !isCompositeType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL composite type.")) : void 0;
- return type;
- }
- /**
- * These types may describe the parent context of a selection set.
- */
- function isAbstractType(type) {
- return isInterfaceType(type) || isUnionType(type);
- }
- function assertAbstractType(type) {
- !isAbstractType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL abstract type.")) : void 0;
- return type;
- }
- /**
- * List Type Wrapper
- *
- * A list is a wrapping type which points to another type.
- * Lists are often created within the context of defining the fields of
- * an object type.
- *
- * Example:
- *
- * const PersonType = new GraphQLObjectType({
- * name: 'Person',
- * fields: () => ({
- * parents: { type: GraphQLList(PersonType) },
- * children: { type: GraphQLList(PersonType) },
- * })
- * })
- *
- */
- // eslint-disable-next-line no-redeclare
- function GraphQLList(ofType) {
- if (this instanceof GraphQLList) {
- this.ofType = assertType(ofType);
- } else {
- return new GraphQLList(ofType);
- }
- } // Need to cast through any to alter the prototype.
- GraphQLList.prototype.toString = function toString() {
- return '[' + String(this.ofType) + ']';
- }; // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- (0, _defineToStringTag.default)(GraphQLList);
- (0, _defineToJSON.default)(GraphQLList);
- /**
- * Non-Null Type Wrapper
- *
- * A non-null is a wrapping type which points to another type.
- * Non-null types enforce that their values are never null and can ensure
- * an error is raised if this ever occurs during a request. It is useful for
- * fields which you can make a strong guarantee on non-nullability, for example
- * usually the id field of a database row will never be null.
- *
- * Example:
- *
- * const RowType = new GraphQLObjectType({
- * name: 'Row',
- * fields: () => ({
- * id: { type: GraphQLNonNull(GraphQLString) },
- * })
- * })
- *
- * Note: the enforcement of non-nullability occurs within the executor.
- */
- // eslint-disable-next-line no-redeclare
- function GraphQLNonNull(ofType) {
- if (this instanceof GraphQLNonNull) {
- this.ofType = assertNullableType(ofType);
- } else {
- return new GraphQLNonNull(ofType);
- }
- } // Need to cast through any to alter the prototype.
- GraphQLNonNull.prototype.toString = function toString() {
- return String(this.ofType) + '!';
- }; // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- (0, _defineToStringTag.default)(GraphQLNonNull);
- (0, _defineToJSON.default)(GraphQLNonNull);
- /**
- * These types wrap and modify other types
- */
- function isWrappingType(type) {
- return isListType(type) || isNonNullType(type);
- }
- function assertWrappingType(type) {
- !isWrappingType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL wrapping type.")) : void 0;
- return type;
- }
- /**
- * These types can all accept null as a value.
- */
- function isNullableType(type) {
- return isType(type) && !isNonNullType(type);
- }
- function assertNullableType(type) {
- !isNullableType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL nullable type.")) : void 0;
- return type;
- }
- /* eslint-disable no-redeclare */
- function getNullableType(type) {
- /* eslint-enable no-redeclare */
- if (type) {
- return isNonNullType(type) ? type.ofType : type;
- }
- }
- /**
- * These named types do not include modifiers like List or NonNull.
- */
- function isNamedType(type) {
- return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type);
- }
- function assertNamedType(type) {
- !isNamedType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL named type.")) : void 0;
- return type;
- }
- /* eslint-disable no-redeclare */
- function getNamedType(type) {
- /* eslint-enable no-redeclare */
- if (type) {
- var unwrappedType = type;
- while (isWrappingType(unwrappedType)) {
- unwrappedType = unwrappedType.ofType;
- }
- return unwrappedType;
- }
- }
- /**
- * Used while defining GraphQL types to allow for circular references in
- * otherwise immutable type definitions.
- */
- function resolveThunk(thunk) {
- // $FlowFixMe(>=0.90.0)
- return typeof thunk === 'function' ? thunk() : thunk;
- }
- function undefineIfEmpty(arr) {
- return arr && arr.length > 0 ? arr : undefined;
- }
- /**
- * Scalar Type Definition
- *
- * The leaf values of any request and input values to arguments are
- * Scalars (or Enums) and are defined with a name and a series of functions
- * used to parse input from ast or variables and to ensure validity.
- *
- * If a type's serialize function does not return a value (i.e. it returns
- * `undefined`) then an error will be raised and a `null` value will be returned
- * in the response. If the serialize function returns `null`, then no error will
- * be included in the response.
- *
- * Example:
- *
- * const OddType = new GraphQLScalarType({
- * name: 'Odd',
- * serialize(value) {
- * if (value % 2 === 1) {
- * return value;
- * }
- * }
- * });
- *
- */
- var GraphQLScalarType =
- /*#__PURE__*/
- function () {
- function GraphQLScalarType(config) {
- this.name = config.name;
- this.description = config.description;
- this.serialize = config.serialize;
- this.parseValue = config.parseValue || function (value) {
- return value;
- };
- this.parseLiteral = config.parseLiteral || _valueFromASTUntyped.valueFromASTUntyped;
- this.astNode = config.astNode;
- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- !(typeof config.serialize === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"serialize\" function. If this custom Scalar ") + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.') : void 0;
- if (config.parseValue || config.parseLiteral) {
- !(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" ") + 'functions.') : void 0;
- }
- }
- var _proto = GraphQLScalarType.prototype;
- _proto.toConfig = function toConfig() {
- return {
- name: this.name,
- description: this.description,
- serialize: this.serialize,
- parseValue: this.parseValue,
- parseLiteral: this.parseLiteral,
- astNode: this.astNode,
- extensionASTNodes: this.extensionASTNodes || []
- };
- };
- _proto.toString = function toString() {
- return this.name;
- };
- return GraphQLScalarType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLScalarType = GraphQLScalarType;
- (0, _defineToStringTag.default)(GraphQLScalarType);
- (0, _defineToJSON.default)(GraphQLScalarType);
- /**
- * Object Type Definition
- *
- * Almost all of the GraphQL types you define will be object types. Object types
- * have a name, but most importantly describe their fields.
- *
- * Example:
- *
- * const AddressType = new GraphQLObjectType({
- * name: 'Address',
- * fields: {
- * street: { type: GraphQLString },
- * number: { type: GraphQLInt },
- * formatted: {
- * type: GraphQLString,
- * resolve(obj) {
- * return obj.number + ' ' + obj.street
- * }
- * }
- * }
- * });
- *
- * When two types need to refer to each other, or a type needs to refer to
- * itself in a field, you can use a function expression (aka a closure or a
- * thunk) to supply the fields lazily.
- *
- * Example:
- *
- * const PersonType = new GraphQLObjectType({
- * name: 'Person',
- * fields: () => ({
- * name: { type: GraphQLString },
- * bestFriend: { type: PersonType },
- * })
- * });
- *
- */
- var GraphQLObjectType =
- /*#__PURE__*/
- function () {
- function GraphQLObjectType(config) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
- this.isTypeOf = config.isTypeOf;
- this._fields = defineFieldMap.bind(undefined, config);
- this._interfaces = defineInterfaces.bind(undefined, config);
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- !(config.isTypeOf == null || typeof config.isTypeOf === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.isTypeOf), ".")) : void 0;
- }
- var _proto2 = GraphQLObjectType.prototype;
- _proto2.getFields = function getFields() {
- if (typeof this._fields === 'function') {
- this._fields = this._fields();
- }
- return this._fields;
- };
- _proto2.getInterfaces = function getInterfaces() {
- if (typeof this._interfaces === 'function') {
- this._interfaces = this._interfaces();
- }
- return this._interfaces;
- };
- _proto2.toConfig = function toConfig() {
- return {
- name: this.name,
- description: this.description,
- isTypeOf: this.isTypeOf,
- interfaces: this.getInterfaces(),
- fields: fieldsToFieldsConfig(this.getFields()),
- astNode: this.astNode,
- extensionASTNodes: this.extensionASTNodes || []
- };
- };
- _proto2.toString = function toString() {
- return this.name;
- };
- return GraphQLObjectType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLObjectType = GraphQLObjectType;
- (0, _defineToStringTag.default)(GraphQLObjectType);
- (0, _defineToJSON.default)(GraphQLObjectType);
- function defineInterfaces(config) {
- var interfaces = resolveThunk(config.interfaces) || [];
- !Array.isArray(interfaces) ? (0, _invariant.default)(0, "".concat(config.name, " interfaces must be an Array or a function which returns ") + 'an Array.') : void 0;
- return interfaces;
- }
- function defineFieldMap(config) {
- var fieldMap = resolveThunk(config.fields) || {};
- !isPlainObj(fieldMap) ? (0, _invariant.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0;
- return (0, _mapValue.default)(fieldMap, function (fieldConfig, fieldName) {
- !isPlainObj(fieldConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object")) : void 0;
- !!('isDeprecated' in fieldConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" ") + 'instead of "isDeprecated".') : void 0;
- !(fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field resolver must be a function if ") + "provided, but got: ".concat((0, _inspect.default)(fieldConfig.resolve), ".")) : void 0;
- var argsConfig = fieldConfig.args || {};
- !isPlainObj(argsConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument ") + 'names as keys.') : void 0;
- var args = (0, _objectEntries.default)(argsConfig).map(function (_ref) {
- var argName = _ref[0],
- arg = _ref[1];
- return {
- name: argName,
- description: arg.description === undefined ? null : arg.description,
- type: arg.type,
- defaultValue: arg.defaultValue,
- astNode: arg.astNode
- };
- });
- return _objectSpread({}, fieldConfig, {
- isDeprecated: Boolean(fieldConfig.deprecationReason),
- name: fieldName,
- args: args
- });
- });
- }
- function isPlainObj(obj) {
- return obj && _typeof(obj) === 'object' && !Array.isArray(obj);
- }
- function fieldsToFieldsConfig(fields) {
- return (0, _mapValue.default)(fields, function (field) {
- return {
- type: field.type,
- args: argsToArgsConfig(field.args),
- resolve: field.resolve,
- subscribe: field.subscribe,
- deprecationReason: field.deprecationReason,
- description: field.description,
- astNode: field.astNode
- };
- });
- }
- function argsToArgsConfig(args) {
- return (0, _keyValMap.default)(args, function (arg) {
- return arg.name;
- }, function (arg) {
- return {
- type: arg.type,
- defaultValue: arg.defaultValue,
- description: arg.description,
- astNode: arg.astNode
- };
- });
- }
- function isRequiredArgument(arg) {
- return isNonNullType(arg.type) && arg.defaultValue === undefined;
- }
- /**
- * Interface Type Definition
- *
- * When a field can return one of a heterogeneous set of types, a Interface type
- * is used to describe what types are possible, what fields are in common across
- * all types, as well as a function to determine which type is actually used
- * when the field is resolved.
- *
- * Example:
- *
- * const EntityType = new GraphQLInterfaceType({
- * name: 'Entity',
- * fields: {
- * name: { type: GraphQLString }
- * }
- * });
- *
- */
- var GraphQLInterfaceType =
- /*#__PURE__*/
- function () {
- function GraphQLInterfaceType(config) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
- this.resolveType = config.resolveType;
- this._fields = defineFieldMap.bind(undefined, config);
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- !(config.resolveType == null || typeof config.resolveType === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")) : void 0;
- }
- var _proto3 = GraphQLInterfaceType.prototype;
- _proto3.getFields = function getFields() {
- if (typeof this._fields === 'function') {
- this._fields = this._fields();
- }
- return this._fields;
- };
- _proto3.toConfig = function toConfig() {
- return {
- name: this.name,
- description: this.description,
- resolveType: this.resolveType,
- fields: fieldsToFieldsConfig(this.getFields()),
- astNode: this.astNode,
- extensionASTNodes: this.extensionASTNodes || []
- };
- };
- _proto3.toString = function toString() {
- return this.name;
- };
- return GraphQLInterfaceType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLInterfaceType = GraphQLInterfaceType;
- (0, _defineToStringTag.default)(GraphQLInterfaceType);
- (0, _defineToJSON.default)(GraphQLInterfaceType);
- /**
- * Union Type Definition
- *
- * When a field can return one of a heterogeneous set of types, a Union type
- * is used to describe what types are possible as well as providing a function
- * to determine which type is actually used when the field is resolved.
- *
- * Example:
- *
- * const PetType = new GraphQLUnionType({
- * name: 'Pet',
- * types: [ DogType, CatType ],
- * resolveType(value) {
- * if (value instanceof Dog) {
- * return DogType;
- * }
- * if (value instanceof Cat) {
- * return CatType;
- * }
- * }
- * });
- *
- */
- var GraphQLUnionType =
- /*#__PURE__*/
- function () {
- function GraphQLUnionType(config) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
- this.resolveType = config.resolveType;
- this._types = defineTypes.bind(undefined, config);
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- !(config.resolveType == null || typeof config.resolveType === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")) : void 0;
- }
- var _proto4 = GraphQLUnionType.prototype;
- _proto4.getTypes = function getTypes() {
- if (typeof this._types === 'function') {
- this._types = this._types();
- }
- return this._types;
- };
- _proto4.toConfig = function toConfig() {
- return {
- name: this.name,
- description: this.description,
- resolveType: this.resolveType,
- types: this.getTypes(),
- astNode: this.astNode,
- extensionASTNodes: this.extensionASTNodes || []
- };
- };
- _proto4.toString = function toString() {
- return this.name;
- };
- return GraphQLUnionType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLUnionType = GraphQLUnionType;
- (0, _defineToStringTag.default)(GraphQLUnionType);
- (0, _defineToJSON.default)(GraphQLUnionType);
- function defineTypes(config) {
- var types = resolveThunk(config.types) || [];
- !Array.isArray(types) ? (0, _invariant.default)(0, 'Must provide Array of types or a function which returns ' + "such an array for Union ".concat(config.name, ".")) : void 0;
- return types;
- }
- /**
- * Enum Type Definition
- *
- * Some leaf values of requests and input values are Enums. GraphQL serializes
- * Enum values as strings, however internally Enums can be represented by any
- * kind of type, often integers.
- *
- * Example:
- *
- * const RGBType = new GraphQLEnumType({
- * name: 'RGB',
- * values: {
- * RED: { value: 0 },
- * GREEN: { value: 1 },
- * BLUE: { value: 2 }
- * }
- * });
- *
- * Note: If a value is not provided in a definition, the name of the enum value
- * will be used as its internal value.
- */
- var GraphQLEnumType
- /* <T> */
- =
- /*#__PURE__*/
- function () {
- function GraphQLEnumType(config) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
- this._values = defineEnumValues(this, config.values);
- this._valueLookup = new Map(this._values.map(function (enumValue) {
- return [enumValue.value, enumValue];
- }));
- this._nameLookup = (0, _keyMap.default)(this._values, function (value) {
- return value.name;
- });
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- }
- var _proto5 = GraphQLEnumType.prototype;
- _proto5.getValues = function getValues() {
- return this._values;
- };
- _proto5.getValue = function getValue(name) {
- return this._nameLookup[name];
- };
- _proto5.serialize = function serialize(value) {
- var enumValue = this._valueLookup.get(value);
- if (enumValue) {
- return enumValue.name;
- }
- };
- _proto5.parseValue = function parseValue(value)
- /* T */
- {
- if (typeof value === 'string') {
- var enumValue = this.getValue(value);
- if (enumValue) {
- return enumValue.value;
- }
- }
- };
- _proto5.parseLiteral = function parseLiteral(valueNode, _variables)
- /* T */
- {
- // Note: variables will be resolved to a value before calling this function.
- if (valueNode.kind === _kinds.Kind.ENUM) {
- var enumValue = this.getValue(valueNode.value);
- if (enumValue) {
- return enumValue.value;
- }
- }
- };
- _proto5.toConfig = function toConfig() {
- var values = (0, _keyValMap.default)(this.getValues(), function (value) {
- return value.name;
- }, function (value) {
- return {
- description: value.description,
- value: value.value,
- deprecationReason: value.deprecationReason,
- astNode: value.astNode
- };
- });
- return {
- name: this.name,
- description: this.description,
- values: values,
- astNode: this.astNode,
- extensionASTNodes: this.extensionASTNodes || []
- };
- };
- _proto5.toString = function toString() {
- return this.name;
- };
- return GraphQLEnumType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLEnumType = GraphQLEnumType;
- (0, _defineToStringTag.default)(GraphQLEnumType);
- (0, _defineToJSON.default)(GraphQLEnumType);
- function defineEnumValues(type, valueMap) {
- !isPlainObj(valueMap) ? (0, _invariant.default)(0, "".concat(type.name, " values must be an object with value names as keys.")) : void 0;
- return (0, _objectEntries.default)(valueMap).map(function (_ref2) {
- var valueName = _ref2[0],
- value = _ref2[1];
- !isPlainObj(value) ? (0, _invariant.default)(0, "".concat(type.name, ".").concat(valueName, " must refer to an object with a \"value\" key ") + "representing an internal value but got: ".concat((0, _inspect.default)(value), ".")) : void 0;
- !!('isDeprecated' in value) ? (0, _invariant.default)(0, "".concat(type.name, ".").concat(valueName, " should provide \"deprecationReason\" instead ") + 'of "isDeprecated".') : void 0;
- return {
- name: valueName,
- description: value.description,
- isDeprecated: Boolean(value.deprecationReason),
- deprecationReason: value.deprecationReason,
- astNode: value.astNode,
- value: 'value' in value ? value.value : valueName
- };
- });
- }
- /**
- * Input Object Type Definition
- *
- * An input object defines a structured collection of fields which may be
- * supplied to a field argument.
- *
- * Using `NonNull` will ensure that a value must be provided by the query
- *
- * Example:
- *
- * const GeoPoint = new GraphQLInputObjectType({
- * name: 'GeoPoint',
- * fields: {
- * lat: { type: GraphQLNonNull(GraphQLFloat) },
- * lon: { type: GraphQLNonNull(GraphQLFloat) },
- * alt: { type: GraphQLFloat, defaultValue: 0 },
- * }
- * });
- *
- */
- var GraphQLInputObjectType =
- /*#__PURE__*/
- function () {
- function GraphQLInputObjectType(config) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
- this._fields = defineInputFieldMap.bind(undefined, config);
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- }
- var _proto6 = GraphQLInputObjectType.prototype;
- _proto6.getFields = function getFields() {
- if (typeof this._fields === 'function') {
- this._fields = this._fields();
- }
- return this._fields;
- };
- _proto6.toConfig = function toConfig() {
- var fields = (0, _mapValue.default)(this.getFields(), function (field) {
- return {
- description: field.description,
- type: field.type,
- defaultValue: field.defaultValue,
- astNode: field.astNode
- };
- });
- return {
- name: this.name,
- description: this.description,
- fields: fields,
- astNode: this.astNode,
- extensionASTNodes: this.extensionASTNodes || []
- };
- };
- _proto6.toString = function toString() {
- return this.name;
- };
- return GraphQLInputObjectType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLInputObjectType = GraphQLInputObjectType;
- (0, _defineToStringTag.default)(GraphQLInputObjectType);
- (0, _defineToJSON.default)(GraphQLInputObjectType);
- function defineInputFieldMap(config) {
- var fieldMap = resolveThunk(config.fields) || {};
- !isPlainObj(fieldMap) ? (0, _invariant.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0;
- return (0, _mapValue.default)(fieldMap, function (fieldConfig, fieldName) {
- !!('resolve' in fieldConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but ") + 'Input Types cannot define resolvers.') : void 0;
- return _objectSpread({}, fieldConfig, {
- name: fieldName
- });
- });
- }
- function isRequiredInputField(field) {
- return isNonNullType(field.type) && field.defaultValue === undefined;
- }
- },{"../jsutils/defineToJSON":30,"../jsutils/defineToStringTag":31,"../jsutils/inspect":32,"../jsutils/instanceOf":33,"../jsutils/invariant":34,"../jsutils/keyMap":38,"../jsutils/keyValMap":39,"../jsutils/mapValue":40,"../language/kinds":51,"../polyfills/objectEntries":63,"../utilities/valueFromASTUntyped":99}],69:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isDirective = isDirective;
- exports.assertDirective = assertDirective;
- exports.isSpecifiedDirective = isSpecifiedDirective;
- exports.specifiedDirectives = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = void 0;
- var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries"));
- var _definition = require("./definition");
- var _scalars = require("./scalars");
- var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag"));
- var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON"));
- var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _directiveLocation = require("../language/directiveLocation");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- // eslint-disable-next-line no-redeclare
- function isDirective(directive) {
- return (0, _instanceOf.default)(directive, GraphQLDirective);
- }
- function assertDirective(directive) {
- !isDirective(directive) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(directive), " to be a GraphQL directive.")) : void 0;
- return directive;
- }
- /**
- * Directives are used by the GraphQL runtime as a way of modifying execution
- * behavior. Type system creators will usually not create these directly.
- */
- var GraphQLDirective =
- /*#__PURE__*/
- function () {
- function GraphQLDirective(config) {
- this.name = config.name;
- this.description = config.description;
- this.locations = config.locations;
- this.astNode = config.astNode;
- !config.name ? (0, _invariant.default)(0, 'Directive must be named.') : void 0;
- !Array.isArray(config.locations) ? (0, _invariant.default)(0, "@".concat(config.name, " locations must be an Array.")) : void 0;
- var args = config.args || {};
- !(_typeof(args) === 'object' && !Array.isArray(args)) ? (0, _invariant.default)(0, "@".concat(config.name, " args must be an object with argument names as keys.")) : void 0;
- this.args = (0, _objectEntries.default)(args).map(function (_ref) {
- var argName = _ref[0],
- arg = _ref[1];
- return {
- name: argName,
- description: arg.description === undefined ? null : arg.description,
- type: arg.type,
- defaultValue: arg.defaultValue,
- astNode: arg.astNode
- };
- });
- }
- var _proto = GraphQLDirective.prototype;
- _proto.toString = function toString() {
- return '@' + this.name;
- };
- _proto.toConfig = function toConfig() {
- return {
- name: this.name,
- description: this.description,
- locations: this.locations,
- args: (0, _definition.argsToArgsConfig)(this.args),
- astNode: this.astNode
- };
- };
- return GraphQLDirective;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLDirective = GraphQLDirective;
- (0, _defineToStringTag.default)(GraphQLDirective);
- (0, _defineToJSON.default)(GraphQLDirective);
- /**
- * Used to conditionally include fields or fragments.
- */
- var GraphQLIncludeDirective = new GraphQLDirective({
- name: 'include',
- description: 'Directs the executor to include this field or fragment only when ' + 'the `if` argument is true.',
- locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT],
- args: {
- if: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean),
- description: 'Included when true.'
- }
- }
- });
- /**
- * Used to conditionally skip (exclude) fields or fragments.
- */
- exports.GraphQLIncludeDirective = GraphQLIncludeDirective;
- var GraphQLSkipDirective = new GraphQLDirective({
- name: 'skip',
- description: 'Directs the executor to skip this field or fragment when the `if` ' + 'argument is true.',
- locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT],
- args: {
- if: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean),
- description: 'Skipped when true.'
- }
- }
- });
- /**
- * Constant string used for default reason for a deprecation.
- */
- exports.GraphQLSkipDirective = GraphQLSkipDirective;
- var DEFAULT_DEPRECATION_REASON = 'No longer supported';
- /**
- * Used to declare element of a GraphQL schema as deprecated.
- */
- exports.DEFAULT_DEPRECATION_REASON = DEFAULT_DEPRECATION_REASON;
- var GraphQLDeprecatedDirective = new GraphQLDirective({
- name: 'deprecated',
- description: 'Marks an element of a GraphQL schema as no longer supported.',
- locations: [_directiveLocation.DirectiveLocation.FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ENUM_VALUE],
- args: {
- reason: {
- type: _scalars.GraphQLString,
- description: 'Explains why this element was deprecated, usually also including a ' + 'suggestion for how to access supported similar data. Formatted using ' + 'the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).',
- defaultValue: DEFAULT_DEPRECATION_REASON
- }
- }
- });
- /**
- * The full list of specified directives.
- */
- exports.GraphQLDeprecatedDirective = GraphQLDeprecatedDirective;
- var specifiedDirectives = [GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective];
- exports.specifiedDirectives = specifiedDirectives;
- function isSpecifiedDirective(directive) {
- return isDirective(directive) && specifiedDirectives.some(function (_ref2) {
- var name = _ref2.name;
- return name === directive.name;
- });
- }
- },{"../jsutils/defineToJSON":30,"../jsutils/defineToStringTag":31,"../jsutils/inspect":32,"../jsutils/instanceOf":33,"../jsutils/invariant":34,"../language/directiveLocation":49,"../polyfills/objectEntries":63,"./definition":68,"./scalars":72}],70:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "isSchema", {
- enumerable: true,
- get: function get() {
- return _schema.isSchema;
- }
- });
- Object.defineProperty(exports, "assertSchema", {
- enumerable: true,
- get: function get() {
- return _schema.assertSchema;
- }
- });
- Object.defineProperty(exports, "GraphQLSchema", {
- enumerable: true,
- get: function get() {
- return _schema.GraphQLSchema;
- }
- });
- Object.defineProperty(exports, "isType", {
- enumerable: true,
- get: function get() {
- return _definition.isType;
- }
- });
- Object.defineProperty(exports, "isScalarType", {
- enumerable: true,
- get: function get() {
- return _definition.isScalarType;
- }
- });
- Object.defineProperty(exports, "isObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.isObjectType;
- }
- });
- Object.defineProperty(exports, "isInterfaceType", {
- enumerable: true,
- get: function get() {
- return _definition.isInterfaceType;
- }
- });
- Object.defineProperty(exports, "isUnionType", {
- enumerable: true,
- get: function get() {
- return _definition.isUnionType;
- }
- });
- Object.defineProperty(exports, "isEnumType", {
- enumerable: true,
- get: function get() {
- return _definition.isEnumType;
- }
- });
- Object.defineProperty(exports, "isInputObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.isInputObjectType;
- }
- });
- Object.defineProperty(exports, "isListType", {
- enumerable: true,
- get: function get() {
- return _definition.isListType;
- }
- });
- Object.defineProperty(exports, "isNonNullType", {
- enumerable: true,
- get: function get() {
- return _definition.isNonNullType;
- }
- });
- Object.defineProperty(exports, "isInputType", {
- enumerable: true,
- get: function get() {
- return _definition.isInputType;
- }
- });
- Object.defineProperty(exports, "isOutputType", {
- enumerable: true,
- get: function get() {
- return _definition.isOutputType;
- }
- });
- Object.defineProperty(exports, "isLeafType", {
- enumerable: true,
- get: function get() {
- return _definition.isLeafType;
- }
- });
- Object.defineProperty(exports, "isCompositeType", {
- enumerable: true,
- get: function get() {
- return _definition.isCompositeType;
- }
- });
- Object.defineProperty(exports, "isAbstractType", {
- enumerable: true,
- get: function get() {
- return _definition.isAbstractType;
- }
- });
- Object.defineProperty(exports, "isWrappingType", {
- enumerable: true,
- get: function get() {
- return _definition.isWrappingType;
- }
- });
- Object.defineProperty(exports, "isNullableType", {
- enumerable: true,
- get: function get() {
- return _definition.isNullableType;
- }
- });
- Object.defineProperty(exports, "isNamedType", {
- enumerable: true,
- get: function get() {
- return _definition.isNamedType;
- }
- });
- Object.defineProperty(exports, "isRequiredArgument", {
- enumerable: true,
- get: function get() {
- return _definition.isRequiredArgument;
- }
- });
- Object.defineProperty(exports, "isRequiredInputField", {
- enumerable: true,
- get: function get() {
- return _definition.isRequiredInputField;
- }
- });
- Object.defineProperty(exports, "assertType", {
- enumerable: true,
- get: function get() {
- return _definition.assertType;
- }
- });
- Object.defineProperty(exports, "assertScalarType", {
- enumerable: true,
- get: function get() {
- return _definition.assertScalarType;
- }
- });
- Object.defineProperty(exports, "assertObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.assertObjectType;
- }
- });
- Object.defineProperty(exports, "assertInterfaceType", {
- enumerable: true,
- get: function get() {
- return _definition.assertInterfaceType;
- }
- });
- Object.defineProperty(exports, "assertUnionType", {
- enumerable: true,
- get: function get() {
- return _definition.assertUnionType;
- }
- });
- Object.defineProperty(exports, "assertEnumType", {
- enumerable: true,
- get: function get() {
- return _definition.assertEnumType;
- }
- });
- Object.defineProperty(exports, "assertInputObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.assertInputObjectType;
- }
- });
- Object.defineProperty(exports, "assertListType", {
- enumerable: true,
- get: function get() {
- return _definition.assertListType;
- }
- });
- Object.defineProperty(exports, "assertNonNullType", {
- enumerable: true,
- get: function get() {
- return _definition.assertNonNullType;
- }
- });
- Object.defineProperty(exports, "assertInputType", {
- enumerable: true,
- get: function get() {
- return _definition.assertInputType;
- }
- });
- Object.defineProperty(exports, "assertOutputType", {
- enumerable: true,
- get: function get() {
- return _definition.assertOutputType;
- }
- });
- Object.defineProperty(exports, "assertLeafType", {
- enumerable: true,
- get: function get() {
- return _definition.assertLeafType;
- }
- });
- Object.defineProperty(exports, "assertCompositeType", {
- enumerable: true,
- get: function get() {
- return _definition.assertCompositeType;
- }
- });
- Object.defineProperty(exports, "assertAbstractType", {
- enumerable: true,
- get: function get() {
- return _definition.assertAbstractType;
- }
- });
- Object.defineProperty(exports, "assertWrappingType", {
- enumerable: true,
- get: function get() {
- return _definition.assertWrappingType;
- }
- });
- Object.defineProperty(exports, "assertNullableType", {
- enumerable: true,
- get: function get() {
- return _definition.assertNullableType;
- }
- });
- Object.defineProperty(exports, "assertNamedType", {
- enumerable: true,
- get: function get() {
- return _definition.assertNamedType;
- }
- });
- Object.defineProperty(exports, "getNullableType", {
- enumerable: true,
- get: function get() {
- return _definition.getNullableType;
- }
- });
- Object.defineProperty(exports, "getNamedType", {
- enumerable: true,
- get: function get() {
- return _definition.getNamedType;
- }
- });
- Object.defineProperty(exports, "GraphQLScalarType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLScalarType;
- }
- });
- Object.defineProperty(exports, "GraphQLObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLObjectType;
- }
- });
- Object.defineProperty(exports, "GraphQLInterfaceType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLInterfaceType;
- }
- });
- Object.defineProperty(exports, "GraphQLUnionType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLUnionType;
- }
- });
- Object.defineProperty(exports, "GraphQLEnumType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLEnumType;
- }
- });
- Object.defineProperty(exports, "GraphQLInputObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLInputObjectType;
- }
- });
- Object.defineProperty(exports, "GraphQLList", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLList;
- }
- });
- Object.defineProperty(exports, "GraphQLNonNull", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLNonNull;
- }
- });
- Object.defineProperty(exports, "isDirective", {
- enumerable: true,
- get: function get() {
- return _directives.isDirective;
- }
- });
- Object.defineProperty(exports, "assertDirective", {
- enumerable: true,
- get: function get() {
- return _directives.assertDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLDirective", {
- enumerable: true,
- get: function get() {
- return _directives.GraphQLDirective;
- }
- });
- Object.defineProperty(exports, "isSpecifiedDirective", {
- enumerable: true,
- get: function get() {
- return _directives.isSpecifiedDirective;
- }
- });
- Object.defineProperty(exports, "specifiedDirectives", {
- enumerable: true,
- get: function get() {
- return _directives.specifiedDirectives;
- }
- });
- Object.defineProperty(exports, "GraphQLIncludeDirective", {
- enumerable: true,
- get: function get() {
- return _directives.GraphQLIncludeDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLSkipDirective", {
- enumerable: true,
- get: function get() {
- return _directives.GraphQLSkipDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLDeprecatedDirective", {
- enumerable: true,
- get: function get() {
- return _directives.GraphQLDeprecatedDirective;
- }
- });
- Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", {
- enumerable: true,
- get: function get() {
- return _directives.DEFAULT_DEPRECATION_REASON;
- }
- });
- Object.defineProperty(exports, "isSpecifiedScalarType", {
- enumerable: true,
- get: function get() {
- return _scalars.isSpecifiedScalarType;
- }
- });
- Object.defineProperty(exports, "specifiedScalarTypes", {
- enumerable: true,
- get: function get() {
- return _scalars.specifiedScalarTypes;
- }
- });
- Object.defineProperty(exports, "GraphQLInt", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLInt;
- }
- });
- Object.defineProperty(exports, "GraphQLFloat", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLFloat;
- }
- });
- Object.defineProperty(exports, "GraphQLString", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLString;
- }
- });
- Object.defineProperty(exports, "GraphQLBoolean", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLBoolean;
- }
- });
- Object.defineProperty(exports, "GraphQLID", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLID;
- }
- });
- Object.defineProperty(exports, "isIntrospectionType", {
- enumerable: true,
- get: function get() {
- return _introspection.isIntrospectionType;
- }
- });
- Object.defineProperty(exports, "introspectionTypes", {
- enumerable: true,
- get: function get() {
- return _introspection.introspectionTypes;
- }
- });
- Object.defineProperty(exports, "__Schema", {
- enumerable: true,
- get: function get() {
- return _introspection.__Schema;
- }
- });
- Object.defineProperty(exports, "__Directive", {
- enumerable: true,
- get: function get() {
- return _introspection.__Directive;
- }
- });
- Object.defineProperty(exports, "__DirectiveLocation", {
- enumerable: true,
- get: function get() {
- return _introspection.__DirectiveLocation;
- }
- });
- Object.defineProperty(exports, "__Type", {
- enumerable: true,
- get: function get() {
- return _introspection.__Type;
- }
- });
- Object.defineProperty(exports, "__Field", {
- enumerable: true,
- get: function get() {
- return _introspection.__Field;
- }
- });
- Object.defineProperty(exports, "__InputValue", {
- enumerable: true,
- get: function get() {
- return _introspection.__InputValue;
- }
- });
- Object.defineProperty(exports, "__EnumValue", {
- enumerable: true,
- get: function get() {
- return _introspection.__EnumValue;
- }
- });
- Object.defineProperty(exports, "__TypeKind", {
- enumerable: true,
- get: function get() {
- return _introspection.__TypeKind;
- }
- });
- Object.defineProperty(exports, "TypeKind", {
- enumerable: true,
- get: function get() {
- return _introspection.TypeKind;
- }
- });
- Object.defineProperty(exports, "SchemaMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _introspection.SchemaMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "TypeMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _introspection.TypeMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "TypeNameMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _introspection.TypeNameMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "validateSchema", {
- enumerable: true,
- get: function get() {
- return _validate.validateSchema;
- }
- });
- Object.defineProperty(exports, "assertValidSchema", {
- enumerable: true,
- get: function get() {
- return _validate.assertValidSchema;
- }
- });
- var _schema = require("./schema");
- var _definition = require("./definition");
- var _directives = require("./directives");
- var _scalars = require("./scalars");
- var _introspection = require("./introspection");
- var _validate = require("./validate");
- },{"./definition":68,"./directives":69,"./introspection":71,"./scalars":72,"./schema":73,"./validate":74}],71:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isIntrospectionType = isIntrospectionType;
- exports.introspectionTypes = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.__TypeKind = exports.TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = void 0;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _astFromValue = require("../utilities/astFromValue");
- var _printer = require("../language/printer");
- var _definition = require("./definition");
- var _scalars = require("./scalars");
- var _directiveLocation = require("../language/directiveLocation");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var __Schema = new _definition.GraphQLObjectType({
- name: '__Schema',
- description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + 'exposes all available types and directives on the server, as well as ' + 'the entry points for query, mutation, and subscription operations.',
- fields: function fields() {
- return {
- types: {
- description: 'A list of all types supported by this server.',
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type))),
- resolve: function resolve(schema) {
- return (0, _objectValues.default)(schema.getTypeMap());
- }
- },
- queryType: {
- description: 'The type that query operations will be rooted at.',
- type: (0, _definition.GraphQLNonNull)(__Type),
- resolve: function resolve(schema) {
- return schema.getQueryType();
- }
- },
- mutationType: {
- description: 'If this server supports mutation, the type that ' + 'mutation operations will be rooted at.',
- type: __Type,
- resolve: function resolve(schema) {
- return schema.getMutationType();
- }
- },
- subscriptionType: {
- description: 'If this server support subscription, the type that ' + 'subscription operations will be rooted at.',
- type: __Type,
- resolve: function resolve(schema) {
- return schema.getSubscriptionType();
- }
- },
- directives: {
- description: 'A list of all directives supported by this server.',
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Directive))),
- resolve: function resolve(schema) {
- return schema.getDirectives();
- }
- }
- };
- }
- });
- exports.__Schema = __Schema;
- var __Directive = new _definition.GraphQLObjectType({
- name: '__Directive',
- description: 'A Directive provides a way to describe alternate runtime execution and ' + 'type validation behavior in a GraphQL document.' + "\n\nIn some cases, you need to provide options to alter GraphQL's " + 'execution behavior in ways field arguments will not suffice, such as ' + 'conditionally including or skipping a field. Directives provide this by ' + 'describing additional information to the executor.',
- fields: function fields() {
- return {
- name: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- locations: {
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__DirectiveLocation))),
- resolve: function resolve(obj) {
- return obj.locations;
- }
- },
- args: {
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue))),
- resolve: function resolve(directive) {
- return directive.args || [];
- }
- }
- };
- }
- });
- exports.__Directive = __Directive;
- var __DirectiveLocation = new _definition.GraphQLEnumType({
- name: '__DirectiveLocation',
- description: 'A Directive can be adjacent to many parts of the GraphQL language, a ' + '__DirectiveLocation describes one such possible adjacencies.',
- values: {
- QUERY: {
- value: _directiveLocation.DirectiveLocation.QUERY,
- description: 'Location adjacent to a query operation.'
- },
- MUTATION: {
- value: _directiveLocation.DirectiveLocation.MUTATION,
- description: 'Location adjacent to a mutation operation.'
- },
- SUBSCRIPTION: {
- value: _directiveLocation.DirectiveLocation.SUBSCRIPTION,
- description: 'Location adjacent to a subscription operation.'
- },
- FIELD: {
- value: _directiveLocation.DirectiveLocation.FIELD,
- description: 'Location adjacent to a field.'
- },
- FRAGMENT_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION,
- description: 'Location adjacent to a fragment definition.'
- },
- FRAGMENT_SPREAD: {
- value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD,
- description: 'Location adjacent to a fragment spread.'
- },
- INLINE_FRAGMENT: {
- value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT,
- description: 'Location adjacent to an inline fragment.'
- },
- VARIABLE_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION,
- description: 'Location adjacent to a variable definition.'
- },
- SCHEMA: {
- value: _directiveLocation.DirectiveLocation.SCHEMA,
- description: 'Location adjacent to a schema definition.'
- },
- SCALAR: {
- value: _directiveLocation.DirectiveLocation.SCALAR,
- description: 'Location adjacent to a scalar definition.'
- },
- OBJECT: {
- value: _directiveLocation.DirectiveLocation.OBJECT,
- description: 'Location adjacent to an object type definition.'
- },
- FIELD_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION,
- description: 'Location adjacent to a field definition.'
- },
- ARGUMENT_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION,
- description: 'Location adjacent to an argument definition.'
- },
- INTERFACE: {
- value: _directiveLocation.DirectiveLocation.INTERFACE,
- description: 'Location adjacent to an interface definition.'
- },
- UNION: {
- value: _directiveLocation.DirectiveLocation.UNION,
- description: 'Location adjacent to a union definition.'
- },
- ENUM: {
- value: _directiveLocation.DirectiveLocation.ENUM,
- description: 'Location adjacent to an enum definition.'
- },
- ENUM_VALUE: {
- value: _directiveLocation.DirectiveLocation.ENUM_VALUE,
- description: 'Location adjacent to an enum value definition.'
- },
- INPUT_OBJECT: {
- value: _directiveLocation.DirectiveLocation.INPUT_OBJECT,
- description: 'Location adjacent to an input object type definition.'
- },
- INPUT_FIELD_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION,
- description: 'Location adjacent to an input object field definition.'
- }
- }
- });
- exports.__DirectiveLocation = __DirectiveLocation;
- var __Type = new _definition.GraphQLObjectType({
- name: '__Type',
- description: 'The fundamental unit of any GraphQL Schema is the type. There are ' + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + '\n\nDepending on the kind of a type, certain fields describe ' + 'information about that type. Scalar types provide no information ' + 'beyond a name and description, while Enum types provide their values. ' + 'Object and Interface types provide the fields they describe. Abstract ' + 'types, Union and Interface, provide the Object types possible ' + 'at runtime. List and NonNull types compose other types.',
- fields: function fields() {
- return {
- kind: {
- type: (0, _definition.GraphQLNonNull)(__TypeKind),
- resolve: function resolve(type) {
- if ((0, _definition.isScalarType)(type)) {
- return TypeKind.SCALAR;
- } else if ((0, _definition.isObjectType)(type)) {
- return TypeKind.OBJECT;
- } else if ((0, _definition.isInterfaceType)(type)) {
- return TypeKind.INTERFACE;
- } else if ((0, _definition.isUnionType)(type)) {
- return TypeKind.UNION;
- } else if ((0, _definition.isEnumType)(type)) {
- return TypeKind.ENUM;
- } else if ((0, _definition.isInputObjectType)(type)) {
- return TypeKind.INPUT_OBJECT;
- } else if ((0, _definition.isListType)(type)) {
- return TypeKind.LIST;
- } else if ((0, _definition.isNonNullType)(type)) {
- return TypeKind.NON_NULL;
- } // Not reachable. All possible types have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected type: \"".concat((0, _inspect.default)(type), "\"."));
- }
- },
- name: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- fields: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Field)),
- args: {
- includeDeprecated: {
- type: _scalars.GraphQLBoolean,
- defaultValue: false
- }
- },
- resolve: function resolve(type, _ref) {
- var includeDeprecated = _ref.includeDeprecated;
- if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) {
- var fields = (0, _objectValues.default)(type.getFields());
- if (!includeDeprecated) {
- fields = fields.filter(function (field) {
- return !field.deprecationReason;
- });
- }
- return fields;
- }
- return null;
- }
- },
- interfaces: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type)),
- resolve: function resolve(type) {
- if ((0, _definition.isObjectType)(type)) {
- return type.getInterfaces();
- }
- }
- },
- possibleTypes: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type)),
- resolve: function resolve(type, args, context, _ref2) {
- var schema = _ref2.schema;
- if ((0, _definition.isAbstractType)(type)) {
- return schema.getPossibleTypes(type);
- }
- }
- },
- enumValues: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__EnumValue)),
- args: {
- includeDeprecated: {
- type: _scalars.GraphQLBoolean,
- defaultValue: false
- }
- },
- resolve: function resolve(type, _ref3) {
- var includeDeprecated = _ref3.includeDeprecated;
- if ((0, _definition.isEnumType)(type)) {
- var values = type.getValues();
- if (!includeDeprecated) {
- values = values.filter(function (value) {
- return !value.deprecationReason;
- });
- }
- return values;
- }
- }
- },
- inputFields: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue)),
- resolve: function resolve(type) {
- if ((0, _definition.isInputObjectType)(type)) {
- return (0, _objectValues.default)(type.getFields());
- }
- }
- },
- ofType: {
- type: __Type,
- resolve: function resolve(obj) {
- return obj.ofType;
- }
- }
- };
- }
- });
- exports.__Type = __Type;
- var __Field = new _definition.GraphQLObjectType({
- name: '__Field',
- description: 'Object and Interface types are described by a list of Fields, each of ' + 'which has a name, potentially a list of arguments, and a return type.',
- fields: function fields() {
- return {
- name: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- args: {
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue))),
- resolve: function resolve(field) {
- return field.args || [];
- }
- },
- type: {
- type: (0, _definition.GraphQLNonNull)(__Type),
- resolve: function resolve(obj) {
- return obj.type;
- }
- },
- isDeprecated: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean),
- resolve: function resolve(obj) {
- return obj.isDeprecated;
- }
- },
- deprecationReason: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.deprecationReason;
- }
- }
- };
- }
- });
- exports.__Field = __Field;
- var __InputValue = new _definition.GraphQLObjectType({
- name: '__InputValue',
- description: 'Arguments provided to Fields or Directives and the input fields of an ' + 'InputObject are represented as Input Values which describe their type ' + 'and optionally a default value.',
- fields: function fields() {
- return {
- name: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- type: {
- type: (0, _definition.GraphQLNonNull)(__Type),
- resolve: function resolve(obj) {
- return obj.type;
- }
- },
- defaultValue: {
- type: _scalars.GraphQLString,
- description: 'A GraphQL-formatted string representing the default value for this ' + 'input value.',
- resolve: function resolve(inputVal) {
- var valueAST = (0, _astFromValue.astFromValue)(inputVal.defaultValue, inputVal.type);
- return valueAST ? (0, _printer.print)(valueAST) : null;
- }
- }
- };
- }
- });
- exports.__InputValue = __InputValue;
- var __EnumValue = new _definition.GraphQLObjectType({
- name: '__EnumValue',
- description: 'One possible value for a given Enum. Enum values are unique values, not ' + 'a placeholder for a string or numeric value. However an Enum value is ' + 'returned in a JSON response as a string.',
- fields: function fields() {
- return {
- name: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- isDeprecated: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean),
- resolve: function resolve(obj) {
- return obj.isDeprecated;
- }
- },
- deprecationReason: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.deprecationReason;
- }
- }
- };
- }
- });
- exports.__EnumValue = __EnumValue;
- var TypeKind = {
- SCALAR: 'SCALAR',
- OBJECT: 'OBJECT',
- INTERFACE: 'INTERFACE',
- UNION: 'UNION',
- ENUM: 'ENUM',
- INPUT_OBJECT: 'INPUT_OBJECT',
- LIST: 'LIST',
- NON_NULL: 'NON_NULL'
- };
- exports.TypeKind = TypeKind;
- var __TypeKind = new _definition.GraphQLEnumType({
- name: '__TypeKind',
- description: 'An enum describing what kind of type a given `__Type` is.',
- values: {
- SCALAR: {
- value: TypeKind.SCALAR,
- description: 'Indicates this type is a scalar.'
- },
- OBJECT: {
- value: TypeKind.OBJECT,
- description: 'Indicates this type is an object. ' + '`fields` and `interfaces` are valid fields.'
- },
- INTERFACE: {
- value: TypeKind.INTERFACE,
- description: 'Indicates this type is an interface. ' + '`fields` and `possibleTypes` are valid fields.'
- },
- UNION: {
- value: TypeKind.UNION,
- description: 'Indicates this type is a union. `possibleTypes` is a valid field.'
- },
- ENUM: {
- value: TypeKind.ENUM,
- description: 'Indicates this type is an enum. `enumValues` is a valid field.'
- },
- INPUT_OBJECT: {
- value: TypeKind.INPUT_OBJECT,
- description: 'Indicates this type is an input object. ' + '`inputFields` is a valid field.'
- },
- LIST: {
- value: TypeKind.LIST,
- description: 'Indicates this type is a list. `ofType` is a valid field.'
- },
- NON_NULL: {
- value: TypeKind.NON_NULL,
- description: 'Indicates this type is a non-null. `ofType` is a valid field.'
- }
- }
- });
- /**
- * Note that these are GraphQLField and not GraphQLFieldConfig,
- * so the format for args is different.
- */
- exports.__TypeKind = __TypeKind;
- var SchemaMetaFieldDef = {
- name: '__schema',
- type: (0, _definition.GraphQLNonNull)(__Schema),
- description: 'Access the current type schema of this server.',
- args: [],
- resolve: function resolve(source, args, context, _ref4) {
- var schema = _ref4.schema;
- return schema;
- }
- };
- exports.SchemaMetaFieldDef = SchemaMetaFieldDef;
- var TypeMetaFieldDef = {
- name: '__type',
- type: __Type,
- description: 'Request the type information of a single type.',
- args: [{
- name: 'name',
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString)
- }],
- resolve: function resolve(source, _ref5, context, _ref6) {
- var name = _ref5.name;
- var schema = _ref6.schema;
- return schema.getType(name);
- }
- };
- exports.TypeMetaFieldDef = TypeMetaFieldDef;
- var TypeNameMetaFieldDef = {
- name: '__typename',
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- description: 'The name of the current Object type at runtime.',
- args: [],
- resolve: function resolve(source, args, context, _ref7) {
- var parentType = _ref7.parentType;
- return parentType.name;
- }
- };
- exports.TypeNameMetaFieldDef = TypeNameMetaFieldDef;
- var introspectionTypes = [__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind];
- exports.introspectionTypes = introspectionTypes;
- function isIntrospectionType(type) {
- return (0, _definition.isNamedType)(type) && introspectionTypes.some(function (_ref8) {
- var name = _ref8.name;
- return type.name === name;
- });
- }
- },{"../jsutils/inspect":32,"../language/directiveLocation":49,"../language/printer":56,"../polyfills/objectValues":64,"../utilities/astFromValue":77,"./definition":68,"./scalars":72}],72:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isSpecifiedScalarType = isSpecifiedScalarType;
- exports.specifiedScalarTypes = exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = void 0;
- var _isFinite = _interopRequireDefault(require("../polyfills/isFinite"));
- var _isInteger = _interopRequireDefault(require("../polyfills/isInteger"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _definition = require("./definition");
- var _kinds = require("../language/kinds");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- // As per the GraphQL Spec, Integers are only treated as valid when a valid
- // 32-bit signed integer, providing the broadest support across platforms.
- //
- // n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because
- // they are internally represented as IEEE 754 doubles.
- var MAX_INT = 2147483647;
- var MIN_INT = -2147483648;
- function serializeInt(value) {
- if (typeof value === 'boolean') {
- return value ? 1 : 0;
- }
- var num = value;
- if (typeof value === 'string' && value !== '') {
- num = Number(value);
- }
- if (!(0, _isInteger.default)(num)) {
- throw new TypeError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(value)));
- }
- if (num > MAX_INT || num < MIN_INT) {
- throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat((0, _inspect.default)(value)));
- }
- return num;
- }
- function coerceInt(value) {
- if (!(0, _isInteger.default)(value)) {
- throw new TypeError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(value)));
- }
- if (value > MAX_INT || value < MIN_INT) {
- throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat((0, _inspect.default)(value)));
- }
- return value;
- }
- var GraphQLInt = new _definition.GraphQLScalarType({
- name: 'Int',
- description: 'The `Int` scalar type represents non-fractional signed whole numeric ' + 'values. Int can represent values between -(2^31) and 2^31 - 1. ',
- serialize: serializeInt,
- parseValue: coerceInt,
- parseLiteral: function parseLiteral(ast) {
- if (ast.kind === _kinds.Kind.INT) {
- var num = parseInt(ast.value, 10);
- if (num <= MAX_INT && num >= MIN_INT) {
- return num;
- }
- }
- return undefined;
- }
- });
- exports.GraphQLInt = GraphQLInt;
- function serializeFloat(value) {
- if (typeof value === 'boolean') {
- return value ? 1 : 0;
- }
- var num = value;
- if (typeof value === 'string' && value !== '') {
- num = Number(value);
- }
- if (!(0, _isFinite.default)(num)) {
- throw new TypeError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(value)));
- }
- return num;
- }
- function coerceFloat(value) {
- if (!(0, _isFinite.default)(value)) {
- throw new TypeError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(value)));
- }
- return value;
- }
- var GraphQLFloat = new _definition.GraphQLScalarType({
- name: 'Float',
- description: 'The `Float` scalar type represents signed double-precision fractional ' + 'values as specified by ' + '[IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point). ',
- serialize: serializeFloat,
- parseValue: coerceFloat,
- parseLiteral: function parseLiteral(ast) {
- return ast.kind === _kinds.Kind.FLOAT || ast.kind === _kinds.Kind.INT ? parseFloat(ast.value) : undefined;
- }
- }); // Support serializing objects with custom valueOf() or toJSON() functions -
- // a common way to represent a complex value which can be represented as
- // a string (ex: MongoDB id objects).
- exports.GraphQLFloat = GraphQLFloat;
- function serializeObject(value) {
- if (_typeof(value) === 'object' && value !== null) {
- if (typeof value.valueOf === 'function') {
- var valueOfResult = value.valueOf();
- if (_typeof(valueOfResult) !== 'object') {
- return valueOfResult;
- }
- }
- if (typeof value.toJSON === 'function') {
- // $FlowFixMe(>=0.90.0)
- return value.toJSON();
- }
- }
- return value;
- }
- function serializeString(rawValue) {
- var value = serializeObject(rawValue); // Serialize string, boolean and number values to a string, but do not
- // attempt to coerce object, function, symbol, or other types as strings.
- if (typeof value === 'string') {
- return value;
- }
- if (typeof value === 'boolean') {
- return value ? 'true' : 'false';
- }
- if ((0, _isFinite.default)(value)) {
- return value.toString();
- }
- throw new TypeError("String cannot represent value: ".concat((0, _inspect.default)(rawValue)));
- }
- function coerceString(value) {
- if (typeof value !== 'string') {
- throw new TypeError("String cannot represent a non string value: ".concat((0, _inspect.default)(value)));
- }
- return value;
- }
- var GraphQLString = new _definition.GraphQLScalarType({
- name: 'String',
- description: 'The `String` scalar type represents textual data, represented as UTF-8 ' + 'character sequences. The String type is most often used by GraphQL to ' + 'represent free-form human-readable text.',
- serialize: serializeString,
- parseValue: coerceString,
- parseLiteral: function parseLiteral(ast) {
- return ast.kind === _kinds.Kind.STRING ? ast.value : undefined;
- }
- });
- exports.GraphQLString = GraphQLString;
- function serializeBoolean(value) {
- if (typeof value === 'boolean') {
- return value;
- }
- if ((0, _isFinite.default)(value)) {
- return value !== 0;
- }
- throw new TypeError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(value)));
- }
- function coerceBoolean(value) {
- if (typeof value !== 'boolean') {
- throw new TypeError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(value)));
- }
- return value;
- }
- var GraphQLBoolean = new _definition.GraphQLScalarType({
- name: 'Boolean',
- description: 'The `Boolean` scalar type represents `true` or `false`.',
- serialize: serializeBoolean,
- parseValue: coerceBoolean,
- parseLiteral: function parseLiteral(ast) {
- return ast.kind === _kinds.Kind.BOOLEAN ? ast.value : undefined;
- }
- });
- exports.GraphQLBoolean = GraphQLBoolean;
- function serializeID(rawValue) {
- var value = serializeObject(rawValue);
- if (typeof value === 'string') {
- return value;
- }
- if ((0, _isInteger.default)(value)) {
- return String(value);
- }
- throw new TypeError("ID cannot represent value: ".concat((0, _inspect.default)(rawValue)));
- }
- function coerceID(value) {
- if (typeof value === 'string') {
- return value;
- }
- if ((0, _isInteger.default)(value)) {
- return value.toString();
- }
- throw new TypeError("ID cannot represent value: ".concat((0, _inspect.default)(value)));
- }
- var GraphQLID = new _definition.GraphQLScalarType({
- name: 'ID',
- description: 'The `ID` scalar type represents a unique identifier, often used to ' + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + 'response as a String; however, it is not intended to be human-readable. ' + 'When expected as an input type, any string (such as `"4"`) or integer ' + '(such as `4`) input value will be accepted as an ID.',
- serialize: serializeID,
- parseValue: coerceID,
- parseLiteral: function parseLiteral(ast) {
- return ast.kind === _kinds.Kind.STRING || ast.kind === _kinds.Kind.INT ? ast.value : undefined;
- }
- });
- exports.GraphQLID = GraphQLID;
- var specifiedScalarTypes = [GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID];
- exports.specifiedScalarTypes = specifiedScalarTypes;
- function isSpecifiedScalarType(type) {
- return (0, _definition.isScalarType)(type) && specifiedScalarTypes.some(function (_ref) {
- var name = _ref.name;
- return type.name === name;
- });
- }
- },{"../jsutils/inspect":32,"../language/kinds":51,"../polyfills/isFinite":61,"../polyfills/isInteger":62,"./definition":68}],73:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isSchema = isSchema;
- exports.assertSchema = assertSchema;
- exports.GraphQLSchema = void 0;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _definition = require("./definition");
- var _directives = require("./directives");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _introspection = require("./introspection");
- var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag"));
- var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- // eslint-disable-next-line no-redeclare
- function isSchema(schema) {
- return (0, _instanceOf.default)(schema, GraphQLSchema);
- }
- function assertSchema(schema) {
- !isSchema(schema) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(schema), " to be a GraphQL schema.")) : void 0;
- return schema;
- }
- /**
- * Schema Definition
- *
- * A Schema is created by supplying the root types of each type of operation,
- * query and mutation (optional). A schema definition is then supplied to the
- * validator and executor.
- *
- * Example:
- *
- * const MyAppSchema = new GraphQLSchema({
- * query: MyAppQueryRootType,
- * mutation: MyAppMutationRootType,
- * })
- *
- * Note: When the schema is constructed, by default only the types that are
- * reachable by traversing the root types are included, other types must be
- * explicitly referenced.
- *
- * Example:
- *
- * const characterInterface = new GraphQLInterfaceType({
- * name: 'Character',
- * ...
- * });
- *
- * const humanType = new GraphQLObjectType({
- * name: 'Human',
- * interfaces: [characterInterface],
- * ...
- * });
- *
- * const droidType = new GraphQLObjectType({
- * name: 'Droid',
- * interfaces: [characterInterface],
- * ...
- * });
- *
- * const schema = new GraphQLSchema({
- * query: new GraphQLObjectType({
- * name: 'Query',
- * fields: {
- * hero: { type: characterInterface, ... },
- * }
- * }),
- * ...
- * // Since this schema references only the `Character` interface it's
- * // necessary to explicitly list the types that implement it if
- * // you want them to be included in the final schema.
- * types: [humanType, droidType],
- * })
- *
- * Note: If an array of `directives` are provided to GraphQLSchema, that will be
- * the exact list of directives represented and allowed. If `directives` is not
- * provided then a default set of the specified directives (e.g. @include and
- * @skip) will be used. If you wish to provide *additional* directives to these
- * specified directives, you must explicitly declare them. Example:
- *
- * const MyAppSchema = new GraphQLSchema({
- * ...
- * directives: specifiedDirectives.concat([ myCustomDirective ]),
- * })
- *
- */
- var GraphQLSchema =
- /*#__PURE__*/
- function () {
- // Used as a cache for validateSchema().
- // Referenced by validateSchema().
- function GraphQLSchema(config) {
- // If this schema was built from a source known to be valid, then it may be
- // marked with assumeValid to avoid an additional type system validation.
- if (config && config.assumeValid) {
- this.__validationErrors = [];
- } else {
- this.__validationErrors = undefined; // Otherwise check for common mistakes during construction to produce
- // clear and early error messages.
- !(_typeof(config) === 'object') ? (0, _invariant.default)(0, 'Must provide configuration object.') : void 0;
- !(!config.types || Array.isArray(config.types)) ? (0, _invariant.default)(0, "\"types\" must be Array if provided but got: ".concat((0, _inspect.default)(config.types), ".")) : void 0;
- !(!config.directives || Array.isArray(config.directives)) ? (0, _invariant.default)(0, '"directives" must be Array if provided but got: ' + "".concat((0, _inspect.default)(config.directives), ".")) : void 0;
- !(!config.allowedLegacyNames || Array.isArray(config.allowedLegacyNames)) ? (0, _invariant.default)(0, '"allowedLegacyNames" must be Array if provided but got: ' + "".concat((0, _inspect.default)(config.allowedLegacyNames), ".")) : void 0;
- }
- this.__allowedLegacyNames = config.allowedLegacyNames || [];
- this._queryType = config.query;
- this._mutationType = config.mutation;
- this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default.
- this._directives = config.directives || _directives.specifiedDirectives;
- this.astNode = config.astNode;
- this.extensionASTNodes = config.extensionASTNodes; // Build type map now to detect any errors within this schema.
- var initialTypes = [this.getQueryType(), this.getMutationType(), this.getSubscriptionType(), _introspection.__Schema];
- var types = config.types;
- if (types) {
- initialTypes = initialTypes.concat(types);
- } // Keep track of all types referenced within the schema.
- var typeMap = Object.create(null); // First by deeply visiting all initial types.
- typeMap = initialTypes.reduce(typeMapReducer, typeMap); // Then by deeply visiting all directive types.
- typeMap = this._directives.reduce(typeMapDirectiveReducer, typeMap); // Storing the resulting map for reference by the schema.
- this._typeMap = typeMap;
- this._possibleTypeMap = Object.create(null); // Keep track of all implementations by interface name.
- this._implementations = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectValues.default)(this._typeMap)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var type = _step.value;
- if ((0, _definition.isObjectType)(type)) {
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = type.getInterfaces()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var iface = _step2.value;
- if ((0, _definition.isInterfaceType)(iface)) {
- var impls = this._implementations[iface.name];
- if (impls) {
- impls.push(type);
- } else {
- this._implementations[iface.name] = [type];
- }
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- } else if ((0, _definition.isAbstractType)(type) && !this._implementations[type.name]) {
- this._implementations[type.name] = [];
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- var _proto = GraphQLSchema.prototype;
- _proto.getQueryType = function getQueryType() {
- return this._queryType;
- };
- _proto.getMutationType = function getMutationType() {
- return this._mutationType;
- };
- _proto.getSubscriptionType = function getSubscriptionType() {
- return this._subscriptionType;
- };
- _proto.getTypeMap = function getTypeMap() {
- return this._typeMap;
- };
- _proto.getType = function getType(name) {
- return this.getTypeMap()[name];
- };
- _proto.getPossibleTypes = function getPossibleTypes(abstractType) {
- if ((0, _definition.isUnionType)(abstractType)) {
- return abstractType.getTypes();
- }
- return this._implementations[abstractType.name];
- };
- _proto.isPossibleType = function isPossibleType(abstractType, possibleType) {
- var possibleTypeMap = this._possibleTypeMap;
- if (!possibleTypeMap[abstractType.name]) {
- var possibleTypes = this.getPossibleTypes(abstractType);
- possibleTypeMap[abstractType.name] = possibleTypes.reduce(function (map, type) {
- map[type.name] = true;
- return map;
- }, Object.create(null));
- }
- return Boolean(possibleTypeMap[abstractType.name][possibleType.name]);
- };
- _proto.getDirectives = function getDirectives() {
- return this._directives;
- };
- _proto.getDirective = function getDirective(name) {
- return (0, _find.default)(this.getDirectives(), function (directive) {
- return directive.name === name;
- });
- };
- _proto.toConfig = function toConfig() {
- return {
- types: (0, _objectValues.default)(this.getTypeMap()),
- directives: this.getDirectives().slice(),
- query: this.getQueryType(),
- mutation: this.getMutationType(),
- subscription: this.getSubscriptionType(),
- astNode: this.astNode,
- extensionASTNodes: this.extensionASTNodes || [],
- assumeValid: this.__validationErrors !== undefined,
- allowedLegacyNames: this.__allowedLegacyNames
- };
- };
- return GraphQLSchema;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLSchema = GraphQLSchema;
- (0, _defineToStringTag.default)(GraphQLSchema);
- function typeMapReducer(map, type) {
- if (!type) {
- return map;
- }
- if ((0, _definition.isWrappingType)(type)) {
- return typeMapReducer(map, type.ofType);
- }
- if (map[type.name]) {
- !(map[type.name] === type) ? (0, _invariant.default)(0, 'Schema must contain uniquely named types but contains multiple ' + "types named \"".concat(type.name, "\".")) : void 0;
- return map;
- }
- map[type.name] = type;
- var reducedMap = map;
- if ((0, _definition.isUnionType)(type)) {
- reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap);
- }
- if ((0, _definition.isObjectType)(type)) {
- reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap);
- }
- if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) {
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var field = _step3.value;
- if (field.args) {
- var fieldArgTypes = field.args.map(function (arg) {
- return arg.type;
- });
- reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap);
- }
- reducedMap = typeMapReducer(reducedMap, field.type);
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- if ((0, _definition.isInputObjectType)(type)) {
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var _field = _step4.value;
- reducedMap = typeMapReducer(reducedMap, _field.type);
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- }
- return reducedMap;
- }
- function typeMapDirectiveReducer(map, directive) {
- // Directives are not validated until validateSchema() is called.
- if (!(0, _directives.isDirective)(directive)) {
- return map;
- }
- return directive.args.reduce(function (_map, arg) {
- return typeMapReducer(_map, arg.type);
- }, map);
- }
- },{"../jsutils/defineToStringTag":31,"../jsutils/inspect":32,"../jsutils/instanceOf":33,"../jsutils/invariant":34,"../polyfills/find":59,"../polyfills/objectValues":64,"./definition":68,"./directives":69,"./introspection":71}],74:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.validateSchema = validateSchema;
- exports.assertValidSchema = assertValidSchema;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _flatMap = _interopRequireDefault(require("../polyfills/flatMap"));
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries"));
- var _definition = require("./definition");
- var _directives = require("./directives");
- var _introspection = require("./introspection");
- var _schema = require("./schema");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _GraphQLError = require("../error/GraphQLError");
- var _assertValidName = require("../utilities/assertValidName");
- var _typeComparators = require("../utilities/typeComparators");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Implements the "Type Validation" sub-sections of the specification's
- * "Type System" section.
- *
- * Validation runs synchronously, returning an array of encountered errors, or
- * an empty array if no errors were encountered and the Schema is valid.
- */
- function validateSchema(schema) {
- // First check to ensure the provided value is in fact a GraphQLSchema.
- (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results.
- if (schema.__validationErrors) {
- return schema.__validationErrors;
- } // Validate the schema, producing a list of errors.
- var context = new SchemaValidationContext(schema);
- validateRootTypes(context);
- validateDirectives(context);
- validateTypes(context); // Persist the results of validation before returning to ensure validation
- // does not run multiple times for this schema.
- var errors = context.getErrors();
- schema.__validationErrors = errors;
- return errors;
- }
- /**
- * Utility function which asserts a schema is valid by throwing an error if
- * it is invalid.
- */
- function assertValidSchema(schema) {
- var errors = validateSchema(schema);
- if (errors.length !== 0) {
- throw new Error(errors.map(function (error) {
- return error.message;
- }).join('\n\n'));
- }
- }
- var SchemaValidationContext =
- /*#__PURE__*/
- function () {
- function SchemaValidationContext(schema) {
- this._errors = [];
- this.schema = schema;
- }
- var _proto = SchemaValidationContext.prototype;
- _proto.reportError = function reportError(message, nodes) {
- var _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes;
- this.addError(new _GraphQLError.GraphQLError(message, _nodes));
- };
- _proto.addError = function addError(error) {
- this._errors.push(error);
- };
- _proto.getErrors = function getErrors() {
- return this._errors;
- };
- return SchemaValidationContext;
- }();
- function validateRootTypes(context) {
- var schema = context.schema;
- var queryType = schema.getQueryType();
- if (!queryType) {
- context.reportError("Query root type must be provided.", schema.astNode);
- } else if (!(0, _definition.isObjectType)(queryType)) {
- context.reportError("Query root type must be Object type, it cannot be ".concat((0, _inspect.default)(queryType), "."), getOperationTypeNode(schema, queryType, 'query'));
- }
- var mutationType = schema.getMutationType();
- if (mutationType && !(0, _definition.isObjectType)(mutationType)) {
- context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(mutationType), "."), getOperationTypeNode(schema, mutationType, 'mutation'));
- }
- var subscriptionType = schema.getSubscriptionType();
- if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) {
- context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(subscriptionType), "."), getOperationTypeNode(schema, subscriptionType, 'subscription'));
- }
- }
- function getOperationTypeNode(schema, type, operation) {
- var operationNodes = getAllSubNodes(schema, function (node) {
- return node.operationTypes;
- });
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = operationNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var node = _step.value;
- if (node.operation === operation) {
- return node.type;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return type.astNode;
- }
- function validateDirectives(context) {
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = context.schema.getDirectives()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var directive = _step2.value;
- // Ensure all directives are in fact GraphQL directives.
- if (!(0, _directives.isDirective)(directive)) {
- context.reportError("Expected directive but got: ".concat((0, _inspect.default)(directive), "."), directive && directive.astNode);
- continue;
- } // Ensure they are named correctly.
- validateName(context, directive); // TODO: Ensure proper locations.
- // Ensure the arguments are valid.
- var argNames = Object.create(null);
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = directive.args[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var arg = _step3.value;
- var argName = arg.name; // Ensure they are named correctly.
- validateName(context, arg); // Ensure they are unique per directive.
- if (argNames[argName]) {
- context.reportError("Argument @".concat(directive.name, "(").concat(argName, ":) can only be defined once."), getAllDirectiveArgNodes(directive, argName));
- continue;
- }
- argNames[argName] = true; // Ensure the type is an input type.
- if (!(0, _definition.isInputType)(arg.type)) {
- context.reportError("The type of @".concat(directive.name, "(").concat(argName, ":) must be Input Type ") + "but got: ".concat((0, _inspect.default)(arg.type), "."), getDirectiveArgTypeNode(directive, argName));
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- }
- function validateName(context, node) {
- // If a schema explicitly allows some legacy name which is no longer valid,
- // allow it to be assumed valid.
- if (context.schema.__allowedLegacyNames.indexOf(node.name) !== -1) {
- return;
- } // Ensure names are valid, however introspection types opt out.
- var error = (0, _assertValidName.isValidNameError)(node.name, node.astNode || undefined);
- if (error) {
- context.addError(error);
- }
- }
- function validateTypes(context) {
- var typeMap = context.schema.getTypeMap();
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = (0, _objectValues.default)(typeMap)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var type = _step4.value;
- // Ensure all provided types are in fact GraphQL type.
- if (!(0, _definition.isNamedType)(type)) {
- context.reportError("Expected GraphQL named type but got: ".concat((0, _inspect.default)(type), "."), type && type.astNode);
- continue;
- } // Ensure it is named correctly (excluding introspection types).
- if (!(0, _introspection.isIntrospectionType)(type)) {
- validateName(context, type);
- }
- if ((0, _definition.isObjectType)(type)) {
- // Ensure fields are valid
- validateFields(context, type); // Ensure objects implement the interfaces they claim to.
- validateObjectInterfaces(context, type);
- } else if ((0, _definition.isInterfaceType)(type)) {
- // Ensure fields are valid.
- validateFields(context, type);
- } else if ((0, _definition.isUnionType)(type)) {
- // Ensure Unions include valid member types.
- validateUnionMembers(context, type);
- } else if ((0, _definition.isEnumType)(type)) {
- // Ensure Enums have valid values.
- validateEnumValues(context, type);
- } else if ((0, _definition.isInputObjectType)(type)) {
- // Ensure Input Object fields are valid.
- validateInputFields(context, type);
- }
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- }
- function validateFields(context, type) {
- var fields = (0, _objectValues.default)(type.getFields()); // Objects and Interfaces both must define one or more fields.
- if (fields.length === 0) {
- context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type));
- }
- var _iteratorNormalCompletion5 = true;
- var _didIteratorError5 = false;
- var _iteratorError5 = undefined;
- try {
- for (var _iterator5 = fields[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
- var field = _step5.value;
- // Ensure they are named correctly.
- validateName(context, field); // Ensure the type is an output type
- if (!(0, _definition.isOutputType)(field.type)) {
- context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), getFieldTypeNode(type, field.name));
- } // Ensure the arguments are valid
- var argNames = Object.create(null);
- var _iteratorNormalCompletion6 = true;
- var _didIteratorError6 = false;
- var _iteratorError6 = undefined;
- try {
- for (var _iterator6 = field.args[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
- var arg = _step6.value;
- var argName = arg.name; // Ensure they are named correctly.
- validateName(context, arg); // Ensure they are unique per field.
- if (argNames[argName]) {
- context.reportError("Field argument ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) can only ") + 'be defined once.', getAllFieldArgNodes(type, field.name, argName));
- }
- argNames[argName] = true; // Ensure the type is an input type
- if (!(0, _definition.isInputType)(arg.type)) {
- context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat((0, _inspect.default)(arg.type), "."), getFieldArgTypeNode(type, field.name, argName));
- }
- }
- } catch (err) {
- _didIteratorError6 = true;
- _iteratorError6 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
- _iterator6.return();
- }
- } finally {
- if (_didIteratorError6) {
- throw _iteratorError6;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError5 = true;
- _iteratorError5 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
- _iterator5.return();
- }
- } finally {
- if (_didIteratorError5) {
- throw _iteratorError5;
- }
- }
- }
- }
- function validateObjectInterfaces(context, object) {
- var implementedTypeNames = Object.create(null);
- var _iteratorNormalCompletion7 = true;
- var _didIteratorError7 = false;
- var _iteratorError7 = undefined;
- try {
- for (var _iterator7 = object.getInterfaces()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
- var iface = _step7.value;
- if (!(0, _definition.isInterfaceType)(iface)) {
- context.reportError("Type ".concat((0, _inspect.default)(object), " must only implement Interface types, ") + "it cannot implement ".concat((0, _inspect.default)(iface), "."), getImplementsInterfaceNode(object, iface));
- continue;
- }
- if (implementedTypeNames[iface.name]) {
- context.reportError("Type ".concat(object.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(object, iface));
- continue;
- }
- implementedTypeNames[iface.name] = true;
- validateObjectImplementsInterface(context, object, iface);
- }
- } catch (err) {
- _didIteratorError7 = true;
- _iteratorError7 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
- _iterator7.return();
- }
- } finally {
- if (_didIteratorError7) {
- throw _iteratorError7;
- }
- }
- }
- }
- function validateObjectImplementsInterface(context, object, iface) {
- var objectFieldMap = object.getFields();
- var ifaceFieldMap = iface.getFields(); // Assert each interface field is implemented.
- var _iteratorNormalCompletion8 = true;
- var _didIteratorError8 = false;
- var _iteratorError8 = undefined;
- try {
- for (var _iterator8 = (0, _objectEntries.default)(ifaceFieldMap)[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
- var _ref2 = _step8.value;
- var fieldName = _ref2[0];
- var ifaceField = _ref2[1];
- var objectField = objectFieldMap[fieldName]; // Assert interface field exists on object.
- if (!objectField) {
- context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ") + "".concat(object.name, " does not provide it."), [getFieldNode(iface, fieldName)].concat(getAllNodes(object)));
- continue;
- } // Assert interface field type is satisfied by object field type, by being
- // a valid subtype. (covariant)
- if (!(0, _typeComparators.isTypeSubTypeOf)(context.schema, objectField.type, ifaceField.type)) {
- context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat((0, _inspect.default)(ifaceField.type), " but ").concat(object.name, ".").concat(fieldName, " ") + "is type ".concat((0, _inspect.default)(objectField.type), "."), [getFieldTypeNode(iface, fieldName), getFieldTypeNode(object, fieldName)]);
- } // Assert each interface field arg is implemented.
- var _iteratorNormalCompletion9 = true;
- var _didIteratorError9 = false;
- var _iteratorError9 = undefined;
- try {
- var _loop = function _loop() {
- var ifaceArg = _step9.value;
- var argName = ifaceArg.name;
- var objectArg = (0, _find.default)(objectField.args, function (arg) {
- return arg.name === argName;
- }); // Assert interface field arg exists on object field.
- if (!objectArg) {
- context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expected but ".concat(object.name, ".").concat(fieldName, " does not provide it."), [getFieldArgNode(iface, fieldName, argName), getFieldNode(object, fieldName)]);
- return "continue";
- } // Assert interface field arg type matches object field arg type.
- // (invariant)
- // TODO: change to contravariant?
- if (!(0, _typeComparators.isEqualType)(ifaceArg.type, objectArg.type)) {
- context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat((0, _inspect.default)(ifaceArg.type), " but ") + "".concat(object.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat((0, _inspect.default)(objectArg.type), "."), [getFieldArgTypeNode(iface, fieldName, argName), getFieldArgTypeNode(object, fieldName, argName)]);
- } // TODO: validate default values?
- };
- for (var _iterator9 = ifaceField.args[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
- var _ret = _loop();
- if (_ret === "continue") continue;
- } // Assert additional arguments must not be required.
- } catch (err) {
- _didIteratorError9 = true;
- _iteratorError9 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
- _iterator9.return();
- }
- } finally {
- if (_didIteratorError9) {
- throw _iteratorError9;
- }
- }
- }
- var _iteratorNormalCompletion10 = true;
- var _didIteratorError10 = false;
- var _iteratorError10 = undefined;
- try {
- var _loop2 = function _loop2() {
- var objectArg = _step10.value;
- var argName = objectArg.name;
- var ifaceArg = (0, _find.default)(ifaceField.args, function (arg) {
- return arg.name === argName;
- });
- if (!ifaceArg && (0, _definition.isRequiredArgument)(objectArg)) {
- context.reportError("Object field ".concat(object.name, ".").concat(fieldName, " includes required ") + "argument ".concat(argName, " that is missing from the Interface field ") + "".concat(iface.name, ".").concat(fieldName, "."), [getFieldArgNode(object, fieldName, argName), getFieldNode(iface, fieldName)]);
- }
- };
- for (var _iterator10 = objectField.args[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
- _loop2();
- }
- } catch (err) {
- _didIteratorError10 = true;
- _iteratorError10 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
- _iterator10.return();
- }
- } finally {
- if (_didIteratorError10) {
- throw _iteratorError10;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError8 = true;
- _iteratorError8 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
- _iterator8.return();
- }
- } finally {
- if (_didIteratorError8) {
- throw _iteratorError8;
- }
- }
- }
- }
- function validateUnionMembers(context, union) {
- var memberTypes = union.getTypes();
- if (memberTypes.length === 0) {
- context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union));
- }
- var includedTypeNames = Object.create(null);
- var _iteratorNormalCompletion11 = true;
- var _didIteratorError11 = false;
- var _iteratorError11 = undefined;
- try {
- for (var _iterator11 = memberTypes[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
- var memberType = _step11.value;
- if (includedTypeNames[memberType.name]) {
- context.reportError("Union type ".concat(union.name, " can only include type ") + "".concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name));
- continue;
- }
- includedTypeNames[memberType.name] = true;
- if (!(0, _definition.isObjectType)(memberType)) {
- context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat((0, _inspect.default)(memberType), "."), getUnionMemberTypeNodes(union, String(memberType)));
- }
- }
- } catch (err) {
- _didIteratorError11 = true;
- _iteratorError11 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion11 && _iterator11.return != null) {
- _iterator11.return();
- }
- } finally {
- if (_didIteratorError11) {
- throw _iteratorError11;
- }
- }
- }
- }
- function validateEnumValues(context, enumType) {
- var enumValues = enumType.getValues();
- if (enumValues.length === 0) {
- context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType));
- }
- var _iteratorNormalCompletion12 = true;
- var _didIteratorError12 = false;
- var _iteratorError12 = undefined;
- try {
- for (var _iterator12 = enumValues[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
- var enumValue = _step12.value;
- var valueName = enumValue.name; // Ensure valid name.
- validateName(context, enumValue);
- if (valueName === 'true' || valueName === 'false' || valueName === 'null') {
- context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode);
- }
- }
- } catch (err) {
- _didIteratorError12 = true;
- _iteratorError12 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion12 && _iterator12.return != null) {
- _iterator12.return();
- }
- } finally {
- if (_didIteratorError12) {
- throw _iteratorError12;
- }
- }
- }
- }
- function validateInputFields(context, inputObj) {
- var fields = (0, _objectValues.default)(inputObj.getFields());
- if (fields.length === 0) {
- context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj));
- } // Ensure the arguments are valid
- var _iteratorNormalCompletion13 = true;
- var _didIteratorError13 = false;
- var _iteratorError13 = undefined;
- try {
- for (var _iterator13 = fields[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
- var field = _step13.value;
- // Ensure they are named correctly.
- validateName(context, field); // Ensure the type is an input type
- if (!(0, _definition.isInputType)(field.type)) {
- context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), field.astNode && field.astNode.type);
- }
- }
- } catch (err) {
- _didIteratorError13 = true;
- _iteratorError13 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion13 && _iterator13.return != null) {
- _iterator13.return();
- }
- } finally {
- if (_didIteratorError13) {
- throw _iteratorError13;
- }
- }
- }
- }
- function getAllNodes(object) {
- var astNode = object.astNode,
- extensionASTNodes = object.extensionASTNodes;
- return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes || [];
- }
- function getAllSubNodes(object, getter) {
- return (0, _flatMap.default)(getAllNodes(object), function (item) {
- return getter(item) || [];
- });
- }
- function getImplementsInterfaceNode(type, iface) {
- return getAllImplementsInterfaceNodes(type, iface)[0];
- }
- function getAllImplementsInterfaceNodes(type, iface) {
- return getAllSubNodes(type, function (typeNode) {
- return typeNode.interfaces;
- }).filter(function (ifaceNode) {
- return ifaceNode.name.value === iface.name;
- });
- }
- function getFieldNode(type, fieldName) {
- return (0, _find.default)(getAllSubNodes(type, function (typeNode) {
- return typeNode.fields;
- }), function (fieldNode) {
- return fieldNode.name.value === fieldName;
- });
- }
- function getFieldTypeNode(type, fieldName) {
- var fieldNode = getFieldNode(type, fieldName);
- return fieldNode && fieldNode.type;
- }
- function getFieldArgNode(type, fieldName, argName) {
- return getAllFieldArgNodes(type, fieldName, argName)[0];
- }
- function getAllFieldArgNodes(type, fieldName, argName) {
- var argNodes = [];
- var fieldNode = getFieldNode(type, fieldName);
- if (fieldNode && fieldNode.arguments) {
- var _iteratorNormalCompletion14 = true;
- var _didIteratorError14 = false;
- var _iteratorError14 = undefined;
- try {
- for (var _iterator14 = fieldNode.arguments[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {
- var node = _step14.value;
- if (node.name.value === argName) {
- argNodes.push(node);
- }
- }
- } catch (err) {
- _didIteratorError14 = true;
- _iteratorError14 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion14 && _iterator14.return != null) {
- _iterator14.return();
- }
- } finally {
- if (_didIteratorError14) {
- throw _iteratorError14;
- }
- }
- }
- }
- return argNodes;
- }
- function getFieldArgTypeNode(type, fieldName, argName) {
- var fieldArgNode = getFieldArgNode(type, fieldName, argName);
- return fieldArgNode && fieldArgNode.type;
- }
- function getAllDirectiveArgNodes(directive, argName) {
- return getAllSubNodes(directive, function (directiveNode) {
- return directiveNode.arguments;
- }).filter(function (argNode) {
- return argNode.name.value === argName;
- });
- }
- function getDirectiveArgTypeNode(directive, argName) {
- var argNode = getAllDirectiveArgNodes(directive, argName)[0];
- return argNode && argNode.type;
- }
- function getUnionMemberTypeNodes(union, typeName) {
- return getAllSubNodes(union, function (unionNode) {
- return unionNode.types;
- }).filter(function (typeNode) {
- return typeNode.name.value === typeName;
- });
- }
- },{"../error/GraphQLError":19,"../jsutils/inspect":32,"../polyfills/find":59,"../polyfills/flatMap":60,"../polyfills/objectEntries":63,"../polyfills/objectValues":64,"../utilities/assertValidName":76,"../utilities/typeComparators":96,"./definition":68,"./directives":69,"./introspection":71,"./schema":73}],75:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.TypeInfo = void 0;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _kinds = require("../language/kinds");
- var _definition = require("../type/definition");
- var _introspection = require("../type/introspection");
- var _typeFromAST = require("./typeFromAST");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * TypeInfo is a utility class which, given a GraphQL schema, can keep track
- * of the current field and type definitions at any point in a GraphQL document
- * AST during a recursive descent by calling `enter(node)` and `leave(node)`.
- */
- var TypeInfo =
- /*#__PURE__*/
- function () {
- function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order
- // to support non-spec-compliant codebases. You should never need to use it.
- // It may disappear in the future.
- getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals
- // beginning somewhere other than documents.
- initialType) {
- this._schema = schema;
- this._typeStack = [];
- this._parentTypeStack = [];
- this._inputTypeStack = [];
- this._fieldDefStack = [];
- this._defaultValueStack = [];
- this._directive = null;
- this._argument = null;
- this._enumValue = null;
- this._getFieldDef = getFieldDefFn || getFieldDef;
- if (initialType) {
- if ((0, _definition.isInputType)(initialType)) {
- this._inputTypeStack.push(initialType);
- }
- if ((0, _definition.isCompositeType)(initialType)) {
- this._parentTypeStack.push(initialType);
- }
- if ((0, _definition.isOutputType)(initialType)) {
- this._typeStack.push(initialType);
- }
- }
- }
- var _proto = TypeInfo.prototype;
- _proto.getType = function getType() {
- if (this._typeStack.length > 0) {
- return this._typeStack[this._typeStack.length - 1];
- }
- };
- _proto.getParentType = function getParentType() {
- if (this._parentTypeStack.length > 0) {
- return this._parentTypeStack[this._parentTypeStack.length - 1];
- }
- };
- _proto.getInputType = function getInputType() {
- if (this._inputTypeStack.length > 0) {
- return this._inputTypeStack[this._inputTypeStack.length - 1];
- }
- };
- _proto.getParentInputType = function getParentInputType() {
- if (this._inputTypeStack.length > 1) {
- return this._inputTypeStack[this._inputTypeStack.length - 2];
- }
- };
- _proto.getFieldDef = function getFieldDef() {
- if (this._fieldDefStack.length > 0) {
- return this._fieldDefStack[this._fieldDefStack.length - 1];
- }
- };
- _proto.getDefaultValue = function getDefaultValue() {
- if (this._defaultValueStack.length > 0) {
- return this._defaultValueStack[this._defaultValueStack.length - 1];
- }
- };
- _proto.getDirective = function getDirective() {
- return this._directive;
- };
- _proto.getArgument = function getArgument() {
- return this._argument;
- };
- _proto.getEnumValue = function getEnumValue() {
- return this._enumValue;
- };
- _proto.enter = function enter(node) {
- var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop
- // any assumptions of a valid schema to ensure runtime types are properly
- // checked before continuing since TypeInfo is used as part of validation
- // which occurs before guarantees of schema and document validity.
- switch (node.kind) {
- case _kinds.Kind.SELECTION_SET:
- {
- var namedType = (0, _definition.getNamedType)(this.getType());
- this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined);
- break;
- }
- case _kinds.Kind.FIELD:
- {
- var parentType = this.getParentType();
- var fieldDef;
- var fieldType;
- if (parentType) {
- fieldDef = this._getFieldDef(schema, parentType, node);
- if (fieldDef) {
- fieldType = fieldDef.type;
- }
- }
- this._fieldDefStack.push(fieldDef);
- this._typeStack.push((0, _definition.isOutputType)(fieldType) ? fieldType : undefined);
- break;
- }
- case _kinds.Kind.DIRECTIVE:
- this._directive = schema.getDirective(node.name.value);
- break;
- case _kinds.Kind.OPERATION_DEFINITION:
- {
- var type;
- if (node.operation === 'query') {
- type = schema.getQueryType();
- } else if (node.operation === 'mutation') {
- type = schema.getMutationType();
- } else if (node.operation === 'subscription') {
- type = schema.getSubscriptionType();
- }
- this._typeStack.push((0, _definition.isObjectType)(type) ? type : undefined);
- break;
- }
- case _kinds.Kind.INLINE_FRAGMENT:
- case _kinds.Kind.FRAGMENT_DEFINITION:
- {
- var typeConditionAST = node.typeCondition;
- var outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : (0, _definition.getNamedType)(this.getType());
- this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined);
- break;
- }
- case _kinds.Kind.VARIABLE_DEFINITION:
- {
- var inputType = (0, _typeFromAST.typeFromAST)(schema, node.type);
- this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined);
- break;
- }
- case _kinds.Kind.ARGUMENT:
- {
- var argDef;
- var argType;
- var fieldOrDirective = this.getDirective() || this.getFieldDef();
- if (fieldOrDirective) {
- argDef = (0, _find.default)(fieldOrDirective.args, function (arg) {
- return arg.name === node.name.value;
- });
- if (argDef) {
- argType = argDef.type;
- }
- }
- this._argument = argDef;
- this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);
- this._inputTypeStack.push((0, _definition.isInputType)(argType) ? argType : undefined);
- break;
- }
- case _kinds.Kind.LIST:
- {
- var listType = (0, _definition.getNullableType)(this.getInputType());
- var itemType = (0, _definition.isListType)(listType) ? listType.ofType : listType; // List positions never have a default value.
- this._defaultValueStack.push(undefined);
- this._inputTypeStack.push((0, _definition.isInputType)(itemType) ? itemType : undefined);
- break;
- }
- case _kinds.Kind.OBJECT_FIELD:
- {
- var objectType = (0, _definition.getNamedType)(this.getInputType());
- var inputFieldType;
- var inputField;
- if ((0, _definition.isInputObjectType)(objectType)) {
- inputField = objectType.getFields()[node.name.value];
- if (inputField) {
- inputFieldType = inputField.type;
- }
- }
- this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined);
- this._inputTypeStack.push((0, _definition.isInputType)(inputFieldType) ? inputFieldType : undefined);
- break;
- }
- case _kinds.Kind.ENUM:
- {
- var enumType = (0, _definition.getNamedType)(this.getInputType());
- var enumValue;
- if ((0, _definition.isEnumType)(enumType)) {
- enumValue = enumType.getValue(node.value);
- }
- this._enumValue = enumValue;
- break;
- }
- }
- };
- _proto.leave = function leave(node) {
- switch (node.kind) {
- case _kinds.Kind.SELECTION_SET:
- this._parentTypeStack.pop();
- break;
- case _kinds.Kind.FIELD:
- this._fieldDefStack.pop();
- this._typeStack.pop();
- break;
- case _kinds.Kind.DIRECTIVE:
- this._directive = null;
- break;
- case _kinds.Kind.OPERATION_DEFINITION:
- case _kinds.Kind.INLINE_FRAGMENT:
- case _kinds.Kind.FRAGMENT_DEFINITION:
- this._typeStack.pop();
- break;
- case _kinds.Kind.VARIABLE_DEFINITION:
- this._inputTypeStack.pop();
- break;
- case _kinds.Kind.ARGUMENT:
- this._argument = null;
- this._defaultValueStack.pop();
- this._inputTypeStack.pop();
- break;
- case _kinds.Kind.LIST:
- case _kinds.Kind.OBJECT_FIELD:
- this._defaultValueStack.pop();
- this._inputTypeStack.pop();
- break;
- case _kinds.Kind.ENUM:
- this._enumValue = null;
- break;
- }
- };
- return TypeInfo;
- }();
- /**
- * Not exactly the same as the executor's definition of getFieldDef, in this
- * statically evaluated environment we do not always have an Object type,
- * and need to handle Interface and Union types.
- */
- exports.TypeInfo = TypeInfo;
- function getFieldDef(schema, parentType, fieldNode) {
- var name = fieldNode.name.value;
- if (name === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
- return _introspection.SchemaMetaFieldDef;
- }
- if (name === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
- return _introspection.TypeMetaFieldDef;
- }
- if (name === _introspection.TypeNameMetaFieldDef.name && (0, _definition.isCompositeType)(parentType)) {
- return _introspection.TypeNameMetaFieldDef;
- }
- if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) {
- return parentType.getFields()[name];
- }
- }
- },{"../language/kinds":51,"../polyfills/find":59,"../type/definition":68,"../type/introspection":71,"./typeFromAST":97}],76:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.assertValidName = assertValidName;
- exports.isValidNameError = isValidNameError;
- var _GraphQLError = require("../error/GraphQLError");
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
- /**
- * Upholds the spec rules about naming.
- */
- function assertValidName(name) {
- var error = isValidNameError(name);
- if (error) {
- throw error;
- }
- return name;
- }
- /**
- * Returns an Error if a name is invalid.
- */
- function isValidNameError(name, node) {
- !(typeof name === 'string') ? (0, _invariant.default)(0, 'Expected string') : void 0;
- if (name.length > 1 && name[0] === '_' && name[1] === '_') {
- return new _GraphQLError.GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by ") + 'GraphQL introspection.', node);
- }
- if (!NAME_RX.test(name)) {
- return new _GraphQLError.GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."), node);
- }
- }
- },{"../error/GraphQLError":19,"../jsutils/invariant":34}],77:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.astFromValue = astFromValue;
- var _iterall = require("iterall");
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _isNullish = _interopRequireDefault(require("../jsutils/isNullish"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _kinds = require("../language/kinds");
- var _definition = require("../type/definition");
- var _scalars = require("../type/scalars");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- /**
- * Produces a GraphQL Value AST given a JavaScript value.
- *
- * A GraphQL type must be provided, which will be used to interpret different
- * JavaScript values.
- *
- * | JSON Value | GraphQL Value |
- * | ------------- | -------------------- |
- * | Object | Input Object |
- * | Array | List |
- * | Boolean | Boolean |
- * | String | String / Enum Value |
- * | Number | Int / Float |
- * | Mixed | Enum Value |
- * | null | NullValue |
- *
- */
- function astFromValue(value, type) {
- if ((0, _definition.isNonNullType)(type)) {
- var astValue = astFromValue(value, type.ofType);
- if (astValue && astValue.kind === _kinds.Kind.NULL) {
- return null;
- }
- return astValue;
- } // only explicit null, not undefined, NaN
- if (value === null) {
- return {
- kind: _kinds.Kind.NULL
- };
- } // undefined, NaN
- if ((0, _isInvalid.default)(value)) {
- return null;
- } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
- // the value is not an array, convert the value using the list's item type.
- if ((0, _definition.isListType)(type)) {
- var itemType = type.ofType;
- if ((0, _iterall.isCollection)(value)) {
- var valuesNodes = [];
- (0, _iterall.forEach)(value, function (item) {
- var itemNode = astFromValue(item, itemType);
- if (itemNode) {
- valuesNodes.push(itemNode);
- }
- });
- return {
- kind: _kinds.Kind.LIST,
- values: valuesNodes
- };
- }
- return astFromValue(value, itemType);
- } // Populate the fields of the input object by creating ASTs from each value
- // in the JavaScript object according to the fields in the input type.
- if ((0, _definition.isInputObjectType)(type)) {
- if (value === null || _typeof(value) !== 'object') {
- return null;
- }
- var fields = (0, _objectValues.default)(type.getFields());
- var fieldNodes = [];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var field = _step.value;
- var fieldValue = astFromValue(value[field.name], field.type);
- if (fieldValue) {
- fieldNodes.push({
- kind: _kinds.Kind.OBJECT_FIELD,
- name: {
- kind: _kinds.Kind.NAME,
- value: field.name
- },
- value: fieldValue
- });
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return {
- kind: _kinds.Kind.OBJECT,
- fields: fieldNodes
- };
- }
- if ((0, _definition.isLeafType)(type)) {
- // Since value is an internally represented value, it must be serialized
- // to an externally represented value before converting into an AST.
- var serialized = type.serialize(value);
- if ((0, _isNullish.default)(serialized)) {
- return null;
- } // Others serialize based on their corresponding JavaScript scalar types.
- if (typeof serialized === 'boolean') {
- return {
- kind: _kinds.Kind.BOOLEAN,
- value: serialized
- };
- } // JavaScript numbers can be Int or Float values.
- if (typeof serialized === 'number') {
- var stringNum = String(serialized);
- return integerStringRegExp.test(stringNum) ? {
- kind: _kinds.Kind.INT,
- value: stringNum
- } : {
- kind: _kinds.Kind.FLOAT,
- value: stringNum
- };
- }
- if (typeof serialized === 'string') {
- // Enum types use Enum literals.
- if ((0, _definition.isEnumType)(type)) {
- return {
- kind: _kinds.Kind.ENUM,
- value: serialized
- };
- } // ID types can use Int literals.
- if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) {
- return {
- kind: _kinds.Kind.INT,
- value: serialized
- };
- }
- return {
- kind: _kinds.Kind.STRING,
- value: serialized
- };
- }
- throw new TypeError("Cannot convert value to AST: ".concat((0, _inspect.default)(serialized)));
- } // Not reachable. All possible input types have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected input type: \"".concat((0, _inspect.default)(type), "\"."));
- }
- /**
- * IntValue:
- * - NegativeSign? 0
- * - NegativeSign? NonZeroDigit ( Digit+ )?
- */
- var integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;
- },{"../jsutils/inspect":32,"../jsutils/isInvalid":35,"../jsutils/isNullish":36,"../language/kinds":51,"../polyfills/objectValues":64,"../type/definition":68,"../type/scalars":72,"iterall":137}],78:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.buildASTSchema = buildASTSchema;
- exports.getDescription = getDescription;
- exports.buildSchema = buildSchema;
- exports.ASTDefinitionBuilder = void 0;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _valueFromAST = require("./valueFromAST");
- var _validate = require("../validation/validate");
- var _blockString = require("../language/blockString");
- var _lexer = require("../language/lexer");
- var _parser = require("../language/parser");
- var _values = require("../execution/values");
- var _kinds = require("../language/kinds");
- var _predicates = require("../language/predicates");
- var _definition = require("../type/definition");
- var _directives = require("../type/directives");
- var _introspection = require("../type/introspection");
- var _scalars = require("../type/scalars");
- var _schema = require("../type/schema");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * This takes the ast of a schema document produced by the parse function in
- * src/language/parser.js.
- *
- * If no schema definition is provided, then it will look for types named Query
- * and Mutation.
- *
- * Given that AST it constructs a GraphQLSchema. The resulting schema
- * has no resolve methods, so execution will use default resolvers.
- *
- * Accepts options as a second argument:
- *
- * - commentDescriptions:
- * Provide true to use preceding comments as the description.
- *
- */
- function buildASTSchema(documentAST, options) {
- !(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0;
- if (!options || !(options.assumeValid || options.assumeValidSDL)) {
- (0, _validate.assertValidSDL)(documentAST);
- }
- var schemaDef;
- var typeDefs = [];
- var directiveDefs = [];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = documentAST.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var def = _step.value;
- if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) {
- schemaDef = def;
- } else if ((0, _predicates.isTypeDefinitionNode)(def)) {
- typeDefs.push(def);
- } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- directiveDefs.push(def);
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var astBuilder = new ASTDefinitionBuilder(options, function (typeName) {
- var type = typeMap[typeName];
- !type ? (0, _invariant.default)(0, "Type \"".concat(typeName, "\" not found in document.")) : void 0;
- return type;
- });
- var typeMap = keyByNameNode(typeDefs, function (node) {
- return astBuilder.buildType(node);
- });
- var operationTypes = schemaDef ? getOperationTypes(schemaDef) : {
- query: 'Query',
- mutation: 'Mutation',
- subscription: 'Subscription'
- };
- var directives = directiveDefs.map(function (def) {
- return astBuilder.buildDirective(def);
- }); // If specified directives were not explicitly declared, add them.
- if (!directives.some(function (directive) {
- return directive.name === 'skip';
- })) {
- directives.push(_directives.GraphQLSkipDirective);
- }
- if (!directives.some(function (directive) {
- return directive.name === 'include';
- })) {
- directives.push(_directives.GraphQLIncludeDirective);
- }
- if (!directives.some(function (directive) {
- return directive.name === 'deprecated';
- })) {
- directives.push(_directives.GraphQLDeprecatedDirective);
- }
- return new _schema.GraphQLSchema({
- // Note: While this could make early assertions to get the correctly
- // typed values below, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- query: operationTypes.query ? typeMap[operationTypes.query] : null,
- mutation: operationTypes.mutation ? typeMap[operationTypes.mutation] : null,
- subscription: operationTypes.subscription ? typeMap[operationTypes.subscription] : null,
- types: (0, _objectValues.default)(typeMap),
- directives: directives,
- astNode: schemaDef,
- assumeValid: options && options.assumeValid,
- allowedLegacyNames: options && options.allowedLegacyNames
- });
- function getOperationTypes(schema) {
- var opTypes = {};
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = schema.operationTypes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var operationType = _step2.value;
- opTypes[operationType.operation] = operationType.type.name.value;
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return opTypes;
- }
- }
- var stdTypeMap = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) {
- return type.name;
- });
- var ASTDefinitionBuilder =
- /*#__PURE__*/
- function () {
- function ASTDefinitionBuilder(options, resolveType) {
- this._options = options;
- this._resolveType = resolveType;
- }
- var _proto = ASTDefinitionBuilder.prototype;
- _proto.getNamedType = function getNamedType(node) {
- var name = node.name.value;
- return stdTypeMap[name] || this._resolveType(name);
- };
- _proto.getWrappedType = function getWrappedType(node) {
- if (node.kind === _kinds.Kind.LIST_TYPE) {
- return new _definition.GraphQLList(this.getWrappedType(node.type));
- }
- if (node.kind === _kinds.Kind.NON_NULL_TYPE) {
- return new _definition.GraphQLNonNull(this.getWrappedType(node.type));
- }
- return this.getNamedType(node);
- };
- _proto.buildDirective = function buildDirective(directive) {
- var _this = this;
- var locations = directive.locations.map(function (_ref) {
- var value = _ref.value;
- return value;
- });
- return new _directives.GraphQLDirective({
- name: directive.name.value,
- description: getDescription(directive, this._options),
- locations: locations,
- args: keyByNameNode(directive.arguments || [], function (arg) {
- return _this.buildArg(arg);
- }),
- astNode: directive
- });
- };
- _proto.buildField = function buildField(field) {
- var _this2 = this;
- return {
- // Note: While this could make assertions to get the correctly typed
- // value, that would throw immediately while type system validation
- // with validateSchema() will produce more actionable results.
- type: this.getWrappedType(field.type),
- description: getDescription(field, this._options),
- args: keyByNameNode(field.arguments || [], function (arg) {
- return _this2.buildArg(arg);
- }),
- deprecationReason: getDeprecationReason(field),
- astNode: field
- };
- };
- _proto.buildArg = function buildArg(value) {
- // Note: While this could make assertions to get the correctly typed
- // value, that would throw immediately while type system validation
- // with validateSchema() will produce more actionable results.
- var type = this.getWrappedType(value.type);
- return {
- type: type,
- description: getDescription(value, this._options),
- defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type),
- astNode: value
- };
- };
- _proto.buildInputField = function buildInputField(value) {
- // Note: While this could make assertions to get the correctly typed
- // value, that would throw immediately while type system validation
- // with validateSchema() will produce more actionable results.
- var type = this.getWrappedType(value.type);
- return {
- type: type,
- description: getDescription(value, this._options),
- defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type),
- astNode: value
- };
- };
- _proto.buildEnumValue = function buildEnumValue(value) {
- return {
- description: getDescription(value, this._options),
- deprecationReason: getDeprecationReason(value),
- astNode: value
- };
- };
- _proto.buildType = function buildType(astNode) {
- var name = astNode.name.value;
- if (stdTypeMap[name]) {
- return stdTypeMap[name];
- }
- switch (astNode.kind) {
- case _kinds.Kind.OBJECT_TYPE_DEFINITION:
- return this._makeTypeDef(astNode);
- case _kinds.Kind.INTERFACE_TYPE_DEFINITION:
- return this._makeInterfaceDef(astNode);
- case _kinds.Kind.ENUM_TYPE_DEFINITION:
- return this._makeEnumDef(astNode);
- case _kinds.Kind.UNION_TYPE_DEFINITION:
- return this._makeUnionDef(astNode);
- case _kinds.Kind.SCALAR_TYPE_DEFINITION:
- return this._makeScalarDef(astNode);
- case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION:
- return this._makeInputObjectDef(astNode);
- } // Not reachable. All possible type definition nodes have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected type definition node: \"".concat((0, _inspect.default)(astNode), "\"."));
- };
- _proto._makeTypeDef = function _makeTypeDef(astNode) {
- var _this3 = this;
- var interfaceNodes = astNode.interfaces;
- var fieldNodes = astNode.fields; // Note: While this could make assertions to get the correctly typed
- // values below, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- var interfaces = interfaceNodes && interfaceNodes.length > 0 ? function () {
- return interfaceNodes.map(function (ref) {
- return _this3.getNamedType(ref);
- });
- } : [];
- var fields = fieldNodes && fieldNodes.length > 0 ? function () {
- return keyByNameNode(fieldNodes, function (field) {
- return _this3.buildField(field);
- });
- } : Object.create(null);
- return new _definition.GraphQLObjectType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- interfaces: interfaces,
- fields: fields,
- astNode: astNode
- });
- };
- _proto._makeInterfaceDef = function _makeInterfaceDef(astNode) {
- var _this4 = this;
- var fieldNodes = astNode.fields;
- var fields = fieldNodes && fieldNodes.length > 0 ? function () {
- return keyByNameNode(fieldNodes, function (field) {
- return _this4.buildField(field);
- });
- } : Object.create(null);
- return new _definition.GraphQLInterfaceType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- fields: fields,
- astNode: astNode
- });
- };
- _proto._makeEnumDef = function _makeEnumDef(astNode) {
- var _this5 = this;
- var valueNodes = astNode.values || [];
- return new _definition.GraphQLEnumType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- values: keyByNameNode(valueNodes, function (value) {
- return _this5.buildEnumValue(value);
- }),
- astNode: astNode
- });
- };
- _proto._makeUnionDef = function _makeUnionDef(astNode) {
- var _this6 = this;
- var typeNodes = astNode.types; // Note: While this could make assertions to get the correctly typed
- // values below, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- var types = typeNodes && typeNodes.length > 0 ? function () {
- return typeNodes.map(function (ref) {
- return _this6.getNamedType(ref);
- });
- } : [];
- return new _definition.GraphQLUnionType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- types: types,
- astNode: astNode
- });
- };
- _proto._makeScalarDef = function _makeScalarDef(astNode) {
- return new _definition.GraphQLScalarType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- astNode: astNode,
- serialize: function serialize(value) {
- return value;
- }
- });
- };
- _proto._makeInputObjectDef = function _makeInputObjectDef(def) {
- var _this7 = this;
- var fields = def.fields;
- return new _definition.GraphQLInputObjectType({
- name: def.name.value,
- description: getDescription(def, this._options),
- fields: fields ? function () {
- return keyByNameNode(fields, function (field) {
- return _this7.buildInputField(field);
- });
- } : Object.create(null),
- astNode: def
- });
- };
- return ASTDefinitionBuilder;
- }();
- exports.ASTDefinitionBuilder = ASTDefinitionBuilder;
- function keyByNameNode(list, valFn) {
- return (0, _keyValMap.default)(list, function (_ref2) {
- var name = _ref2.name;
- return name.value;
- }, valFn);
- }
- /**
- * Given a field or enum value node, returns the string value for the
- * deprecation reason.
- */
- function getDeprecationReason(node) {
- var deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node);
- return deprecated && deprecated.reason;
- }
- /**
- * Given an ast node, returns its string description.
- * @deprecated: provided to ease adoption and will be removed in v16.
- *
- * Accepts options as a second argument:
- *
- * - commentDescriptions:
- * Provide true to use preceding comments as the description.
- *
- */
- function getDescription(node, options) {
- if (node.description) {
- return node.description.value;
- }
- if (options && options.commentDescriptions) {
- var rawValue = getLeadingCommentBlock(node);
- if (rawValue !== undefined) {
- return (0, _blockString.dedentBlockStringValue)('\n' + rawValue);
- }
- }
- }
- function getLeadingCommentBlock(node) {
- var loc = node.loc;
- if (!loc) {
- return;
- }
- var comments = [];
- var token = loc.startToken.prev;
- while (token && token.kind === _lexer.TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) {
- var value = String(token.value);
- comments.push(value);
- token = token.prev;
- }
- return comments.reverse().join('\n');
- }
- /**
- * A helper function to build a GraphQLSchema directly from a source
- * document.
- */
- function buildSchema(source, options) {
- return buildASTSchema((0, _parser.parse)(source, options), options);
- }
- },{"../execution/values":27,"../jsutils/inspect":32,"../jsutils/invariant":34,"../jsutils/keyMap":38,"../jsutils/keyValMap":39,"../language/blockString":48,"../language/kinds":51,"../language/lexer":52,"../language/parser":54,"../language/predicates":55,"../polyfills/objectValues":64,"../type/definition":68,"../type/directives":69,"../type/introspection":71,"../type/scalars":72,"../type/schema":73,"../validation/validate":136,"./valueFromAST":98}],79:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.buildClientSchema = buildClientSchema;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _valueFromAST = require("./valueFromAST");
- var _parser = require("../language/parser");
- var _schema = require("../type/schema");
- var _definition = require("../type/definition");
- var _directives = require("../type/directives");
- var _introspection = require("../type/introspection");
- var _scalars = require("../type/scalars");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Build a GraphQLSchema for use by client tools.
- *
- * Given the result of a client running the introspection query, creates and
- * returns a GraphQLSchema instance which can be then used with all graphql-js
- * tools, but cannot be used to execute a query, as introspection does not
- * represent the "resolver", "parse" or "serialize" functions or any other
- * server-internal mechanisms.
- *
- * This function expects a complete introspection result. Don't forget to check
- * the "errors" field of a server response before calling this function.
- */
- function buildClientSchema(introspection, options) {
- // Get the schema from the introspection result.
- var schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each.
- var typeMap = (0, _keyValMap.default)(schemaIntrospection.types, function (typeIntrospection) {
- return typeIntrospection.name;
- }, function (typeIntrospection) {
- return buildType(typeIntrospection);
- });
- for (var _i = 0, _arr = [].concat(_scalars.specifiedScalarTypes, _introspection.introspectionTypes); _i < _arr.length; _i++) {
- var stdType = _arr[_i];
- if (typeMap[stdType.name]) {
- typeMap[stdType.name] = stdType;
- }
- } // Get the root Query, Mutation, and Subscription types.
- var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null;
- var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null;
- var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if
- // directives were not queried for.
- var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types.
- return new _schema.GraphQLSchema({
- query: queryType,
- mutation: mutationType,
- subscription: subscriptionType,
- types: (0, _objectValues.default)(typeMap),
- directives: directives,
- assumeValid: options && options.assumeValid,
- allowedLegacyNames: options && options.allowedLegacyNames
- }); // Given a type reference in introspection, return the GraphQLType instance.
- // preferring cached instances before building new instances.
- function getType(typeRef) {
- if (typeRef.kind === _introspection.TypeKind.LIST) {
- var itemRef = typeRef.ofType;
- if (!itemRef) {
- throw new Error('Decorated type deeper than introspection query.');
- }
- return (0, _definition.GraphQLList)(getType(itemRef));
- }
- if (typeRef.kind === _introspection.TypeKind.NON_NULL) {
- var nullableRef = typeRef.ofType;
- if (!nullableRef) {
- throw new Error('Decorated type deeper than introspection query.');
- }
- var nullableType = getType(nullableRef);
- return (0, _definition.GraphQLNonNull)((0, _definition.assertNullableType)(nullableType));
- }
- if (!typeRef.name) {
- throw new Error('Unknown type reference: ' + (0, _inspect.default)(typeRef));
- }
- return getNamedType(typeRef.name);
- }
- function getNamedType(typeName) {
- var type = typeMap[typeName];
- if (!type) {
- throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure ") + 'that a full introspection query is used in order to build a ' + 'client schema.');
- }
- return type;
- }
- function getInputType(typeRef) {
- var type = getType(typeRef);
- !(0, _definition.isInputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide input type for arguments, but received: ' + (0, _inspect.default)(type) + '.') : void 0;
- return type;
- }
- function getOutputType(typeRef) {
- var type = getType(typeRef);
- !(0, _definition.isOutputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide output type for fields, but received: ' + (0, _inspect.default)(type) + '.') : void 0;
- return type;
- }
- function getObjectType(typeRef) {
- var type = getType(typeRef);
- return (0, _definition.assertObjectType)(type);
- }
- function getInterfaceType(typeRef) {
- var type = getType(typeRef);
- return (0, _definition.assertInterfaceType)(type);
- } // Given a type's introspection result, construct the correct
- // GraphQLType instance.
- function buildType(type) {
- if (type && type.name && type.kind) {
- switch (type.kind) {
- case _introspection.TypeKind.SCALAR:
- return buildScalarDef(type);
- case _introspection.TypeKind.OBJECT:
- return buildObjectDef(type);
- case _introspection.TypeKind.INTERFACE:
- return buildInterfaceDef(type);
- case _introspection.TypeKind.UNION:
- return buildUnionDef(type);
- case _introspection.TypeKind.ENUM:
- return buildEnumDef(type);
- case _introspection.TypeKind.INPUT_OBJECT:
- return buildInputObjectDef(type);
- }
- }
- throw new Error('Invalid or incomplete introspection result. Ensure that a full ' + 'introspection query is used in order to build a client schema:' + (0, _inspect.default)(type));
- }
- function buildScalarDef(scalarIntrospection) {
- return new _definition.GraphQLScalarType({
- name: scalarIntrospection.name,
- description: scalarIntrospection.description,
- serialize: function serialize(value) {
- return value;
- }
- });
- }
- function buildObjectDef(objectIntrospection) {
- if (!objectIntrospection.interfaces) {
- throw new Error('Introspection result missing interfaces: ' + (0, _inspect.default)(objectIntrospection));
- }
- return new _definition.GraphQLObjectType({
- name: objectIntrospection.name,
- description: objectIntrospection.description,
- interfaces: function interfaces() {
- return objectIntrospection.interfaces.map(getInterfaceType);
- },
- fields: function fields() {
- return buildFieldDefMap(objectIntrospection);
- }
- });
- }
- function buildInterfaceDef(interfaceIntrospection) {
- return new _definition.GraphQLInterfaceType({
- name: interfaceIntrospection.name,
- description: interfaceIntrospection.description,
- fields: function fields() {
- return buildFieldDefMap(interfaceIntrospection);
- }
- });
- }
- function buildUnionDef(unionIntrospection) {
- if (!unionIntrospection.possibleTypes) {
- throw new Error('Introspection result missing possibleTypes: ' + (0, _inspect.default)(unionIntrospection));
- }
- return new _definition.GraphQLUnionType({
- name: unionIntrospection.name,
- description: unionIntrospection.description,
- types: function types() {
- return unionIntrospection.possibleTypes.map(getObjectType);
- }
- });
- }
- function buildEnumDef(enumIntrospection) {
- if (!enumIntrospection.enumValues) {
- throw new Error('Introspection result missing enumValues: ' + (0, _inspect.default)(enumIntrospection));
- }
- return new _definition.GraphQLEnumType({
- name: enumIntrospection.name,
- description: enumIntrospection.description,
- values: (0, _keyValMap.default)(enumIntrospection.enumValues, function (valueIntrospection) {
- return valueIntrospection.name;
- }, function (valueIntrospection) {
- return {
- description: valueIntrospection.description,
- deprecationReason: valueIntrospection.deprecationReason
- };
- })
- });
- }
- function buildInputObjectDef(inputObjectIntrospection) {
- if (!inputObjectIntrospection.inputFields) {
- throw new Error('Introspection result missing inputFields: ' + (0, _inspect.default)(inputObjectIntrospection));
- }
- return new _definition.GraphQLInputObjectType({
- name: inputObjectIntrospection.name,
- description: inputObjectIntrospection.description,
- fields: function fields() {
- return buildInputValueDefMap(inputObjectIntrospection.inputFields);
- }
- });
- }
- function buildFieldDefMap(typeIntrospection) {
- if (!typeIntrospection.fields) {
- throw new Error('Introspection result missing fields: ' + (0, _inspect.default)(typeIntrospection));
- }
- return (0, _keyValMap.default)(typeIntrospection.fields, function (fieldIntrospection) {
- return fieldIntrospection.name;
- }, function (fieldIntrospection) {
- if (!fieldIntrospection.args) {
- throw new Error('Introspection result missing field args: ' + (0, _inspect.default)(fieldIntrospection));
- }
- return {
- description: fieldIntrospection.description,
- deprecationReason: fieldIntrospection.deprecationReason,
- type: getOutputType(fieldIntrospection.type),
- args: buildInputValueDefMap(fieldIntrospection.args)
- };
- });
- }
- function buildInputValueDefMap(inputValueIntrospections) {
- return (0, _keyValMap.default)(inputValueIntrospections, function (inputValue) {
- return inputValue.name;
- }, buildInputValue);
- }
- function buildInputValue(inputValueIntrospection) {
- var type = getInputType(inputValueIntrospection.type);
- var defaultValue = inputValueIntrospection.defaultValue ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined;
- return {
- description: inputValueIntrospection.description,
- type: type,
- defaultValue: defaultValue
- };
- }
- function buildDirective(directiveIntrospection) {
- if (!directiveIntrospection.args) {
- throw new Error('Introspection result missing directive args: ' + (0, _inspect.default)(directiveIntrospection));
- }
- if (!directiveIntrospection.locations) {
- throw new Error('Introspection result missing directive locations: ' + (0, _inspect.default)(directiveIntrospection));
- }
- return new _directives.GraphQLDirective({
- name: directiveIntrospection.name,
- description: directiveIntrospection.description,
- locations: directiveIntrospection.locations.slice(),
- args: buildInputValueDefMap(directiveIntrospection.args)
- });
- }
- }
- },{"../jsutils/inspect":32,"../jsutils/invariant":34,"../jsutils/keyValMap":39,"../language/parser":54,"../polyfills/objectValues":64,"../type/definition":68,"../type/directives":69,"../type/introspection":71,"../type/scalars":72,"../type/schema":73,"./valueFromAST":98}],80:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.coerceValue = coerceValue;
- var _iterall = require("iterall");
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _orList = _interopRequireDefault(require("../jsutils/orList"));
- var _suggestionList = _interopRequireDefault(require("../jsutils/suggestionList"));
- var _GraphQLError = require("../error/GraphQLError");
- var _definition = require("../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- /**
- * Coerces a JavaScript value given a GraphQL Type.
- *
- * Returns either a value which is valid for the provided type or a list of
- * encountered coercion errors.
- *
- */
- function coerceValue(value, type, blameNode, path) {
- // A value must be provided if the type is non-null.
- if ((0, _definition.isNonNullType)(type)) {
- if (value == null) {
- return ofErrors([coercionError("Expected non-nullable type ".concat((0, _inspect.default)(type), " not to be null"), blameNode, path)]);
- }
- return coerceValue(value, type.ofType, blameNode, path);
- }
- if (value == null) {
- // Explicitly return the value null.
- return ofValue(null);
- }
- if ((0, _definition.isScalarType)(type)) {
- // Scalars determine if a value is valid via parseValue(), which can
- // throw to indicate failure. If it throws, maintain a reference to
- // the original error.
- try {
- var parseResult = type.parseValue(value);
- if ((0, _isInvalid.default)(parseResult)) {
- return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path)]);
- }
- return ofValue(parseResult);
- } catch (error) {
- return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, error.message, error)]);
- }
- }
- if ((0, _definition.isEnumType)(type)) {
- if (typeof value === 'string') {
- var enumValue = type.getValue(value);
- if (enumValue) {
- return ofValue(enumValue.value);
- }
- }
- var suggestions = (0, _suggestionList.default)(String(value), type.getValues().map(function (enumValue) {
- return enumValue.name;
- }));
- var didYouMean = suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(suggestions), "?") : undefined;
- return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, didYouMean)]);
- }
- if ((0, _definition.isListType)(type)) {
- var itemType = type.ofType;
- if ((0, _iterall.isCollection)(value)) {
- var errors;
- var coercedValue = [];
- (0, _iterall.forEach)(value, function (itemValue, index) {
- var coercedItem = coerceValue(itemValue, itemType, blameNode, atPath(path, index));
- if (coercedItem.errors) {
- errors = add(errors, coercedItem.errors);
- } else if (!errors) {
- coercedValue.push(coercedItem.value);
- }
- });
- return errors ? ofErrors(errors) : ofValue(coercedValue);
- } // Lists accept a non-list value as a list of one.
- var coercedItem = coerceValue(value, itemType, blameNode);
- return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]);
- }
- if ((0, _definition.isInputObjectType)(type)) {
- if (_typeof(value) !== 'object') {
- return ofErrors([coercionError("Expected type ".concat(type.name, " to be an object"), blameNode, path)]);
- }
- var _errors;
- var _coercedValue = {};
- var fields = type.getFields(); // Ensure every defined field is valid.
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectValues.default)(fields)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var field = _step.value;
- var fieldValue = value[field.name];
- if ((0, _isInvalid.default)(fieldValue)) {
- if (!(0, _isInvalid.default)(field.defaultValue)) {
- _coercedValue[field.name] = field.defaultValue;
- } else if ((0, _definition.isNonNullType)(field.type)) {
- _errors = add(_errors, coercionError("Field ".concat(printPath(atPath(path, field.name)), " of required ") + "type ".concat((0, _inspect.default)(field.type), " was not provided"), blameNode));
- }
- } else {
- var coercedField = coerceValue(fieldValue, field.type, blameNode, atPath(path, field.name));
- if (coercedField.errors) {
- _errors = add(_errors, coercedField.errors);
- } else if (!_errors) {
- _coercedValue[field.name] = coercedField.value;
- }
- }
- } // Ensure every provided field is defined.
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- for (var _i = 0, _Object$keys = Object.keys(value); _i < _Object$keys.length; _i++) {
- var fieldName = _Object$keys[_i];
- if (!fields[fieldName]) {
- var _suggestions = (0, _suggestionList.default)(fieldName, Object.keys(fields));
- var _didYouMean = _suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(_suggestions), "?") : undefined;
- _errors = add(_errors, coercionError("Field \"".concat(fieldName, "\" is not defined by type ").concat(type.name), blameNode, path, _didYouMean));
- }
- }
- return _errors ? ofErrors(_errors) : ofValue(_coercedValue);
- } // Not reachable. All possible input types have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected input type: \"".concat((0, _inspect.default)(type), "\"."));
- }
- function ofValue(value) {
- return {
- errors: undefined,
- value: value
- };
- }
- function ofErrors(errors) {
- return {
- errors: errors,
- value: undefined
- };
- }
- function add(errors, moreErrors) {
- return (errors || []).concat(moreErrors);
- }
- function atPath(prev, key) {
- return {
- prev: prev,
- key: key
- };
- }
- function coercionError(message, blameNode, path, subMessage, originalError) {
- var pathStr = printPath(path); // Return a GraphQLError instance
- return new _GraphQLError.GraphQLError(message + (pathStr ? ' at ' + pathStr : '') + (subMessage ? '; ' + subMessage : '.'), blameNode, undefined, undefined, undefined, originalError);
- } // Build a string describing the path into the value where the error was found
- function printPath(path) {
- var pathStr = '';
- var currentPath = path;
- while (currentPath) {
- pathStr = (typeof currentPath.key === 'string' ? '.' + currentPath.key : '[' + String(currentPath.key) + ']') + pathStr;
- currentPath = currentPath.prev;
- }
- return pathStr ? 'value' + pathStr : '';
- }
- },{"../error/GraphQLError":19,"../jsutils/inspect":32,"../jsutils/isInvalid":35,"../jsutils/orList":43,"../jsutils/suggestionList":47,"../polyfills/objectValues":64,"../type/definition":68,"iterall":137}],81:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.concatAST = concatAST;
- var _flatMap = _interopRequireDefault(require("../polyfills/flatMap"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Provided a collection of ASTs, presumably each from different files,
- * concatenate the ASTs together into batched AST, useful for validating many
- * GraphQL source files which together represent one conceptual application.
- */
- function concatAST(asts) {
- return {
- kind: 'Document',
- definitions: (0, _flatMap.default)(asts, function (ast) {
- return ast.definitions;
- })
- };
- }
- },{"../polyfills/flatMap":60}],82:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.extendSchema = extendSchema;
- var _flatMap = _interopRequireDefault(require("../polyfills/flatMap"));
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _mapValue = _interopRequireDefault(require("../jsutils/mapValue"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _buildASTSchema = require("./buildASTSchema");
- var _validate = require("../validation/validate");
- var _schema = require("../type/schema");
- var _introspection = require("../type/introspection");
- var _scalars = require("../type/scalars");
- var _definition = require("../type/definition");
- var _directives = require("../type/directives");
- var _kinds = require("../language/kinds");
- var _predicates = require("../language/predicates");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * Produces a new schema given an existing schema and a document which may
- * contain GraphQL type extensions and definitions. The original schema will
- * remain unaltered.
- *
- * Because a schema represents a graph of references, a schema cannot be
- * extended without effectively making an entire copy. We do not know until it's
- * too late if subgraphs remain unchanged.
- *
- * This algorithm copies the provided schema, applying extensions while
- * producing the copy. The original schema remains unaltered.
- *
- * Accepts options as a third argument:
- *
- * - commentDescriptions:
- * Provide true to use preceding comments as the description.
- *
- */
- function extendSchema(schema, documentAST, options) {
- (0, _schema.assertSchema)(schema);
- !(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0;
- if (!options || !(options.assumeValid || options.assumeValidSDL)) {
- (0, _validate.assertValidSDLExtension)(documentAST, schema);
- } // Collect the type definitions and extensions found in the document.
- var typeDefs = [];
- var typeExtsMap = Object.create(null); // New directives and types are separate because a directives and types can
- // have the same name. For example, a type named "skip".
- var directiveDefs = [];
- var schemaDef; // Schema extensions are collected which may add additional operation types.
- var schemaExts = [];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = documentAST.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var def = _step.value;
- if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) {
- schemaDef = def;
- } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) {
- schemaExts.push(def);
- } else if ((0, _predicates.isTypeDefinitionNode)(def)) {
- typeDefs.push(def);
- } else if ((0, _predicates.isTypeExtensionNode)(def)) {
- var extendedTypeName = def.name.value;
- var existingTypeExts = typeExtsMap[extendedTypeName];
- typeExtsMap[extendedTypeName] = existingTypeExts ? existingTypeExts.concat([def]) : [def];
- } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- directiveDefs.push(def);
- }
- } // If this document contains no new types, extensions, or directives then
- // return the same unmodified GraphQLSchema instance.
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- if (Object.keys(typeExtsMap).length === 0 && typeDefs.length === 0 && directiveDefs.length === 0 && schemaExts.length === 0 && !schemaDef) {
- return schema;
- }
- var schemaConfig = schema.toConfig();
- var astBuilder = new _buildASTSchema.ASTDefinitionBuilder(options, function (typeName) {
- var type = typeMap[typeName];
- !type ? (0, _invariant.default)(0, "Unknown type: \"".concat(typeName, "\".")) : void 0;
- return type;
- });
- var typeMap = (0, _keyValMap.default)(typeDefs, function (node) {
- return node.name.value;
- }, function (node) {
- return astBuilder.buildType(node);
- });
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = schemaConfig.types[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var existingType = _step2.value;
- typeMap[existingType.name] = extendNamedType(existingType);
- } // Get the extended root operation types.
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- var operationTypes = {
- query: schemaConfig.query && schemaConfig.query.name,
- mutation: schemaConfig.mutation && schemaConfig.mutation.name,
- subscription: schemaConfig.subscription && schemaConfig.subscription.name
- };
- if (schemaDef) {
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = schemaDef.operationTypes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var _ref2 = _step3.value;
- var operation = _ref2.operation;
- var type = _ref2.type;
- operationTypes[operation] = type.name.value;
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- } // Then, incorporate schema definition and all schema extensions.
- for (var _i = 0, _schemaExts = schemaExts; _i < _schemaExts.length; _i++) {
- var schemaExt = _schemaExts[_i];
- if (schemaExt.operationTypes) {
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = schemaExt.operationTypes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var _ref4 = _step4.value;
- var _operation = _ref4.operation;
- var _type = _ref4.type;
- operationTypes[_operation] = _type.name.value;
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- }
- } // Support both original legacy names and extended legacy names.
- var allowedLegacyNames = schemaConfig.allowedLegacyNames.concat(options && options.allowedLegacyNames || []); // Then produce and return a Schema with these types.
- return new _schema.GraphQLSchema({
- // Note: While this could make early assertions to get the correctly
- // typed values, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- query: getMaybeTypeByName(operationTypes.query),
- mutation: getMaybeTypeByName(operationTypes.mutation),
- subscription: getMaybeTypeByName(operationTypes.subscription),
- types: (0, _objectValues.default)(typeMap),
- directives: getMergedDirectives(),
- astNode: schemaDef || schemaConfig.astNode,
- extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExts),
- allowedLegacyNames: allowedLegacyNames
- }); // Below are functions used for producing this schema that have closed over
- // this scope and have access to the schema, cache, and newly defined types.
- function replaceType(type) {
- if ((0, _definition.isListType)(type)) {
- return new _definition.GraphQLList(replaceType(type.ofType));
- } else if ((0, _definition.isNonNullType)(type)) {
- return new _definition.GraphQLNonNull(replaceType(type.ofType));
- }
- return replaceNamedType(type);
- }
- function replaceNamedType(type) {
- return typeMap[type.name];
- }
- function getMaybeTypeByName(typeName) {
- return typeName ? typeMap[typeName] : null;
- }
- function getMergedDirectives() {
- var existingDirectives = schema.getDirectives().map(extendDirective);
- !existingDirectives ? (0, _invariant.default)(0, 'schema must have default directives') : void 0;
- return existingDirectives.concat(directiveDefs.map(function (node) {
- return astBuilder.buildDirective(node);
- }));
- }
- function extendNamedType(type) {
- if ((0, _introspection.isIntrospectionType)(type) || (0, _scalars.isSpecifiedScalarType)(type)) {
- // Builtin types are not extended.
- return type;
- } else if ((0, _definition.isScalarType)(type)) {
- return extendScalarType(type);
- } else if ((0, _definition.isObjectType)(type)) {
- return extendObjectType(type);
- } else if ((0, _definition.isInterfaceType)(type)) {
- return extendInterfaceType(type);
- } else if ((0, _definition.isUnionType)(type)) {
- return extendUnionType(type);
- } else if ((0, _definition.isEnumType)(type)) {
- return extendEnumType(type);
- } else if ((0, _definition.isInputObjectType)(type)) {
- return extendInputObjectType(type);
- } // Not reachable. All possible types have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected type: \"".concat((0, _inspect.default)(type), "\"."));
- }
- function extendDirective(directive) {
- var config = directive.toConfig();
- return new _directives.GraphQLDirective(_objectSpread({}, config, {
- args: (0, _mapValue.default)(config.args, extendArg)
- }));
- }
- function extendInputObjectType(type) {
- var config = type.toConfig();
- var extensions = typeExtsMap[config.name] || [];
- var fieldNodes = (0, _flatMap.default)(extensions, function (node) {
- return node.fields || [];
- });
- return new _definition.GraphQLInputObjectType(_objectSpread({}, config, {
- fields: function fields() {
- return _objectSpread({}, (0, _mapValue.default)(config.fields, function (field) {
- return _objectSpread({}, field, {
- type: replaceType(field.type)
- });
- }), (0, _keyValMap.default)(fieldNodes, function (field) {
- return field.name.value;
- }, function (field) {
- return astBuilder.buildInputField(field);
- }));
- },
- extensionASTNodes: config.extensionASTNodes.concat(extensions)
- }));
- }
- function extendEnumType(type) {
- var config = type.toConfig();
- var extensions = typeExtsMap[type.name] || [];
- var valueNodes = (0, _flatMap.default)(extensions, function (node) {
- return node.values || [];
- });
- return new _definition.GraphQLEnumType(_objectSpread({}, config, {
- values: _objectSpread({}, config.values, (0, _keyValMap.default)(valueNodes, function (value) {
- return value.name.value;
- }, function (value) {
- return astBuilder.buildEnumValue(value);
- })),
- extensionASTNodes: config.extensionASTNodes.concat(extensions)
- }));
- }
- function extendScalarType(type) {
- var config = type.toConfig();
- var extensions = typeExtsMap[config.name] || [];
- return new _definition.GraphQLScalarType(_objectSpread({}, config, {
- extensionASTNodes: config.extensionASTNodes.concat(extensions)
- }));
- }
- function extendObjectType(type) {
- var config = type.toConfig();
- var extensions = typeExtsMap[config.name] || [];
- var interfaceNodes = (0, _flatMap.default)(extensions, function (node) {
- return node.interfaces || [];
- });
- var fieldNodes = (0, _flatMap.default)(extensions, function (node) {
- return node.fields || [];
- });
- return new _definition.GraphQLObjectType(_objectSpread({}, config, {
- interfaces: function interfaces() {
- return [].concat(type.getInterfaces().map(replaceNamedType), interfaceNodes.map(function (node) {
- return astBuilder.getNamedType(node);
- }));
- },
- fields: function fields() {
- return _objectSpread({}, (0, _mapValue.default)(config.fields, extendField), (0, _keyValMap.default)(fieldNodes, function (node) {
- return node.name.value;
- }, function (node) {
- return astBuilder.buildField(node);
- }));
- },
- extensionASTNodes: config.extensionASTNodes.concat(extensions)
- }));
- }
- function extendInterfaceType(type) {
- var config = type.toConfig();
- var extensions = typeExtsMap[config.name] || [];
- var fieldNodes = (0, _flatMap.default)(extensions, function (node) {
- return node.fields || [];
- });
- return new _definition.GraphQLInterfaceType(_objectSpread({}, config, {
- fields: function fields() {
- return _objectSpread({}, (0, _mapValue.default)(config.fields, extendField), (0, _keyValMap.default)(fieldNodes, function (node) {
- return node.name.value;
- }, function (node) {
- return astBuilder.buildField(node);
- }));
- },
- extensionASTNodes: config.extensionASTNodes.concat(extensions)
- }));
- }
- function extendUnionType(type) {
- var config = type.toConfig();
- var extensions = typeExtsMap[config.name] || [];
- var typeNodes = (0, _flatMap.default)(extensions, function (node) {
- return node.types || [];
- });
- return new _definition.GraphQLUnionType(_objectSpread({}, config, {
- types: function types() {
- return [].concat(type.getTypes().map(replaceNamedType), typeNodes.map(function (node) {
- return astBuilder.getNamedType(node);
- }));
- },
- extensionASTNodes: config.extensionASTNodes.concat(extensions)
- }));
- }
- function extendField(field) {
- return _objectSpread({}, field, {
- type: replaceType(field.type),
- args: (0, _mapValue.default)(field.args, extendArg)
- });
- }
- function extendArg(arg) {
- return _objectSpread({}, arg, {
- type: replaceType(arg.type)
- });
- }
- }
- },{"../jsutils/inspect":32,"../jsutils/invariant":34,"../jsutils/keyValMap":39,"../jsutils/mapValue":40,"../language/kinds":51,"../language/predicates":55,"../polyfills/flatMap":60,"../polyfills/objectValues":64,"../type/definition":68,"../type/directives":69,"../type/introspection":71,"../type/scalars":72,"../type/schema":73,"../validation/validate":136,"./buildASTSchema":78}],83:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.findBreakingChanges = findBreakingChanges;
- exports.findDangerousChanges = findDangerousChanges;
- exports.DangerousChangeType = exports.BreakingChangeType = void 0;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _definition = require("../type/definition");
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var BreakingChangeType = {
- FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND',
- FIELD_REMOVED: 'FIELD_REMOVED',
- TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND',
- TYPE_REMOVED: 'TYPE_REMOVED',
- TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION',
- VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM',
- ARG_REMOVED: 'ARG_REMOVED',
- ARG_CHANGED_KIND: 'ARG_CHANGED_KIND',
- REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED',
- REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED',
- INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT',
- DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED',
- DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED',
- DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED',
- REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED'
- };
- exports.BreakingChangeType = BreakingChangeType;
- var DangerousChangeType = {
- ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE',
- VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM',
- INTERFACE_ADDED_TO_OBJECT: 'INTERFACE_ADDED_TO_OBJECT',
- TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION',
- OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED',
- OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED'
- };
- exports.DangerousChangeType = DangerousChangeType;
- /**
- * Given two schemas, returns an Array containing descriptions of all the types
- * of breaking changes covered by the other functions down below.
- */
- function findBreakingChanges(oldSchema, newSchema) {
- return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema));
- }
- /**
- * Given two schemas, returns an Array containing descriptions of all the types
- * of potentially dangerous changes covered by the other functions down below.
- */
- function findDangerousChanges(oldSchema, newSchema) {
- return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges);
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any breaking
- * changes in the newSchema related to removing an entire type.
- */
- function findRemovedTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- for (var _i = 0, _Object$keys = Object.keys(oldTypeMap); _i < _Object$keys.length; _i++) {
- var typeName = _Object$keys[_i];
- if (!newTypeMap[typeName]) {
- breakingChanges.push({
- type: BreakingChangeType.TYPE_REMOVED,
- description: "".concat(typeName, " was removed.")
- });
- }
- }
- return breakingChanges;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any breaking
- * changes in the newSchema related to changing the type of a type.
- */
- function findTypesThatChangedKind(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- for (var _i2 = 0, _Object$keys2 = Object.keys(oldTypeMap); _i2 < _Object$keys2.length; _i2++) {
- var typeName = _Object$keys2[_i2];
- if (!newTypeMap[typeName]) {
- continue;
- }
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (oldType.constructor !== newType.constructor) {
- breakingChanges.push({
- type: BreakingChangeType.TYPE_CHANGED_KIND,
- description: "".concat(typeName, " changed from ") + "".concat(typeKindName(oldType), " to ").concat(typeKindName(newType), ".")
- });
- }
- }
- return breakingChanges;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any
- * breaking or dangerous changes in the newSchema related to arguments
- * (such as removal or change of type of an argument, or a change in an
- * argument's default value).
- */
- function findArgChanges(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- var dangerousChanges = [];
- for (var _i3 = 0, _Object$keys3 = Object.keys(oldTypeMap); _i3 < _Object$keys3.length; _i3++) {
- var typeName = _Object$keys3[_i3];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!((0, _definition.isObjectType)(oldType) || (0, _definition.isInterfaceType)(oldType)) || !((0, _definition.isObjectType)(newType) || (0, _definition.isInterfaceType)(newType)) || newType.constructor !== oldType.constructor) {
- continue;
- }
- var oldTypeFields = oldType.getFields();
- var newTypeFields = newType.getFields();
- for (var _i4 = 0, _Object$keys4 = Object.keys(oldTypeFields); _i4 < _Object$keys4.length; _i4++) {
- var fieldName = _Object$keys4[_i4];
- if (!newTypeFields[fieldName]) {
- continue;
- }
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- var _loop = function _loop() {
- var oldArgDef = _step.value;
- var newArgs = newTypeFields[fieldName].args;
- var newArgDef = (0, _find.default)(newArgs, function (arg) {
- return arg.name === oldArgDef.name;
- }); // Arg not present
- if (!newArgDef) {
- breakingChanges.push({
- type: BreakingChangeType.ARG_REMOVED,
- description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " was removed")
- });
- } else {
- var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);
- if (!isSafe) {
- breakingChanges.push({
- type: BreakingChangeType.ARG_CHANGED_KIND,
- description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed type from ") + "".concat(oldArgDef.type.toString(), " to ").concat(newArgDef.type.toString())
- });
- } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {
- dangerousChanges.push({
- type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,
- description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed defaultValue")
- });
- }
- }
- };
- for (var _iterator = oldTypeFields[fieldName].args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- _loop();
- } // Check if arg was added to the field
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- var _loop2 = function _loop2() {
- var newArgDef = _step2.value;
- var oldArgs = oldTypeFields[fieldName].args;
- var oldArgDef = (0, _find.default)(oldArgs, function (arg) {
- return arg.name === newArgDef.name;
- });
- if (!oldArgDef) {
- var argName = newArgDef.name;
- if ((0, _definition.isRequiredArgument)(newArgDef)) {
- breakingChanges.push({
- type: BreakingChangeType.REQUIRED_ARG_ADDED,
- description: "A required arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added")
- });
- } else {
- dangerousChanges.push({
- type: DangerousChangeType.OPTIONAL_ARG_ADDED,
- description: "An optional arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added")
- });
- }
- }
- };
- for (var _iterator2 = newTypeFields[fieldName].args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- _loop2();
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- }
- }
- return {
- breakingChanges: breakingChanges,
- dangerousChanges: dangerousChanges
- };
- }
- function typeKindName(type) {
- if ((0, _definition.isScalarType)(type)) {
- return 'a Scalar type';
- }
- if ((0, _definition.isObjectType)(type)) {
- return 'an Object type';
- }
- if ((0, _definition.isInterfaceType)(type)) {
- return 'an Interface type';
- }
- if ((0, _definition.isUnionType)(type)) {
- return 'a Union type';
- }
- if ((0, _definition.isEnumType)(type)) {
- return 'an Enum type';
- }
- if ((0, _definition.isInputObjectType)(type)) {
- return 'an Input type';
- } // Not reachable. All possible named types have been considered.
- /* istanbul ignore next */
- throw new TypeError("Unexpected type: ".concat((0, _inspect.default)(type), "."));
- }
- function findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- for (var _i5 = 0, _Object$keys5 = Object.keys(oldTypeMap); _i5 < _Object$keys5.length; _i5++) {
- var typeName = _Object$keys5[_i5];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!((0, _definition.isObjectType)(oldType) || (0, _definition.isInterfaceType)(oldType)) || !((0, _definition.isObjectType)(newType) || (0, _definition.isInterfaceType)(newType)) || newType.constructor !== oldType.constructor) {
- continue;
- }
- var oldTypeFieldsDef = oldType.getFields();
- var newTypeFieldsDef = newType.getFields();
- for (var _i6 = 0, _Object$keys6 = Object.keys(oldTypeFieldsDef); _i6 < _Object$keys6.length; _i6++) {
- var fieldName = _Object$keys6[_i6];
- // Check if the field is missing on the type in the new schema.
- if (!(fieldName in newTypeFieldsDef)) {
- breakingChanges.push({
- type: BreakingChangeType.FIELD_REMOVED,
- description: "".concat(typeName, ".").concat(fieldName, " was removed.")
- });
- } else {
- var oldFieldType = oldTypeFieldsDef[fieldName].type;
- var newFieldType = newTypeFieldsDef[fieldName].type;
- var isSafe = isChangeSafeForObjectOrInterfaceField(oldFieldType, newFieldType);
- if (!isSafe) {
- var oldFieldTypeString = (0, _definition.isNamedType)(oldFieldType) ? oldFieldType.name : oldFieldType.toString();
- var newFieldTypeString = (0, _definition.isNamedType)(newFieldType) ? newFieldType.name : newFieldType.toString();
- breakingChanges.push({
- type: BreakingChangeType.FIELD_CHANGED_KIND,
- description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".")
- });
- }
- }
- }
- }
- return breakingChanges;
- }
- function findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- var dangerousChanges = [];
- for (var _i7 = 0, _Object$keys7 = Object.keys(oldTypeMap); _i7 < _Object$keys7.length; _i7++) {
- var typeName = _Object$keys7[_i7];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isInputObjectType)(oldType) || !(0, _definition.isInputObjectType)(newType)) {
- continue;
- }
- var oldTypeFieldsDef = oldType.getFields();
- var newTypeFieldsDef = newType.getFields();
- for (var _i8 = 0, _Object$keys8 = Object.keys(oldTypeFieldsDef); _i8 < _Object$keys8.length; _i8++) {
- var fieldName = _Object$keys8[_i8];
- // Check if the field is missing on the type in the new schema.
- if (!(fieldName in newTypeFieldsDef)) {
- breakingChanges.push({
- type: BreakingChangeType.FIELD_REMOVED,
- description: "".concat(typeName, ".").concat(fieldName, " was removed.")
- });
- } else {
- var oldFieldType = oldTypeFieldsDef[fieldName].type;
- var newFieldType = newTypeFieldsDef[fieldName].type;
- var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldFieldType, newFieldType);
- if (!isSafe) {
- var oldFieldTypeString = (0, _definition.isNamedType)(oldFieldType) ? oldFieldType.name : oldFieldType.toString();
- var newFieldTypeString = (0, _definition.isNamedType)(newFieldType) ? newFieldType.name : newFieldType.toString();
- breakingChanges.push({
- type: BreakingChangeType.FIELD_CHANGED_KIND,
- description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".")
- });
- }
- }
- } // Check if a field was added to the input object type
- for (var _i9 = 0, _Object$keys9 = Object.keys(newTypeFieldsDef); _i9 < _Object$keys9.length; _i9++) {
- var _fieldName = _Object$keys9[_i9];
- if (!(_fieldName in oldTypeFieldsDef)) {
- if ((0, _definition.isRequiredInputField)(newTypeFieldsDef[_fieldName])) {
- breakingChanges.push({
- type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED,
- description: "A required field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.")
- });
- } else {
- dangerousChanges.push({
- type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED,
- description: "An optional field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.")
- });
- }
- }
- }
- }
- return {
- breakingChanges: breakingChanges,
- dangerousChanges: dangerousChanges
- };
- }
- function isChangeSafeForObjectOrInterfaceField(oldType, newType) {
- if ((0, _definition.isListType)(oldType)) {
- return (// if they're both lists, make sure the underlying types are compatible
- (0, _definition.isListType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || // moving from nullable to non-null of the same underlying type is safe
- (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)
- );
- }
- if ((0, _definition.isNonNullType)(oldType)) {
- // if they're both non-null, make sure the underlying types are compatible
- return (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType);
- }
- return (// if they're both named types, see if their names are equivalent
- (0, _definition.isNamedType)(newType) && oldType.name === newType.name || // moving from nullable to non-null of the same underlying type is safe
- (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)
- );
- }
- function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) {
- if ((0, _definition.isListType)(oldType)) {
- // if they're both lists, make sure the underlying types are compatible
- return (0, _definition.isListType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType);
- }
- if ((0, _definition.isNonNullType)(oldType)) {
- return (// if they're both non-null, make sure the underlying types are
- // compatible
- (0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || // moving from non-null to nullable of the same underlying type is safe
- !(0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)
- );
- } // if they're both named types, see if their names are equivalent
- return (0, _definition.isNamedType)(newType) && oldType.name === newType.name;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any breaking
- * changes in the newSchema related to removing types from a union type.
- */
- function findTypesRemovedFromUnions(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var typesRemovedFromUnion = [];
- for (var _i10 = 0, _Object$keys10 = Object.keys(oldTypeMap); _i10 < _Object$keys10.length; _i10++) {
- var typeName = _Object$keys10[_i10];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isUnionType)(oldType) || !(0, _definition.isUnionType)(newType)) {
- continue;
- }
- var typeNamesInNewUnion = Object.create(null);
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var type = _step3.value;
- typeNamesInNewUnion[type.name] = true;
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var _type = _step4.value;
- if (!typeNamesInNewUnion[_type.name]) {
- typesRemovedFromUnion.push({
- type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,
- description: "".concat(_type.name, " was removed from union type ").concat(typeName, ".")
- });
- }
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- }
- return typesRemovedFromUnion;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any dangerous
- * changes in the newSchema related to adding types to a union type.
- */
- function findTypesAddedToUnions(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var typesAddedToUnion = [];
- for (var _i11 = 0, _Object$keys11 = Object.keys(newTypeMap); _i11 < _Object$keys11.length; _i11++) {
- var typeName = _Object$keys11[_i11];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isUnionType)(oldType) || !(0, _definition.isUnionType)(newType)) {
- continue;
- }
- var typeNamesInOldUnion = Object.create(null);
- var _iteratorNormalCompletion5 = true;
- var _didIteratorError5 = false;
- var _iteratorError5 = undefined;
- try {
- for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
- var type = _step5.value;
- typeNamesInOldUnion[type.name] = true;
- }
- } catch (err) {
- _didIteratorError5 = true;
- _iteratorError5 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
- _iterator5.return();
- }
- } finally {
- if (_didIteratorError5) {
- throw _iteratorError5;
- }
- }
- }
- var _iteratorNormalCompletion6 = true;
- var _didIteratorError6 = false;
- var _iteratorError6 = undefined;
- try {
- for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
- var _type2 = _step6.value;
- if (!typeNamesInOldUnion[_type2.name]) {
- typesAddedToUnion.push({
- type: DangerousChangeType.TYPE_ADDED_TO_UNION,
- description: "".concat(_type2.name, " was added to union type ").concat(typeName, ".")
- });
- }
- }
- } catch (err) {
- _didIteratorError6 = true;
- _iteratorError6 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
- _iterator6.return();
- }
- } finally {
- if (_didIteratorError6) {
- throw _iteratorError6;
- }
- }
- }
- }
- return typesAddedToUnion;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any breaking
- * changes in the newSchema related to removing values from an enum type.
- */
- function findValuesRemovedFromEnums(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var valuesRemovedFromEnums = [];
- for (var _i12 = 0, _Object$keys12 = Object.keys(oldTypeMap); _i12 < _Object$keys12.length; _i12++) {
- var typeName = _Object$keys12[_i12];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isEnumType)(oldType) || !(0, _definition.isEnumType)(newType)) {
- continue;
- }
- var valuesInNewEnum = Object.create(null);
- var _iteratorNormalCompletion7 = true;
- var _didIteratorError7 = false;
- var _iteratorError7 = undefined;
- try {
- for (var _iterator7 = newType.getValues()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
- var value = _step7.value;
- valuesInNewEnum[value.name] = true;
- }
- } catch (err) {
- _didIteratorError7 = true;
- _iteratorError7 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
- _iterator7.return();
- }
- } finally {
- if (_didIteratorError7) {
- throw _iteratorError7;
- }
- }
- }
- var _iteratorNormalCompletion8 = true;
- var _didIteratorError8 = false;
- var _iteratorError8 = undefined;
- try {
- for (var _iterator8 = oldType.getValues()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
- var _value = _step8.value;
- if (!valuesInNewEnum[_value.name]) {
- valuesRemovedFromEnums.push({
- type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,
- description: "".concat(_value.name, " was removed from enum type ").concat(typeName, ".")
- });
- }
- }
- } catch (err) {
- _didIteratorError8 = true;
- _iteratorError8 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
- _iterator8.return();
- }
- } finally {
- if (_didIteratorError8) {
- throw _iteratorError8;
- }
- }
- }
- }
- return valuesRemovedFromEnums;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any dangerous
- * changes in the newSchema related to adding values to an enum type.
- */
- function findValuesAddedToEnums(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var valuesAddedToEnums = [];
- for (var _i13 = 0, _Object$keys13 = Object.keys(oldTypeMap); _i13 < _Object$keys13.length; _i13++) {
- var typeName = _Object$keys13[_i13];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isEnumType)(oldType) || !(0, _definition.isEnumType)(newType)) {
- continue;
- }
- var valuesInOldEnum = Object.create(null);
- var _iteratorNormalCompletion9 = true;
- var _didIteratorError9 = false;
- var _iteratorError9 = undefined;
- try {
- for (var _iterator9 = oldType.getValues()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
- var value = _step9.value;
- valuesInOldEnum[value.name] = true;
- }
- } catch (err) {
- _didIteratorError9 = true;
- _iteratorError9 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
- _iterator9.return();
- }
- } finally {
- if (_didIteratorError9) {
- throw _iteratorError9;
- }
- }
- }
- var _iteratorNormalCompletion10 = true;
- var _didIteratorError10 = false;
- var _iteratorError10 = undefined;
- try {
- for (var _iterator10 = newType.getValues()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
- var _value2 = _step10.value;
- if (!valuesInOldEnum[_value2.name]) {
- valuesAddedToEnums.push({
- type: DangerousChangeType.VALUE_ADDED_TO_ENUM,
- description: "".concat(_value2.name, " was added to enum type ").concat(typeName, ".")
- });
- }
- }
- } catch (err) {
- _didIteratorError10 = true;
- _iteratorError10 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
- _iterator10.return();
- }
- } finally {
- if (_didIteratorError10) {
- throw _iteratorError10;
- }
- }
- }
- }
- return valuesAddedToEnums;
- }
- function findInterfacesRemovedFromObjectTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- for (var _i14 = 0, _Object$keys14 = Object.keys(oldTypeMap); _i14 < _Object$keys14.length; _i14++) {
- var typeName = _Object$keys14[_i14];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isObjectType)(oldType) || !(0, _definition.isObjectType)(newType)) {
- continue;
- }
- var oldInterfaces = oldType.getInterfaces();
- var newInterfaces = newType.getInterfaces();
- var _iteratorNormalCompletion11 = true;
- var _didIteratorError11 = false;
- var _iteratorError11 = undefined;
- try {
- var _loop3 = function _loop3() {
- var oldInterface = _step11.value;
- if (!newInterfaces.some(function (int) {
- return int.name === oldInterface.name;
- })) {
- breakingChanges.push({
- type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT,
- description: "".concat(typeName, " no longer implements interface ") + "".concat(oldInterface.name, ".")
- });
- }
- };
- for (var _iterator11 = oldInterfaces[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
- _loop3();
- }
- } catch (err) {
- _didIteratorError11 = true;
- _iteratorError11 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion11 && _iterator11.return != null) {
- _iterator11.return();
- }
- } finally {
- if (_didIteratorError11) {
- throw _iteratorError11;
- }
- }
- }
- }
- return breakingChanges;
- }
- function findInterfacesAddedToObjectTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var interfacesAddedToObjectTypes = [];
- for (var _i15 = 0, _Object$keys15 = Object.keys(newTypeMap); _i15 < _Object$keys15.length; _i15++) {
- var typeName = _Object$keys15[_i15];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isObjectType)(oldType) || !(0, _definition.isObjectType)(newType)) {
- continue;
- }
- var oldInterfaces = oldType.getInterfaces();
- var newInterfaces = newType.getInterfaces();
- var _iteratorNormalCompletion12 = true;
- var _didIteratorError12 = false;
- var _iteratorError12 = undefined;
- try {
- var _loop4 = function _loop4() {
- var newInterface = _step12.value;
- if (!oldInterfaces.some(function (int) {
- return int.name === newInterface.name;
- })) {
- interfacesAddedToObjectTypes.push({
- type: DangerousChangeType.INTERFACE_ADDED_TO_OBJECT,
- description: "".concat(newInterface.name, " added to interfaces implemented ") + "by ".concat(typeName, ".")
- });
- }
- };
- for (var _iterator12 = newInterfaces[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
- _loop4();
- }
- } catch (err) {
- _didIteratorError12 = true;
- _iteratorError12 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion12 && _iterator12.return != null) {
- _iterator12.return();
- }
- } finally {
- if (_didIteratorError12) {
- throw _iteratorError12;
- }
- }
- }
- }
- return interfacesAddedToObjectTypes;
- }
- function findRemovedDirectives(oldSchema, newSchema) {
- var removedDirectives = [];
- var newSchemaDirectiveMap = getDirectiveMapForSchema(newSchema);
- var _iteratorNormalCompletion13 = true;
- var _didIteratorError13 = false;
- var _iteratorError13 = undefined;
- try {
- for (var _iterator13 = oldSchema.getDirectives()[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
- var directive = _step13.value;
- if (!newSchemaDirectiveMap[directive.name]) {
- removedDirectives.push({
- type: BreakingChangeType.DIRECTIVE_REMOVED,
- description: "".concat(directive.name, " was removed")
- });
- }
- }
- } catch (err) {
- _didIteratorError13 = true;
- _iteratorError13 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion13 && _iterator13.return != null) {
- _iterator13.return();
- }
- } finally {
- if (_didIteratorError13) {
- throw _iteratorError13;
- }
- }
- }
- return removedDirectives;
- }
- function findRemovedArgsForDirective(oldDirective, newDirective) {
- var removedArgs = [];
- var newArgMap = getArgumentMapForDirective(newDirective);
- var _iteratorNormalCompletion14 = true;
- var _didIteratorError14 = false;
- var _iteratorError14 = undefined;
- try {
- for (var _iterator14 = oldDirective.args[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {
- var arg = _step14.value;
- if (!newArgMap[arg.name]) {
- removedArgs.push(arg);
- }
- }
- } catch (err) {
- _didIteratorError14 = true;
- _iteratorError14 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion14 && _iterator14.return != null) {
- _iterator14.return();
- }
- } finally {
- if (_didIteratorError14) {
- throw _iteratorError14;
- }
- }
- }
- return removedArgs;
- }
- function findRemovedDirectiveArgs(oldSchema, newSchema) {
- var removedDirectiveArgs = [];
- var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema);
- var _iteratorNormalCompletion15 = true;
- var _didIteratorError15 = false;
- var _iteratorError15 = undefined;
- try {
- for (var _iterator15 = newSchema.getDirectives()[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) {
- var newDirective = _step15.value;
- var oldDirective = oldSchemaDirectiveMap[newDirective.name];
- if (!oldDirective) {
- continue;
- }
- var _iteratorNormalCompletion16 = true;
- var _didIteratorError16 = false;
- var _iteratorError16 = undefined;
- try {
- for (var _iterator16 = findRemovedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) {
- var arg = _step16.value;
- removedDirectiveArgs.push({
- type: BreakingChangeType.DIRECTIVE_ARG_REMOVED,
- description: "".concat(arg.name, " was removed from ").concat(newDirective.name)
- });
- }
- } catch (err) {
- _didIteratorError16 = true;
- _iteratorError16 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion16 && _iterator16.return != null) {
- _iterator16.return();
- }
- } finally {
- if (_didIteratorError16) {
- throw _iteratorError16;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError15 = true;
- _iteratorError15 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion15 && _iterator15.return != null) {
- _iterator15.return();
- }
- } finally {
- if (_didIteratorError15) {
- throw _iteratorError15;
- }
- }
- }
- return removedDirectiveArgs;
- }
- function findAddedArgsForDirective(oldDirective, newDirective) {
- var addedArgs = [];
- var oldArgMap = getArgumentMapForDirective(oldDirective);
- var _iteratorNormalCompletion17 = true;
- var _didIteratorError17 = false;
- var _iteratorError17 = undefined;
- try {
- for (var _iterator17 = newDirective.args[Symbol.iterator](), _step17; !(_iteratorNormalCompletion17 = (_step17 = _iterator17.next()).done); _iteratorNormalCompletion17 = true) {
- var arg = _step17.value;
- if (!oldArgMap[arg.name]) {
- addedArgs.push(arg);
- }
- }
- } catch (err) {
- _didIteratorError17 = true;
- _iteratorError17 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion17 && _iterator17.return != null) {
- _iterator17.return();
- }
- } finally {
- if (_didIteratorError17) {
- throw _iteratorError17;
- }
- }
- }
- return addedArgs;
- }
- function findAddedNonNullDirectiveArgs(oldSchema, newSchema) {
- var addedNonNullableArgs = [];
- var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema);
- var _iteratorNormalCompletion18 = true;
- var _didIteratorError18 = false;
- var _iteratorError18 = undefined;
- try {
- for (var _iterator18 = newSchema.getDirectives()[Symbol.iterator](), _step18; !(_iteratorNormalCompletion18 = (_step18 = _iterator18.next()).done); _iteratorNormalCompletion18 = true) {
- var newDirective = _step18.value;
- var oldDirective = oldSchemaDirectiveMap[newDirective.name];
- if (!oldDirective) {
- continue;
- }
- var _iteratorNormalCompletion19 = true;
- var _didIteratorError19 = false;
- var _iteratorError19 = undefined;
- try {
- for (var _iterator19 = findAddedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step19; !(_iteratorNormalCompletion19 = (_step19 = _iterator19.next()).done); _iteratorNormalCompletion19 = true) {
- var arg = _step19.value;
- if ((0, _definition.isRequiredArgument)(arg)) {
- addedNonNullableArgs.push({
- type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED,
- description: "A required arg ".concat(arg.name, " on directive ") + "".concat(newDirective.name, " was added")
- });
- }
- }
- } catch (err) {
- _didIteratorError19 = true;
- _iteratorError19 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion19 && _iterator19.return != null) {
- _iterator19.return();
- }
- } finally {
- if (_didIteratorError19) {
- throw _iteratorError19;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError18 = true;
- _iteratorError18 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion18 && _iterator18.return != null) {
- _iterator18.return();
- }
- } finally {
- if (_didIteratorError18) {
- throw _iteratorError18;
- }
- }
- }
- return addedNonNullableArgs;
- }
- function findRemovedLocationsForDirective(oldDirective, newDirective) {
- var removedLocations = [];
- var newLocationSet = new Set(newDirective.locations);
- var _iteratorNormalCompletion20 = true;
- var _didIteratorError20 = false;
- var _iteratorError20 = undefined;
- try {
- for (var _iterator20 = oldDirective.locations[Symbol.iterator](), _step20; !(_iteratorNormalCompletion20 = (_step20 = _iterator20.next()).done); _iteratorNormalCompletion20 = true) {
- var oldLocation = _step20.value;
- if (!newLocationSet.has(oldLocation)) {
- removedLocations.push(oldLocation);
- }
- }
- } catch (err) {
- _didIteratorError20 = true;
- _iteratorError20 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion20 && _iterator20.return != null) {
- _iterator20.return();
- }
- } finally {
- if (_didIteratorError20) {
- throw _iteratorError20;
- }
- }
- }
- return removedLocations;
- }
- function findRemovedDirectiveLocations(oldSchema, newSchema) {
- var removedLocations = [];
- var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema);
- var _iteratorNormalCompletion21 = true;
- var _didIteratorError21 = false;
- var _iteratorError21 = undefined;
- try {
- for (var _iterator21 = newSchema.getDirectives()[Symbol.iterator](), _step21; !(_iteratorNormalCompletion21 = (_step21 = _iterator21.next()).done); _iteratorNormalCompletion21 = true) {
- var newDirective = _step21.value;
- var oldDirective = oldSchemaDirectiveMap[newDirective.name];
- if (!oldDirective) {
- continue;
- }
- var _iteratorNormalCompletion22 = true;
- var _didIteratorError22 = false;
- var _iteratorError22 = undefined;
- try {
- for (var _iterator22 = findRemovedLocationsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step22; !(_iteratorNormalCompletion22 = (_step22 = _iterator22.next()).done); _iteratorNormalCompletion22 = true) {
- var location = _step22.value;
- removedLocations.push({
- type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED,
- description: "".concat(location, " was removed from ").concat(newDirective.name)
- });
- }
- } catch (err) {
- _didIteratorError22 = true;
- _iteratorError22 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion22 && _iterator22.return != null) {
- _iterator22.return();
- }
- } finally {
- if (_didIteratorError22) {
- throw _iteratorError22;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError21 = true;
- _iteratorError21 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion21 && _iterator21.return != null) {
- _iterator21.return();
- }
- } finally {
- if (_didIteratorError21) {
- throw _iteratorError21;
- }
- }
- }
- return removedLocations;
- }
- function getDirectiveMapForSchema(schema) {
- return (0, _keyMap.default)(schema.getDirectives(), function (dir) {
- return dir.name;
- });
- }
- function getArgumentMapForDirective(directive) {
- return (0, _keyMap.default)(directive.args, function (arg) {
- return arg.name;
- });
- }
- },{"../jsutils/inspect":32,"../jsutils/keyMap":38,"../polyfills/find":59,"../type/definition":68}],84:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.findDeprecatedUsages = findDeprecatedUsages;
- var _GraphQLError = require("../error/GraphQLError");
- var _visitor = require("../language/visitor");
- var _definition = require("../type/definition");
- var _TypeInfo = require("./TypeInfo");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * A validation rule which reports deprecated usages.
- *
- * Returns a list of GraphQLError instances describing each deprecated use.
- */
- function findDeprecatedUsages(schema, ast) {
- var errors = [];
- var typeInfo = new _TypeInfo.TypeInfo(schema);
- (0, _visitor.visit)(ast, (0, _visitor.visitWithTypeInfo)(typeInfo, {
- Field: function Field(node) {
- var fieldDef = typeInfo.getFieldDef();
- if (fieldDef && fieldDef.isDeprecated) {
- var parentType = typeInfo.getParentType();
- if (parentType) {
- var reason = fieldDef.deprecationReason;
- errors.push(new _GraphQLError.GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated.") + (reason ? ' ' + reason : ''), node));
- }
- }
- },
- EnumValue: function EnumValue(node) {
- var enumVal = typeInfo.getEnumValue();
- if (enumVal && enumVal.isDeprecated) {
- var type = (0, _definition.getNamedType)(typeInfo.getInputType());
- if (type) {
- var reason = enumVal.deprecationReason;
- errors.push(new _GraphQLError.GraphQLError("The enum value ".concat(type.name, ".").concat(enumVal.name, " is deprecated.") + (reason ? ' ' + reason : ''), node));
- }
- }
- }
- }));
- return errors;
- }
- },{"../error/GraphQLError":19,"../language/visitor":58,"../type/definition":68,"./TypeInfo":75}],85:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getOperationAST = getOperationAST;
- var _kinds = require("../language/kinds");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Returns an operation AST given a document AST and optionally an operation
- * name. If a name is not provided, an operation is only returned if only one is
- * provided in the document.
- */
- function getOperationAST(documentAST, operationName) {
- var operation = null;
- for (var i = 0; i < documentAST.definitions.length; i++) {
- var definition = documentAST.definitions[i];
- if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) {
- if (!operationName) {
- // If no operation name was provided, only return an Operation if there
- // is one defined in the document. Upon encountering the second, return
- // null.
- if (operation) {
- return null;
- }
- operation = definition;
- } else if (definition.name && definition.name.value === operationName) {
- return definition;
- }
- }
- }
- return operation;
- }
- },{"../language/kinds":51}],86:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getOperationRootType = getOperationRootType;
- var _GraphQLError = require("../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Extracts the root type of the operation from the schema.
- */
- function getOperationRootType(schema, operation) {
- if (operation.operation === 'query') {
- var queryType = schema.getQueryType();
- if (!queryType) {
- throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', operation);
- }
- return queryType;
- }
- if (operation.operation === 'mutation') {
- var mutationType = schema.getMutationType();
- if (!mutationType) {
- throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', operation);
- }
- return mutationType;
- }
- if (operation.operation === 'subscription') {
- var subscriptionType = schema.getSubscriptionType();
- if (!subscriptionType) {
- throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', operation);
- }
- return subscriptionType;
- }
- throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', operation);
- }
- },{"../error/GraphQLError":19}],87:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "getIntrospectionQuery", {
- enumerable: true,
- get: function get() {
- return _introspectionQuery.getIntrospectionQuery;
- }
- });
- Object.defineProperty(exports, "introspectionQuery", {
- enumerable: true,
- get: function get() {
- return _introspectionQuery.introspectionQuery;
- }
- });
- Object.defineProperty(exports, "getOperationAST", {
- enumerable: true,
- get: function get() {
- return _getOperationAST.getOperationAST;
- }
- });
- Object.defineProperty(exports, "getOperationRootType", {
- enumerable: true,
- get: function get() {
- return _getOperationRootType.getOperationRootType;
- }
- });
- Object.defineProperty(exports, "introspectionFromSchema", {
- enumerable: true,
- get: function get() {
- return _introspectionFromSchema.introspectionFromSchema;
- }
- });
- Object.defineProperty(exports, "buildClientSchema", {
- enumerable: true,
- get: function get() {
- return _buildClientSchema.buildClientSchema;
- }
- });
- Object.defineProperty(exports, "buildASTSchema", {
- enumerable: true,
- get: function get() {
- return _buildASTSchema.buildASTSchema;
- }
- });
- Object.defineProperty(exports, "buildSchema", {
- enumerable: true,
- get: function get() {
- return _buildASTSchema.buildSchema;
- }
- });
- Object.defineProperty(exports, "getDescription", {
- enumerable: true,
- get: function get() {
- return _buildASTSchema.getDescription;
- }
- });
- Object.defineProperty(exports, "extendSchema", {
- enumerable: true,
- get: function get() {
- return _extendSchema.extendSchema;
- }
- });
- Object.defineProperty(exports, "lexicographicSortSchema", {
- enumerable: true,
- get: function get() {
- return _lexicographicSortSchema.lexicographicSortSchema;
- }
- });
- Object.defineProperty(exports, "printSchema", {
- enumerable: true,
- get: function get() {
- return _schemaPrinter.printSchema;
- }
- });
- Object.defineProperty(exports, "printType", {
- enumerable: true,
- get: function get() {
- return _schemaPrinter.printType;
- }
- });
- Object.defineProperty(exports, "printIntrospectionSchema", {
- enumerable: true,
- get: function get() {
- return _schemaPrinter.printIntrospectionSchema;
- }
- });
- Object.defineProperty(exports, "typeFromAST", {
- enumerable: true,
- get: function get() {
- return _typeFromAST.typeFromAST;
- }
- });
- Object.defineProperty(exports, "valueFromAST", {
- enumerable: true,
- get: function get() {
- return _valueFromAST.valueFromAST;
- }
- });
- Object.defineProperty(exports, "valueFromASTUntyped", {
- enumerable: true,
- get: function get() {
- return _valueFromASTUntyped.valueFromASTUntyped;
- }
- });
- Object.defineProperty(exports, "astFromValue", {
- enumerable: true,
- get: function get() {
- return _astFromValue.astFromValue;
- }
- });
- Object.defineProperty(exports, "TypeInfo", {
- enumerable: true,
- get: function get() {
- return _TypeInfo.TypeInfo;
- }
- });
- Object.defineProperty(exports, "coerceValue", {
- enumerable: true,
- get: function get() {
- return _coerceValue.coerceValue;
- }
- });
- Object.defineProperty(exports, "isValidJSValue", {
- enumerable: true,
- get: function get() {
- return _isValidJSValue.isValidJSValue;
- }
- });
- Object.defineProperty(exports, "isValidLiteralValue", {
- enumerable: true,
- get: function get() {
- return _isValidLiteralValue.isValidLiteralValue;
- }
- });
- Object.defineProperty(exports, "concatAST", {
- enumerable: true,
- get: function get() {
- return _concatAST.concatAST;
- }
- });
- Object.defineProperty(exports, "separateOperations", {
- enumerable: true,
- get: function get() {
- return _separateOperations.separateOperations;
- }
- });
- Object.defineProperty(exports, "stripIgnoredCharacters", {
- enumerable: true,
- get: function get() {
- return _stripIgnoredCharacters.stripIgnoredCharacters;
- }
- });
- Object.defineProperty(exports, "isEqualType", {
- enumerable: true,
- get: function get() {
- return _typeComparators.isEqualType;
- }
- });
- Object.defineProperty(exports, "isTypeSubTypeOf", {
- enumerable: true,
- get: function get() {
- return _typeComparators.isTypeSubTypeOf;
- }
- });
- Object.defineProperty(exports, "doTypesOverlap", {
- enumerable: true,
- get: function get() {
- return _typeComparators.doTypesOverlap;
- }
- });
- Object.defineProperty(exports, "assertValidName", {
- enumerable: true,
- get: function get() {
- return _assertValidName.assertValidName;
- }
- });
- Object.defineProperty(exports, "isValidNameError", {
- enumerable: true,
- get: function get() {
- return _assertValidName.isValidNameError;
- }
- });
- Object.defineProperty(exports, "BreakingChangeType", {
- enumerable: true,
- get: function get() {
- return _findBreakingChanges.BreakingChangeType;
- }
- });
- Object.defineProperty(exports, "DangerousChangeType", {
- enumerable: true,
- get: function get() {
- return _findBreakingChanges.DangerousChangeType;
- }
- });
- Object.defineProperty(exports, "findBreakingChanges", {
- enumerable: true,
- get: function get() {
- return _findBreakingChanges.findBreakingChanges;
- }
- });
- Object.defineProperty(exports, "findDangerousChanges", {
- enumerable: true,
- get: function get() {
- return _findBreakingChanges.findDangerousChanges;
- }
- });
- Object.defineProperty(exports, "findDeprecatedUsages", {
- enumerable: true,
- get: function get() {
- return _findDeprecatedUsages.findDeprecatedUsages;
- }
- });
- var _introspectionQuery = require("./introspectionQuery");
- var _getOperationAST = require("./getOperationAST");
- var _getOperationRootType = require("./getOperationRootType");
- var _introspectionFromSchema = require("./introspectionFromSchema");
- var _buildClientSchema = require("./buildClientSchema");
- var _buildASTSchema = require("./buildASTSchema");
- var _extendSchema = require("./extendSchema");
- var _lexicographicSortSchema = require("./lexicographicSortSchema");
- var _schemaPrinter = require("./schemaPrinter");
- var _typeFromAST = require("./typeFromAST");
- var _valueFromAST = require("./valueFromAST");
- var _valueFromASTUntyped = require("./valueFromASTUntyped");
- var _astFromValue = require("./astFromValue");
- var _TypeInfo = require("./TypeInfo");
- var _coerceValue = require("./coerceValue");
- var _isValidJSValue = require("./isValidJSValue");
- var _isValidLiteralValue = require("./isValidLiteralValue");
- var _concatAST = require("./concatAST");
- var _separateOperations = require("./separateOperations");
- var _stripIgnoredCharacters = require("./stripIgnoredCharacters");
- var _typeComparators = require("./typeComparators");
- var _assertValidName = require("./assertValidName");
- var _findBreakingChanges = require("./findBreakingChanges");
- var _findDeprecatedUsages = require("./findDeprecatedUsages");
- },{"./TypeInfo":75,"./assertValidName":76,"./astFromValue":77,"./buildASTSchema":78,"./buildClientSchema":79,"./coerceValue":80,"./concatAST":81,"./extendSchema":82,"./findBreakingChanges":83,"./findDeprecatedUsages":84,"./getOperationAST":85,"./getOperationRootType":86,"./introspectionFromSchema":88,"./introspectionQuery":89,"./isValidJSValue":90,"./isValidLiteralValue":91,"./lexicographicSortSchema":92,"./schemaPrinter":93,"./separateOperations":94,"./stripIgnoredCharacters":95,"./typeComparators":96,"./typeFromAST":97,"./valueFromAST":98,"./valueFromASTUntyped":99}],88:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.introspectionFromSchema = introspectionFromSchema;
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _isPromise = _interopRequireDefault(require("../jsutils/isPromise"));
- var _execute = require("../execution/execute");
- var _parser = require("../language/parser");
- var _introspectionQuery = require("./introspectionQuery");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Build an IntrospectionQuery from a GraphQLSchema
- *
- * IntrospectionQuery is useful for utilities that care about type and field
- * relationships, but do not need to traverse through those relationships.
- *
- * This is the inverse of buildClientSchema. The primary use case is outside
- * of the server context, for instance when doing schema comparisons.
- */
- function introspectionFromSchema(schema, options) {
- var queryAST = (0, _parser.parse)((0, _introspectionQuery.getIntrospectionQuery)(options));
- var result = (0, _execute.execute)(schema, queryAST);
- !(!(0, _isPromise.default)(result) && !result.errors && result.data) ? (0, _invariant.default)(0) : void 0;
- return result.data;
- }
- },{"../execution/execute":25,"../jsutils/invariant":34,"../jsutils/isPromise":37,"../language/parser":54,"./introspectionQuery":89}],89:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getIntrospectionQuery = getIntrospectionQuery;
- exports.introspectionQuery = void 0;
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function getIntrospectionQuery(options) {
- var descriptions = !(options && options.descriptions === false);
- return "\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ".concat(descriptions ? 'description' : '', "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions ? 'description' : '', "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions ? 'description' : '', "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n ");
- }
- /**
- * Deprecated, call getIntrospectionQuery directly.
- *
- * This function will be removed in v15
- */
- var introspectionQuery = getIntrospectionQuery();
- exports.introspectionQuery = introspectionQuery;
- },{}],90:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isValidJSValue = isValidJSValue;
- var _coerceValue = require("./coerceValue");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* istanbul ignore file */
- /**
- * Deprecated. Use coerceValue() directly for richer information.
- *
- * This function will be removed in v15
- */
- function isValidJSValue(value, type) {
- var errors = (0, _coerceValue.coerceValue)(value, type).errors;
- return errors ? errors.map(function (error) {
- return error.message;
- }) : [];
- }
- },{"./coerceValue":80}],91:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isValidLiteralValue = isValidLiteralValue;
- var _TypeInfo = require("./TypeInfo");
- var _kinds = require("../language/kinds");
- var _visitor = require("../language/visitor");
- var _schema = require("../type/schema");
- var _ValuesOfCorrectType = require("../validation/rules/ValuesOfCorrectType");
- var _ValidationContext = require("../validation/ValidationContext");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Utility which determines if a value literal node is valid for an input type.
- *
- * Deprecated. Rely on validation for documents containing literal values.
- *
- * This function will be removed in v15
- */
- function isValidLiteralValue(type, valueNode) {
- var emptySchema = new _schema.GraphQLSchema({});
- var emptyDoc = {
- kind: _kinds.Kind.DOCUMENT,
- definitions: []
- };
- var typeInfo = new _TypeInfo.TypeInfo(emptySchema, undefined, type);
- var context = new _ValidationContext.ValidationContext(emptySchema, emptyDoc, typeInfo);
- var visitor = (0, _ValuesOfCorrectType.ValuesOfCorrectType)(context);
- (0, _visitor.visit)(valueNode, (0, _visitor.visitWithTypeInfo)(typeInfo, visitor));
- return context.getErrors();
- }
- },{"../language/kinds":51,"../language/visitor":58,"../type/schema":73,"../validation/ValidationContext":100,"../validation/rules/ValuesOfCorrectType":132,"./TypeInfo":75}],92:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.lexicographicSortSchema = lexicographicSortSchema;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _schema = require("../type/schema");
- var _directives = require("../type/directives");
- var _definition = require("../type/definition");
- var _introspection = require("../type/introspection");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * Sort GraphQLSchema.
- */
- function lexicographicSortSchema(schema) {
- var schemaConfig = schema.toConfig();
- var typeMap = (0, _keyValMap.default)(sortByName(schemaConfig.types), function (type) {
- return type.name;
- }, sortNamedType);
- return new _schema.GraphQLSchema(_objectSpread({}, schemaConfig, {
- types: (0, _objectValues.default)(typeMap),
- directives: sortByName(schemaConfig.directives).map(sortDirective),
- query: replaceMaybeType(schemaConfig.query),
- mutation: replaceMaybeType(schemaConfig.mutation),
- subscription: replaceMaybeType(schemaConfig.subscription)
- }));
- function replaceType(type) {
- if ((0, _definition.isListType)(type)) {
- return new _definition.GraphQLList(replaceType(type.ofType));
- } else if ((0, _definition.isNonNullType)(type)) {
- return new _definition.GraphQLNonNull(replaceType(type.ofType));
- }
- return replaceNamedType(type);
- }
- function replaceNamedType(type) {
- return typeMap[type.name];
- }
- function replaceMaybeType(maybeType) {
- return maybeType && replaceNamedType(maybeType);
- }
- function sortDirective(directive) {
- var config = directive.toConfig();
- return new _directives.GraphQLDirective(_objectSpread({}, config, {
- locations: sortBy(config.locations, function (x) {
- return x;
- }),
- args: sortArgs(config.args)
- }));
- }
- function sortArgs(args) {
- return sortObjMap(args, function (arg) {
- return _objectSpread({}, arg, {
- type: replaceType(arg.type)
- });
- });
- }
- function sortFields(fieldsMap) {
- return sortObjMap(fieldsMap, function (field) {
- return _objectSpread({}, field, {
- type: replaceType(field.type),
- args: sortArgs(field.args)
- });
- });
- }
- function sortInputFields(fieldsMap) {
- return sortObjMap(fieldsMap, function (field) {
- return _objectSpread({}, field, {
- type: replaceType(field.type)
- });
- });
- }
- function sortTypes(arr) {
- return sortByName(arr).map(replaceNamedType);
- }
- function sortNamedType(type) {
- if ((0, _definition.isScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) {
- return type;
- } else if ((0, _definition.isObjectType)(type)) {
- var config = type.toConfig();
- return new _definition.GraphQLObjectType(_objectSpread({}, config, {
- interfaces: function interfaces() {
- return sortTypes(config.interfaces);
- },
- fields: function fields() {
- return sortFields(config.fields);
- }
- }));
- } else if ((0, _definition.isInterfaceType)(type)) {
- var _config = type.toConfig();
- return new _definition.GraphQLInterfaceType(_objectSpread({}, _config, {
- fields: function fields() {
- return sortFields(_config.fields);
- }
- }));
- } else if ((0, _definition.isUnionType)(type)) {
- var _config2 = type.toConfig();
- return new _definition.GraphQLUnionType(_objectSpread({}, _config2, {
- types: function types() {
- return sortTypes(_config2.types);
- }
- }));
- } else if ((0, _definition.isEnumType)(type)) {
- var _config3 = type.toConfig();
- return new _definition.GraphQLEnumType(_objectSpread({}, _config3, {
- values: sortObjMap(_config3.values)
- }));
- } else if ((0, _definition.isInputObjectType)(type)) {
- var _config4 = type.toConfig();
- return new _definition.GraphQLInputObjectType(_objectSpread({}, _config4, {
- fields: function fields() {
- return sortInputFields(_config4.fields);
- }
- }));
- } // Not reachable. All possible types have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected type: \"".concat((0, _inspect.default)(type), "\"."));
- }
- }
- function sortObjMap(map, sortValueFn) {
- var sortedMap = Object.create(null);
- var sortedKeys = sortBy(Object.keys(map), function (x) {
- return x;
- });
- for (var _i = 0, _sortedKeys = sortedKeys; _i < _sortedKeys.length; _i++) {
- var key = _sortedKeys[_i];
- var value = map[key];
- sortedMap[key] = sortValueFn ? sortValueFn(value) : value;
- }
- return sortedMap;
- }
- function sortByName(array) {
- return sortBy(array, function (obj) {
- return obj.name;
- });
- }
- function sortBy(array, mapToKey) {
- return array.slice().sort(function (obj1, obj2) {
- var key1 = mapToKey(obj1);
- var key2 = mapToKey(obj2);
- return key1.localeCompare(key2);
- });
- }
- },{"../jsutils/inspect":32,"../jsutils/keyValMap":39,"../polyfills/objectValues":64,"../type/definition":68,"../type/directives":69,"../type/introspection":71,"../type/schema":73}],93:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.printSchema = printSchema;
- exports.printIntrospectionSchema = printIntrospectionSchema;
- exports.printType = printType;
- var _flatMap = _interopRequireDefault(require("../polyfills/flatMap"));
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _astFromValue = require("../utilities/astFromValue");
- var _printer = require("../language/printer");
- var _blockString = require("../language/blockString");
- var _definition = require("../type/definition");
- var _scalars = require("../type/scalars");
- var _directives = require("../type/directives");
- var _introspection = require("../type/introspection");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Accepts options as a second argument:
- *
- * - commentDescriptions:
- * Provide true to use preceding comments as the description.
- *
- */
- function printSchema(schema, options) {
- return printFilteredSchema(schema, function (n) {
- return !(0, _directives.isSpecifiedDirective)(n);
- }, isDefinedType, options);
- }
- function printIntrospectionSchema(schema, options) {
- return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType, options);
- }
- function isDefinedType(type) {
- return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type);
- }
- function printFilteredSchema(schema, directiveFilter, typeFilter, options) {
- var directives = schema.getDirectives().filter(directiveFilter);
- var typeMap = schema.getTypeMap();
- var types = (0, _objectValues.default)(typeMap).sort(function (type1, type2) {
- return type1.name.localeCompare(type2.name);
- }).filter(typeFilter);
- return [printSchemaDefinition(schema)].concat(directives.map(function (directive) {
- return printDirective(directive, options);
- }), types.map(function (type) {
- return printType(type, options);
- })).filter(Boolean).join('\n\n') + '\n';
- }
- function printSchemaDefinition(schema) {
- if (isSchemaOfCommonNames(schema)) {
- return;
- }
- var operationTypes = [];
- var queryType = schema.getQueryType();
- if (queryType) {
- operationTypes.push(" query: ".concat(queryType.name));
- }
- var mutationType = schema.getMutationType();
- if (mutationType) {
- operationTypes.push(" mutation: ".concat(mutationType.name));
- }
- var subscriptionType = schema.getSubscriptionType();
- if (subscriptionType) {
- operationTypes.push(" subscription: ".concat(subscriptionType.name));
- }
- return "schema {\n".concat(operationTypes.join('\n'), "\n}");
- }
- /**
- * GraphQL schema define root types for each type of operation. These types are
- * the same as any other type and can be named in any manner, however there is
- * a common naming convention:
- *
- * schema {
- * query: Query
- * mutation: Mutation
- * }
- *
- * When using this naming convention, the schema description can be omitted.
- */
- function isSchemaOfCommonNames(schema) {
- var queryType = schema.getQueryType();
- if (queryType && queryType.name !== 'Query') {
- return false;
- }
- var mutationType = schema.getMutationType();
- if (mutationType && mutationType.name !== 'Mutation') {
- return false;
- }
- var subscriptionType = schema.getSubscriptionType();
- if (subscriptionType && subscriptionType.name !== 'Subscription') {
- return false;
- }
- return true;
- }
- function printType(type, options) {
- if ((0, _definition.isScalarType)(type)) {
- return printScalar(type, options);
- } else if ((0, _definition.isObjectType)(type)) {
- return printObject(type, options);
- } else if ((0, _definition.isInterfaceType)(type)) {
- return printInterface(type, options);
- } else if ((0, _definition.isUnionType)(type)) {
- return printUnion(type, options);
- } else if ((0, _definition.isEnumType)(type)) {
- return printEnum(type, options);
- } else if ((0, _definition.isInputObjectType)(type)) {
- return printInputObject(type, options);
- } // Not reachable. All possible types have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected type: \"".concat((0, _inspect.default)(type), "\"."));
- }
- function printScalar(type, options) {
- return printDescription(options, type) + "scalar ".concat(type.name);
- }
- function printObject(type, options) {
- var interfaces = type.getInterfaces();
- var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) {
- return i.name;
- }).join(' & ') : '';
- return printDescription(options, type) + "type ".concat(type.name).concat(implementedInterfaces) + printFields(options, type);
- }
- function printInterface(type, options) {
- return printDescription(options, type) + "interface ".concat(type.name) + printFields(options, type);
- }
- function printUnion(type, options) {
- var types = type.getTypes();
- var possibleTypes = types.length ? ' = ' + types.join(' | ') : '';
- return printDescription(options, type) + 'union ' + type.name + possibleTypes;
- }
- function printEnum(type, options) {
- var values = type.getValues().map(function (value, i) {
- return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value);
- });
- return printDescription(options, type) + "enum ".concat(type.name) + printBlock(values);
- }
- function printInputObject(type, options) {
- var fields = (0, _objectValues.default)(type.getFields()).map(function (f, i) {
- return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f);
- });
- return printDescription(options, type) + "input ".concat(type.name) + printBlock(fields);
- }
- function printFields(options, type) {
- var fields = (0, _objectValues.default)(type.getFields()).map(function (f, i) {
- return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f);
- });
- return printBlock(fields);
- }
- function printBlock(items) {
- return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : '';
- }
- function printArgs(options, args) {
- var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
- if (args.length === 0) {
- return '';
- } // If every arg does not have a description, print them on one line.
- if (args.every(function (arg) {
- return !arg.description;
- })) {
- return '(' + args.map(printInputValue).join(', ') + ')';
- }
- return '(\n' + args.map(function (arg, i) {
- return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg);
- }).join('\n') + '\n' + indentation + ')';
- }
- function printInputValue(arg) {
- var defaultAST = (0, _astFromValue.astFromValue)(arg.defaultValue, arg.type);
- var argDecl = arg.name + ': ' + String(arg.type);
- if (defaultAST) {
- argDecl += " = ".concat((0, _printer.print)(defaultAST));
- }
- return argDecl;
- }
- function printDirective(directive, options) {
- return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + ' on ' + directive.locations.join(' | ');
- }
- function printDeprecated(fieldOrEnumVal) {
- if (!fieldOrEnumVal.isDeprecated) {
- return '';
- }
- var reason = fieldOrEnumVal.deprecationReason;
- var reasonAST = (0, _astFromValue.astFromValue)(reason, _scalars.GraphQLString);
- if (reasonAST && reason !== '' && reason !== _directives.DEFAULT_DEPRECATION_REASON) {
- return ' @deprecated(reason: ' + (0, _printer.print)(reasonAST) + ')';
- }
- return ' @deprecated';
- }
- function printDescription(options, def) {
- var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
- var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
- if (!def.description) {
- return '';
- }
- var lines = descriptionLines(def.description, 120 - indentation.length);
- if (options && options.commentDescriptions) {
- return printDescriptionWithComments(lines, indentation, firstInBlock);
- }
- var text = lines.join('\n');
- var preferMultipleLines = text.length > 70;
- var blockString = (0, _blockString.printBlockString)(text, '', preferMultipleLines);
- var prefix = indentation && !firstInBlock ? '\n' + indentation : indentation;
- return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n';
- }
- function printDescriptionWithComments(lines, indentation, firstInBlock) {
- var description = indentation && !firstInBlock ? '\n' : '';
- for (var i = 0; i < lines.length; i++) {
- if (lines[i] === '') {
- description += indentation + '#\n';
- } else {
- description += indentation + '# ' + lines[i] + '\n';
- }
- }
- return description;
- }
- function descriptionLines(description, maxLen) {
- var rawLines = description.split('\n');
- return (0, _flatMap.default)(rawLines, function (line) {
- if (line.length < maxLen + 5) {
- return line;
- } // For > 120 character long lines, cut at space boundaries into sublines
- // of ~80 chars.
- return breakLine(line, maxLen);
- });
- }
- function breakLine(line, maxLen) {
- var parts = line.split(new RegExp("((?: |^).{15,".concat(maxLen - 40, "}(?= |$))")));
- if (parts.length < 4) {
- return [line];
- }
- var sublines = [parts[0] + parts[1] + parts[2]];
- for (var i = 3; i < parts.length; i += 2) {
- sublines.push(parts[i].slice(1) + parts[i + 1]);
- }
- return sublines;
- }
- },{"../jsutils/inspect":32,"../language/blockString":48,"../language/printer":56,"../polyfills/flatMap":60,"../polyfills/objectValues":64,"../type/definition":68,"../type/directives":69,"../type/introspection":71,"../type/scalars":72,"../utilities/astFromValue":77}],94:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.separateOperations = separateOperations;
- var _visitor = require("../language/visitor");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * separateOperations accepts a single AST document which may contain many
- * operations and fragments and returns a collection of AST documents each of
- * which contains a single operation as well the fragment definitions it
- * refers to.
- */
- function separateOperations(documentAST) {
- var operations = [];
- var fragments = Object.create(null);
- var positions = new Map();
- var depGraph = Object.create(null);
- var fromName;
- var idx = 0; // Populate metadata and build a dependency graph.
- (0, _visitor.visit)(documentAST, {
- OperationDefinition: function OperationDefinition(node) {
- fromName = opName(node);
- operations.push(node);
- positions.set(node, idx++);
- },
- FragmentDefinition: function FragmentDefinition(node) {
- fromName = node.name.value;
- fragments[fromName] = node;
- positions.set(node, idx++);
- },
- FragmentSpread: function FragmentSpread(node) {
- var toName = node.name.value;
- (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true;
- }
- }); // For each operation, produce a new synthesized AST which includes only what
- // is necessary for completing that operation.
- var separatedDocumentASTs = Object.create(null);
- for (var _i = 0, _operations = operations; _i < _operations.length; _i++) {
- var operation = _operations[_i];
- var operationName = opName(operation);
- var dependencies = Object.create(null);
- collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted
- // to retain the same order as the original document.
- var definitions = [operation];
- for (var _i2 = 0, _Object$keys = Object.keys(dependencies); _i2 < _Object$keys.length; _i2++) {
- var name = _Object$keys[_i2];
- definitions.push(fragments[name]);
- }
- definitions.sort(function (n1, n2) {
- return (positions.get(n1) || 0) - (positions.get(n2) || 0);
- });
- separatedDocumentASTs[operationName] = {
- kind: 'Document',
- definitions: definitions
- };
- }
- return separatedDocumentASTs;
- }
- // Provides the empty string for anonymous operations.
- function opName(operation) {
- return operation.name ? operation.name.value : '';
- } // From a dependency graph, collects a list of transitive dependencies by
- // recursing through a dependency graph.
- function collectTransitiveDependencies(collected, depGraph, fromName) {
- var immediateDeps = depGraph[fromName];
- if (immediateDeps) {
- for (var _i3 = 0, _Object$keys2 = Object.keys(immediateDeps); _i3 < _Object$keys2.length; _i3++) {
- var toName = _Object$keys2[_i3];
- if (!collected[toName]) {
- collected[toName] = true;
- collectTransitiveDependencies(collected, depGraph, toName);
- }
- }
- }
- }
- },{"../language/visitor":58}],95:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.stripIgnoredCharacters = stripIgnoredCharacters;
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _source = require("../language/source");
- var _lexer = require("../language/lexer");
- var _blockString = require("../language/blockString");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Strips characters that are not significant to the validity or execution
- * of a GraphQL document:
- * - UnicodeBOM
- * - WhiteSpace
- * - LineTerminator
- * - Comment
- * - Comma
- * - BlockString indentation
- *
- * Note: It is required to have a delimiter character between neighboring
- * non-punctuator tokens and this function always uses single space as delimiter.
- *
- * It is guaranteed that both input and output documents if parsed would result
- * in the exact same AST except for nodes location.
- *
- * Warning: It is guaranteed that this function will always produce stable results.
- * However, it's not guaranteed that it will stay the same between different
- * releases due to bugfixes or changes in the GraphQL specification.
- *
- * Query example:
- *
- * query SomeQuery($foo: String!, $bar: String) {
- * someField(foo: $foo, bar: $bar) {
- * a
- * b {
- * c
- * d
- * }
- * }
- * }
- *
- * Becomes:
- *
- * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}
- *
- * SDL example:
- *
- * """
- * Type description
- * """
- * type Foo {
- * """
- * Field description
- * """
- * bar: String
- * }
- *
- * Becomes:
- *
- * """Type description""" type Foo{"""Field description""" bar:String}
- */
- function stripIgnoredCharacters(source) {
- var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
- if (!(sourceObj instanceof _source.Source)) {
- throw new TypeError("Must provide string or Source. Received: ".concat((0, _inspect.default)(sourceObj)));
- }
- var body = sourceObj.body;
- var lexer = (0, _lexer.createLexer)(sourceObj);
- var strippedBody = '';
- var wasLastAddedTokenNonPunctuator = false;
- while (lexer.advance().kind !== _lexer.TokenKind.EOF) {
- var currentToken = lexer.token;
- var tokenKind = currentToken.kind;
- /**
- * Every two non-punctuator tokens should have space between them.
- * Also prevent case of non-punctuator token following by spread resulting
- * in invalid token (e.g. `1...` is invalid Float token).
- */
- var isNonPunctuator = !(0, _lexer.isPunctuatorToken)(currentToken);
- if (wasLastAddedTokenNonPunctuator) {
- if (isNonPunctuator || currentToken.kind === _lexer.TokenKind.SPREAD) {
- strippedBody += ' ';
- }
- }
- var tokenBody = body.slice(currentToken.start, currentToken.end);
- if (tokenKind === _lexer.TokenKind.BLOCK_STRING) {
- strippedBody += dedentBlockString(tokenBody);
- } else {
- strippedBody += tokenBody;
- }
- wasLastAddedTokenNonPunctuator = isNonPunctuator;
- }
- return strippedBody;
- }
- function dedentBlockString(blockStr) {
- // skip leading and trailing triple quotations
- var rawStr = blockStr.slice(3, -3);
- var body = (0, _blockString.dedentBlockStringValue)(rawStr);
- var lines = body.split(/\r\n|[\n\r]/g);
- if ((0, _blockString.getBlockStringIndentation)(lines) > 0) {
- body = '\n' + body;
- }
- var lastChar = body[body.length - 1];
- var hasTrailingQuote = lastChar === '"' && body.slice(-4) !== '\\"""';
- if (hasTrailingQuote || lastChar === '\\') {
- body += '\n';
- }
- return '"""' + body + '"""';
- }
- },{"../jsutils/inspect":32,"../language/blockString":48,"../language/lexer":52,"../language/source":57}],96:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isEqualType = isEqualType;
- exports.isTypeSubTypeOf = isTypeSubTypeOf;
- exports.doTypesOverlap = doTypesOverlap;
- var _definition = require("../type/definition");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Provided two types, return true if the types are equal (invariant).
- */
- function isEqualType(typeA, typeB) {
- // Equivalent types are equal.
- if (typeA === typeB) {
- return true;
- } // If either type is non-null, the other must also be non-null.
- if ((0, _definition.isNonNullType)(typeA) && (0, _definition.isNonNullType)(typeB)) {
- return isEqualType(typeA.ofType, typeB.ofType);
- } // If either type is a list, the other must also be a list.
- if ((0, _definition.isListType)(typeA) && (0, _definition.isListType)(typeB)) {
- return isEqualType(typeA.ofType, typeB.ofType);
- } // Otherwise the types are not equal.
- return false;
- }
- /**
- * Provided a type and a super type, return true if the first type is either
- * equal or a subset of the second super type (covariant).
- */
- function isTypeSubTypeOf(schema, maybeSubType, superType) {
- // Equivalent type is a valid subtype
- if (maybeSubType === superType) {
- return true;
- } // If superType is non-null, maybeSubType must also be non-null.
- if ((0, _definition.isNonNullType)(superType)) {
- if ((0, _definition.isNonNullType)(maybeSubType)) {
- return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
- }
- return false;
- }
- if ((0, _definition.isNonNullType)(maybeSubType)) {
- // If superType is nullable, maybeSubType may be non-null or nullable.
- return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);
- } // If superType type is a list, maybeSubType type must also be a list.
- if ((0, _definition.isListType)(superType)) {
- if ((0, _definition.isListType)(maybeSubType)) {
- return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
- }
- return false;
- }
- if ((0, _definition.isListType)(maybeSubType)) {
- // If superType is not a list, maybeSubType must also be not a list.
- return false;
- } // If superType type is an abstract type, maybeSubType type may be a currently
- // possible object type.
- if ((0, _definition.isAbstractType)(superType) && (0, _definition.isObjectType)(maybeSubType) && schema.isPossibleType(superType, maybeSubType)) {
- return true;
- } // Otherwise, the child type is not a valid subtype of the parent type.
- return false;
- }
- /**
- * Provided two composite types, determine if they "overlap". Two composite
- * types overlap when the Sets of possible concrete types for each intersect.
- *
- * This is often used to determine if a fragment of a given type could possibly
- * be visited in a context of another type.
- *
- * This function is commutative.
- */
- function doTypesOverlap(schema, typeA, typeB) {
- // Equivalent types overlap
- if (typeA === typeB) {
- return true;
- }
- if ((0, _definition.isAbstractType)(typeA)) {
- if ((0, _definition.isAbstractType)(typeB)) {
- // If both types are abstract, then determine if there is any intersection
- // between possible concrete types of each.
- return schema.getPossibleTypes(typeA).some(function (type) {
- return schema.isPossibleType(typeB, type);
- });
- } // Determine if the latter type is a possible concrete type of the former.
- return schema.isPossibleType(typeA, typeB);
- }
- if ((0, _definition.isAbstractType)(typeB)) {
- // Determine if the former type is a possible concrete type of the latter.
- return schema.isPossibleType(typeB, typeA);
- } // Otherwise the types do not overlap.
- return false;
- }
- },{"../type/definition":68}],97:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.typeFromAST = typeFromAST;
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _kinds = require("../language/kinds");
- var _definition = require("../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function typeFromAST(schema, typeNode) {
- /* eslint-enable no-redeclare */
- var innerType;
- if (typeNode.kind === _kinds.Kind.LIST_TYPE) {
- innerType = typeFromAST(schema, typeNode.type);
- return innerType && (0, _definition.GraphQLList)(innerType);
- }
- if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) {
- innerType = typeFromAST(schema, typeNode.type);
- return innerType && (0, _definition.GraphQLNonNull)(innerType);
- }
- if (typeNode.kind === _kinds.Kind.NAMED_TYPE) {
- return schema.getType(typeNode.name.value);
- } // Not reachable. All possible type nodes have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected type node: \"".concat((0, _inspect.default)(typeNode), "\"."));
- }
- },{"../jsutils/inspect":32,"../language/kinds":51,"../type/definition":68}],98:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.valueFromAST = valueFromAST;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _kinds = require("../language/kinds");
- var _definition = require("../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Produces a JavaScript value given a GraphQL Value AST.
- *
- * A GraphQL type must be provided, which will be used to interpret different
- * GraphQL Value literals.
- *
- * Returns `undefined` when the value could not be validly coerced according to
- * the provided type.
- *
- * | GraphQL Value | JSON Value |
- * | -------------------- | ------------- |
- * | Input Object | Object |
- * | List | Array |
- * | Boolean | Boolean |
- * | String | String |
- * | Int / Float | Number |
- * | Enum Value | Mixed |
- * | NullValue | null |
- *
- */
- function valueFromAST(valueNode, type, variables) {
- if (!valueNode) {
- // When there is no node, then there is also no value.
- // Importantly, this is different from returning the value null.
- return;
- }
- if ((0, _definition.isNonNullType)(type)) {
- if (valueNode.kind === _kinds.Kind.NULL) {
- return; // Invalid: intentionally return no value.
- }
- return valueFromAST(valueNode, type.ofType, variables);
- }
- if (valueNode.kind === _kinds.Kind.NULL) {
- // This is explicitly returning the value null.
- return null;
- }
- if (valueNode.kind === _kinds.Kind.VARIABLE) {
- var variableName = valueNode.name.value;
- if (!variables || (0, _isInvalid.default)(variables[variableName])) {
- // No valid return value.
- return;
- }
- var variableValue = variables[variableName];
- if (variableValue === null && (0, _definition.isNonNullType)(type)) {
- return; // Invalid: intentionally return no value.
- } // Note: This does no further checking that this variable is correct.
- // This assumes that this query has been validated and the variable
- // usage here is of the correct type.
- return variableValue;
- }
- if ((0, _definition.isListType)(type)) {
- var itemType = type.ofType;
- if (valueNode.kind === _kinds.Kind.LIST) {
- var coercedValues = [];
- var itemNodes = valueNode.values;
- for (var i = 0; i < itemNodes.length; i++) {
- if (isMissingVariable(itemNodes[i], variables)) {
- // If an array contains a missing variable, it is either coerced to
- // null or if the item type is non-null, it considered invalid.
- if ((0, _definition.isNonNullType)(itemType)) {
- return; // Invalid: intentionally return no value.
- }
- coercedValues.push(null);
- } else {
- var itemValue = valueFromAST(itemNodes[i], itemType, variables);
- if ((0, _isInvalid.default)(itemValue)) {
- return; // Invalid: intentionally return no value.
- }
- coercedValues.push(itemValue);
- }
- }
- return coercedValues;
- }
- var coercedValue = valueFromAST(valueNode, itemType, variables);
- if ((0, _isInvalid.default)(coercedValue)) {
- return; // Invalid: intentionally return no value.
- }
- return [coercedValue];
- }
- if ((0, _definition.isInputObjectType)(type)) {
- if (valueNode.kind !== _kinds.Kind.OBJECT) {
- return; // Invalid: intentionally return no value.
- }
- var coercedObj = Object.create(null);
- var fieldNodes = (0, _keyMap.default)(valueNode.fields, function (field) {
- return field.name.value;
- });
- var fields = (0, _objectValues.default)(type.getFields());
- for (var _i = 0; _i < fields.length; _i++) {
- var field = fields[_i];
- var fieldNode = fieldNodes[field.name];
- if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
- if (field.defaultValue !== undefined) {
- coercedObj[field.name] = field.defaultValue;
- } else if ((0, _definition.isNonNullType)(field.type)) {
- return; // Invalid: intentionally return no value.
- }
- continue;
- }
- var fieldValue = valueFromAST(fieldNode.value, field.type, variables);
- if ((0, _isInvalid.default)(fieldValue)) {
- return; // Invalid: intentionally return no value.
- }
- coercedObj[field.name] = fieldValue;
- }
- return coercedObj;
- }
- if ((0, _definition.isEnumType)(type)) {
- if (valueNode.kind !== _kinds.Kind.ENUM) {
- return; // Invalid: intentionally return no value.
- }
- var enumValue = type.getValue(valueNode.value);
- if (!enumValue) {
- return; // Invalid: intentionally return no value.
- }
- return enumValue.value;
- }
- if ((0, _definition.isScalarType)(type)) {
- // Scalars fulfill parsing a literal value via parseLiteral().
- // Invalid values represent a failure to parse correctly, in which case
- // no value is returned.
- var result;
- try {
- result = type.parseLiteral(valueNode, variables);
- } catch (_error) {
- return; // Invalid: intentionally return no value.
- }
- if ((0, _isInvalid.default)(result)) {
- return; // Invalid: intentionally return no value.
- }
- return result;
- } // Not reachable. All possible input types have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected input type: \"".concat((0, _inspect.default)(type), "\"."));
- } // Returns true if the provided valueNode is a variable which is not defined
- // in the set of variables.
- function isMissingVariable(valueNode, variables) {
- return valueNode.kind === _kinds.Kind.VARIABLE && (!variables || (0, _isInvalid.default)(variables[valueNode.name.value]));
- }
- },{"../jsutils/inspect":32,"../jsutils/isInvalid":35,"../jsutils/keyMap":38,"../language/kinds":51,"../polyfills/objectValues":64,"../type/definition":68}],99:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.valueFromASTUntyped = valueFromASTUntyped;
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _kinds = require("../language/kinds");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Produces a JavaScript value given a GraphQL Value AST.
- *
- * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value
- * will reflect the provided GraphQL value AST.
- *
- * | GraphQL Value | JavaScript Value |
- * | -------------------- | ---------------- |
- * | Input Object | Object |
- * | List | Array |
- * | Boolean | Boolean |
- * | String / Enum | String |
- * | Int / Float | Number |
- * | Null | null |
- *
- */
- function valueFromASTUntyped(valueNode, variables) {
- switch (valueNode.kind) {
- case _kinds.Kind.NULL:
- return null;
- case _kinds.Kind.INT:
- return parseInt(valueNode.value, 10);
- case _kinds.Kind.FLOAT:
- return parseFloat(valueNode.value);
- case _kinds.Kind.STRING:
- case _kinds.Kind.ENUM:
- case _kinds.Kind.BOOLEAN:
- return valueNode.value;
- case _kinds.Kind.LIST:
- return valueNode.values.map(function (node) {
- return valueFromASTUntyped(node, variables);
- });
- case _kinds.Kind.OBJECT:
- return (0, _keyValMap.default)(valueNode.fields, function (field) {
- return field.name.value;
- }, function (field) {
- return valueFromASTUntyped(field.value, variables);
- });
- case _kinds.Kind.VARIABLE:
- {
- var variableName = valueNode.name.value;
- return variables && !(0, _isInvalid.default)(variables[variableName]) ? variables[variableName] : undefined;
- }
- } // Not reachable. All possible value nodes have been considered.
- /* istanbul ignore next */
- throw new Error("Unexpected value node: \"".concat((0, _inspect.default)(valueNode), "\"."));
- }
- },{"../jsutils/inspect":32,"../jsutils/isInvalid":35,"../jsutils/keyValMap":39,"../language/kinds":51}],100:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = void 0;
- var _visitor = require("../language/visitor");
- var _kinds = require("../language/kinds");
- var _TypeInfo = require("../utilities/TypeInfo");
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- /**
- * An instance of this class is passed as the "this" context to all validators,
- * allowing access to commonly useful contextual information from within a
- * validation rule.
- */
- var ASTValidationContext =
- /*#__PURE__*/
- function () {
- function ASTValidationContext(ast) {
- this._ast = ast;
- this._errors = [];
- this._fragments = undefined;
- this._fragmentSpreads = new Map();
- this._recursivelyReferencedFragments = new Map();
- }
- var _proto = ASTValidationContext.prototype;
- _proto.reportError = function reportError(error) {
- this._errors.push(error);
- };
- _proto.getErrors = function getErrors() {
- return this._errors;
- };
- _proto.getDocument = function getDocument() {
- return this._ast;
- };
- _proto.getFragment = function getFragment(name) {
- var fragments = this._fragments;
- if (!fragments) {
- this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) {
- if (statement.kind === _kinds.Kind.FRAGMENT_DEFINITION) {
- frags[statement.name.value] = statement;
- }
- return frags;
- }, Object.create(null));
- }
- return fragments[name];
- };
- _proto.getFragmentSpreads = function getFragmentSpreads(node) {
- var spreads = this._fragmentSpreads.get(node);
- if (!spreads) {
- spreads = [];
- var setsToVisit = [node];
- while (setsToVisit.length !== 0) {
- var set = setsToVisit.pop();
- for (var i = 0; i < set.selections.length; i++) {
- var selection = set.selections[i];
- if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) {
- spreads.push(selection);
- } else if (selection.selectionSet) {
- setsToVisit.push(selection.selectionSet);
- }
- }
- }
- this._fragmentSpreads.set(node, spreads);
- }
- return spreads;
- };
- _proto.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) {
- var fragments = this._recursivelyReferencedFragments.get(operation);
- if (!fragments) {
- fragments = [];
- var collectedNames = Object.create(null);
- var nodesToVisit = [operation.selectionSet];
- while (nodesToVisit.length !== 0) {
- var node = nodesToVisit.pop();
- var spreads = this.getFragmentSpreads(node);
- for (var i = 0; i < spreads.length; i++) {
- var fragName = spreads[i].name.value;
- if (collectedNames[fragName] !== true) {
- collectedNames[fragName] = true;
- var fragment = this.getFragment(fragName);
- if (fragment) {
- fragments.push(fragment);
- nodesToVisit.push(fragment.selectionSet);
- }
- }
- }
- }
- this._recursivelyReferencedFragments.set(operation, fragments);
- }
- return fragments;
- };
- return ASTValidationContext;
- }();
- exports.ASTValidationContext = ASTValidationContext;
- var SDLValidationContext =
- /*#__PURE__*/
- function (_ASTValidationContext) {
- _inheritsLoose(SDLValidationContext, _ASTValidationContext);
- function SDLValidationContext(ast, schema) {
- var _this;
- _this = _ASTValidationContext.call(this, ast) || this;
- _this._schema = schema;
- return _this;
- }
- var _proto2 = SDLValidationContext.prototype;
- _proto2.getSchema = function getSchema() {
- return this._schema;
- };
- return SDLValidationContext;
- }(ASTValidationContext);
- exports.SDLValidationContext = SDLValidationContext;
- var ValidationContext =
- /*#__PURE__*/
- function (_ASTValidationContext2) {
- _inheritsLoose(ValidationContext, _ASTValidationContext2);
- function ValidationContext(schema, ast, typeInfo) {
- var _this2;
- _this2 = _ASTValidationContext2.call(this, ast) || this;
- _this2._schema = schema;
- _this2._typeInfo = typeInfo;
- _this2._variableUsages = new Map();
- _this2._recursiveVariableUsages = new Map();
- return _this2;
- }
- var _proto3 = ValidationContext.prototype;
- _proto3.getSchema = function getSchema() {
- return this._schema;
- };
- _proto3.getVariableUsages = function getVariableUsages(node) {
- var usages = this._variableUsages.get(node);
- if (!usages) {
- var newUsages = [];
- var typeInfo = new _TypeInfo.TypeInfo(this._schema);
- (0, _visitor.visit)(node, (0, _visitor.visitWithTypeInfo)(typeInfo, {
- VariableDefinition: function VariableDefinition() {
- return false;
- },
- Variable: function Variable(variable) {
- newUsages.push({
- node: variable,
- type: typeInfo.getInputType(),
- defaultValue: typeInfo.getDefaultValue()
- });
- }
- }));
- usages = newUsages;
- this._variableUsages.set(node, usages);
- }
- return usages;
- };
- _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) {
- var usages = this._recursiveVariableUsages.get(operation);
- if (!usages) {
- usages = this.getVariableUsages(operation);
- var fragments = this.getRecursivelyReferencedFragments(operation);
- for (var i = 0; i < fragments.length; i++) {
- Array.prototype.push.apply(usages, this.getVariableUsages(fragments[i]));
- }
- this._recursiveVariableUsages.set(operation, usages);
- }
- return usages;
- };
- _proto3.getType = function getType() {
- return this._typeInfo.getType();
- };
- _proto3.getParentType = function getParentType() {
- return this._typeInfo.getParentType();
- };
- _proto3.getInputType = function getInputType() {
- return this._typeInfo.getInputType();
- };
- _proto3.getParentInputType = function getParentInputType() {
- return this._typeInfo.getParentInputType();
- };
- _proto3.getFieldDef = function getFieldDef() {
- return this._typeInfo.getFieldDef();
- };
- _proto3.getDirective = function getDirective() {
- return this._typeInfo.getDirective();
- };
- _proto3.getArgument = function getArgument() {
- return this._typeInfo.getArgument();
- };
- return ValidationContext;
- }(ASTValidationContext);
- exports.ValidationContext = ValidationContext;
- },{"../language/kinds":51,"../language/visitor":58,"../utilities/TypeInfo":75}],101:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "validate", {
- enumerable: true,
- get: function get() {
- return _validate.validate;
- }
- });
- Object.defineProperty(exports, "ValidationContext", {
- enumerable: true,
- get: function get() {
- return _ValidationContext.ValidationContext;
- }
- });
- Object.defineProperty(exports, "specifiedRules", {
- enumerable: true,
- get: function get() {
- return _specifiedRules.specifiedRules;
- }
- });
- Object.defineProperty(exports, "FieldsOnCorrectTypeRule", {
- enumerable: true,
- get: function get() {
- return _FieldsOnCorrectType.FieldsOnCorrectType;
- }
- });
- Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", {
- enumerable: true,
- get: function get() {
- return _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes;
- }
- });
- Object.defineProperty(exports, "KnownArgumentNamesRule", {
- enumerable: true,
- get: function get() {
- return _KnownArgumentNames.KnownArgumentNames;
- }
- });
- Object.defineProperty(exports, "KnownDirectivesRule", {
- enumerable: true,
- get: function get() {
- return _KnownDirectives.KnownDirectives;
- }
- });
- Object.defineProperty(exports, "KnownFragmentNamesRule", {
- enumerable: true,
- get: function get() {
- return _KnownFragmentNames.KnownFragmentNames;
- }
- });
- Object.defineProperty(exports, "KnownTypeNamesRule", {
- enumerable: true,
- get: function get() {
- return _KnownTypeNames.KnownTypeNames;
- }
- });
- Object.defineProperty(exports, "LoneAnonymousOperationRule", {
- enumerable: true,
- get: function get() {
- return _LoneAnonymousOperation.LoneAnonymousOperation;
- }
- });
- Object.defineProperty(exports, "NoFragmentCyclesRule", {
- enumerable: true,
- get: function get() {
- return _NoFragmentCycles.NoFragmentCycles;
- }
- });
- Object.defineProperty(exports, "NoUndefinedVariablesRule", {
- enumerable: true,
- get: function get() {
- return _NoUndefinedVariables.NoUndefinedVariables;
- }
- });
- Object.defineProperty(exports, "NoUnusedFragmentsRule", {
- enumerable: true,
- get: function get() {
- return _NoUnusedFragments.NoUnusedFragments;
- }
- });
- Object.defineProperty(exports, "NoUnusedVariablesRule", {
- enumerable: true,
- get: function get() {
- return _NoUnusedVariables.NoUnusedVariables;
- }
- });
- Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", {
- enumerable: true,
- get: function get() {
- return _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged;
- }
- });
- Object.defineProperty(exports, "PossibleFragmentSpreadsRule", {
- enumerable: true,
- get: function get() {
- return _PossibleFragmentSpreads.PossibleFragmentSpreads;
- }
- });
- Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", {
- enumerable: true,
- get: function get() {
- return _ProvidedRequiredArguments.ProvidedRequiredArguments;
- }
- });
- Object.defineProperty(exports, "ScalarLeafsRule", {
- enumerable: true,
- get: function get() {
- return _ScalarLeafs.ScalarLeafs;
- }
- });
- Object.defineProperty(exports, "SingleFieldSubscriptionsRule", {
- enumerable: true,
- get: function get() {
- return _SingleFieldSubscriptions.SingleFieldSubscriptions;
- }
- });
- Object.defineProperty(exports, "UniqueArgumentNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueArgumentNames.UniqueArgumentNames;
- }
- });
- Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", {
- enumerable: true,
- get: function get() {
- return _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation;
- }
- });
- Object.defineProperty(exports, "UniqueFragmentNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueFragmentNames.UniqueFragmentNames;
- }
- });
- Object.defineProperty(exports, "UniqueInputFieldNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueInputFieldNames.UniqueInputFieldNames;
- }
- });
- Object.defineProperty(exports, "UniqueOperationNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueOperationNames.UniqueOperationNames;
- }
- });
- Object.defineProperty(exports, "UniqueVariableNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueVariableNames.UniqueVariableNames;
- }
- });
- Object.defineProperty(exports, "ValuesOfCorrectTypeRule", {
- enumerable: true,
- get: function get() {
- return _ValuesOfCorrectType.ValuesOfCorrectType;
- }
- });
- Object.defineProperty(exports, "VariablesAreInputTypesRule", {
- enumerable: true,
- get: function get() {
- return _VariablesAreInputTypes.VariablesAreInputTypes;
- }
- });
- Object.defineProperty(exports, "VariablesInAllowedPositionRule", {
- enumerable: true,
- get: function get() {
- return _VariablesInAllowedPosition.VariablesInAllowedPosition;
- }
- });
- var _validate = require("./validate");
- var _ValidationContext = require("./ValidationContext");
- var _specifiedRules = require("./specifiedRules");
- var _FieldsOnCorrectType = require("./rules/FieldsOnCorrectType");
- var _FragmentsOnCompositeTypes = require("./rules/FragmentsOnCompositeTypes");
- var _KnownArgumentNames = require("./rules/KnownArgumentNames");
- var _KnownDirectives = require("./rules/KnownDirectives");
- var _KnownFragmentNames = require("./rules/KnownFragmentNames");
- var _KnownTypeNames = require("./rules/KnownTypeNames");
- var _LoneAnonymousOperation = require("./rules/LoneAnonymousOperation");
- var _NoFragmentCycles = require("./rules/NoFragmentCycles");
- var _NoUndefinedVariables = require("./rules/NoUndefinedVariables");
- var _NoUnusedFragments = require("./rules/NoUnusedFragments");
- var _NoUnusedVariables = require("./rules/NoUnusedVariables");
- var _OverlappingFieldsCanBeMerged = require("./rules/OverlappingFieldsCanBeMerged");
- var _PossibleFragmentSpreads = require("./rules/PossibleFragmentSpreads");
- var _ProvidedRequiredArguments = require("./rules/ProvidedRequiredArguments");
- var _ScalarLeafs = require("./rules/ScalarLeafs");
- var _SingleFieldSubscriptions = require("./rules/SingleFieldSubscriptions");
- var _UniqueArgumentNames = require("./rules/UniqueArgumentNames");
- var _UniqueDirectivesPerLocation = require("./rules/UniqueDirectivesPerLocation");
- var _UniqueFragmentNames = require("./rules/UniqueFragmentNames");
- var _UniqueInputFieldNames = require("./rules/UniqueInputFieldNames");
- var _UniqueOperationNames = require("./rules/UniqueOperationNames");
- var _UniqueVariableNames = require("./rules/UniqueVariableNames");
- var _ValuesOfCorrectType = require("./rules/ValuesOfCorrectType");
- var _VariablesAreInputTypes = require("./rules/VariablesAreInputTypes");
- var _VariablesInAllowedPosition = require("./rules/VariablesInAllowedPosition");
- },{"./ValidationContext":100,"./rules/FieldsOnCorrectType":103,"./rules/FragmentsOnCompositeTypes":104,"./rules/KnownArgumentNames":105,"./rules/KnownDirectives":106,"./rules/KnownFragmentNames":107,"./rules/KnownTypeNames":108,"./rules/LoneAnonymousOperation":109,"./rules/NoFragmentCycles":111,"./rules/NoUndefinedVariables":112,"./rules/NoUnusedFragments":113,"./rules/NoUnusedVariables":114,"./rules/OverlappingFieldsCanBeMerged":115,"./rules/PossibleFragmentSpreads":116,"./rules/ProvidedRequiredArguments":118,"./rules/ScalarLeafs":119,"./rules/SingleFieldSubscriptions":120,"./rules/UniqueArgumentNames":121,"./rules/UniqueDirectivesPerLocation":123,"./rules/UniqueFragmentNames":126,"./rules/UniqueInputFieldNames":127,"./rules/UniqueOperationNames":128,"./rules/UniqueVariableNames":131,"./rules/ValuesOfCorrectType":132,"./rules/VariablesAreInputTypes":133,"./rules/VariablesInAllowedPosition":134,"./specifiedRules":135,"./validate":136}],102:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.nonExecutableDefinitionMessage = nonExecutableDefinitionMessage;
- exports.ExecutableDefinitions = ExecutableDefinitions;
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _predicates = require("../../language/predicates");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function nonExecutableDefinitionMessage(defName) {
- return "The ".concat(defName, " definition is not executable.");
- }
- /**
- * Executable definitions
- *
- * A GraphQL document is only valid for execution if all definitions are either
- * operation or fragment definitions.
- */
- function ExecutableDefinitions(context) {
- return {
- Document: function Document(node) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = node.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var definition = _step.value;
- if (!(0, _predicates.isExecutableDefinitionNode)(definition)) {
- context.reportError(new _GraphQLError.GraphQLError(nonExecutableDefinitionMessage(definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : definition.name.value), definition));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":19,"../../language/kinds":51,"../../language/predicates":55}],103:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.undefinedFieldMessage = undefinedFieldMessage;
- exports.FieldsOnCorrectType = FieldsOnCorrectType;
- var _GraphQLError = require("../../error/GraphQLError");
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList"));
- var _definition = require("../../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function undefinedFieldMessage(fieldName, type, suggestedTypeNames, suggestedFieldNames) {
- var message = "Cannot query field \"".concat(fieldName, "\" on type \"").concat(type, "\".");
- if (suggestedTypeNames.length !== 0) {
- var suggestions = (0, _quotedOrList.default)(suggestedTypeNames);
- message += " Did you mean to use an inline fragment on ".concat(suggestions, "?");
- } else if (suggestedFieldNames.length !== 0) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedFieldNames), "?");
- }
- return message;
- }
- /**
- * Fields on correct type
- *
- * A GraphQL document is only valid if all fields selected are defined by the
- * parent type, or are an allowed meta field such as __typename.
- */
- function FieldsOnCorrectType(context) {
- return {
- Field: function Field(node) {
- var type = context.getParentType();
- if (type) {
- var fieldDef = context.getFieldDef();
- if (!fieldDef) {
- // This field doesn't exist, lets look for suggestions.
- var schema = context.getSchema();
- var fieldName = node.name.value; // First determine if there are any suggested types to condition on.
- var suggestedTypeNames = getSuggestedTypeNames(schema, type, fieldName); // If there are no suggested types, then perhaps this was a typo?
- var suggestedFieldNames = suggestedTypeNames.length !== 0 ? [] : getSuggestedFieldNames(schema, type, fieldName); // Report an error, including helpful suggestions.
- context.reportError(new _GraphQLError.GraphQLError(undefinedFieldMessage(fieldName, type.name, suggestedTypeNames, suggestedFieldNames), node));
- }
- }
- }
- };
- }
- /**
- * Go through all of the implementations of type, as well as the interfaces that
- * they implement. If any of those types include the provided field, suggest
- * them, sorted by how often the type is referenced, starting with Interfaces.
- */
- function getSuggestedTypeNames(schema, type, fieldName) {
- if ((0, _definition.isAbstractType)(type)) {
- var suggestedObjectTypes = [];
- var interfaceUsageCount = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = schema.getPossibleTypes(type)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var possibleType = _step.value;
- if (!possibleType.getFields()[fieldName]) {
- continue;
- } // This object type defines this field.
- suggestedObjectTypes.push(possibleType.name);
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = possibleType.getInterfaces()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var possibleInterface = _step2.value;
- if (!possibleInterface.getFields()[fieldName]) {
- continue;
- } // This interface type defines this field.
- interfaceUsageCount[possibleInterface.name] = (interfaceUsageCount[possibleInterface.name] || 0) + 1;
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- } // Suggest interface types based on how common they are.
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort(function (a, b) {
- return interfaceUsageCount[b] - interfaceUsageCount[a];
- }); // Suggest both interface and object types.
- return suggestedInterfaceTypes.concat(suggestedObjectTypes);
- } // Otherwise, must be an Object type, which does not have possible fields.
- return [];
- }
- /**
- * For the field name provided, determine if there are any similar field names
- * that may be the result of a typo.
- */
- function getSuggestedFieldNames(schema, type, fieldName) {
- if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) {
- var possibleFieldNames = Object.keys(type.getFields());
- return (0, _suggestionList.default)(fieldName, possibleFieldNames);
- } // Otherwise, must be a Union type, which does not define fields.
- return [];
- }
- },{"../../error/GraphQLError":19,"../../jsutils/quotedOrList":46,"../../jsutils/suggestionList":47,"../../type/definition":68}],104:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.inlineFragmentOnNonCompositeErrorMessage = inlineFragmentOnNonCompositeErrorMessage;
- exports.fragmentOnNonCompositeErrorMessage = fragmentOnNonCompositeErrorMessage;
- exports.FragmentsOnCompositeTypes = FragmentsOnCompositeTypes;
- var _GraphQLError = require("../../error/GraphQLError");
- var _printer = require("../../language/printer");
- var _definition = require("../../type/definition");
- var _typeFromAST = require("../../utilities/typeFromAST");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function inlineFragmentOnNonCompositeErrorMessage(type) {
- return "Fragment cannot condition on non composite type \"".concat(type, "\".");
- }
- function fragmentOnNonCompositeErrorMessage(fragName, type) {
- return "Fragment \"".concat(fragName, "\" cannot condition on non composite ") + "type \"".concat(type, "\".");
- }
- /**
- * Fragments on composite type
- *
- * Fragments use a type condition to determine if they apply, since fragments
- * can only be spread into a composite type (object, interface, or union), the
- * type condition must also be a composite type.
- */
- function FragmentsOnCompositeTypes(context) {
- return {
- InlineFragment: function InlineFragment(node) {
- var typeCondition = node.typeCondition;
- if (typeCondition) {
- var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition);
- if (type && !(0, _definition.isCompositeType)(type)) {
- context.reportError(new _GraphQLError.GraphQLError(inlineFragmentOnNonCompositeErrorMessage((0, _printer.print)(typeCondition)), typeCondition));
- }
- }
- },
- FragmentDefinition: function FragmentDefinition(node) {
- var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition);
- if (type && !(0, _definition.isCompositeType)(type)) {
- context.reportError(new _GraphQLError.GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, (0, _printer.print)(node.typeCondition)), node.typeCondition));
- }
- }
- };
- }
- },{"../../error/GraphQLError":19,"../../language/printer":56,"../../type/definition":68,"../../utilities/typeFromAST":97}],105:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unknownArgMessage = unknownArgMessage;
- exports.unknownDirectiveArgMessage = unknownDirectiveArgMessage;
- exports.KnownArgumentNames = KnownArgumentNames;
- exports.KnownArgumentNamesOnDirectives = KnownArgumentNamesOnDirectives;
- var _GraphQLError = require("../../error/GraphQLError");
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList"));
- var _kinds = require("../../language/kinds");
- var _directives = require("../../type/directives");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function unknownArgMessage(argName, fieldName, typeName, suggestedArgs) {
- var message = "Unknown argument \"".concat(argName, "\" on field \"").concat(fieldName, "\" of ") + "type \"".concat(typeName, "\".");
- if (suggestedArgs.length) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedArgs), "?");
- }
- return message;
- }
- function unknownDirectiveArgMessage(argName, directiveName, suggestedArgs) {
- var message = "Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\".");
- if (suggestedArgs.length) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedArgs), "?");
- }
- return message;
- }
- /**
- * Known argument names
- *
- * A GraphQL field is only valid if all supplied arguments are defined by
- * that field.
- */
- function KnownArgumentNames(context) {
- return _objectSpread({}, KnownArgumentNamesOnDirectives(context), {
- Argument: function Argument(argNode) {
- var argDef = context.getArgument();
- var fieldDef = context.getFieldDef();
- var parentType = context.getParentType();
- if (!argDef && fieldDef && parentType) {
- var argName = argNode.name.value;
- var knownArgsNames = fieldDef.args.map(function (arg) {
- return arg.name;
- });
- context.reportError(new _GraphQLError.GraphQLError(unknownArgMessage(argName, fieldDef.name, parentType.name, (0, _suggestionList.default)(argName, knownArgsNames)), argNode));
- }
- }
- });
- } // @internal
- function KnownArgumentNamesOnDirectives(context) {
- var directiveArgs = Object.create(null);
- var schema = context.getSchema();
- var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var directive = _step.value;
- directiveArgs[directive.name] = directive.args.map(function (arg) {
- return arg.name;
- });
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var astDefinitions = context.getDocument().definitions;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var def = _step2.value;
- if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- directiveArgs[def.name.value] = def.arguments ? def.arguments.map(function (arg) {
- return arg.name.value;
- }) : [];
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return {
- Directive: function Directive(directiveNode) {
- var directiveName = directiveNode.name.value;
- var knownArgs = directiveArgs[directiveName];
- if (directiveNode.arguments && knownArgs) {
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = directiveNode.arguments[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var argNode = _step3.value;
- var argName = argNode.name.value;
- if (knownArgs.indexOf(argName) === -1) {
- var suggestions = (0, _suggestionList.default)(argName, knownArgs);
- context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveArgMessage(argName, directiveName, suggestions), argNode));
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":19,"../../jsutils/quotedOrList":46,"../../jsutils/suggestionList":47,"../../language/kinds":51,"../../type/directives":69}],106:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unknownDirectiveMessage = unknownDirectiveMessage;
- exports.misplacedDirectiveMessage = misplacedDirectiveMessage;
- exports.KnownDirectives = KnownDirectives;
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _directiveLocation = require("../../language/directiveLocation");
- var _directives = require("../../type/directives");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unknownDirectiveMessage(directiveName) {
- return "Unknown directive \"".concat(directiveName, "\".");
- }
- function misplacedDirectiveMessage(directiveName, location) {
- return "Directive \"".concat(directiveName, "\" may not be used on ").concat(location, ".");
- }
- /**
- * Known directives
- *
- * A GraphQL document is only valid if all `@directives` are known by the
- * schema and legally positioned.
- */
- function KnownDirectives(context) {
- var locationsMap = Object.create(null);
- var schema = context.getSchema();
- var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var directive = _step.value;
- locationsMap[directive.name] = directive.locations;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var astDefinitions = context.getDocument().definitions;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var def = _step2.value;
- if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- locationsMap[def.name.value] = def.locations.map(function (name) {
- return name.value;
- });
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return {
- Directive: function Directive(node, key, parent, path, ancestors) {
- var name = node.name.value;
- var locations = locationsMap[name];
- if (!locations) {
- context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveMessage(name), node));
- return;
- }
- var candidateLocation = getDirectiveLocationForASTPath(ancestors);
- if (candidateLocation && locations.indexOf(candidateLocation) === -1) {
- context.reportError(new _GraphQLError.GraphQLError(misplacedDirectiveMessage(name, candidateLocation), node));
- }
- }
- };
- }
- function getDirectiveLocationForASTPath(ancestors) {
- var appliedTo = ancestors[ancestors.length - 1];
- if (!Array.isArray(appliedTo)) {
- switch (appliedTo.kind) {
- case _kinds.Kind.OPERATION_DEFINITION:
- switch (appliedTo.operation) {
- case 'query':
- return _directiveLocation.DirectiveLocation.QUERY;
- case 'mutation':
- return _directiveLocation.DirectiveLocation.MUTATION;
- case 'subscription':
- return _directiveLocation.DirectiveLocation.SUBSCRIPTION;
- }
- break;
- case _kinds.Kind.FIELD:
- return _directiveLocation.DirectiveLocation.FIELD;
- case _kinds.Kind.FRAGMENT_SPREAD:
- return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD;
- case _kinds.Kind.INLINE_FRAGMENT:
- return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT;
- case _kinds.Kind.FRAGMENT_DEFINITION:
- return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION;
- case _kinds.Kind.VARIABLE_DEFINITION:
- return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION;
- case _kinds.Kind.SCHEMA_DEFINITION:
- case _kinds.Kind.SCHEMA_EXTENSION:
- return _directiveLocation.DirectiveLocation.SCHEMA;
- case _kinds.Kind.SCALAR_TYPE_DEFINITION:
- case _kinds.Kind.SCALAR_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.SCALAR;
- case _kinds.Kind.OBJECT_TYPE_DEFINITION:
- case _kinds.Kind.OBJECT_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.OBJECT;
- case _kinds.Kind.FIELD_DEFINITION:
- return _directiveLocation.DirectiveLocation.FIELD_DEFINITION;
- case _kinds.Kind.INTERFACE_TYPE_DEFINITION:
- case _kinds.Kind.INTERFACE_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.INTERFACE;
- case _kinds.Kind.UNION_TYPE_DEFINITION:
- case _kinds.Kind.UNION_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.UNION;
- case _kinds.Kind.ENUM_TYPE_DEFINITION:
- case _kinds.Kind.ENUM_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.ENUM;
- case _kinds.Kind.ENUM_VALUE_DEFINITION:
- return _directiveLocation.DirectiveLocation.ENUM_VALUE;
- case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION:
- case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.INPUT_OBJECT;
- case _kinds.Kind.INPUT_VALUE_DEFINITION:
- {
- var parentNode = ancestors[ancestors.length - 3];
- return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION;
- }
- }
- }
- }
- },{"../../error/GraphQLError":19,"../../language/directiveLocation":49,"../../language/kinds":51,"../../type/directives":69}],107:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unknownFragmentMessage = unknownFragmentMessage;
- exports.KnownFragmentNames = KnownFragmentNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unknownFragmentMessage(fragName) {
- return "Unknown fragment \"".concat(fragName, "\".");
- }
- /**
- * Known fragment names
- *
- * A GraphQL document is only valid if all `...Fragment` fragment spreads refer
- * to fragments defined in the same document.
- */
- function KnownFragmentNames(context) {
- return {
- FragmentSpread: function FragmentSpread(node) {
- var fragmentName = node.name.value;
- var fragment = context.getFragment(fragmentName);
- if (!fragment) {
- context.reportError(new _GraphQLError.GraphQLError(unknownFragmentMessage(fragmentName), node.name));
- }
- }
- };
- }
- },{"../../error/GraphQLError":19}],108:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unknownTypeMessage = unknownTypeMessage;
- exports.KnownTypeNames = KnownTypeNames;
- var _GraphQLError = require("../../error/GraphQLError");
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList"));
- var _predicates = require("../../language/predicates");
- var _scalars = require("../../type/scalars");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unknownTypeMessage(typeName, suggestedTypes) {
- var message = "Unknown type \"".concat(typeName, "\".");
- if (suggestedTypes.length) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedTypes), "?");
- }
- return message;
- }
- /**
- * Known type names
- *
- * A GraphQL document is only valid if referenced types (specifically
- * variable definitions and fragment conditions) are defined by the type schema.
- */
- function KnownTypeNames(context) {
- var schema = context.getSchema();
- var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);
- var definedTypes = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = context.getDocument().definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var def = _step.value;
- if ((0, _predicates.isTypeDefinitionNode)(def)) {
- definedTypes[def.name.value] = true;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes));
- return {
- NamedType: function NamedType(node, _1, parent, _2, ancestors) {
- var typeName = node.name.value;
- if (!existingTypesMap[typeName] && !definedTypes[typeName]) {
- var definitionNode = ancestors[2] || parent;
- var isSDL = isSDLNode(definitionNode);
- if (isSDL && isSpecifiedScalarName(typeName)) {
- return;
- }
- var suggestedTypes = (0, _suggestionList.default)(typeName, isSDL ? specifiedScalarsNames.concat(typeNames) : typeNames);
- context.reportError(new _GraphQLError.GraphQLError(unknownTypeMessage(typeName, suggestedTypes), node));
- }
- }
- };
- }
- var specifiedScalarsNames = _scalars.specifiedScalarTypes.map(function (type) {
- return type.name;
- });
- function isSpecifiedScalarName(typeName) {
- return specifiedScalarsNames.indexOf(typeName) !== -1;
- }
- function isSDLNode(value) {
- return Boolean(value && !Array.isArray(value) && ((0, _predicates.isTypeSystemDefinitionNode)(value) || (0, _predicates.isTypeSystemExtensionNode)(value)));
- }
- },{"../../error/GraphQLError":19,"../../jsutils/quotedOrList":46,"../../jsutils/suggestionList":47,"../../language/predicates":55,"../../type/scalars":72}],109:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.anonOperationNotAloneMessage = anonOperationNotAloneMessage;
- exports.LoneAnonymousOperation = LoneAnonymousOperation;
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function anonOperationNotAloneMessage() {
- return 'This anonymous operation must be the only defined operation.';
- }
- /**
- * Lone anonymous operation
- *
- * A GraphQL document is only valid if when it contains an anonymous operation
- * (the query short-hand) that it contains only that one operation definition.
- */
- function LoneAnonymousOperation(context) {
- var operationCount = 0;
- return {
- Document: function Document(node) {
- operationCount = node.definitions.filter(function (definition) {
- return definition.kind === _kinds.Kind.OPERATION_DEFINITION;
- }).length;
- },
- OperationDefinition: function OperationDefinition(node) {
- if (!node.name && operationCount > 1) {
- context.reportError(new _GraphQLError.GraphQLError(anonOperationNotAloneMessage(), node));
- }
- }
- };
- }
- },{"../../error/GraphQLError":19,"../../language/kinds":51}],110:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.schemaDefinitionNotAloneMessage = schemaDefinitionNotAloneMessage;
- exports.canNotDefineSchemaWithinExtensionMessage = canNotDefineSchemaWithinExtensionMessage;
- exports.LoneSchemaDefinition = LoneSchemaDefinition;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function schemaDefinitionNotAloneMessage() {
- return 'Must provide only one schema definition.';
- }
- function canNotDefineSchemaWithinExtensionMessage() {
- return 'Cannot define a new schema within a schema extension.';
- }
- /**
- * Lone Schema definition
- *
- * A GraphQL document is only valid if it contains only one schema definition.
- */
- function LoneSchemaDefinition(context) {
- var oldSchema = context.getSchema();
- var alreadyDefined = oldSchema && (oldSchema.astNode || oldSchema.getQueryType() || oldSchema.getMutationType() || oldSchema.getSubscriptionType());
- var schemaDefinitionsCount = 0;
- return {
- SchemaDefinition: function SchemaDefinition(node) {
- if (alreadyDefined) {
- context.reportError(new _GraphQLError.GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node));
- return;
- }
- if (schemaDefinitionsCount > 0) {
- context.reportError(new _GraphQLError.GraphQLError(schemaDefinitionNotAloneMessage(), node));
- }
- ++schemaDefinitionsCount;
- }
- };
- }
- },{"../../error/GraphQLError":19}],111:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.cycleErrorMessage = cycleErrorMessage;
- exports.NoFragmentCycles = NoFragmentCycles;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function cycleErrorMessage(fragName, spreadNames) {
- var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : '';
- return "Cannot spread fragment \"".concat(fragName, "\" within itself").concat(via, ".");
- }
- function NoFragmentCycles(context) {
- // Tracks already visited fragments to maintain O(N) and to ensure that cycles
- // are not redundantly reported.
- var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors
- var spreadPath = []; // Position in the spread path
- var spreadPathIndexByName = Object.create(null);
- return {
- OperationDefinition: function OperationDefinition() {
- return false;
- },
- FragmentDefinition: function FragmentDefinition(node) {
- detectCycleRecursive(node);
- return false;
- }
- }; // This does a straight-forward DFS to find cycles.
- // It does not terminate when a cycle was found but continues to explore
- // the graph to find all possible cycles.
- function detectCycleRecursive(fragment) {
- if (visitedFrags[fragment.name.value]) {
- return;
- }
- var fragmentName = fragment.name.value;
- visitedFrags[fragmentName] = true;
- var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
- if (spreadNodes.length === 0) {
- return;
- }
- spreadPathIndexByName[fragmentName] = spreadPath.length;
- for (var i = 0; i < spreadNodes.length; i++) {
- var spreadNode = spreadNodes[i];
- var spreadName = spreadNode.name.value;
- var cycleIndex = spreadPathIndexByName[spreadName];
- spreadPath.push(spreadNode);
- if (cycleIndex === undefined) {
- var spreadFragment = context.getFragment(spreadName);
- if (spreadFragment) {
- detectCycleRecursive(spreadFragment);
- }
- } else {
- var cyclePath = spreadPath.slice(cycleIndex);
- var fragmentNames = cyclePath.slice(0, -1).map(function (s) {
- return s.name.value;
- });
- context.reportError(new _GraphQLError.GraphQLError(cycleErrorMessage(spreadName, fragmentNames), cyclePath));
- }
- spreadPath.pop();
- }
- spreadPathIndexByName[fragmentName] = undefined;
- }
- }
- },{"../../error/GraphQLError":19}],112:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.undefinedVarMessage = undefinedVarMessage;
- exports.NoUndefinedVariables = NoUndefinedVariables;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function undefinedVarMessage(varName, opName) {
- return opName ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is not defined.");
- }
- /**
- * No undefined variables
- *
- * A GraphQL operation is only valid if all variables encountered, both directly
- * and via fragment spreads, are defined by that operation.
- */
- function NoUndefinedVariables(context) {
- var variableNameDefined = Object.create(null);
- return {
- OperationDefinition: {
- enter: function enter() {
- variableNameDefined = Object.create(null);
- },
- leave: function leave(operation) {
- var usages = context.getRecursiveVariableUsages(operation);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref2 = _step.value;
- var node = _ref2.node;
- var varName = node.name.value;
- if (variableNameDefined[varName] !== true) {
- context.reportError(new _GraphQLError.GraphQLError(undefinedVarMessage(varName, operation.name && operation.name.value), [node, operation]));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- },
- VariableDefinition: function VariableDefinition(node) {
- variableNameDefined[node.variable.name.value] = true;
- }
- };
- }
- },{"../../error/GraphQLError":19}],113:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unusedFragMessage = unusedFragMessage;
- exports.NoUnusedFragments = NoUnusedFragments;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unusedFragMessage(fragName) {
- return "Fragment \"".concat(fragName, "\" is never used.");
- }
- /**
- * No unused fragments
- *
- * A GraphQL document is only valid if all fragment definitions are spread
- * within operations, or spread within other fragments spread within operations.
- */
- function NoUnusedFragments(context) {
- var operationDefs = [];
- var fragmentDefs = [];
- return {
- OperationDefinition: function OperationDefinition(node) {
- operationDefs.push(node);
- return false;
- },
- FragmentDefinition: function FragmentDefinition(node) {
- fragmentDefs.push(node);
- return false;
- },
- Document: {
- leave: function leave() {
- var fragmentNameUsed = Object.create(null);
- for (var _i = 0, _operationDefs = operationDefs; _i < _operationDefs.length; _i++) {
- var operation = _operationDefs[_i];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = context.getRecursivelyReferencedFragments(operation)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var fragment = _step.value;
- fragmentNameUsed[fragment.name.value] = true;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- for (var _i2 = 0, _fragmentDefs = fragmentDefs; _i2 < _fragmentDefs.length; _i2++) {
- var fragmentDef = _fragmentDefs[_i2];
- var fragName = fragmentDef.name.value;
- if (fragmentNameUsed[fragName] !== true) {
- context.reportError(new _GraphQLError.GraphQLError(unusedFragMessage(fragName), fragmentDef));
- }
- }
- }
- }
- };
- }
- },{"../../error/GraphQLError":19}],114:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unusedVariableMessage = unusedVariableMessage;
- exports.NoUnusedVariables = NoUnusedVariables;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unusedVariableMessage(varName, opName) {
- return opName ? "Variable \"$".concat(varName, "\" is never used in operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is never used.");
- }
- /**
- * No unused variables
- *
- * A GraphQL operation is only valid if all variables defined by an operation
- * are used, either directly or within a spread fragment.
- */
- function NoUnusedVariables(context) {
- var variableDefs = [];
- return {
- OperationDefinition: {
- enter: function enter() {
- variableDefs = [];
- },
- leave: function leave(operation) {
- var variableNameUsed = Object.create(null);
- var usages = context.getRecursiveVariableUsages(operation);
- var opName = operation.name ? operation.name.value : null;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref2 = _step.value;
- var node = _ref2.node;
- variableNameUsed[node.name.value] = true;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- for (var _i = 0, _variableDefs = variableDefs; _i < _variableDefs.length; _i++) {
- var variableDef = _variableDefs[_i];
- var variableName = variableDef.variable.name.value;
- if (variableNameUsed[variableName] !== true) {
- context.reportError(new _GraphQLError.GraphQLError(unusedVariableMessage(variableName, opName), variableDef));
- }
- }
- }
- },
- VariableDefinition: function VariableDefinition(def) {
- variableDefs.push(def);
- }
- };
- }
- },{"../../error/GraphQLError":19}],115:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.fieldsConflictMessage = fieldsConflictMessage;
- exports.OverlappingFieldsCanBeMerged = OverlappingFieldsCanBeMerged;
- var _find = _interopRequireDefault(require("../../polyfills/find"));
- var _objectEntries = _interopRequireDefault(require("../../polyfills/objectEntries"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _kinds = require("../../language/kinds");
- var _printer = require("../../language/printer");
- var _definition = require("../../type/definition");
- var _typeFromAST = require("../../utilities/typeFromAST");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function fieldsConflictMessage(responseName, reason) {
- return "Fields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(reason), ". ") + 'Use different aliases on the fields to fetch both if this was intentional.';
- }
- function reasonMessage(reason) {
- if (Array.isArray(reason)) {
- return reason.map(function (_ref) {
- var responseName = _ref[0],
- subreason = _ref[1];
- return "subfields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(subreason));
- }).join(' and ');
- }
- return reason;
- }
- /**
- * Overlapping fields can be merged
- *
- * A selection set is only valid if all fields (including spreading any
- * fragments) either correspond to distinct response names or can be merged
- * without ambiguity.
- */
- function OverlappingFieldsCanBeMerged(context) {
- // A memoization for when two fragments are compared "between" each other for
- // conflicts. Two fragments may be compared many times, so memoizing this can
- // dramatically improve the performance of this validator.
- var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given
- // selection set. Selection sets may be asked for this information multiple
- // times, so this improves the performance of this validator.
- var cachedFieldsAndFragmentNames = new Map();
- return {
- SelectionSet: function SelectionSet(selectionSet) {
- var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet);
- for (var _i = 0, _conflicts = conflicts; _i < _conflicts.length; _i++) {
- var _ref3 = _conflicts[_i];
- var _ref2$ = _ref3[0];
- var responseName = _ref2$[0];
- var reason = _ref2$[1];
- var fields1 = _ref3[1];
- var fields2 = _ref3[2];
- context.reportError(new _GraphQLError.GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2)));
- }
- }
- };
- }
- /**
- * Algorithm:
- *
- * Conflicts occur when two fields exist in a query which will produce the same
- * response name, but represent differing values, thus creating a conflict.
- * The algorithm below finds all conflicts via making a series of comparisons
- * between fields. In order to compare as few fields as possible, this makes
- * a series of comparisons "within" sets of fields and "between" sets of fields.
- *
- * Given any selection set, a collection produces both a set of fields by
- * also including all inline fragments, as well as a list of fragments
- * referenced by fragment spreads.
- *
- * A) Each selection set represented in the document first compares "within" its
- * collected set of fields, finding any conflicts between every pair of
- * overlapping fields.
- * Note: This is the *only time* that a the fields "within" a set are compared
- * to each other. After this only fields "between" sets are compared.
- *
- * B) Also, if any fragment is referenced in a selection set, then a
- * comparison is made "between" the original set of fields and the
- * referenced fragment.
- *
- * C) Also, if multiple fragments are referenced, then comparisons
- * are made "between" each referenced fragment.
- *
- * D) When comparing "between" a set of fields and a referenced fragment, first
- * a comparison is made between each field in the original set of fields and
- * each field in the the referenced set of fields.
- *
- * E) Also, if any fragment is referenced in the referenced selection set,
- * then a comparison is made "between" the original set of fields and the
- * referenced fragment (recursively referring to step D).
- *
- * F) When comparing "between" two fragments, first a comparison is made between
- * each field in the first referenced set of fields and each field in the the
- * second referenced set of fields.
- *
- * G) Also, any fragments referenced by the first must be compared to the
- * second, and any fragments referenced by the second must be compared to the
- * first (recursively referring to step F).
- *
- * H) When comparing two fields, if both have selection sets, then a comparison
- * is made "between" both selection sets, first comparing the set of fields in
- * the first selection set with the set of fields in the second.
- *
- * I) Also, if any fragment is referenced in either selection set, then a
- * comparison is made "between" the other set of fields and the
- * referenced fragment.
- *
- * J) Also, if two fragments are referenced in both selection sets, then a
- * comparison is made "between" the two fragments.
- *
- */
- // Find all conflicts found "within" a selection set, including those found
- // via spreading in fragments. Called when visiting each SelectionSet in the
- // GraphQL Document.
- function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) {
- var conflicts = [];
- var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet),
- fieldMap = _getFieldsAndFragment[0],
- fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set.
- // Note: this is the *only place* `collectConflictsWithin` is called.
- collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap);
- if (fragmentNames.length !== 0) {
- // (B) Then collect conflicts between these fields and those represented by
- // each spread fragment name found.
- var comparedFragments = Object.create(null);
- for (var i = 0; i < fragmentNames.length; i++) {
- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this
- // selection set to collect conflicts between fragments spread together.
- // This compares each item in the list of fragment names to every other
- // item in that same list (except for itself).
- for (var j = i + 1; j < fragmentNames.length; j++) {
- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]);
- }
- }
- }
- return conflicts;
- } // Collect all conflicts found between a set of fields and a fragment reference
- // including via spreading in any nested fragments.
- function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) {
- // Memoize so a fragment is not compared for conflicts more than once.
- if (comparedFragments[fragmentName]) {
- return;
- }
- comparedFragments[fragmentName] = true;
- var fragment = context.getFragment(fragmentName);
- if (!fragment) {
- return;
- }
- var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment),
- fieldMap2 = _getReferencedFieldsA[0],
- fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself.
- if (fieldMap === fieldMap2) {
- return;
- } // (D) First collect any conflicts between the provided collection of fields
- // and the collection of fields represented by the given fragment.
- collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields
- // and any fragment names found in the given fragment.
- for (var i = 0; i < fragmentNames2.length; i++) {
- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]);
- }
- } // Collect all conflicts found between two fragments, including via spreading in
- // any nested fragments.
- function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) {
- // No need to compare a fragment to itself.
- if (fragmentName1 === fragmentName2) {
- return;
- } // Memoize so two fragments are not compared for conflicts more than once.
- if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) {
- return;
- }
- comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);
- var fragment1 = context.getFragment(fragmentName1);
- var fragment2 = context.getFragment(fragmentName2);
- if (!fragment1 || !fragment2) {
- return;
- }
- var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1),
- fieldMap1 = _getReferencedFieldsA2[0],
- fragmentNames1 = _getReferencedFieldsA2[1];
- var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2),
- fieldMap2 = _getReferencedFieldsA3[0],
- fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields
- // (not including any nested fragments).
- collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested
- // fragments spread in the second fragment.
- for (var j = 0; j < fragmentNames2.length; j++) {
- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]);
- } // (G) Then collect conflicts between the second fragment and any nested
- // fragments spread in the first fragment.
- for (var i = 0; i < fragmentNames1.length; i++) {
- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2);
- }
- } // Find all conflicts found between two selection sets, including those found
- // via spreading in fragments. Called when determining if conflicts exist
- // between the sub-fields of two overlapping fields.
- function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) {
- var conflicts = [];
- var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1),
- fieldMap1 = _getFieldsAndFragment2[0],
- fragmentNames1 = _getFieldsAndFragment2[1];
- var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2),
- fieldMap2 = _getFieldsAndFragment3[0],
- fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field.
- collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and
- // those referenced by each fragment name associated with the second.
- if (fragmentNames2.length !== 0) {
- var comparedFragments = Object.create(null);
- for (var j = 0; j < fragmentNames2.length; j++) {
- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]);
- }
- } // (I) Then collect conflicts between the second collection of fields and
- // those referenced by each fragment name associated with the first.
- if (fragmentNames1.length !== 0) {
- var _comparedFragments = Object.create(null);
- for (var i = 0; i < fragmentNames1.length; i++) {
- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, _comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]);
- }
- } // (J) Also collect conflicts between any fragment names by the first and
- // fragment names by the second. This compares each item in the first set of
- // names to each item in the second set of names.
- for (var _i2 = 0; _i2 < fragmentNames1.length; _i2++) {
- for (var _j = 0; _j < fragmentNames2.length; _j++) {
- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i2], fragmentNames2[_j]);
- }
- }
- return conflicts;
- } // Collect all Conflicts "within" one collection of fields.
- function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) {
- // A field map is a keyed collection, where each key represents a response
- // name and the value at that key is a list of all fields which provide that
- // response name. For every response name, if there are multiple fields, they
- // must be compared to find a potential conflict.
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectEntries.default)(fieldMap)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref5 = _step.value;
- var responseName = _ref5[0];
- var fields = _ref5[1];
- // This compares every field in the list to every other field in this list
- // (except to itself). If the list only has one item, nothing needs to
- // be compared.
- if (fields.length > 1) {
- for (var i = 0; i < fields.length; i++) {
- for (var j = i + 1; j < fields.length; j++) {
- var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive
- responseName, fields[i], fields[j]);
- if (conflict) {
- conflicts.push(conflict);
- }
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- } // Collect all Conflicts between two collections of fields. This is similar to,
- // but different from the `collectConflictsWithin` function above. This check
- // assumes that `collectConflictsWithin` has already been called on each
- // provided collection of fields. This is true because this validator traverses
- // each individual selection set.
- function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) {
- // A field map is a keyed collection, where each key represents a response
- // name and the value at that key is a list of all fields which provide that
- // response name. For any response name which appears in both provided field
- // maps, each field from the first field map must be compared to every field
- // in the second field map to find potential conflicts.
- for (var _i3 = 0, _Object$keys = Object.keys(fieldMap1); _i3 < _Object$keys.length; _i3++) {
- var responseName = _Object$keys[_i3];
- var fields2 = fieldMap2[responseName];
- if (fields2) {
- var fields1 = fieldMap1[responseName];
- for (var i = 0; i < fields1.length; i++) {
- for (var j = 0; j < fields2.length; j++) {
- var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]);
- if (conflict) {
- conflicts.push(conflict);
- }
- }
- }
- }
- }
- } // Determines if there is a conflict between two particular fields, including
- // comparing their sub-fields.
- function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) {
- var parentType1 = field1[0],
- node1 = field1[1],
- def1 = field1[2];
- var parentType2 = field2[0],
- node2 = field2[1],
- def2 = field2[2]; // If it is known that two fields could not possibly apply at the same
- // time, due to the parent types, then it is safe to permit them to diverge
- // in aliased field or arguments used as they will not present any ambiguity
- // by differing.
- // It is known that two parent types could never overlap if they are
- // different Object types. Interface or Union types might overlap - if not
- // in the current state of the schema, then perhaps in some future version,
- // thus may not safely diverge.
- var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); // The return type for each field.
- var type1 = def1 && def1.type;
- var type2 = def2 && def2.type;
- if (!areMutuallyExclusive) {
- // Two aliases must refer to the same field.
- var name1 = node1.name.value;
- var name2 = node2.name.value;
- if (name1 !== name2) {
- return [[responseName, "".concat(name1, " and ").concat(name2, " are different fields")], [node1], [node2]];
- } // Two field calls must have the same arguments.
- if (!sameArguments(node1.arguments || [], node2.arguments || [])) {
- return [[responseName, 'they have differing arguments'], [node1], [node2]];
- }
- }
- if (type1 && type2 && doTypesConflict(type1, type2)) {
- return [[responseName, "they return conflicting types ".concat((0, _inspect.default)(type1), " and ").concat((0, _inspect.default)(type2))], [node1], [node2]];
- } // Collect and compare sub-fields. Use the same "visited fragment names" list
- // for both collections so fields in a fragment reference are never
- // compared to themselves.
- var selectionSet1 = node1.selectionSet;
- var selectionSet2 = node2.selectionSet;
- if (selectionSet1 && selectionSet2) {
- var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2);
- return subfieldConflicts(conflicts, responseName, node1, node2);
- }
- }
- function sameArguments(arguments1, arguments2) {
- if (arguments1.length !== arguments2.length) {
- return false;
- }
- return arguments1.every(function (argument1) {
- var argument2 = (0, _find.default)(arguments2, function (argument) {
- return argument.name.value === argument1.name.value;
- });
- if (!argument2) {
- return false;
- }
- return sameValue(argument1.value, argument2.value);
- });
- }
- function sameValue(value1, value2) {
- return !value1 && !value2 || (0, _printer.print)(value1) === (0, _printer.print)(value2);
- } // Two types conflict if both types could not apply to a value simultaneously.
- // Composite types are ignored as their individual field types will be compared
- // later recursively. However List and Non-Null types must match.
- function doTypesConflict(type1, type2) {
- if ((0, _definition.isListType)(type1)) {
- return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
- }
- if ((0, _definition.isListType)(type2)) {
- return true;
- }
- if ((0, _definition.isNonNullType)(type1)) {
- return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
- }
- if ((0, _definition.isNonNullType)(type2)) {
- return true;
- }
- if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) {
- return type1 !== type2;
- }
- return false;
- } // Given a selection set, return the collection of fields (a mapping of response
- // name to field nodes and definitions) as well as a list of fragment names
- // referenced via fragment spreads.
- function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) {
- var cached = cachedFieldsAndFragmentNames.get(selectionSet);
- if (!cached) {
- var nodeAndDefs = Object.create(null);
- var fragmentNames = Object.create(null);
- _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames);
- cached = [nodeAndDefs, Object.keys(fragmentNames)];
- cachedFieldsAndFragmentNames.set(selectionSet, cached);
- }
- return cached;
- } // Given a reference to a fragment, return the represented collection of fields
- // as well as a list of nested fragment names referenced via fragment spreads.
- function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) {
- // Short-circuit building a type from the node if possible.
- var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);
- if (cached) {
- return cached;
- }
- var fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition);
- return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet);
- }
- function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) {
- for (var i = 0; i < selectionSet.selections.length; i++) {
- var selection = selectionSet.selections[i];
- switch (selection.kind) {
- case _kinds.Kind.FIELD:
- {
- var fieldName = selection.name.value;
- var fieldDef = void 0;
- if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) {
- fieldDef = parentType.getFields()[fieldName];
- }
- var responseName = selection.alias ? selection.alias.value : fieldName;
- if (!nodeAndDefs[responseName]) {
- nodeAndDefs[responseName] = [];
- }
- nodeAndDefs[responseName].push([parentType, selection, fieldDef]);
- break;
- }
- case _kinds.Kind.FRAGMENT_SPREAD:
- fragmentNames[selection.name.value] = true;
- break;
- case _kinds.Kind.INLINE_FRAGMENT:
- {
- var typeCondition = selection.typeCondition;
- var inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType;
- _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames);
- break;
- }
- }
- }
- } // Given a series of Conflicts which occurred between two sub-fields, generate
- // a single Conflict.
- function subfieldConflicts(conflicts, responseName, node1, node2) {
- if (conflicts.length > 0) {
- return [[responseName, conflicts.map(function (_ref6) {
- var reason = _ref6[0];
- return reason;
- })], conflicts.reduce(function (allFields, _ref7) {
- var fields1 = _ref7[1];
- return allFields.concat(fields1);
- }, [node1]), conflicts.reduce(function (allFields, _ref8) {
- var fields2 = _ref8[2];
- return allFields.concat(fields2);
- }, [node2])];
- }
- }
- /**
- * A way to keep track of pairs of things when the ordering of the pair does
- * not matter. We do this by maintaining a sort of double adjacency sets.
- */
- var PairSet =
- /*#__PURE__*/
- function () {
- function PairSet() {
- this._data = Object.create(null);
- }
- var _proto = PairSet.prototype;
- _proto.has = function has(a, b, areMutuallyExclusive) {
- var first = this._data[a];
- var result = first && first[b];
- if (result === undefined) {
- return false;
- } // areMutuallyExclusive being false is a superset of being true,
- // hence if we want to know if this PairSet "has" these two with no
- // exclusivity, we have to ensure it was added as such.
- if (areMutuallyExclusive === false) {
- return result === false;
- }
- return true;
- };
- _proto.add = function add(a, b, areMutuallyExclusive) {
- _pairSetAdd(this._data, a, b, areMutuallyExclusive);
- _pairSetAdd(this._data, b, a, areMutuallyExclusive);
- };
- return PairSet;
- }();
- function _pairSetAdd(data, a, b, areMutuallyExclusive) {
- var map = data[a];
- if (!map) {
- map = Object.create(null);
- data[a] = map;
- }
- map[b] = areMutuallyExclusive;
- }
- },{"../../error/GraphQLError":19,"../../jsutils/inspect":32,"../../language/kinds":51,"../../language/printer":56,"../../polyfills/find":59,"../../polyfills/objectEntries":63,"../../type/definition":68,"../../utilities/typeFromAST":97}],116:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.typeIncompatibleSpreadMessage = typeIncompatibleSpreadMessage;
- exports.typeIncompatibleAnonSpreadMessage = typeIncompatibleAnonSpreadMessage;
- exports.PossibleFragmentSpreads = PossibleFragmentSpreads;
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _typeComparators = require("../../utilities/typeComparators");
- var _typeFromAST = require("../../utilities/typeFromAST");
- var _definition = require("../../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function typeIncompatibleSpreadMessage(fragName, parentType, fragType) {
- return "Fragment \"".concat(fragName, "\" cannot be spread here as objects of ") + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\".");
- }
- function typeIncompatibleAnonSpreadMessage(parentType, fragType) {
- return 'Fragment cannot be spread here as objects of ' + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\".");
- }
- /**
- * Possible fragment spread
- *
- * A fragment spread is only valid if the type condition could ever possibly
- * be true: if there is a non-empty intersection of the possible parent types,
- * and possible types which pass the type condition.
- */
- function PossibleFragmentSpreads(context) {
- return {
- InlineFragment: function InlineFragment(node) {
- var fragType = context.getType();
- var parentType = context.getParentType();
- if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) {
- context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleAnonSpreadMessage((0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), node));
- }
- },
- FragmentSpread: function FragmentSpread(node) {
- var fragName = node.name.value;
- var fragType = getFragmentType(context, fragName);
- var parentType = context.getParentType();
- if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) {
- context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleSpreadMessage(fragName, (0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), node));
- }
- }
- };
- }
- function getFragmentType(context, name) {
- var frag = context.getFragment(name);
- if (frag) {
- var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition);
- if ((0, _definition.isCompositeType)(type)) {
- return type;
- }
- }
- }
- },{"../../error/GraphQLError":19,"../../jsutils/inspect":32,"../../type/definition":68,"../../utilities/typeComparators":96,"../../utilities/typeFromAST":97}],117:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.extendingUnknownTypeMessage = extendingUnknownTypeMessage;
- exports.extendingDifferentTypeKindMessage = extendingDifferentTypeKindMessage;
- exports.PossibleTypeExtensions = PossibleTypeExtensions;
- var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList"));
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _predicates = require("../../language/predicates");
- var _definition = require("../../type/definition");
- var _defKindToExtKind;
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function extendingUnknownTypeMessage(typeName, suggestedTypes) {
- var message = "Cannot extend type \"".concat(typeName, "\" because it is not defined.");
- if (suggestedTypes.length) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedTypes), "?");
- }
- return message;
- }
- function extendingDifferentTypeKindMessage(typeName, kind) {
- return "Cannot extend non-".concat(kind, " type \"").concat(typeName, "\".");
- }
- /**
- * Possible type extension
- *
- * A type extension is only valid if the type is defined and has the same kind.
- */
- function PossibleTypeExtensions(context) {
- var schema = context.getSchema();
- var definedTypes = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = context.getDocument().definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var def = _step.value;
- if ((0, _predicates.isTypeDefinitionNode)(def)) {
- definedTypes[def.name.value] = def;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return {
- ScalarTypeExtension: checkExtension,
- ObjectTypeExtension: checkExtension,
- InterfaceTypeExtension: checkExtension,
- UnionTypeExtension: checkExtension,
- EnumTypeExtension: checkExtension,
- InputObjectTypeExtension: checkExtension
- };
- function checkExtension(node) {
- var typeName = node.name.value;
- var defNode = definedTypes[typeName];
- var existingType = schema && schema.getType(typeName);
- if (defNode) {
- var expectedKind = defKindToExtKind[defNode.kind];
- if (expectedKind !== node.kind) {
- context.reportError(new _GraphQLError.GraphQLError(extendingDifferentTypeKindMessage(typeName, extensionKindToTypeName(expectedKind)), [defNode, node]));
- }
- } else if (existingType) {
- var _expectedKind = typeToExtKind(existingType);
- if (_expectedKind !== node.kind) {
- context.reportError(new _GraphQLError.GraphQLError(extendingDifferentTypeKindMessage(typeName, extensionKindToTypeName(_expectedKind)), node));
- }
- } else {
- var allTypeNames = Object.keys(definedTypes);
- if (schema) {
- allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap()));
- }
- var suggestedTypes = (0, _suggestionList.default)(typeName, allTypeNames);
- context.reportError(new _GraphQLError.GraphQLError(extendingUnknownTypeMessage(typeName, suggestedTypes), node.name));
- }
- }
- }
- var defKindToExtKind = (_defKindToExtKind = {}, _defineProperty(_defKindToExtKind, _kinds.Kind.SCALAR_TYPE_DEFINITION, _kinds.Kind.SCALAR_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.OBJECT_TYPE_DEFINITION, _kinds.Kind.OBJECT_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.INTERFACE_TYPE_DEFINITION, _kinds.Kind.INTERFACE_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.UNION_TYPE_DEFINITION, _kinds.Kind.UNION_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.ENUM_TYPE_DEFINITION, _kinds.Kind.ENUM_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION), _defKindToExtKind);
- function typeToExtKind(type) {
- if ((0, _definition.isScalarType)(type)) {
- return _kinds.Kind.SCALAR_TYPE_EXTENSION;
- } else if ((0, _definition.isObjectType)(type)) {
- return _kinds.Kind.OBJECT_TYPE_EXTENSION;
- } else if ((0, _definition.isInterfaceType)(type)) {
- return _kinds.Kind.INTERFACE_TYPE_EXTENSION;
- } else if ((0, _definition.isUnionType)(type)) {
- return _kinds.Kind.UNION_TYPE_EXTENSION;
- } else if ((0, _definition.isEnumType)(type)) {
- return _kinds.Kind.ENUM_TYPE_EXTENSION;
- } else if ((0, _definition.isInputObjectType)(type)) {
- return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION;
- }
- }
- function extensionKindToTypeName(kind) {
- switch (kind) {
- case _kinds.Kind.SCALAR_TYPE_EXTENSION:
- return 'scalar';
- case _kinds.Kind.OBJECT_TYPE_EXTENSION:
- return 'object';
- case _kinds.Kind.INTERFACE_TYPE_EXTENSION:
- return 'interface';
- case _kinds.Kind.UNION_TYPE_EXTENSION:
- return 'union';
- case _kinds.Kind.ENUM_TYPE_EXTENSION:
- return 'enum';
- case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION:
- return 'input object';
- default:
- return 'unknown type';
- }
- }
- },{"../../error/GraphQLError":19,"../../jsutils/quotedOrList":46,"../../jsutils/suggestionList":47,"../../language/kinds":51,"../../language/predicates":55,"../../type/definition":68}],118:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.missingFieldArgMessage = missingFieldArgMessage;
- exports.missingDirectiveArgMessage = missingDirectiveArgMessage;
- exports.ProvidedRequiredArguments = ProvidedRequiredArguments;
- exports.ProvidedRequiredArgumentsOnDirectives = ProvidedRequiredArgumentsOnDirectives;
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap"));
- var _definition = require("../../type/definition");
- var _printer = require("../../language/printer");
- var _directives = require("../../type/directives");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function missingFieldArgMessage(fieldName, argName, type) {
- return "Field \"".concat(fieldName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required, but it was not provided.");
- }
- function missingDirectiveArgMessage(directiveName, argName, type) {
- return "Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required, but it was not provided.");
- }
- /**
- * Provided required arguments
- *
- * A field or directive is only valid if all required (non-null without a
- * default value) field arguments have been provided.
- */
- function ProvidedRequiredArguments(context) {
- return _objectSpread({}, ProvidedRequiredArgumentsOnDirectives(context), {
- Field: {
- // Validate on leave to allow for deeper errors to appear first.
- leave: function leave(fieldNode) {
- var fieldDef = context.getFieldDef();
- if (!fieldDef) {
- return false;
- }
- var argNodes = fieldNode.arguments || [];
- var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) {
- return arg.name.value;
- });
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = fieldDef.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var argDef = _step.value;
- var argNode = argNodeMap[argDef.name];
- if (!argNode && (0, _definition.isRequiredArgument)(argDef)) {
- context.reportError(new _GraphQLError.GraphQLError(missingFieldArgMessage(fieldDef.name, argDef.name, (0, _inspect.default)(argDef.type)), fieldNode));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- }
- });
- } // @internal
- function ProvidedRequiredArgumentsOnDirectives(context) {
- var requiredArgsMap = Object.create(null);
- var schema = context.getSchema();
- var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = definedDirectives[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var directive = _step2.value;
- requiredArgsMap[directive.name] = (0, _keyMap.default)(directive.args.filter(_definition.isRequiredArgument), function (arg) {
- return arg.name;
- });
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- var astDefinitions = context.getDocument().definitions;
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = astDefinitions[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var def = _step3.value;
- if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- requiredArgsMap[def.name.value] = (0, _keyMap.default)(def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], function (arg) {
- return arg.name.value;
- });
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- return {
- Directive: {
- // Validate on leave to allow for deeper errors to appear first.
- leave: function leave(directiveNode) {
- var directiveName = directiveNode.name.value;
- var requiredArgs = requiredArgsMap[directiveName];
- if (requiredArgs) {
- var argNodes = directiveNode.arguments || [];
- var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) {
- return arg.name.value;
- });
- for (var _i = 0, _Object$keys = Object.keys(requiredArgs); _i < _Object$keys.length; _i++) {
- var argName = _Object$keys[_i];
- if (!argNodeMap[argName]) {
- var argType = requiredArgs[argName].type;
- context.reportError(new _GraphQLError.GraphQLError(missingDirectiveArgMessage(directiveName, argName, (0, _definition.isType)(argType) ? (0, _inspect.default)(argType) : (0, _printer.print)(argType)), directiveNode));
- }
- }
- }
- }
- }
- };
- }
- function isRequiredArgumentNode(arg) {
- return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null;
- }
- },{"../../error/GraphQLError":19,"../../jsutils/inspect":32,"../../jsutils/keyMap":38,"../../language/kinds":51,"../../language/printer":56,"../../type/definition":68,"../../type/directives":69}],119:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.noSubselectionAllowedMessage = noSubselectionAllowedMessage;
- exports.requiredSubselectionMessage = requiredSubselectionMessage;
- exports.ScalarLeafs = ScalarLeafs;
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _definition = require("../../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function noSubselectionAllowedMessage(fieldName, type) {
- return "Field \"".concat(fieldName, "\" must not have a selection since ") + "type \"".concat(type, "\" has no subfields.");
- }
- function requiredSubselectionMessage(fieldName, type) {
- return "Field \"".concat(fieldName, "\" of type \"").concat(type, "\" must have a ") + "selection of subfields. Did you mean \"".concat(fieldName, " { ... }\"?");
- }
- /**
- * Scalar leafs
- *
- * A GraphQL document is valid only if all leaf fields (fields without
- * sub selections) are of scalar or enum types.
- */
- function ScalarLeafs(context) {
- return {
- Field: function Field(node) {
- var type = context.getType();
- var selectionSet = node.selectionSet;
- if (type) {
- if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) {
- if (selectionSet) {
- context.reportError(new _GraphQLError.GraphQLError(noSubselectionAllowedMessage(node.name.value, (0, _inspect.default)(type)), selectionSet));
- }
- } else if (!selectionSet) {
- context.reportError(new _GraphQLError.GraphQLError(requiredSubselectionMessage(node.name.value, (0, _inspect.default)(type)), node));
- }
- }
- }
- };
- }
- },{"../../error/GraphQLError":19,"../../jsutils/inspect":32,"../../type/definition":68}],120:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.singleFieldOnlyMessage = singleFieldOnlyMessage;
- exports.SingleFieldSubscriptions = SingleFieldSubscriptions;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function singleFieldOnlyMessage(name) {
- return (name ? "Subscription \"".concat(name, "\" ") : 'Anonymous Subscription ') + 'must select only one top level field.';
- }
- /**
- * Subscriptions must only include one field.
- *
- * A GraphQL subscription is valid only if it contains a single root field.
- */
- function SingleFieldSubscriptions(context) {
- return {
- OperationDefinition: function OperationDefinition(node) {
- if (node.operation === 'subscription') {
- if (node.selectionSet.selections.length !== 1) {
- context.reportError(new _GraphQLError.GraphQLError(singleFieldOnlyMessage(node.name && node.name.value), node.selectionSet.selections.slice(1)));
- }
- }
- }
- };
- }
- },{"../../error/GraphQLError":19}],121:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateArgMessage = duplicateArgMessage;
- exports.UniqueArgumentNames = UniqueArgumentNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateArgMessage(argName) {
- return "There can be only one argument named \"".concat(argName, "\".");
- }
- /**
- * Unique argument names
- *
- * A GraphQL field or directive is only valid if all supplied arguments are
- * uniquely named.
- */
- function UniqueArgumentNames(context) {
- var knownArgNames = Object.create(null);
- return {
- Field: function Field() {
- knownArgNames = Object.create(null);
- },
- Directive: function Directive() {
- knownArgNames = Object.create(null);
- },
- Argument: function Argument(node) {
- var argName = node.name.value;
- if (knownArgNames[argName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name]));
- } else {
- knownArgNames[argName] = node.name;
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":19}],122:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateDirectiveNameMessage = duplicateDirectiveNameMessage;
- exports.existedDirectiveNameMessage = existedDirectiveNameMessage;
- exports.UniqueDirectiveNames = UniqueDirectiveNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateDirectiveNameMessage(directiveName) {
- return "There can be only one directive named \"".concat(directiveName, "\".");
- }
- function existedDirectiveNameMessage(directiveName) {
- return "Directive \"".concat(directiveName, "\" already exists in the schema. ") + 'It cannot be redefined.';
- }
- /**
- * Unique directive names
- *
- * A GraphQL document is only valid if all defined directives have unique names.
- */
- function UniqueDirectiveNames(context) {
- var knownDirectiveNames = Object.create(null);
- var schema = context.getSchema();
- return {
- DirectiveDefinition: function DirectiveDefinition(node) {
- var directiveName = node.name.value;
- if (schema && schema.getDirective(directiveName)) {
- context.reportError(new _GraphQLError.GraphQLError(existedDirectiveNameMessage(directiveName), node.name));
- return;
- }
- if (knownDirectiveNames[directiveName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateDirectiveNameMessage(directiveName), [knownDirectiveNames[directiveName], node.name]));
- } else {
- knownDirectiveNames[directiveName] = node.name;
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":19}],123:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateDirectiveMessage = duplicateDirectiveMessage;
- exports.UniqueDirectivesPerLocation = UniqueDirectivesPerLocation;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateDirectiveMessage(directiveName) {
- return "The directive \"".concat(directiveName, "\" can only be used once at ") + 'this location.';
- }
- /**
- * Unique directive names per location
- *
- * A GraphQL document is only valid if all directives at a given location
- * are uniquely named.
- */
- function UniqueDirectivesPerLocation(context) {
- return {
- // Many different AST nodes may contain directives. Rather than listing
- // them all, just listen for entering any node, and check to see if it
- // defines any directives.
- enter: function enter(node) {
- // Flow can't refine that node.directives will only contain directives,
- // so we cast so the rest of the code is well typed.
- var directives = node.directives;
- if (directives) {
- var knownDirectives = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = directives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var directive = _step.value;
- var directiveName = directive.name.value;
- if (knownDirectives[directiveName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], directive]));
- } else {
- knownDirectives[directiveName] = directive;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- }
- };
- }
- },{"../../error/GraphQLError":19}],124:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateEnumValueNameMessage = duplicateEnumValueNameMessage;
- exports.existedEnumValueNameMessage = existedEnumValueNameMessage;
- exports.UniqueEnumValueNames = UniqueEnumValueNames;
- var _GraphQLError = require("../../error/GraphQLError");
- var _definition = require("../../type/definition");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateEnumValueNameMessage(typeName, valueName) {
- return "Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once.");
- }
- function existedEnumValueNameMessage(typeName, valueName) {
- return "Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. ") + 'It cannot also be defined in this type extension.';
- }
- /**
- * Unique enum value names
- *
- * A GraphQL enum type is only valid if all its values are uniquely named.
- */
- function UniqueEnumValueNames(context) {
- var schema = context.getSchema();
- var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
- var knownValueNames = Object.create(null);
- return {
- EnumTypeDefinition: checkValueUniqueness,
- EnumTypeExtension: checkValueUniqueness
- };
- function checkValueUniqueness(node) {
- var typeName = node.name.value;
- if (!knownValueNames[typeName]) {
- knownValueNames[typeName] = Object.create(null);
- }
- if (node.values) {
- var valueNames = knownValueNames[typeName];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = node.values[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var valueDef = _step.value;
- var valueName = valueDef.name.value;
- var existingType = existingTypeMap[typeName];
- if ((0, _definition.isEnumType)(existingType) && existingType.getValue(valueName)) {
- context.reportError(new _GraphQLError.GraphQLError(existedEnumValueNameMessage(typeName, valueName), valueDef.name));
- } else if (valueNames[valueName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateEnumValueNameMessage(typeName, valueName), [valueNames[valueName], valueDef.name]));
- } else {
- valueNames[valueName] = valueDef.name;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- return false;
- }
- }
- },{"../../error/GraphQLError":19,"../../type/definition":68}],125:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateFieldDefinitionNameMessage = duplicateFieldDefinitionNameMessage;
- exports.existedFieldDefinitionNameMessage = existedFieldDefinitionNameMessage;
- exports.UniqueFieldDefinitionNames = UniqueFieldDefinitionNames;
- var _GraphQLError = require("../../error/GraphQLError");
- var _definition = require("../../type/definition");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateFieldDefinitionNameMessage(typeName, fieldName) {
- return "Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once.");
- }
- function existedFieldDefinitionNameMessage(typeName, fieldName) {
- return "Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. ") + 'It cannot also be defined in this type extension.';
- }
- /**
- * Unique field definition names
- *
- * A GraphQL complex type is only valid if all its fields are uniquely named.
- */
- function UniqueFieldDefinitionNames(context) {
- var schema = context.getSchema();
- var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
- var knownFieldNames = Object.create(null);
- return {
- InputObjectTypeDefinition: checkFieldUniqueness,
- InputObjectTypeExtension: checkFieldUniqueness,
- InterfaceTypeDefinition: checkFieldUniqueness,
- InterfaceTypeExtension: checkFieldUniqueness,
- ObjectTypeDefinition: checkFieldUniqueness,
- ObjectTypeExtension: checkFieldUniqueness
- };
- function checkFieldUniqueness(node) {
- var typeName = node.name.value;
- if (!knownFieldNames[typeName]) {
- knownFieldNames[typeName] = Object.create(null);
- }
- if (node.fields) {
- var fieldNames = knownFieldNames[typeName];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = node.fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var fieldDef = _step.value;
- var fieldName = fieldDef.name.value;
- if (hasField(existingTypeMap[typeName], fieldName)) {
- context.reportError(new _GraphQLError.GraphQLError(existedFieldDefinitionNameMessage(typeName, fieldName), fieldDef.name));
- } else if (fieldNames[fieldName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateFieldDefinitionNameMessage(typeName, fieldName), [fieldNames[fieldName], fieldDef.name]));
- } else {
- fieldNames[fieldName] = fieldDef.name;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- return false;
- }
- }
- function hasField(type, fieldName) {
- if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type) || (0, _definition.isInputObjectType)(type)) {
- return type.getFields()[fieldName];
- }
- return false;
- }
- },{"../../error/GraphQLError":19,"../../type/definition":68}],126:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateFragmentNameMessage = duplicateFragmentNameMessage;
- exports.UniqueFragmentNames = UniqueFragmentNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateFragmentNameMessage(fragName) {
- return "There can be only one fragment named \"".concat(fragName, "\".");
- }
- /**
- * Unique fragment names
- *
- * A GraphQL document is only valid if all defined fragments have unique names.
- */
- function UniqueFragmentNames(context) {
- var knownFragmentNames = Object.create(null);
- return {
- OperationDefinition: function OperationDefinition() {
- return false;
- },
- FragmentDefinition: function FragmentDefinition(node) {
- var fragmentName = node.name.value;
- if (knownFragmentNames[fragmentName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name]));
- } else {
- knownFragmentNames[fragmentName] = node.name;
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":19}],127:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateInputFieldMessage = duplicateInputFieldMessage;
- exports.UniqueInputFieldNames = UniqueInputFieldNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateInputFieldMessage(fieldName) {
- return "There can be only one input field named \"".concat(fieldName, "\".");
- }
- /**
- * Unique input field names
- *
- * A GraphQL input object value is only valid if all supplied fields are
- * uniquely named.
- */
- function UniqueInputFieldNames(context) {
- var knownNameStack = [];
- var knownNames = Object.create(null);
- return {
- ObjectValue: {
- enter: function enter() {
- knownNameStack.push(knownNames);
- knownNames = Object.create(null);
- },
- leave: function leave() {
- knownNames = knownNameStack.pop();
- }
- },
- ObjectField: function ObjectField(node) {
- var fieldName = node.name.value;
- if (knownNames[fieldName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateInputFieldMessage(fieldName), [knownNames[fieldName], node.name]));
- } else {
- knownNames[fieldName] = node.name;
- }
- }
- };
- }
- },{"../../error/GraphQLError":19}],128:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateOperationNameMessage = duplicateOperationNameMessage;
- exports.UniqueOperationNames = UniqueOperationNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateOperationNameMessage(operationName) {
- return "There can be only one operation named \"".concat(operationName, "\".");
- }
- /**
- * Unique operation names
- *
- * A GraphQL document is only valid if all defined operations have unique names.
- */
- function UniqueOperationNames(context) {
- var knownOperationNames = Object.create(null);
- return {
- OperationDefinition: function OperationDefinition(node) {
- var operationName = node.name;
- if (operationName) {
- if (knownOperationNames[operationName.value]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateOperationNameMessage(operationName.value), [knownOperationNames[operationName.value], operationName]));
- } else {
- knownOperationNames[operationName.value] = operationName;
- }
- }
- return false;
- },
- FragmentDefinition: function FragmentDefinition() {
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":19}],129:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateOperationTypeMessage = duplicateOperationTypeMessage;
- exports.existedOperationTypeMessage = existedOperationTypeMessage;
- exports.UniqueOperationTypes = UniqueOperationTypes;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateOperationTypeMessage(operation) {
- return "There can be only one ".concat(operation, " type in schema.");
- }
- function existedOperationTypeMessage(operation) {
- return "Type for ".concat(operation, " already defined in the schema. ") + 'It cannot be redefined.';
- }
- /**
- * Unique operation types
- *
- * A GraphQL document is only valid if it has only one type per operation.
- */
- function UniqueOperationTypes(context) {
- var schema = context.getSchema();
- var definedOperationTypes = Object.create(null);
- var existingOperationTypes = schema ? {
- query: schema.getQueryType(),
- mutation: schema.getMutationType(),
- subscription: schema.getSubscriptionType()
- } : {};
- return {
- SchemaDefinition: checkOperationTypes,
- SchemaExtension: checkOperationTypes
- };
- function checkOperationTypes(node) {
- if (node.operationTypes) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (node.operationTypes || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var operationType = _step.value;
- var operation = operationType.operation;
- var alreadyDefinedOperationType = definedOperationTypes[operation];
- if (existingOperationTypes[operation]) {
- context.reportError(new _GraphQLError.GraphQLError(existedOperationTypeMessage(operation), operationType));
- } else if (alreadyDefinedOperationType) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateOperationTypeMessage(operation), [alreadyDefinedOperationType, operationType]));
- } else {
- definedOperationTypes[operation] = operationType;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- return false;
- }
- }
- },{"../../error/GraphQLError":19}],130:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateTypeNameMessage = duplicateTypeNameMessage;
- exports.existedTypeNameMessage = existedTypeNameMessage;
- exports.UniqueTypeNames = UniqueTypeNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateTypeNameMessage(typeName) {
- return "There can be only one type named \"".concat(typeName, "\".");
- }
- function existedTypeNameMessage(typeName) {
- return "Type \"".concat(typeName, "\" already exists in the schema. ") + 'It cannot also be defined in this type definition.';
- }
- /**
- * Unique type names
- *
- * A GraphQL document is only valid if all defined types have unique names.
- */
- function UniqueTypeNames(context) {
- var knownTypeNames = Object.create(null);
- var schema = context.getSchema();
- return {
- ScalarTypeDefinition: checkTypeName,
- ObjectTypeDefinition: checkTypeName,
- InterfaceTypeDefinition: checkTypeName,
- UnionTypeDefinition: checkTypeName,
- EnumTypeDefinition: checkTypeName,
- InputObjectTypeDefinition: checkTypeName
- };
- function checkTypeName(node) {
- var typeName = node.name.value;
- if (schema && schema.getType(typeName)) {
- context.reportError(new _GraphQLError.GraphQLError(existedTypeNameMessage(typeName), node.name));
- return;
- }
- if (knownTypeNames[typeName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateTypeNameMessage(typeName), [knownTypeNames[typeName], node.name]));
- } else {
- knownTypeNames[typeName] = node.name;
- }
- return false;
- }
- }
- },{"../../error/GraphQLError":19}],131:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateVariableMessage = duplicateVariableMessage;
- exports.UniqueVariableNames = UniqueVariableNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateVariableMessage(variableName) {
- return "There can be only one variable named \"".concat(variableName, "\".");
- }
- /**
- * Unique variable names
- *
- * A GraphQL operation is only valid if all its variables are uniquely named.
- */
- function UniqueVariableNames(context) {
- var knownVariableNames = Object.create(null);
- return {
- OperationDefinition: function OperationDefinition() {
- knownVariableNames = Object.create(null);
- },
- VariableDefinition: function VariableDefinition(node) {
- var variableName = node.variable.name.value;
- if (knownVariableNames[variableName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateVariableMessage(variableName), [knownVariableNames[variableName], node.variable.name]));
- } else {
- knownVariableNames[variableName] = node.variable.name;
- }
- }
- };
- }
- },{"../../error/GraphQLError":19}],132:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.badValueMessage = badValueMessage;
- exports.requiredFieldMessage = requiredFieldMessage;
- exports.unknownFieldMessage = unknownFieldMessage;
- exports.ValuesOfCorrectType = ValuesOfCorrectType;
- var _objectValues = _interopRequireDefault(require("../../polyfills/objectValues"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _printer = require("../../language/printer");
- var _definition = require("../../type/definition");
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _isInvalid = _interopRequireDefault(require("../../jsutils/isInvalid"));
- var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap"));
- var _orList = _interopRequireDefault(require("../../jsutils/orList"));
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function badValueMessage(typeName, valueName, message) {
- return "Expected type ".concat(typeName, ", found ").concat(valueName) + (message ? "; ".concat(message) : '.');
- }
- function requiredFieldMessage(typeName, fieldName, fieldTypeName) {
- return "Field ".concat(typeName, ".").concat(fieldName, " of required type ") + "".concat(fieldTypeName, " was not provided.");
- }
- function unknownFieldMessage(typeName, fieldName, message) {
- return "Field \"".concat(fieldName, "\" is not defined by type ").concat(typeName) + (message ? "; ".concat(message) : '.');
- }
- /**
- * Value literals of correct type
- *
- * A GraphQL document is only valid if all value literals are of the type
- * expected at their position.
- */
- function ValuesOfCorrectType(context) {
- return {
- NullValue: function NullValue(node) {
- var type = context.getInputType();
- if ((0, _definition.isNonNullType)(type)) {
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(type), (0, _printer.print)(node)), node));
- }
- },
- ListValue: function ListValue(node) {
- // Note: TypeInfo will traverse into a list's item type, so look to the
- // parent input type to check if it is a list.
- var type = (0, _definition.getNullableType)(context.getParentInputType());
- if (!(0, _definition.isListType)(type)) {
- isValidScalar(context, node);
- return false; // Don't traverse further.
- }
- },
- ObjectValue: function ObjectValue(node) {
- var type = (0, _definition.getNamedType)(context.getInputType());
- if (!(0, _definition.isInputObjectType)(type)) {
- isValidScalar(context, node);
- return false; // Don't traverse further.
- } // Ensure every required field exists.
- var fieldNodeMap = (0, _keyMap.default)(node.fields, function (field) {
- return field.name.value;
- });
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var fieldDef = _step.value;
- var fieldNode = fieldNodeMap[fieldDef.name];
- if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) {
- var typeStr = (0, _inspect.default)(fieldDef.type);
- context.reportError(new _GraphQLError.GraphQLError(requiredFieldMessage(type.name, fieldDef.name, typeStr), node));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- },
- ObjectField: function ObjectField(node) {
- var parentType = (0, _definition.getNamedType)(context.getParentInputType());
- var fieldType = context.getInputType();
- if (!fieldType && (0, _definition.isInputObjectType)(parentType)) {
- var suggestions = (0, _suggestionList.default)(node.name.value, Object.keys(parentType.getFields()));
- var didYouMean = suggestions.length !== 0 ? "Did you mean ".concat((0, _orList.default)(suggestions), "?") : undefined;
- context.reportError(new _GraphQLError.GraphQLError(unknownFieldMessage(parentType.name, node.name.value, didYouMean), node));
- }
- },
- EnumValue: function EnumValue(node) {
- var type = (0, _definition.getNamedType)(context.getInputType());
- if (!(0, _definition.isEnumType)(type)) {
- isValidScalar(context, node);
- } else if (!type.getValue(node.value)) {
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage(type.name, (0, _printer.print)(node), enumTypeSuggestion(type, node)), node));
- }
- },
- IntValue: function IntValue(node) {
- return isValidScalar(context, node);
- },
- FloatValue: function FloatValue(node) {
- return isValidScalar(context, node);
- },
- StringValue: function StringValue(node) {
- return isValidScalar(context, node);
- },
- BooleanValue: function BooleanValue(node) {
- return isValidScalar(context, node);
- }
- };
- }
- /**
- * Any value literal may be a valid representation of a Scalar, depending on
- * that scalar type.
- */
- function isValidScalar(context, node) {
- // Report any error at the full type expected by the location.
- var locationType = context.getInputType();
- if (!locationType) {
- return;
- }
- var type = (0, _definition.getNamedType)(locationType);
- if (!(0, _definition.isScalarType)(type)) {
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node), enumTypeSuggestion(type, node)), node));
- return;
- } // Scalars determine if a literal value is valid via parseLiteral() which
- // may throw or return an invalid value to indicate failure.
- try {
- var parseResult = type.parseLiteral(node, undefined
- /* variables */
- );
- if ((0, _isInvalid.default)(parseResult)) {
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node)), node));
- }
- } catch (error) {
- // Ensure a reference to the original error is maintained.
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node), error.message), node, undefined, undefined, undefined, error));
- }
- }
- function enumTypeSuggestion(type, node) {
- if ((0, _definition.isEnumType)(type)) {
- var suggestions = (0, _suggestionList.default)((0, _printer.print)(node), type.getValues().map(function (value) {
- return value.name;
- }));
- if (suggestions.length !== 0) {
- return "Did you mean the enum value ".concat((0, _orList.default)(suggestions), "?");
- }
- }
- }
- },{"../../error/GraphQLError":19,"../../jsutils/inspect":32,"../../jsutils/isInvalid":35,"../../jsutils/keyMap":38,"../../jsutils/orList":43,"../../jsutils/suggestionList":47,"../../language/printer":56,"../../polyfills/objectValues":64,"../../type/definition":68}],133:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.nonInputTypeOnVarMessage = nonInputTypeOnVarMessage;
- exports.VariablesAreInputTypes = VariablesAreInputTypes;
- var _GraphQLError = require("../../error/GraphQLError");
- var _printer = require("../../language/printer");
- var _definition = require("../../type/definition");
- var _typeFromAST = require("../../utilities/typeFromAST");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function nonInputTypeOnVarMessage(variableName, typeName) {
- return "Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\".");
- }
- /**
- * Variables are input types
- *
- * A GraphQL operation is only valid if all the variables it defines are of
- * input types (scalar, enum, or input object).
- */
- function VariablesAreInputTypes(context) {
- return {
- VariableDefinition: function VariableDefinition(node) {
- var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.type); // If the variable type is not an input type, return an error.
- if (type && !(0, _definition.isInputType)(type)) {
- var variableName = node.variable.name.value;
- context.reportError(new _GraphQLError.GraphQLError(nonInputTypeOnVarMessage(variableName, (0, _printer.print)(node.type)), node.type));
- }
- }
- };
- }
- },{"../../error/GraphQLError":19,"../../language/printer":56,"../../type/definition":68,"../../utilities/typeFromAST":97}],134:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.badVarPosMessage = badVarPosMessage;
- exports.VariablesInAllowedPosition = VariablesInAllowedPosition;
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _definition = require("../../type/definition");
- var _typeComparators = require("../../utilities/typeComparators");
- var _typeFromAST = require("../../utilities/typeFromAST");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function badVarPosMessage(varName, varType, expectedType) {
- return "Variable \"$".concat(varName, "\" of type \"").concat(varType, "\" used in ") + "position expecting type \"".concat(expectedType, "\".");
- }
- /**
- * Variables passed to field arguments conform to type
- */
- function VariablesInAllowedPosition(context) {
- var varDefMap = Object.create(null);
- return {
- OperationDefinition: {
- enter: function enter() {
- varDefMap = Object.create(null);
- },
- leave: function leave(operation) {
- var usages = context.getRecursiveVariableUsages(operation);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref2 = _step.value;
- var node = _ref2.node;
- var type = _ref2.type;
- var defaultValue = _ref2.defaultValue;
- var varName = node.name.value;
- var varDef = varDefMap[varName];
- if (varDef && type) {
- // A var type is allowed if it is the same or more strict (e.g. is
- // a subtype of) than the expected type. It can be more strict if
- // the variable type is non-null when the expected type is nullable.
- // If both are list types, the variable item type can be more strict
- // than the expected item type (contravariant).
- var schema = context.getSchema();
- var varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type);
- if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) {
- context.reportError(new _GraphQLError.GraphQLError(badVarPosMessage(varName, (0, _inspect.default)(varType), (0, _inspect.default)(type)), [varDef, node]));
- }
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- },
- VariableDefinition: function VariableDefinition(node) {
- varDefMap[node.variable.name.value] = node;
- }
- };
- }
- /**
- * Returns true if the variable is allowed in the location it was found,
- * which includes considering if default values exist for either the variable
- * or the location at which it is located.
- */
- function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) {
- if ((0, _definition.isNonNullType)(locationType) && !(0, _definition.isNonNullType)(varType)) {
- var hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== _kinds.Kind.NULL;
- var hasLocationDefaultValue = locationDefaultValue !== undefined;
- if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) {
- return false;
- }
- var nullableLocationType = locationType.ofType;
- return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, nullableLocationType);
- }
- return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType);
- }
- },{"../../error/GraphQLError":19,"../../jsutils/inspect":32,"../../language/kinds":51,"../../type/definition":68,"../../utilities/typeComparators":96,"../../utilities/typeFromAST":97}],135:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.specifiedSDLRules = exports.specifiedRules = void 0;
- var _ExecutableDefinitions = require("./rules/ExecutableDefinitions");
- var _UniqueOperationNames = require("./rules/UniqueOperationNames");
- var _LoneAnonymousOperation = require("./rules/LoneAnonymousOperation");
- var _SingleFieldSubscriptions = require("./rules/SingleFieldSubscriptions");
- var _KnownTypeNames = require("./rules/KnownTypeNames");
- var _FragmentsOnCompositeTypes = require("./rules/FragmentsOnCompositeTypes");
- var _VariablesAreInputTypes = require("./rules/VariablesAreInputTypes");
- var _ScalarLeafs = require("./rules/ScalarLeafs");
- var _FieldsOnCorrectType = require("./rules/FieldsOnCorrectType");
- var _UniqueFragmentNames = require("./rules/UniqueFragmentNames");
- var _KnownFragmentNames = require("./rules/KnownFragmentNames");
- var _NoUnusedFragments = require("./rules/NoUnusedFragments");
- var _PossibleFragmentSpreads = require("./rules/PossibleFragmentSpreads");
- var _NoFragmentCycles = require("./rules/NoFragmentCycles");
- var _UniqueVariableNames = require("./rules/UniqueVariableNames");
- var _NoUndefinedVariables = require("./rules/NoUndefinedVariables");
- var _NoUnusedVariables = require("./rules/NoUnusedVariables");
- var _KnownDirectives = require("./rules/KnownDirectives");
- var _UniqueDirectivesPerLocation = require("./rules/UniqueDirectivesPerLocation");
- var _KnownArgumentNames = require("./rules/KnownArgumentNames");
- var _UniqueArgumentNames = require("./rules/UniqueArgumentNames");
- var _ValuesOfCorrectType = require("./rules/ValuesOfCorrectType");
- var _ProvidedRequiredArguments = require("./rules/ProvidedRequiredArguments");
- var _VariablesInAllowedPosition = require("./rules/VariablesInAllowedPosition");
- var _OverlappingFieldsCanBeMerged = require("./rules/OverlappingFieldsCanBeMerged");
- var _UniqueInputFieldNames = require("./rules/UniqueInputFieldNames");
- var _LoneSchemaDefinition = require("./rules/LoneSchemaDefinition");
- var _UniqueOperationTypes = require("./rules/UniqueOperationTypes");
- var _UniqueTypeNames = require("./rules/UniqueTypeNames");
- var _UniqueEnumValueNames = require("./rules/UniqueEnumValueNames");
- var _UniqueFieldDefinitionNames = require("./rules/UniqueFieldDefinitionNames");
- var _UniqueDirectiveNames = require("./rules/UniqueDirectiveNames");
- var _PossibleTypeExtensions = require("./rules/PossibleTypeExtensions");
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- // Spec Section: "Executable Definitions"
- // Spec Section: "Operation Name Uniqueness"
- // Spec Section: "Lone Anonymous Operation"
- // Spec Section: "Subscriptions with Single Root Field"
- // Spec Section: "Fragment Spread Type Existence"
- // Spec Section: "Fragments on Composite Types"
- // Spec Section: "Variables are Input Types"
- // Spec Section: "Leaf Field Selections"
- // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types"
- // Spec Section: "Fragment Name Uniqueness"
- // Spec Section: "Fragment spread target defined"
- // Spec Section: "Fragments must be used"
- // Spec Section: "Fragment spread is possible"
- // Spec Section: "Fragments must not form cycles"
- // Spec Section: "Variable Uniqueness"
- // Spec Section: "All Variable Used Defined"
- // Spec Section: "All Variables Used"
- // Spec Section: "Directives Are Defined"
- // Spec Section: "Directives Are Unique Per Location"
- // Spec Section: "Argument Names"
- // Spec Section: "Argument Uniqueness"
- // Spec Section: "Value Type Correctness"
- // Spec Section: "Argument Optionality"
- // Spec Section: "All Variable Usages Are Allowed"
- // Spec Section: "Field Selection Merging"
- // Spec Section: "Input Object Field Uniqueness"
- /**
- * This set includes all validation rules defined by the GraphQL spec.
- *
- * The order of the rules in this list has been adjusted to lead to the
- * most clear output when encountering multiple validation errors.
- */
- var specifiedRules = [_ExecutableDefinitions.ExecutableDefinitions, _UniqueOperationNames.UniqueOperationNames, _LoneAnonymousOperation.LoneAnonymousOperation, _SingleFieldSubscriptions.SingleFieldSubscriptions, _KnownTypeNames.KnownTypeNames, _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes, _VariablesAreInputTypes.VariablesAreInputTypes, _ScalarLeafs.ScalarLeafs, _FieldsOnCorrectType.FieldsOnCorrectType, _UniqueFragmentNames.UniqueFragmentNames, _KnownFragmentNames.KnownFragmentNames, _NoUnusedFragments.NoUnusedFragments, _PossibleFragmentSpreads.PossibleFragmentSpreads, _NoFragmentCycles.NoFragmentCycles, _UniqueVariableNames.UniqueVariableNames, _NoUndefinedVariables.NoUndefinedVariables, _NoUnusedVariables.NoUnusedVariables, _KnownDirectives.KnownDirectives, _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation, _KnownArgumentNames.KnownArgumentNames, _UniqueArgumentNames.UniqueArgumentNames, _ValuesOfCorrectType.ValuesOfCorrectType, _ProvidedRequiredArguments.ProvidedRequiredArguments, _VariablesInAllowedPosition.VariablesInAllowedPosition, _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged, _UniqueInputFieldNames.UniqueInputFieldNames];
- exports.specifiedRules = specifiedRules;
- // @internal
- var specifiedSDLRules = [_LoneSchemaDefinition.LoneSchemaDefinition, _UniqueOperationTypes.UniqueOperationTypes, _UniqueTypeNames.UniqueTypeNames, _UniqueEnumValueNames.UniqueEnumValueNames, _UniqueFieldDefinitionNames.UniqueFieldDefinitionNames, _UniqueDirectiveNames.UniqueDirectiveNames, _KnownTypeNames.KnownTypeNames, _KnownDirectives.KnownDirectives, _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation, _PossibleTypeExtensions.PossibleTypeExtensions, _KnownArgumentNames.KnownArgumentNamesOnDirectives, _UniqueArgumentNames.UniqueArgumentNames, _UniqueInputFieldNames.UniqueInputFieldNames, _ProvidedRequiredArguments.ProvidedRequiredArgumentsOnDirectives];
- exports.specifiedSDLRules = specifiedSDLRules;
- },{"./rules/ExecutableDefinitions":102,"./rules/FieldsOnCorrectType":103,"./rules/FragmentsOnCompositeTypes":104,"./rules/KnownArgumentNames":105,"./rules/KnownDirectives":106,"./rules/KnownFragmentNames":107,"./rules/KnownTypeNames":108,"./rules/LoneAnonymousOperation":109,"./rules/LoneSchemaDefinition":110,"./rules/NoFragmentCycles":111,"./rules/NoUndefinedVariables":112,"./rules/NoUnusedFragments":113,"./rules/NoUnusedVariables":114,"./rules/OverlappingFieldsCanBeMerged":115,"./rules/PossibleFragmentSpreads":116,"./rules/PossibleTypeExtensions":117,"./rules/ProvidedRequiredArguments":118,"./rules/ScalarLeafs":119,"./rules/SingleFieldSubscriptions":120,"./rules/UniqueArgumentNames":121,"./rules/UniqueDirectiveNames":122,"./rules/UniqueDirectivesPerLocation":123,"./rules/UniqueEnumValueNames":124,"./rules/UniqueFieldDefinitionNames":125,"./rules/UniqueFragmentNames":126,"./rules/UniqueInputFieldNames":127,"./rules/UniqueOperationNames":128,"./rules/UniqueOperationTypes":129,"./rules/UniqueTypeNames":130,"./rules/UniqueVariableNames":131,"./rules/ValuesOfCorrectType":132,"./rules/VariablesAreInputTypes":133,"./rules/VariablesInAllowedPosition":134}],136:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.validate = validate;
- exports.validateSDL = validateSDL;
- exports.assertValidSDL = assertValidSDL;
- exports.assertValidSDLExtension = assertValidSDLExtension;
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _visitor = require("../language/visitor");
- var _validate = require("../type/validate");
- var _TypeInfo = require("../utilities/TypeInfo");
- var _specifiedRules = require("./specifiedRules");
- var _ValidationContext = require("./ValidationContext");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Implements the "Validation" section of the spec.
- *
- * Validation runs synchronously, returning an array of encountered errors, or
- * an empty array if no errors were encountered and the document is valid.
- *
- * A list of specific validation rules may be provided. If not provided, the
- * default list of rules defined by the GraphQL specification will be used.
- *
- * Each validation rules is a function which returns a visitor
- * (see the language/visitor API). Visitor methods are expected to return
- * GraphQLErrors, or Arrays of GraphQLErrors when invalid.
- *
- * Optionally a custom TypeInfo instance may be provided. If not provided, one
- * will be created from the provided schema.
- */
- function validate(schema, documentAST) {
- var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedRules;
- var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new _TypeInfo.TypeInfo(schema);
- !documentAST ? (0, _invariant.default)(0, 'Must provide document') : void 0; // If the schema used for validation is invalid, throw an error.
- (0, _validate.assertValidSchema)(schema);
- var context = new _ValidationContext.ValidationContext(schema, documentAST, typeInfo); // This uses a specialized visitor which runs multiple visitors in parallel,
- // while maintaining the visitor skip and break API.
- var visitor = (0, _visitor.visitInParallel)(rules.map(function (rule) {
- return rule(context);
- })); // Visit the whole document with each instance of all provided rules.
- (0, _visitor.visit)(documentAST, (0, _visitor.visitWithTypeInfo)(typeInfo, visitor));
- return context.getErrors();
- } // @internal
- function validateSDL(documentAST, schemaToExtend) {
- var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedSDLRules;
- var context = new _ValidationContext.SDLValidationContext(documentAST, schemaToExtend);
- var visitors = rules.map(function (rule) {
- return rule(context);
- });
- (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors));
- return context.getErrors();
- }
- /**
- * Utility function which asserts a SDL document is valid by throwing an error
- * if it is invalid.
- *
- * @internal
- */
- function assertValidSDL(documentAST) {
- var errors = validateSDL(documentAST);
- if (errors.length !== 0) {
- throw new Error(errors.map(function (error) {
- return error.message;
- }).join('\n\n'));
- }
- }
- /**
- * Utility function which asserts a SDL document is valid by throwing an error
- * if it is invalid.
- *
- * @internal
- */
- function assertValidSDLExtension(documentAST, schema) {
- var errors = validateSDL(documentAST, schema);
- if (errors.length !== 0) {
- throw new Error(errors.map(function (error) {
- return error.message;
- }).join('\n\n'));
- }
- }
- },{"../jsutils/invariant":34,"../language/visitor":58,"../type/validate":74,"../utilities/TypeInfo":75,"./ValidationContext":100,"./specifiedRules":135}],137:[function(require,module,exports){
- 'use strict';
- exports.isIterable = isIterable;
- exports.isArrayLike = isArrayLike;
- exports.isCollection = isCollection;
- exports.getIterator = getIterator;
- exports.getIteratorMethod = getIteratorMethod;
- exports.createIterator = createIterator;
- exports.forEach = forEach;
- exports.isAsyncIterable = isAsyncIterable;
- exports.getAsyncIterator = getAsyncIterator;
- exports.getAsyncIteratorMethod = getAsyncIteratorMethod;
- exports.createAsyncIterator = createAsyncIterator;
- exports.forAwaitEach = forAwaitEach;
- var SYMBOL = typeof Symbol === 'function' ? Symbol : void 0;
- var SYMBOL_ITERATOR = SYMBOL && SYMBOL.iterator;
- var $$iterator = exports.$$iterator = SYMBOL_ITERATOR || '@@iterator';
- function isIterable(obj) {
- return !!getIteratorMethod(obj);
- }
- function isArrayLike(obj) {
- var length = obj != null && obj.length;
- return typeof length === 'number' && length >= 0 && length % 1 === 0;
- }
- function isCollection(obj) {
- return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj));
- }
- function getIterator(iterable) {
- var method = getIteratorMethod(iterable);
- if (method) {
- return method.call(iterable);
- }
- }
- function getIteratorMethod(iterable) {
- if (iterable != null) {
- var method = SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR] || iterable['@@iterator'];
- if (typeof method === 'function') {
- return method;
- }
- }
- }
- function createIterator(collection) {
- if (collection != null) {
- var iterator = getIterator(collection);
- if (iterator) {
- return iterator;
- }
- if (isArrayLike(collection)) {
- return new ArrayLikeIterator(collection);
- }
- }
- }
- function ArrayLikeIterator(obj) {
- this._o = obj;
- this._i = 0;
- }
- ArrayLikeIterator.prototype[$$iterator] = function () {
- return this;
- };
- ArrayLikeIterator.prototype.next = function () {
- if (this._o === void 0 || this._i >= this._o.length) {
- this._o = void 0;
- return { value: void 0, done: true };
- }
- return { value: this._o[this._i++], done: false };
- };
- function forEach(collection, callback, thisArg) {
- if (collection != null) {
- if (typeof collection.forEach === 'function') {
- return collection.forEach(callback, thisArg);
- }
- var i = 0;
- var iterator = getIterator(collection);
- if (iterator) {
- var step;
- while (!(step = iterator.next()).done) {
- callback.call(thisArg, step.value, i++, collection);
- if (i > 9999999) {
- throw new TypeError('Near-infinite iteration.');
- }
- }
- } else if (isArrayLike(collection)) {
- for (; i < collection.length; i++) {
- if (collection.hasOwnProperty(i)) {
- callback.call(thisArg, collection[i], i, collection);
- }
- }
- }
- }
- }
- var SYMBOL_ASYNC_ITERATOR = SYMBOL && SYMBOL.asyncIterator;
- var $$asyncIterator = exports.$$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator';
- function isAsyncIterable(obj) {
- return !!getAsyncIteratorMethod(obj);
- }
- function getAsyncIterator(asyncIterable) {
- var method = getAsyncIteratorMethod(asyncIterable);
- if (method) {
- return method.call(asyncIterable);
- }
- }
- function getAsyncIteratorMethod(asyncIterable) {
- if (asyncIterable != null) {
- var method = SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR] || asyncIterable['@@asyncIterator'];
- if (typeof method === 'function') {
- return method;
- }
- }
- }
- function createAsyncIterator(source) {
- if (source != null) {
- var asyncIterator = getAsyncIterator(source);
- if (asyncIterator) {
- return asyncIterator;
- }
- var iterator = createIterator(source);
- if (iterator) {
- return new AsyncFromSyncIterator(iterator);
- }
- }
- }
- function AsyncFromSyncIterator(iterator) {
- this._i = iterator;
- }
- AsyncFromSyncIterator.prototype[$$asyncIterator] = function () {
- return this;
- };
- AsyncFromSyncIterator.prototype.next = function () {
- var step = this._i.next();
- return Promise.resolve(step.value).then(function (value) {
- return { value: value, done: step.done };
- });
- };
- function forAwaitEach(source, callback, thisArg) {
- var asyncIterator = createAsyncIterator(source);
- if (asyncIterator) {
- var i = 0;
- return new Promise(function (resolve, reject) {
- function next() {
- asyncIterator.next().then(function (step) {
- if (!step.done) {
- Promise.resolve(callback.call(thisArg, step.value, i++, source)).then(next).catch(reject);
- } else {
- resolve();
- }
- return null;
- }).catch(reject);
- return null;
- }
- next();
- });
- }
- }
- },{}],138:[function(require,module,exports){
- 'use strict';
- ////////////////////////////////////////////////////////////////////////////////
- // Helpers
- // Merge objects
- //
- function assign(obj /*from1, from2, from3, ...*/) {
- var sources = Array.prototype.slice.call(arguments, 1);
- sources.forEach(function (source) {
- if (!source) { return; }
- Object.keys(source).forEach(function (key) {
- obj[key] = source[key];
- });
- });
- return obj;
- }
- function _class(obj) { return Object.prototype.toString.call(obj); }
- function isString(obj) { return _class(obj) === '[object String]'; }
- function isObject(obj) { return _class(obj) === '[object Object]'; }
- function isRegExp(obj) { return _class(obj) === '[object RegExp]'; }
- function isFunction(obj) { return _class(obj) === '[object Function]'; }
- function escapeRE(str) { return str.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&'); }
- ////////////////////////////////////////////////////////////////////////////////
- var defaultOptions = {
- fuzzyLink: true,
- fuzzyEmail: true,
- fuzzyIP: false
- };
- function isOptionsObj(obj) {
- return Object.keys(obj || {}).reduce(function (acc, k) {
- return acc || defaultOptions.hasOwnProperty(k);
- }, false);
- }
- var defaultSchemas = {
- 'http:': {
- validate: function (text, pos, self) {
- var tail = text.slice(pos);
- if (!self.re.http) {
- // compile lazily, because "host"-containing variables can change on tlds update.
- self.re.http = new RegExp(
- '^\\/\\/' + self.re.src_auth + self.re.src_host_port_strict + self.re.src_path, 'i'
- );
- }
- if (self.re.http.test(tail)) {
- return tail.match(self.re.http)[0].length;
- }
- return 0;
- }
- },
- 'https:': 'http:',
- 'ftp:': 'http:',
- '//': {
- validate: function (text, pos, self) {
- var tail = text.slice(pos);
- if (!self.re.no_http) {
- // compile lazily, because "host"-containing variables can change on tlds update.
- self.re.no_http = new RegExp(
- '^' +
- self.re.src_auth +
- // Don't allow single-level domains, because of false positives like '//test'
- // with code comments
- '(?:localhost|(?:(?:' + self.re.src_domain + ')\\.)+' + self.re.src_domain_root + ')' +
- self.re.src_port +
- self.re.src_host_terminator +
- self.re.src_path,
- 'i'
- );
- }
- if (self.re.no_http.test(tail)) {
- // should not be `://` & `///`, that protects from errors in protocol name
- if (pos >= 3 && text[pos - 3] === ':') { return 0; }
- if (pos >= 3 && text[pos - 3] === '/') { return 0; }
- return tail.match(self.re.no_http)[0].length;
- }
- return 0;
- }
- },
- 'mailto:': {
- validate: function (text, pos, self) {
- var tail = text.slice(pos);
- if (!self.re.mailto) {
- self.re.mailto = new RegExp(
- '^' + self.re.src_email_name + '@' + self.re.src_host_strict, 'i'
- );
- }
- if (self.re.mailto.test(tail)) {
- return tail.match(self.re.mailto)[0].length;
- }
- return 0;
- }
- }
- };
- /*eslint-disable max-len*/
- // RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js)
- var tlds_2ch_src_re = 'a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]';
- // DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead
- var tlds_default = 'biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф'.split('|');
- /*eslint-enable max-len*/
- ////////////////////////////////////////////////////////////////////////////////
- function resetScanCache(self) {
- self.__index__ = -1;
- self.__text_cache__ = '';
- }
- function createValidator(re) {
- return function (text, pos) {
- var tail = text.slice(pos);
- if (re.test(tail)) {
- return tail.match(re)[0].length;
- }
- return 0;
- };
- }
- function createNormalizer() {
- return function (match, self) {
- self.normalize(match);
- };
- }
- // Schemas compiler. Build regexps.
- //
- function compile(self) {
- // Load & clone RE patterns.
- var re = self.re = require('./lib/re')(self.__opts__);
- // Define dynamic patterns
- var tlds = self.__tlds__.slice();
- self.onCompile();
- if (!self.__tlds_replaced__) {
- tlds.push(tlds_2ch_src_re);
- }
- tlds.push(re.src_xn);
- re.src_tlds = tlds.join('|');
- function untpl(tpl) { return tpl.replace('%TLDS%', re.src_tlds); }
- re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), 'i');
- re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), 'i');
- re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), 'i');
- re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), 'i');
- //
- // Compile each schema
- //
- var aliases = [];
- self.__compiled__ = {}; // Reset compiled data
- function schemaError(name, val) {
- throw new Error('(LinkifyIt) Invalid schema "' + name + '": ' + val);
- }
- Object.keys(self.__schemas__).forEach(function (name) {
- var val = self.__schemas__[name];
- // skip disabled methods
- if (val === null) { return; }
- var compiled = { validate: null, link: null };
- self.__compiled__[name] = compiled;
- if (isObject(val)) {
- if (isRegExp(val.validate)) {
- compiled.validate = createValidator(val.validate);
- } else if (isFunction(val.validate)) {
- compiled.validate = val.validate;
- } else {
- schemaError(name, val);
- }
- if (isFunction(val.normalize)) {
- compiled.normalize = val.normalize;
- } else if (!val.normalize) {
- compiled.normalize = createNormalizer();
- } else {
- schemaError(name, val);
- }
- return;
- }
- if (isString(val)) {
- aliases.push(name);
- return;
- }
- schemaError(name, val);
- });
- //
- // Compile postponed aliases
- //
- aliases.forEach(function (alias) {
- if (!self.__compiled__[self.__schemas__[alias]]) {
- // Silently fail on missed schemas to avoid errons on disable.
- // schemaError(alias, self.__schemas__[alias]);
- return;
- }
- self.__compiled__[alias].validate =
- self.__compiled__[self.__schemas__[alias]].validate;
- self.__compiled__[alias].normalize =
- self.__compiled__[self.__schemas__[alias]].normalize;
- });
- //
- // Fake record for guessed links
- //
- self.__compiled__[''] = { validate: null, normalize: createNormalizer() };
- //
- // Build schema condition
- //
- var slist = Object.keys(self.__compiled__)
- .filter(function (name) {
- // Filter disabled & fake schemas
- return name.length > 0 && self.__compiled__[name];
- })
- .map(escapeRE)
- .join('|');
- // (?!_) cause 1.5x slowdown
- self.re.schema_test = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'i');
- self.re.schema_search = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'ig');
- self.re.pretest = RegExp(
- '(' + self.re.schema_test.source + ')|' +
- '(' + self.re.host_fuzzy_test.source + ')|' +
- '@',
- 'i');
- //
- // Cleanup
- //
- resetScanCache(self);
- }
- /**
- * class Match
- *
- * Match result. Single element of array, returned by [[LinkifyIt#match]]
- **/
- function Match(self, shift) {
- var start = self.__index__,
- end = self.__last_index__,
- text = self.__text_cache__.slice(start, end);
- /**
- * Match#schema -> String
- *
- * Prefix (protocol) for matched string.
- **/
- this.schema = self.__schema__.toLowerCase();
- /**
- * Match#index -> Number
- *
- * First position of matched string.
- **/
- this.index = start + shift;
- /**
- * Match#lastIndex -> Number
- *
- * Next position after matched string.
- **/
- this.lastIndex = end + shift;
- /**
- * Match#raw -> String
- *
- * Matched string.
- **/
- this.raw = text;
- /**
- * Match#text -> String
- *
- * Notmalized text of matched string.
- **/
- this.text = text;
- /**
- * Match#url -> String
- *
- * Normalized url of matched string.
- **/
- this.url = text;
- }
- function createMatch(self, shift) {
- var match = new Match(self, shift);
- self.__compiled__[match.schema].normalize(match, self);
- return match;
- }
- /**
- * class LinkifyIt
- **/
- /**
- * new LinkifyIt(schemas, options)
- * - schemas (Object): Optional. Additional schemas to validate (prefix/validator)
- * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false }
- *
- * Creates new linkifier instance with optional additional schemas.
- * Can be called without `new` keyword for convenience.
- *
- * By default understands:
- *
- * - `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links
- * - "fuzzy" links and emails (example.com, foo@bar.com).
- *
- * `schemas` is an object, where each key/value describes protocol/rule:
- *
- * - __key__ - link prefix (usually, protocol name with `:` at the end, `skype:`
- * for example). `linkify-it` makes shure that prefix is not preceeded with
- * alphanumeric char and symbols. Only whitespaces and punctuation allowed.
- * - __value__ - rule to check tail after link prefix
- * - _String_ - just alias to existing rule
- * - _Object_
- * - _validate_ - validator function (should return matched length on success),
- * or `RegExp`.
- * - _normalize_ - optional function to normalize text & url of matched result
- * (for example, for @twitter mentions).
- *
- * `options`:
- *
- * - __fuzzyLink__ - recognige URL-s without `http(s):` prefix. Default `true`.
- * - __fuzzyIP__ - allow IPs in fuzzy links above. Can conflict with some texts
- * like version numbers. Default `false`.
- * - __fuzzyEmail__ - recognize emails without `mailto:` prefix.
- *
- **/
- function LinkifyIt(schemas, options) {
- if (!(this instanceof LinkifyIt)) {
- return new LinkifyIt(schemas, options);
- }
- if (!options) {
- if (isOptionsObj(schemas)) {
- options = schemas;
- schemas = {};
- }
- }
- this.__opts__ = assign({}, defaultOptions, options);
- // Cache last tested result. Used to skip repeating steps on next `match` call.
- this.__index__ = -1;
- this.__last_index__ = -1; // Next scan position
- this.__schema__ = '';
- this.__text_cache__ = '';
- this.__schemas__ = assign({}, defaultSchemas, schemas);
- this.__compiled__ = {};
- this.__tlds__ = tlds_default;
- this.__tlds_replaced__ = false;
- this.re = {};
- compile(this);
- }
- /** chainable
- * LinkifyIt#add(schema, definition)
- * - schema (String): rule name (fixed pattern prefix)
- * - definition (String|RegExp|Object): schema definition
- *
- * Add new rule definition. See constructor description for details.
- **/
- LinkifyIt.prototype.add = function add(schema, definition) {
- this.__schemas__[schema] = definition;
- compile(this);
- return this;
- };
- /** chainable
- * LinkifyIt#set(options)
- * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false }
- *
- * Set recognition options for links without schema.
- **/
- LinkifyIt.prototype.set = function set(options) {
- this.__opts__ = assign(this.__opts__, options);
- return this;
- };
- /**
- * LinkifyIt#test(text) -> Boolean
- *
- * Searches linkifiable pattern and returns `true` on success or `false` on fail.
- **/
- LinkifyIt.prototype.test = function test(text) {
- // Reset scan cache
- this.__text_cache__ = text;
- this.__index__ = -1;
- if (!text.length) { return false; }
- var m, ml, me, len, shift, next, re, tld_pos, at_pos;
- // try to scan for link with schema - that's the most simple rule
- if (this.re.schema_test.test(text)) {
- re = this.re.schema_search;
- re.lastIndex = 0;
- while ((m = re.exec(text)) !== null) {
- len = this.testSchemaAt(text, m[2], re.lastIndex);
- if (len) {
- this.__schema__ = m[2];
- this.__index__ = m.index + m[1].length;
- this.__last_index__ = m.index + m[0].length + len;
- break;
- }
- }
- }
- if (this.__opts__.fuzzyLink && this.__compiled__['http:']) {
- // guess schemaless links
- tld_pos = text.search(this.re.host_fuzzy_test);
- if (tld_pos >= 0) {
- // if tld is located after found link - no need to check fuzzy pattern
- if (this.__index__ < 0 || tld_pos < this.__index__) {
- if ((ml = text.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) {
- shift = ml.index + ml[1].length;
- if (this.__index__ < 0 || shift < this.__index__) {
- this.__schema__ = '';
- this.__index__ = shift;
- this.__last_index__ = ml.index + ml[0].length;
- }
- }
- }
- }
- }
- if (this.__opts__.fuzzyEmail && this.__compiled__['mailto:']) {
- // guess schemaless emails
- at_pos = text.indexOf('@');
- if (at_pos >= 0) {
- // We can't skip this check, because this cases are possible:
- // 192.168.1.1@gmail.com, my.in@example.com
- if ((me = text.match(this.re.email_fuzzy)) !== null) {
- shift = me.index + me[1].length;
- next = me.index + me[0].length;
- if (this.__index__ < 0 || shift < this.__index__ ||
- (shift === this.__index__ && next > this.__last_index__)) {
- this.__schema__ = 'mailto:';
- this.__index__ = shift;
- this.__last_index__ = next;
- }
- }
- }
- }
- return this.__index__ >= 0;
- };
- /**
- * LinkifyIt#pretest(text) -> Boolean
- *
- * Very quick check, that can give false positives. Returns true if link MAY BE
- * can exists. Can be used for speed optimization, when you need to check that
- * link NOT exists.
- **/
- LinkifyIt.prototype.pretest = function pretest(text) {
- return this.re.pretest.test(text);
- };
- /**
- * LinkifyIt#testSchemaAt(text, name, position) -> Number
- * - text (String): text to scan
- * - name (String): rule (schema) name
- * - position (Number): text offset to check from
- *
- * Similar to [[LinkifyIt#test]] but checks only specific protocol tail exactly
- * at given position. Returns length of found pattern (0 on fail).
- **/
- LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text, schema, pos) {
- // If not supported schema check requested - terminate
- if (!this.__compiled__[schema.toLowerCase()]) {
- return 0;
- }
- return this.__compiled__[schema.toLowerCase()].validate(text, pos, this);
- };
- /**
- * LinkifyIt#match(text) -> Array|null
- *
- * Returns array of found link descriptions or `null` on fail. We strongly
- * recommend to use [[LinkifyIt#test]] first, for best speed.
- *
- * ##### Result match description
- *
- * - __schema__ - link schema, can be empty for fuzzy links, or `//` for
- * protocol-neutral links.
- * - __index__ - offset of matched text
- * - __lastIndex__ - index of next char after mathch end
- * - __raw__ - matched text
- * - __text__ - normalized text
- * - __url__ - link, generated from matched text
- **/
- LinkifyIt.prototype.match = function match(text) {
- var shift = 0, result = [];
- // Try to take previous element from cache, if .test() called before
- if (this.__index__ >= 0 && this.__text_cache__ === text) {
- result.push(createMatch(this, shift));
- shift = this.__last_index__;
- }
- // Cut head if cache was used
- var tail = shift ? text.slice(shift) : text;
- // Scan string until end reached
- while (this.test(tail)) {
- result.push(createMatch(this, shift));
- tail = tail.slice(this.__last_index__);
- shift += this.__last_index__;
- }
- if (result.length) {
- return result;
- }
- return null;
- };
- /** chainable
- * LinkifyIt#tlds(list [, keepOld]) -> this
- * - list (Array): list of tlds
- * - keepOld (Boolean): merge with current list if `true` (`false` by default)
- *
- * Load (or merge) new tlds list. Those are user for fuzzy links (without prefix)
- * to avoid false positives. By default this algorythm used:
- *
- * - hostname with any 2-letter root zones are ok.
- * - biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф
- * are ok.
- * - encoded (`xn--...`) root zones are ok.
- *
- * If list is replaced, then exact match for 2-chars root zones will be checked.
- **/
- LinkifyIt.prototype.tlds = function tlds(list, keepOld) {
- list = Array.isArray(list) ? list : [ list ];
- if (!keepOld) {
- this.__tlds__ = list.slice();
- this.__tlds_replaced__ = true;
- compile(this);
- return this;
- }
- this.__tlds__ = this.__tlds__.concat(list)
- .sort()
- .filter(function (el, idx, arr) {
- return el !== arr[idx - 1];
- })
- .reverse();
- compile(this);
- return this;
- };
- /**
- * LinkifyIt#normalize(match)
- *
- * Default normalizer (if schema does not define it's own).
- **/
- LinkifyIt.prototype.normalize = function normalize(match) {
- // Do minimal possible changes by default. Need to collect feedback prior
- // to move forward https://github.com/markdown-it/linkify-it/issues/1
- if (!match.schema) { match.url = 'http://' + match.url; }
- if (match.schema === 'mailto:' && !/^mailto:/i.test(match.url)) {
- match.url = 'mailto:' + match.url;
- }
- };
- /**
- * LinkifyIt#onCompile()
- *
- * Override to modify basic RegExp-s.
- **/
- LinkifyIt.prototype.onCompile = function onCompile() {
- };
- module.exports = LinkifyIt;
- },{"./lib/re":139}],139:[function(require,module,exports){
- 'use strict';
- module.exports = function (opts) {
- var re = {};
- // Use direct extract instead of `regenerate` to reduse browserified size
- re.src_Any = require('uc.micro/properties/Any/regex').source;
- re.src_Cc = require('uc.micro/categories/Cc/regex').source;
- re.src_Z = require('uc.micro/categories/Z/regex').source;
- re.src_P = require('uc.micro/categories/P/regex').source;
- // \p{\Z\P\Cc\CF} (white spaces + control + format + punctuation)
- re.src_ZPCc = [ re.src_Z, re.src_P, re.src_Cc ].join('|');
- // \p{\Z\Cc} (white spaces + control)
- re.src_ZCc = [ re.src_Z, re.src_Cc ].join('|');
- // Experimental. List of chars, completely prohibited in links
- // because can separate it from other part of text
- var text_separators = '[><\uff5c]';
- // All possible word characters (everything without punctuation, spaces & controls)
- // Defined via punctuation & spaces to save space
- // Should be something like \p{\L\N\S\M} (\w but without `_`)
- re.src_pseudo_letter = '(?:(?!' + text_separators + '|' + re.src_ZPCc + ')' + re.src_Any + ')';
- // The same as abothe but without [0-9]
- // var src_pseudo_letter_non_d = '(?:(?![0-9]|' + src_ZPCc + ')' + src_Any + ')';
- ////////////////////////////////////////////////////////////////////////////////
- re.src_ip4 =
- '(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)';
- // Prohibit any of "@/[]()" in user/pass to avoid wrong domain fetch.
- re.src_auth = '(?:(?:(?!' + re.src_ZCc + '|[@/\\[\\]()]).)+@)?';
- re.src_port =
- '(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?';
- re.src_host_terminator =
- '(?=$|' + text_separators + '|' + re.src_ZPCc + ')(?!-|_|:\\d|\\.-|\\.(?!$|' + re.src_ZPCc + '))';
- re.src_path =
- '(?:' +
- '[/?#]' +
- '(?:' +
- '(?!' + re.src_ZCc + '|' + text_separators + '|[()[\\]{}.,"\'?!\\-]).|' +
- '\\[(?:(?!' + re.src_ZCc + '|\\]).)*\\]|' +
- '\\((?:(?!' + re.src_ZCc + '|[)]).)*\\)|' +
- '\\{(?:(?!' + re.src_ZCc + '|[}]).)*\\}|' +
- '\\"(?:(?!' + re.src_ZCc + '|["]).)+\\"|' +
- "\\'(?:(?!" + re.src_ZCc + "|[']).)+\\'|" +
- "\\'(?=" + re.src_pseudo_letter + '|[-]).|' + // allow `I'm_king` if no pair found
- '\\.{2,3}[a-zA-Z0-9%/]|' + // github has ... in commit range links. Restrict to
- // - english
- // - percent-encoded
- // - parts of file path
- // until more examples found.
- '\\.(?!' + re.src_ZCc + '|[.]).|' +
- (opts && opts['---'] ?
- '\\-(?!--(?:[^-]|$))(?:-*)|' // `---` => long dash, terminate
- :
- '\\-+|'
- ) +
- '\\,(?!' + re.src_ZCc + ').|' + // allow `,,,` in paths
- '\\!(?!' + re.src_ZCc + '|[!]).|' +
- '\\?(?!' + re.src_ZCc + '|[?]).' +
- ')+' +
- '|\\/' +
- ')?';
- re.src_email_name =
- '[\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]+';
- re.src_xn =
- 'xn--[a-z0-9\\-]{1,59}';
- // More to read about domain names
- // http://serverfault.com/questions/638260/
- re.src_domain_root =
- // Allow letters & digits (http://test1)
- '(?:' +
- re.src_xn +
- '|' +
- re.src_pseudo_letter + '{1,63}' +
- ')';
- re.src_domain =
- '(?:' +
- re.src_xn +
- '|' +
- '(?:' + re.src_pseudo_letter + ')' +
- '|' +
- // don't allow `--` in domain names, because:
- // - that can conflict with markdown — / –
- // - nobody use those anyway
- '(?:' + re.src_pseudo_letter + '(?:-(?!-)|' + re.src_pseudo_letter + '){0,61}' + re.src_pseudo_letter + ')' +
- ')';
- re.src_host =
- '(?:' +
- // Don't need IP check, because digits are already allowed in normal domain names
- // src_ip4 +
- // '|' +
- '(?:(?:(?:' + re.src_domain + ')\\.)*' + re.src_domain/*_root*/ + ')' +
- ')';
- re.tpl_host_fuzzy =
- '(?:' +
- re.src_ip4 +
- '|' +
- '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))' +
- ')';
- re.tpl_host_no_ip_fuzzy =
- '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))';
- re.src_host_strict =
- re.src_host + re.src_host_terminator;
- re.tpl_host_fuzzy_strict =
- re.tpl_host_fuzzy + re.src_host_terminator;
- re.src_host_port_strict =
- re.src_host + re.src_port + re.src_host_terminator;
- re.tpl_host_port_fuzzy_strict =
- re.tpl_host_fuzzy + re.src_port + re.src_host_terminator;
- re.tpl_host_port_no_ip_fuzzy_strict =
- re.tpl_host_no_ip_fuzzy + re.src_port + re.src_host_terminator;
- ////////////////////////////////////////////////////////////////////////////////
- // Main rules
- // Rude test fuzzy links by host, for quick deny
- re.tpl_host_fuzzy_test =
- 'localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:' + re.src_ZPCc + '|>|$))';
- re.tpl_email_fuzzy =
- '(^|' + text_separators + '|\\(|' + re.src_ZCc + ')(' + re.src_email_name + '@' + re.tpl_host_fuzzy_strict + ')';
- re.tpl_link_fuzzy =
- // Fuzzy link can't be prepended with .:/\- and non punctuation.
- // but can start with > (markdown blockquote)
- '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' +
- '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_fuzzy_strict + re.src_path + ')';
- re.tpl_link_no_ip_fuzzy =
- // Fuzzy link can't be prepended with .:/\- and non punctuation.
- // but can start with > (markdown blockquote)
- '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' +
- '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_no_ip_fuzzy_strict + re.src_path + ')';
- return re;
- };
- },{"uc.micro/categories/Cc/regex":208,"uc.micro/categories/P/regex":210,"uc.micro/categories/Z/regex":211,"uc.micro/properties/Any/regex":213}],140:[function(require,module,exports){
- 'use strict';
- module.exports = require('./lib/');
- },{"./lib/":149}],141:[function(require,module,exports){
- // HTML5 entities map: { name -> utf16string }
- //
- 'use strict';
- /*eslint quotes:0*/
- module.exports = require('entities/maps/entities.json');
- },{"entities/maps/entities.json":18}],142:[function(require,module,exports){
- // List of valid html blocks names, accorting to commonmark spec
- // http://jgm.github.io/CommonMark/spec.html#html-blocks
- 'use strict';
- module.exports = [
- 'address',
- 'article',
- 'aside',
- 'base',
- 'basefont',
- 'blockquote',
- 'body',
- 'caption',
- 'center',
- 'col',
- 'colgroup',
- 'dd',
- 'details',
- 'dialog',
- 'dir',
- 'div',
- 'dl',
- 'dt',
- 'fieldset',
- 'figcaption',
- 'figure',
- 'footer',
- 'form',
- 'frame',
- 'frameset',
- 'h1',
- 'h2',
- 'h3',
- 'h4',
- 'h5',
- 'h6',
- 'head',
- 'header',
- 'hr',
- 'html',
- 'iframe',
- 'legend',
- 'li',
- 'link',
- 'main',
- 'menu',
- 'menuitem',
- 'meta',
- 'nav',
- 'noframes',
- 'ol',
- 'optgroup',
- 'option',
- 'p',
- 'param',
- 'section',
- 'source',
- 'summary',
- 'table',
- 'tbody',
- 'td',
- 'tfoot',
- 'th',
- 'thead',
- 'title',
- 'tr',
- 'track',
- 'ul'
- ];
- },{}],143:[function(require,module,exports){
- // Regexps to match html elements
- 'use strict';
- var attr_name = '[a-zA-Z_:][a-zA-Z0-9:._-]*';
- var unquoted = '[^"\'=<>`\\x00-\\x20]+';
- var single_quoted = "'[^']*'";
- var double_quoted = '"[^"]*"';
- var attr_value = '(?:' + unquoted + '|' + single_quoted + '|' + double_quoted + ')';
- var attribute = '(?:\\s+' + attr_name + '(?:\\s*=\\s*' + attr_value + ')?)';
- var open_tag = '<[A-Za-z][A-Za-z0-9\\-]*' + attribute + '*\\s*\\/?>';
- var close_tag = '<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>';
- var comment = '<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->';
- var processing = '<[?].*?[?]>';
- var declaration = '<![A-Z]+\\s+[^>]*>';
- var cdata = '<!\\[CDATA\\[[\\s\\S]*?\\]\\]>';
- var HTML_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + '|' + comment +
- '|' + processing + '|' + declaration + '|' + cdata + ')');
- var HTML_OPEN_CLOSE_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + ')');
- module.exports.HTML_TAG_RE = HTML_TAG_RE;
- module.exports.HTML_OPEN_CLOSE_TAG_RE = HTML_OPEN_CLOSE_TAG_RE;
- },{}],144:[function(require,module,exports){
- // Utilities
- //
- 'use strict';
- function _class(obj) { return Object.prototype.toString.call(obj); }
- function isString(obj) { return _class(obj) === '[object String]'; }
- var _hasOwnProperty = Object.prototype.hasOwnProperty;
- function has(object, key) {
- return _hasOwnProperty.call(object, key);
- }
- // Merge objects
- //
- function assign(obj /*from1, from2, from3, ...*/) {
- var sources = Array.prototype.slice.call(arguments, 1);
- sources.forEach(function (source) {
- if (!source) { return; }
- if (typeof source !== 'object') {
- throw new TypeError(source + 'must be object');
- }
- Object.keys(source).forEach(function (key) {
- obj[key] = source[key];
- });
- });
- return obj;
- }
- // Remove element from array and put another array at those position.
- // Useful for some operations with tokens
- function arrayReplaceAt(src, pos, newElements) {
- return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1));
- }
- ////////////////////////////////////////////////////////////////////////////////
- function isValidEntityCode(c) {
- /*eslint no-bitwise:0*/
- // broken sequence
- if (c >= 0xD800 && c <= 0xDFFF) { return false; }
- // never used
- if (c >= 0xFDD0 && c <= 0xFDEF) { return false; }
- if ((c & 0xFFFF) === 0xFFFF || (c & 0xFFFF) === 0xFFFE) { return false; }
- // control codes
- if (c >= 0x00 && c <= 0x08) { return false; }
- if (c === 0x0B) { return false; }
- if (c >= 0x0E && c <= 0x1F) { return false; }
- if (c >= 0x7F && c <= 0x9F) { return false; }
- // out of range
- if (c > 0x10FFFF) { return false; }
- return true;
- }
- function fromCodePoint(c) {
- /*eslint no-bitwise:0*/
- if (c > 0xffff) {
- c -= 0x10000;
- var surrogate1 = 0xd800 + (c >> 10),
- surrogate2 = 0xdc00 + (c & 0x3ff);
- return String.fromCharCode(surrogate1, surrogate2);
- }
- return String.fromCharCode(c);
- }
- var UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])/g;
- var ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi;
- var UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + '|' + ENTITY_RE.source, 'gi');
- var DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;
- var entities = require('./entities');
- function replaceEntityPattern(match, name) {
- var code = 0;
- if (has(entities, name)) {
- return entities[name];
- }
- if (name.charCodeAt(0) === 0x23/* # */ && DIGITAL_ENTITY_TEST_RE.test(name)) {
- code = name[1].toLowerCase() === 'x' ?
- parseInt(name.slice(2), 16)
- :
- parseInt(name.slice(1), 10);
- if (isValidEntityCode(code)) {
- return fromCodePoint(code);
- }
- }
- return match;
- }
- /*function replaceEntities(str) {
- if (str.indexOf('&') < 0) { return str; }
- return str.replace(ENTITY_RE, replaceEntityPattern);
- }*/
- function unescapeMd(str) {
- if (str.indexOf('\\') < 0) { return str; }
- return str.replace(UNESCAPE_MD_RE, '$1');
- }
- function unescapeAll(str) {
- if (str.indexOf('\\') < 0 && str.indexOf('&') < 0) { return str; }
- return str.replace(UNESCAPE_ALL_RE, function (match, escaped, entity) {
- if (escaped) { return escaped; }
- return replaceEntityPattern(match, entity);
- });
- }
- ////////////////////////////////////////////////////////////////////////////////
- var HTML_ESCAPE_TEST_RE = /[&<>"]/;
- var HTML_ESCAPE_REPLACE_RE = /[&<>"]/g;
- var HTML_REPLACEMENTS = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"'
- };
- function replaceUnsafeChar(ch) {
- return HTML_REPLACEMENTS[ch];
- }
- function escapeHtml(str) {
- if (HTML_ESCAPE_TEST_RE.test(str)) {
- return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);
- }
- return str;
- }
- ////////////////////////////////////////////////////////////////////////////////
- var REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g;
- function escapeRE(str) {
- return str.replace(REGEXP_ESCAPE_RE, '\\$&');
- }
- ////////////////////////////////////////////////////////////////////////////////
- function isSpace(code) {
- switch (code) {
- case 0x09:
- case 0x20:
- return true;
- }
- return false;
- }
- // Zs (unicode class) || [\t\f\v\r\n]
- function isWhiteSpace(code) {
- if (code >= 0x2000 && code <= 0x200A) { return true; }
- switch (code) {
- case 0x09: // \t
- case 0x0A: // \n
- case 0x0B: // \v
- case 0x0C: // \f
- case 0x0D: // \r
- case 0x20:
- case 0xA0:
- case 0x1680:
- case 0x202F:
- case 0x205F:
- case 0x3000:
- return true;
- }
- return false;
- }
- ////////////////////////////////////////////////////////////////////////////////
- /*eslint-disable max-len*/
- var UNICODE_PUNCT_RE = require('uc.micro/categories/P/regex');
- // Currently without astral characters support.
- function isPunctChar(ch) {
- return UNICODE_PUNCT_RE.test(ch);
- }
- // Markdown ASCII punctuation characters.
- //
- // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~
- // http://spec.commonmark.org/0.15/#ascii-punctuation-character
- //
- // Don't confuse with unicode punctuation !!! It lacks some chars in ascii range.
- //
- function isMdAsciiPunct(ch) {
- switch (ch) {
- case 0x21/* ! */:
- case 0x22/* " */:
- case 0x23/* # */:
- case 0x24/* $ */:
- case 0x25/* % */:
- case 0x26/* & */:
- case 0x27/* ' */:
- case 0x28/* ( */:
- case 0x29/* ) */:
- case 0x2A/* * */:
- case 0x2B/* + */:
- case 0x2C/* , */:
- case 0x2D/* - */:
- case 0x2E/* . */:
- case 0x2F/* / */:
- case 0x3A/* : */:
- case 0x3B/* ; */:
- case 0x3C/* < */:
- case 0x3D/* = */:
- case 0x3E/* > */:
- case 0x3F/* ? */:
- case 0x40/* @ */:
- case 0x5B/* [ */:
- case 0x5C/* \ */:
- case 0x5D/* ] */:
- case 0x5E/* ^ */:
- case 0x5F/* _ */:
- case 0x60/* ` */:
- case 0x7B/* { */:
- case 0x7C/* | */:
- case 0x7D/* } */:
- case 0x7E/* ~ */:
- return true;
- default:
- return false;
- }
- }
- // Hepler to unify [reference labels].
- //
- function normalizeReference(str) {
- // use .toUpperCase() instead of .toLowerCase()
- // here to avoid a conflict with Object.prototype
- // members (most notably, `__proto__`)
- return str.trim().replace(/\s+/g, ' ').toUpperCase();
- }
- ////////////////////////////////////////////////////////////////////////////////
- // Re-export libraries commonly used in both markdown-it and its plugins,
- // so plugins won't have to depend on them explicitly, which reduces their
- // bundled size (e.g. a browser build).
- //
- exports.lib = {};
- exports.lib.mdurl = require('mdurl');
- exports.lib.ucmicro = require('uc.micro');
- exports.assign = assign;
- exports.isString = isString;
- exports.has = has;
- exports.unescapeMd = unescapeMd;
- exports.unescapeAll = unescapeAll;
- exports.isValidEntityCode = isValidEntityCode;
- exports.fromCodePoint = fromCodePoint;
- // exports.replaceEntities = replaceEntities;
- exports.escapeHtml = escapeHtml;
- exports.arrayReplaceAt = arrayReplaceAt;
- exports.isSpace = isSpace;
- exports.isWhiteSpace = isWhiteSpace;
- exports.isMdAsciiPunct = isMdAsciiPunct;
- exports.isPunctChar = isPunctChar;
- exports.escapeRE = escapeRE;
- exports.normalizeReference = normalizeReference;
- },{"./entities":141,"mdurl":195,"uc.micro":212,"uc.micro/categories/P/regex":210}],145:[function(require,module,exports){
- // Just a shortcut for bulk export
- 'use strict';
- exports.parseLinkLabel = require('./parse_link_label');
- exports.parseLinkDestination = require('./parse_link_destination');
- exports.parseLinkTitle = require('./parse_link_title');
- },{"./parse_link_destination":146,"./parse_link_label":147,"./parse_link_title":148}],146:[function(require,module,exports){
- // Parse link destination
- //
- 'use strict';
- var isSpace = require('../common/utils').isSpace;
- var unescapeAll = require('../common/utils').unescapeAll;
- module.exports = function parseLinkDestination(str, pos, max) {
- var code, level,
- lines = 0,
- start = pos,
- result = {
- ok: false,
- pos: 0,
- lines: 0,
- str: ''
- };
- if (str.charCodeAt(pos) === 0x3C /* < */) {
- pos++;
- while (pos < max) {
- code = str.charCodeAt(pos);
- if (code === 0x0A /* \n */ || isSpace(code)) { return result; }
- if (code === 0x3E /* > */) {
- result.pos = pos + 1;
- result.str = unescapeAll(str.slice(start + 1, pos));
- result.ok = true;
- return result;
- }
- if (code === 0x5C /* \ */ && pos + 1 < max) {
- pos += 2;
- continue;
- }
- pos++;
- }
- // no closing '>'
- return result;
- }
- // this should be ... } else { ... branch
- level = 0;
- while (pos < max) {
- code = str.charCodeAt(pos);
- if (code === 0x20) { break; }
- // ascii control characters
- if (code < 0x20 || code === 0x7F) { break; }
- if (code === 0x5C /* \ */ && pos + 1 < max) {
- pos += 2;
- continue;
- }
- if (code === 0x28 /* ( */) {
- level++;
- }
- if (code === 0x29 /* ) */) {
- if (level === 0) { break; }
- level--;
- }
- pos++;
- }
- if (start === pos) { return result; }
- if (level !== 0) { return result; }
- result.str = unescapeAll(str.slice(start, pos));
- result.lines = lines;
- result.pos = pos;
- result.ok = true;
- return result;
- };
- },{"../common/utils":144}],147:[function(require,module,exports){
- // Parse link label
- //
- // this function assumes that first character ("[") already matches;
- // returns the end of the label
- //
- 'use strict';
- module.exports = function parseLinkLabel(state, start, disableNested) {
- var level, found, marker, prevPos,
- labelEnd = -1,
- max = state.posMax,
- oldPos = state.pos;
- state.pos = start + 1;
- level = 1;
- while (state.pos < max) {
- marker = state.src.charCodeAt(state.pos);
- if (marker === 0x5D /* ] */) {
- level--;
- if (level === 0) {
- found = true;
- break;
- }
- }
- prevPos = state.pos;
- state.md.inline.skipToken(state);
- if (marker === 0x5B /* [ */) {
- if (prevPos === state.pos - 1) {
- // increase level if we find text `[`, which is not a part of any token
- level++;
- } else if (disableNested) {
- state.pos = oldPos;
- return -1;
- }
- }
- }
- if (found) {
- labelEnd = state.pos;
- }
- // restore old state
- state.pos = oldPos;
- return labelEnd;
- };
- },{}],148:[function(require,module,exports){
- // Parse link title
- //
- 'use strict';
- var unescapeAll = require('../common/utils').unescapeAll;
- module.exports = function parseLinkTitle(str, pos, max) {
- var code,
- marker,
- lines = 0,
- start = pos,
- result = {
- ok: false,
- pos: 0,
- lines: 0,
- str: ''
- };
- if (pos >= max) { return result; }
- marker = str.charCodeAt(pos);
- if (marker !== 0x22 /* " */ && marker !== 0x27 /* ' */ && marker !== 0x28 /* ( */) { return result; }
- pos++;
- // if opening marker is "(", switch it to closing marker ")"
- if (marker === 0x28) { marker = 0x29; }
- while (pos < max) {
- code = str.charCodeAt(pos);
- if (code === marker) {
- result.pos = pos + 1;
- result.lines = lines;
- result.str = unescapeAll(str.slice(start + 1, pos));
- result.ok = true;
- return result;
- } else if (code === 0x0A) {
- lines++;
- } else if (code === 0x5C /* \ */ && pos + 1 < max) {
- pos++;
- if (str.charCodeAt(pos) === 0x0A) {
- lines++;
- }
- }
- pos++;
- }
- return result;
- };
- },{"../common/utils":144}],149:[function(require,module,exports){
- // Main parser class
- 'use strict';
- var utils = require('./common/utils');
- var helpers = require('./helpers');
- var Renderer = require('./renderer');
- var ParserCore = require('./parser_core');
- var ParserBlock = require('./parser_block');
- var ParserInline = require('./parser_inline');
- var LinkifyIt = require('linkify-it');
- var mdurl = require('mdurl');
- var punycode = require('punycode');
- var config = {
- 'default': require('./presets/default'),
- zero: require('./presets/zero'),
- commonmark: require('./presets/commonmark')
- };
- ////////////////////////////////////////////////////////////////////////////////
- //
- // This validator can prohibit more than really needed to prevent XSS. It's a
- // tradeoff to keep code simple and to be secure by default.
- //
- // If you need different setup - override validator method as you wish. Or
- // replace it with dummy function and use external sanitizer.
- //
- var BAD_PROTO_RE = /^(vbscript|javascript|file|data):/;
- var GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/;
- function validateLink(url) {
- // url should be normalized at this point, and existing entities are decoded
- var str = url.trim().toLowerCase();
- return BAD_PROTO_RE.test(str) ? (GOOD_DATA_RE.test(str) ? true : false) : true;
- }
- ////////////////////////////////////////////////////////////////////////////////
- var RECODE_HOSTNAME_FOR = [ 'http:', 'https:', 'mailto:' ];
- function normalizeLink(url) {
- var parsed = mdurl.parse(url, true);
- if (parsed.hostname) {
- // Encode hostnames in urls like:
- // `http://host/`, `https://host/`, `mailto:user@host`, `//host/`
- //
- // We don't encode unknown schemas, because it's likely that we encode
- // something we shouldn't (e.g. `skype:name` treated as `skype:host`)
- //
- if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
- try {
- parsed.hostname = punycode.toASCII(parsed.hostname);
- } catch (er) { /**/ }
- }
- }
- return mdurl.encode(mdurl.format(parsed));
- }
- function normalizeLinkText(url) {
- var parsed = mdurl.parse(url, true);
- if (parsed.hostname) {
- // Encode hostnames in urls like:
- // `http://host/`, `https://host/`, `mailto:user@host`, `//host/`
- //
- // We don't encode unknown schemas, because it's likely that we encode
- // something we shouldn't (e.g. `skype:name` treated as `skype:host`)
- //
- if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
- try {
- parsed.hostname = punycode.toUnicode(parsed.hostname);
- } catch (er) { /**/ }
- }
- }
- return mdurl.decode(mdurl.format(parsed));
- }
- /**
- * class MarkdownIt
- *
- * Main parser/renderer class.
- *
- * ##### Usage
- *
- * ```javascript
- * // node.js, "classic" way:
- * var MarkdownIt = require('markdown-it'),
- * md = new MarkdownIt();
- * var result = md.render('# markdown-it rulezz!');
- *
- * // node.js, the same, but with sugar:
- * var md = require('markdown-it')();
- * var result = md.render('# markdown-it rulezz!');
- *
- * // browser without AMD, added to "window" on script load
- * // Note, there are no dash.
- * var md = window.markdownit();
- * var result = md.render('# markdown-it rulezz!');
- * ```
- *
- * Single line rendering, without paragraph wrap:
- *
- * ```javascript
- * var md = require('markdown-it')();
- * var result = md.renderInline('__markdown-it__ rulezz!');
- * ```
- **/
- /**
- * new MarkdownIt([presetName, options])
- * - presetName (String): optional, `commonmark` / `zero`
- * - options (Object)
- *
- * Creates parser instanse with given config. Can be called without `new`.
- *
- * ##### presetName
- *
- * MarkdownIt provides named presets as a convenience to quickly
- * enable/disable active syntax rules and options for common use cases.
- *
- * - ["commonmark"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.js) -
- * configures parser to strict [CommonMark](http://commonmark.org/) mode.
- * - [default](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/default.js) -
- * similar to GFM, used when no preset name given. Enables all available rules,
- * but still without html, typographer & autolinker.
- * - ["zero"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/zero.js) -
- * all rules disabled. Useful to quickly setup your config via `.enable()`.
- * For example, when you need only `bold` and `italic` markup and nothing else.
- *
- * ##### options:
- *
- * - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful!
- * That's not safe! You may need external sanitizer to protect output from XSS.
- * It's better to extend features via plugins, instead of enabling HTML.
- * - __xhtmlOut__ - `false`. Set `true` to add '/' when closing single tags
- * (`<br />`). This is needed only for full CommonMark compatibility. In real
- * world you will need HTML output.
- * - __breaks__ - `false`. Set `true` to convert `\n` in paragraphs into `<br>`.
- * - __langPrefix__ - `language-`. CSS language class prefix for fenced blocks.
- * Can be useful for external highlighters.
- * - __linkify__ - `false`. Set `true` to autoconvert URL-like text to links.
- * - __typographer__ - `false`. Set `true` to enable [some language-neutral
- * replacement](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.js) +
- * quotes beautification (smartquotes).
- * - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement
- * pairs, when typographer enabled and smartquotes on. For example, you can
- * use `'«»„“'` for Russian, `'„“‚‘'` for German, and
- * `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp).
- * - __highlight__ - `null`. Highlighter function for fenced code blocks.
- * Highlighter `function (str, lang)` should return escaped HTML. It can also
- * return empty string if the source was not changed and should be escaped
- * externaly. If result starts with <pre... internal wrapper is skipped.
- *
- * ##### Example
- *
- * ```javascript
- * // commonmark mode
- * var md = require('markdown-it')('commonmark');
- *
- * // default mode
- * var md = require('markdown-it')();
- *
- * // enable everything
- * var md = require('markdown-it')({
- * html: true,
- * linkify: true,
- * typographer: true
- * });
- * ```
- *
- * ##### Syntax highlighting
- *
- * ```js
- * var hljs = require('highlight.js') // https://highlightjs.org/
- *
- * var md = require('markdown-it')({
- * highlight: function (str, lang) {
- * if (lang && hljs.getLanguage(lang)) {
- * try {
- * return hljs.highlight(lang, str, true).value;
- * } catch (__) {}
- * }
- *
- * return ''; // use external default escaping
- * }
- * });
- * ```
- *
- * Or with full wrapper override (if you need assign class to `<pre>`):
- *
- * ```javascript
- * var hljs = require('highlight.js') // https://highlightjs.org/
- *
- * // Actual default values
- * var md = require('markdown-it')({
- * highlight: function (str, lang) {
- * if (lang && hljs.getLanguage(lang)) {
- * try {
- * return '<pre class="hljs"><code>' +
- * hljs.highlight(lang, str, true).value +
- * '</code></pre>';
- * } catch (__) {}
- * }
- *
- * return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
- * }
- * });
- * ```
- *
- **/
- function MarkdownIt(presetName, options) {
- if (!(this instanceof MarkdownIt)) {
- return new MarkdownIt(presetName, options);
- }
- if (!options) {
- if (!utils.isString(presetName)) {
- options = presetName || {};
- presetName = 'default';
- }
- }
- /**
- * MarkdownIt#inline -> ParserInline
- *
- * Instance of [[ParserInline]]. You may need it to add new rules when
- * writing plugins. For simple rules control use [[MarkdownIt.disable]] and
- * [[MarkdownIt.enable]].
- **/
- this.inline = new ParserInline();
- /**
- * MarkdownIt#block -> ParserBlock
- *
- * Instance of [[ParserBlock]]. You may need it to add new rules when
- * writing plugins. For simple rules control use [[MarkdownIt.disable]] and
- * [[MarkdownIt.enable]].
- **/
- this.block = new ParserBlock();
- /**
- * MarkdownIt#core -> Core
- *
- * Instance of [[Core]] chain executor. You may need it to add new rules when
- * writing plugins. For simple rules control use [[MarkdownIt.disable]] and
- * [[MarkdownIt.enable]].
- **/
- this.core = new ParserCore();
- /**
- * MarkdownIt#renderer -> Renderer
- *
- * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering
- * rules for new token types, generated by plugins.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')();
- *
- * function myToken(tokens, idx, options, env, self) {
- * //...
- * return result;
- * };
- *
- * md.renderer.rules['my_token'] = myToken
- * ```
- *
- * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js).
- **/
- this.renderer = new Renderer();
- /**
- * MarkdownIt#linkify -> LinkifyIt
- *
- * [linkify-it](https://github.com/markdown-it/linkify-it) instance.
- * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.js)
- * rule.
- **/
- this.linkify = new LinkifyIt();
- /**
- * MarkdownIt#validateLink(url) -> Boolean
- *
- * Link validation function. CommonMark allows too much in links. By default
- * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas
- * except some embedded image types.
- *
- * You can change this behaviour:
- *
- * ```javascript
- * var md = require('markdown-it')();
- * // enable everything
- * md.validateLink = function () { return true; }
- * ```
- **/
- this.validateLink = validateLink;
- /**
- * MarkdownIt#normalizeLink(url) -> String
- *
- * Function used to encode link url to a machine-readable format,
- * which includes url-encoding, punycode, etc.
- **/
- this.normalizeLink = normalizeLink;
- /**
- * MarkdownIt#normalizeLinkText(url) -> String
- *
- * Function used to decode link url to a human-readable format`
- **/
- this.normalizeLinkText = normalizeLinkText;
- // Expose utils & helpers for easy acces from plugins
- /**
- * MarkdownIt#utils -> utils
- *
- * Assorted utility functions, useful to write plugins. See details
- * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.js).
- **/
- this.utils = utils;
- /**
- * MarkdownIt#helpers -> helpers
- *
- * Link components parser functions, useful to write plugins. See details
- * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers).
- **/
- this.helpers = utils.assign({}, helpers);
- this.options = {};
- this.configure(presetName);
- if (options) { this.set(options); }
- }
- /** chainable
- * MarkdownIt.set(options)
- *
- * Set parser options (in the same format as in constructor). Probably, you
- * will never need it, but you can change options after constructor call.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')()
- * .set({ html: true, breaks: true })
- * .set({ typographer, true });
- * ```
- *
- * __Note:__ To achieve the best possible performance, don't modify a
- * `markdown-it` instance options on the fly. If you need multiple configurations
- * it's best to create multiple instances and initialize each with separate
- * config.
- **/
- MarkdownIt.prototype.set = function (options) {
- utils.assign(this.options, options);
- return this;
- };
- /** chainable, internal
- * MarkdownIt.configure(presets)
- *
- * Batch load of all options and compenent settings. This is internal method,
- * and you probably will not need it. But if you with - see available presets
- * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets)
- *
- * We strongly recommend to use presets instead of direct config loads. That
- * will give better compatibility with next versions.
- **/
- MarkdownIt.prototype.configure = function (presets) {
- var self = this, presetName;
- if (utils.isString(presets)) {
- presetName = presets;
- presets = config[presetName];
- if (!presets) { throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name'); }
- }
- if (!presets) { throw new Error('Wrong `markdown-it` preset, can\'t be empty'); }
- if (presets.options) { self.set(presets.options); }
- if (presets.components) {
- Object.keys(presets.components).forEach(function (name) {
- if (presets.components[name].rules) {
- self[name].ruler.enableOnly(presets.components[name].rules);
- }
- if (presets.components[name].rules2) {
- self[name].ruler2.enableOnly(presets.components[name].rules2);
- }
- });
- }
- return this;
- };
- /** chainable
- * MarkdownIt.enable(list, ignoreInvalid)
- * - list (String|Array): rule name or list of rule names to enable
- * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
- *
- * Enable list or rules. It will automatically find appropriate components,
- * containing rules with given names. If rule not found, and `ignoreInvalid`
- * not set - throws exception.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')()
- * .enable(['sub', 'sup'])
- * .disable('smartquotes');
- * ```
- **/
- MarkdownIt.prototype.enable = function (list, ignoreInvalid) {
- var result = [];
- if (!Array.isArray(list)) { list = [ list ]; }
- [ 'core', 'block', 'inline' ].forEach(function (chain) {
- result = result.concat(this[chain].ruler.enable(list, true));
- }, this);
- result = result.concat(this.inline.ruler2.enable(list, true));
- var missed = list.filter(function (name) { return result.indexOf(name) < 0; });
- if (missed.length && !ignoreInvalid) {
- throw new Error('MarkdownIt. Failed to enable unknown rule(s): ' + missed);
- }
- return this;
- };
- /** chainable
- * MarkdownIt.disable(list, ignoreInvalid)
- * - list (String|Array): rule name or list of rule names to disable.
- * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
- *
- * The same as [[MarkdownIt.enable]], but turn specified rules off.
- **/
- MarkdownIt.prototype.disable = function (list, ignoreInvalid) {
- var result = [];
- if (!Array.isArray(list)) { list = [ list ]; }
- [ 'core', 'block', 'inline' ].forEach(function (chain) {
- result = result.concat(this[chain].ruler.disable(list, true));
- }, this);
- result = result.concat(this.inline.ruler2.disable(list, true));
- var missed = list.filter(function (name) { return result.indexOf(name) < 0; });
- if (missed.length && !ignoreInvalid) {
- throw new Error('MarkdownIt. Failed to disable unknown rule(s): ' + missed);
- }
- return this;
- };
- /** chainable
- * MarkdownIt.use(plugin, params)
- *
- * Load specified plugin with given params into current parser instance.
- * It's just a sugar to call `plugin(md, params)` with curring.
- *
- * ##### Example
- *
- * ```javascript
- * var iterator = require('markdown-it-for-inline');
- * var md = require('markdown-it')()
- * .use(iterator, 'foo_replace', 'text', function (tokens, idx) {
- * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar');
- * });
- * ```
- **/
- MarkdownIt.prototype.use = function (plugin /*, params, ... */) {
- var args = [ this ].concat(Array.prototype.slice.call(arguments, 1));
- plugin.apply(plugin, args);
- return this;
- };
- /** internal
- * MarkdownIt.parse(src, env) -> Array
- * - src (String): source string
- * - env (Object): environment sandbox
- *
- * Parse input string and returns list of block tokens (special token type
- * "inline" will contain list of inline tokens). You should not call this
- * method directly, until you write custom renderer (for example, to produce
- * AST).
- *
- * `env` is used to pass data between "distributed" rules and return additional
- * metadata like reference info, needed for the renderer. It also can be used to
- * inject data in specific cases. Usually, you will be ok to pass `{}`,
- * and then pass updated object to renderer.
- **/
- MarkdownIt.prototype.parse = function (src, env) {
- if (typeof src !== 'string') {
- throw new Error('Input data should be a String');
- }
- var state = new this.core.State(src, this, env);
- this.core.process(state);
- return state.tokens;
- };
- /**
- * MarkdownIt.render(src [, env]) -> String
- * - src (String): source string
- * - env (Object): environment sandbox
- *
- * Render markdown string into html. It does all magic for you :).
- *
- * `env` can be used to inject additional metadata (`{}` by default).
- * But you will not need it with high probability. See also comment
- * in [[MarkdownIt.parse]].
- **/
- MarkdownIt.prototype.render = function (src, env) {
- env = env || {};
- return this.renderer.render(this.parse(src, env), this.options, env);
- };
- /** internal
- * MarkdownIt.parseInline(src, env) -> Array
- * - src (String): source string
- * - env (Object): environment sandbox
- *
- * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the
- * block tokens list with the single `inline` element, containing parsed inline
- * tokens in `children` property. Also updates `env` object.
- **/
- MarkdownIt.prototype.parseInline = function (src, env) {
- var state = new this.core.State(src, this, env);
- state.inlineMode = true;
- this.core.process(state);
- return state.tokens;
- };
- /**
- * MarkdownIt.renderInline(src [, env]) -> String
- * - src (String): source string
- * - env (Object): environment sandbox
- *
- * Similar to [[MarkdownIt.render]] but for single paragraph content. Result
- * will NOT be wrapped into `<p>` tags.
- **/
- MarkdownIt.prototype.renderInline = function (src, env) {
- env = env || {};
- return this.renderer.render(this.parseInline(src, env), this.options, env);
- };
- module.exports = MarkdownIt;
- },{"./common/utils":144,"./helpers":145,"./parser_block":150,"./parser_core":151,"./parser_inline":152,"./presets/commonmark":153,"./presets/default":154,"./presets/zero":155,"./renderer":156,"linkify-it":138,"mdurl":195,"punycode":2}],150:[function(require,module,exports){
- /** internal
- * class ParserBlock
- *
- * Block-level tokenizer.
- **/
- 'use strict';
- var Ruler = require('./ruler');
- var _rules = [
- // First 2 params - rule name & source. Secondary array - list of rules,
- // which can be terminated by this one.
- [ 'table', require('./rules_block/table'), [ 'paragraph', 'reference' ] ],
- [ 'code', require('./rules_block/code') ],
- [ 'fence', require('./rules_block/fence'), [ 'paragraph', 'reference', 'blockquote', 'list' ] ],
- [ 'blockquote', require('./rules_block/blockquote'), [ 'paragraph', 'reference', 'blockquote', 'list' ] ],
- [ 'hr', require('./rules_block/hr'), [ 'paragraph', 'reference', 'blockquote', 'list' ] ],
- [ 'list', require('./rules_block/list'), [ 'paragraph', 'reference', 'blockquote' ] ],
- [ 'reference', require('./rules_block/reference') ],
- [ 'heading', require('./rules_block/heading'), [ 'paragraph', 'reference', 'blockquote' ] ],
- [ 'lheading', require('./rules_block/lheading') ],
- [ 'html_block', require('./rules_block/html_block'), [ 'paragraph', 'reference', 'blockquote' ] ],
- [ 'paragraph', require('./rules_block/paragraph') ]
- ];
- /**
- * new ParserBlock()
- **/
- function ParserBlock() {
- /**
- * ParserBlock#ruler -> Ruler
- *
- * [[Ruler]] instance. Keep configuration of block rules.
- **/
- this.ruler = new Ruler();
- for (var i = 0; i < _rules.length; i++) {
- this.ruler.push(_rules[i][0], _rules[i][1], { alt: (_rules[i][2] || []).slice() });
- }
- }
- // Generate tokens for input range
- //
- ParserBlock.prototype.tokenize = function (state, startLine, endLine) {
- var ok, i,
- rules = this.ruler.getRules(''),
- len = rules.length,
- line = startLine,
- hasEmptyLines = false,
- maxNesting = state.md.options.maxNesting;
- while (line < endLine) {
- state.line = line = state.skipEmptyLines(line);
- if (line >= endLine) { break; }
- // Termination condition for nested calls.
- // Nested calls currently used for blockquotes & lists
- if (state.sCount[line] < state.blkIndent) { break; }
- // If nesting level exceeded - skip tail to the end. That's not ordinary
- // situation and we should not care about content.
- if (state.level >= maxNesting) {
- state.line = endLine;
- break;
- }
- // Try all possible rules.
- // On success, rule should:
- //
- // - update `state.line`
- // - update `state.tokens`
- // - return true
- for (i = 0; i < len; i++) {
- ok = rules[i](state, line, endLine, false);
- if (ok) { break; }
- }
- // set state.tight if we had an empty line before current tag
- // i.e. latest empty line should not count
- state.tight = !hasEmptyLines;
- // paragraph might "eat" one newline after it in nested lists
- if (state.isEmpty(state.line - 1)) {
- hasEmptyLines = true;
- }
- line = state.line;
- if (line < endLine && state.isEmpty(line)) {
- hasEmptyLines = true;
- line++;
- state.line = line;
- }
- }
- };
- /**
- * ParserBlock.parse(str, md, env, outTokens)
- *
- * Process input string and push block tokens into `outTokens`
- **/
- ParserBlock.prototype.parse = function (src, md, env, outTokens) {
- var state;
- if (!src) { return; }
- state = new this.State(src, md, env, outTokens);
- this.tokenize(state, state.line, state.lineMax);
- };
- ParserBlock.prototype.State = require('./rules_block/state_block');
- module.exports = ParserBlock;
- },{"./ruler":157,"./rules_block/blockquote":158,"./rules_block/code":159,"./rules_block/fence":160,"./rules_block/heading":161,"./rules_block/hr":162,"./rules_block/html_block":163,"./rules_block/lheading":164,"./rules_block/list":165,"./rules_block/paragraph":166,"./rules_block/reference":167,"./rules_block/state_block":168,"./rules_block/table":169}],151:[function(require,module,exports){
- /** internal
- * class Core
- *
- * Top-level rules executor. Glues block/inline parsers and does intermediate
- * transformations.
- **/
- 'use strict';
- var Ruler = require('./ruler');
- var _rules = [
- [ 'normalize', require('./rules_core/normalize') ],
- [ 'block', require('./rules_core/block') ],
- [ 'inline', require('./rules_core/inline') ],
- [ 'linkify', require('./rules_core/linkify') ],
- [ 'replacements', require('./rules_core/replacements') ],
- [ 'smartquotes', require('./rules_core/smartquotes') ]
- ];
- /**
- * new Core()
- **/
- function Core() {
- /**
- * Core#ruler -> Ruler
- *
- * [[Ruler]] instance. Keep configuration of core rules.
- **/
- this.ruler = new Ruler();
- for (var i = 0; i < _rules.length; i++) {
- this.ruler.push(_rules[i][0], _rules[i][1]);
- }
- }
- /**
- * Core.process(state)
- *
- * Executes core chain rules.
- **/
- Core.prototype.process = function (state) {
- var i, l, rules;
- rules = this.ruler.getRules('');
- for (i = 0, l = rules.length; i < l; i++) {
- rules[i](state);
- }
- };
- Core.prototype.State = require('./rules_core/state_core');
- module.exports = Core;
- },{"./ruler":157,"./rules_core/block":170,"./rules_core/inline":171,"./rules_core/linkify":172,"./rules_core/normalize":173,"./rules_core/replacements":174,"./rules_core/smartquotes":175,"./rules_core/state_core":176}],152:[function(require,module,exports){
- /** internal
- * class ParserInline
- *
- * Tokenizes paragraph content.
- **/
- 'use strict';
- var Ruler = require('./ruler');
- ////////////////////////////////////////////////////////////////////////////////
- // Parser rules
- var _rules = [
- [ 'text', require('./rules_inline/text') ],
- [ 'newline', require('./rules_inline/newline') ],
- [ 'escape', require('./rules_inline/escape') ],
- [ 'backticks', require('./rules_inline/backticks') ],
- [ 'strikethrough', require('./rules_inline/strikethrough').tokenize ],
- [ 'emphasis', require('./rules_inline/emphasis').tokenize ],
- [ 'link', require('./rules_inline/link') ],
- [ 'image', require('./rules_inline/image') ],
- [ 'autolink', require('./rules_inline/autolink') ],
- [ 'html_inline', require('./rules_inline/html_inline') ],
- [ 'entity', require('./rules_inline/entity') ]
- ];
- var _rules2 = [
- [ 'balance_pairs', require('./rules_inline/balance_pairs') ],
- [ 'strikethrough', require('./rules_inline/strikethrough').postProcess ],
- [ 'emphasis', require('./rules_inline/emphasis').postProcess ],
- [ 'text_collapse', require('./rules_inline/text_collapse') ]
- ];
- /**
- * new ParserInline()
- **/
- function ParserInline() {
- var i;
- /**
- * ParserInline#ruler -> Ruler
- *
- * [[Ruler]] instance. Keep configuration of inline rules.
- **/
- this.ruler = new Ruler();
- for (i = 0; i < _rules.length; i++) {
- this.ruler.push(_rules[i][0], _rules[i][1]);
- }
- /**
- * ParserInline#ruler2 -> Ruler
- *
- * [[Ruler]] instance. Second ruler used for post-processing
- * (e.g. in emphasis-like rules).
- **/
- this.ruler2 = new Ruler();
- for (i = 0; i < _rules2.length; i++) {
- this.ruler2.push(_rules2[i][0], _rules2[i][1]);
- }
- }
- // Skip single token by running all rules in validation mode;
- // returns `true` if any rule reported success
- //
- ParserInline.prototype.skipToken = function (state) {
- var ok, i, pos = state.pos,
- rules = this.ruler.getRules(''),
- len = rules.length,
- maxNesting = state.md.options.maxNesting,
- cache = state.cache;
- if (typeof cache[pos] !== 'undefined') {
- state.pos = cache[pos];
- return;
- }
- if (state.level < maxNesting) {
- for (i = 0; i < len; i++) {
- // Increment state.level and decrement it later to limit recursion.
- // It's harmless to do here, because no tokens are created. But ideally,
- // we'd need a separate private state variable for this purpose.
- //
- state.level++;
- ok = rules[i](state, true);
- state.level--;
- if (ok) { break; }
- }
- } else {
- // Too much nesting, just skip until the end of the paragraph.
- //
- // NOTE: this will cause links to behave incorrectly in the following case,
- // when an amount of `[` is exactly equal to `maxNesting + 1`:
- //
- // [[[[[[[[[[[[[[[[[[[[[foo]()
- //
- // TODO: remove this workaround when CM standard will allow nested links
- // (we can replace it by preventing links from being parsed in
- // validation mode)
- //
- state.pos = state.posMax;
- }
- if (!ok) { state.pos++; }
- cache[pos] = state.pos;
- };
- // Generate tokens for input range
- //
- ParserInline.prototype.tokenize = function (state) {
- var ok, i,
- rules = this.ruler.getRules(''),
- len = rules.length,
- end = state.posMax,
- maxNesting = state.md.options.maxNesting;
- while (state.pos < end) {
- // Try all possible rules.
- // On success, rule should:
- //
- // - update `state.pos`
- // - update `state.tokens`
- // - return true
- if (state.level < maxNesting) {
- for (i = 0; i < len; i++) {
- ok = rules[i](state, false);
- if (ok) { break; }
- }
- }
- if (ok) {
- if (state.pos >= end) { break; }
- continue;
- }
- state.pending += state.src[state.pos++];
- }
- if (state.pending) {
- state.pushPending();
- }
- };
- /**
- * ParserInline.parse(str, md, env, outTokens)
- *
- * Process input string and push inline tokens into `outTokens`
- **/
- ParserInline.prototype.parse = function (str, md, env, outTokens) {
- var i, rules, len;
- var state = new this.State(str, md, env, outTokens);
- this.tokenize(state);
- rules = this.ruler2.getRules('');
- len = rules.length;
- for (i = 0; i < len; i++) {
- rules[i](state);
- }
- };
- ParserInline.prototype.State = require('./rules_inline/state_inline');
- module.exports = ParserInline;
- },{"./ruler":157,"./rules_inline/autolink":177,"./rules_inline/backticks":178,"./rules_inline/balance_pairs":179,"./rules_inline/emphasis":180,"./rules_inline/entity":181,"./rules_inline/escape":182,"./rules_inline/html_inline":183,"./rules_inline/image":184,"./rules_inline/link":185,"./rules_inline/newline":186,"./rules_inline/state_inline":187,"./rules_inline/strikethrough":188,"./rules_inline/text":189,"./rules_inline/text_collapse":190}],153:[function(require,module,exports){
- // Commonmark default options
- 'use strict';
- module.exports = {
- options: {
- html: true, // Enable HTML tags in source
- xhtmlOut: true, // Use '/' to close single tags (<br />)
- breaks: false, // Convert '\n' in paragraphs into <br>
- langPrefix: 'language-', // CSS language prefix for fenced blocks
- linkify: false, // autoconvert URL-like texts to links
- // Enable some language-neutral replacements + quotes beautification
- typographer: false,
- // Double + single quotes replacement pairs, when typographer enabled,
- // and smartquotes on. Could be either a String or an Array.
- //
- // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
- // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
- quotes: '\u201c\u201d\u2018\u2019', /* “”‘’ */
- // Highlighter function. Should return escaped HTML,
- // or '' if the source string is not changed and should be escaped externaly.
- // If result starts with <pre... internal wrapper is skipped.
- //
- // function (/*str, lang*/) { return ''; }
- //
- highlight: null,
- maxNesting: 20 // Internal protection, recursion limit
- },
- components: {
- core: {
- rules: [
- 'normalize',
- 'block',
- 'inline'
- ]
- },
- block: {
- rules: [
- 'blockquote',
- 'code',
- 'fence',
- 'heading',
- 'hr',
- 'html_block',
- 'lheading',
- 'list',
- 'reference',
- 'paragraph'
- ]
- },
- inline: {
- rules: [
- 'autolink',
- 'backticks',
- 'emphasis',
- 'entity',
- 'escape',
- 'html_inline',
- 'image',
- 'link',
- 'newline',
- 'text'
- ],
- rules2: [
- 'balance_pairs',
- 'emphasis',
- 'text_collapse'
- ]
- }
- }
- };
- },{}],154:[function(require,module,exports){
- // markdown-it default options
- 'use strict';
- module.exports = {
- options: {
- html: false, // Enable HTML tags in source
- xhtmlOut: false, // Use '/' to close single tags (<br />)
- breaks: false, // Convert '\n' in paragraphs into <br>
- langPrefix: 'language-', // CSS language prefix for fenced blocks
- linkify: false, // autoconvert URL-like texts to links
- // Enable some language-neutral replacements + quotes beautification
- typographer: false,
- // Double + single quotes replacement pairs, when typographer enabled,
- // and smartquotes on. Could be either a String or an Array.
- //
- // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
- // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
- quotes: '\u201c\u201d\u2018\u2019', /* “”‘’ */
- // Highlighter function. Should return escaped HTML,
- // or '' if the source string is not changed and should be escaped externaly.
- // If result starts with <pre... internal wrapper is skipped.
- //
- // function (/*str, lang*/) { return ''; }
- //
- highlight: null,
- maxNesting: 100 // Internal protection, recursion limit
- },
- components: {
- core: {},
- block: {},
- inline: {}
- }
- };
- },{}],155:[function(require,module,exports){
- // "Zero" preset, with nothing enabled. Useful for manual configuring of simple
- // modes. For example, to parse bold/italic only.
- 'use strict';
- module.exports = {
- options: {
- html: false, // Enable HTML tags in source
- xhtmlOut: false, // Use '/' to close single tags (<br />)
- breaks: false, // Convert '\n' in paragraphs into <br>
- langPrefix: 'language-', // CSS language prefix for fenced blocks
- linkify: false, // autoconvert URL-like texts to links
- // Enable some language-neutral replacements + quotes beautification
- typographer: false,
- // Double + single quotes replacement pairs, when typographer enabled,
- // and smartquotes on. Could be either a String or an Array.
- //
- // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
- // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
- quotes: '\u201c\u201d\u2018\u2019', /* “”‘’ */
- // Highlighter function. Should return escaped HTML,
- // or '' if the source string is not changed and should be escaped externaly.
- // If result starts with <pre... internal wrapper is skipped.
- //
- // function (/*str, lang*/) { return ''; }
- //
- highlight: null,
- maxNesting: 20 // Internal protection, recursion limit
- },
- components: {
- core: {
- rules: [
- 'normalize',
- 'block',
- 'inline'
- ]
- },
- block: {
- rules: [
- 'paragraph'
- ]
- },
- inline: {
- rules: [
- 'text'
- ],
- rules2: [
- 'balance_pairs',
- 'text_collapse'
- ]
- }
- }
- };
- },{}],156:[function(require,module,exports){
- /**
- * class Renderer
- *
- * Generates HTML from parsed token stream. Each instance has independent
- * copy of rules. Those can be rewritten with ease. Also, you can add new
- * rules if you create plugin and adds new token types.
- **/
- 'use strict';
- var assign = require('./common/utils').assign;
- var unescapeAll = require('./common/utils').unescapeAll;
- var escapeHtml = require('./common/utils').escapeHtml;
- ////////////////////////////////////////////////////////////////////////////////
- var default_rules = {};
- default_rules.code_inline = function (tokens, idx, options, env, slf) {
- var token = tokens[idx];
- return '<code' + slf.renderAttrs(token) + '>' +
- escapeHtml(tokens[idx].content) +
- '</code>';
- };
- default_rules.code_block = function (tokens, idx, options, env, slf) {
- var token = tokens[idx];
- return '<pre' + slf.renderAttrs(token) + '><code>' +
- escapeHtml(tokens[idx].content) +
- '</code></pre>\n';
- };
- default_rules.fence = function (tokens, idx, options, env, slf) {
- var token = tokens[idx],
- info = token.info ? unescapeAll(token.info).trim() : '',
- langName = '',
- highlighted, i, tmpAttrs, tmpToken;
- if (info) {
- langName = info.split(/\s+/g)[0];
- }
- if (options.highlight) {
- highlighted = options.highlight(token.content, langName) || escapeHtml(token.content);
- } else {
- highlighted = escapeHtml(token.content);
- }
- if (highlighted.indexOf('<pre') === 0) {
- return highlighted + '\n';
- }
- // If language exists, inject class gently, without modifying original token.
- // May be, one day we will add .clone() for token and simplify this part, but
- // now we prefer to keep things local.
- if (info) {
- i = token.attrIndex('class');
- tmpAttrs = token.attrs ? token.attrs.slice() : [];
- if (i < 0) {
- tmpAttrs.push([ 'class', options.langPrefix + langName ]);
- } else {
- tmpAttrs[i][1] += ' ' + options.langPrefix + langName;
- }
- // Fake token just to render attributes
- tmpToken = {
- attrs: tmpAttrs
- };
- return '<pre><code' + slf.renderAttrs(tmpToken) + '>'
- + highlighted
- + '</code></pre>\n';
- }
- return '<pre><code' + slf.renderAttrs(token) + '>'
- + highlighted
- + '</code></pre>\n';
- };
- default_rules.image = function (tokens, idx, options, env, slf) {
- var token = tokens[idx];
- // "alt" attr MUST be set, even if empty. Because it's mandatory and
- // should be placed on proper position for tests.
- //
- // Replace content with actual value
- token.attrs[token.attrIndex('alt')][1] =
- slf.renderInlineAsText(token.children, options, env);
- return slf.renderToken(tokens, idx, options);
- };
- default_rules.hardbreak = function (tokens, idx, options /*, env */) {
- return options.xhtmlOut ? '<br />\n' : '<br>\n';
- };
- default_rules.softbreak = function (tokens, idx, options /*, env */) {
- return options.breaks ? (options.xhtmlOut ? '<br />\n' : '<br>\n') : '\n';
- };
- default_rules.text = function (tokens, idx /*, options, env */) {
- return escapeHtml(tokens[idx].content);
- };
- default_rules.html_block = function (tokens, idx /*, options, env */) {
- return tokens[idx].content;
- };
- default_rules.html_inline = function (tokens, idx /*, options, env */) {
- return tokens[idx].content;
- };
- /**
- * new Renderer()
- *
- * Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults.
- **/
- function Renderer() {
- /**
- * Renderer#rules -> Object
- *
- * Contains render rules for tokens. Can be updated and extended.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')();
- *
- * md.renderer.rules.strong_open = function () { return '<b>'; };
- * md.renderer.rules.strong_close = function () { return '</b>'; };
- *
- * var result = md.renderInline(...);
- * ```
- *
- * Each rule is called as independent static function with fixed signature:
- *
- * ```javascript
- * function my_token_render(tokens, idx, options, env, renderer) {
- * // ...
- * return renderedHTML;
- * }
- * ```
- *
- * See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js)
- * for more details and examples.
- **/
- this.rules = assign({}, default_rules);
- }
- /**
- * Renderer.renderAttrs(token) -> String
- *
- * Render token attributes to string.
- **/
- Renderer.prototype.renderAttrs = function renderAttrs(token) {
- var i, l, result;
- if (!token.attrs) { return ''; }
- result = '';
- for (i = 0, l = token.attrs.length; i < l; i++) {
- result += ' ' + escapeHtml(token.attrs[i][0]) + '="' + escapeHtml(token.attrs[i][1]) + '"';
- }
- return result;
- };
- /**
- * Renderer.renderToken(tokens, idx, options) -> String
- * - tokens (Array): list of tokens
- * - idx (Numbed): token index to render
- * - options (Object): params of parser instance
- *
- * Default token renderer. Can be overriden by custom function
- * in [[Renderer#rules]].
- **/
- Renderer.prototype.renderToken = function renderToken(tokens, idx, options) {
- var nextToken,
- result = '',
- needLf = false,
- token = tokens[idx];
- // Tight list paragraphs
- if (token.hidden) {
- return '';
- }
- // Insert a newline between hidden paragraph and subsequent opening
- // block-level tag.
- //
- // For example, here we should insert a newline before blockquote:
- // - a
- // >
- //
- if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) {
- result += '\n';
- }
- // Add token name, e.g. `<img`
- result += (token.nesting === -1 ? '</' : '<') + token.tag;
- // Encode attributes, e.g. `<img src="foo"`
- result += this.renderAttrs(token);
- // Add a slash for self-closing tags, e.g. `<img src="foo" /`
- if (token.nesting === 0 && options.xhtmlOut) {
- result += ' /';
- }
- // Check if we need to add a newline after this tag
- if (token.block) {
- needLf = true;
- if (token.nesting === 1) {
- if (idx + 1 < tokens.length) {
- nextToken = tokens[idx + 1];
- if (nextToken.type === 'inline' || nextToken.hidden) {
- // Block-level tag containing an inline tag.
- //
- needLf = false;
- } else if (nextToken.nesting === -1 && nextToken.tag === token.tag) {
- // Opening tag + closing tag of the same type. E.g. `<li></li>`.
- //
- needLf = false;
- }
- }
- }
- }
- result += needLf ? '>\n' : '>';
- return result;
- };
- /**
- * Renderer.renderInline(tokens, options, env) -> String
- * - tokens (Array): list on block tokens to renter
- * - options (Object): params of parser instance
- * - env (Object): additional data from parsed input (references, for example)
- *
- * The same as [[Renderer.render]], but for single token of `inline` type.
- **/
- Renderer.prototype.renderInline = function (tokens, options, env) {
- var type,
- result = '',
- rules = this.rules;
- for (var i = 0, len = tokens.length; i < len; i++) {
- type = tokens[i].type;
- if (typeof rules[type] !== 'undefined') {
- result += rules[type](tokens, i, options, env, this);
- } else {
- result += this.renderToken(tokens, i, options);
- }
- }
- return result;
- };
- /** internal
- * Renderer.renderInlineAsText(tokens, options, env) -> String
- * - tokens (Array): list on block tokens to renter
- * - options (Object): params of parser instance
- * - env (Object): additional data from parsed input (references, for example)
- *
- * Special kludge for image `alt` attributes to conform CommonMark spec.
- * Don't try to use it! Spec requires to show `alt` content with stripped markup,
- * instead of simple escaping.
- **/
- Renderer.prototype.renderInlineAsText = function (tokens, options, env) {
- var result = '';
- for (var i = 0, len = tokens.length; i < len; i++) {
- if (tokens[i].type === 'text') {
- result += tokens[i].content;
- } else if (tokens[i].type === 'image') {
- result += this.renderInlineAsText(tokens[i].children, options, env);
- }
- }
- return result;
- };
- /**
- * Renderer.render(tokens, options, env) -> String
- * - tokens (Array): list on block tokens to renter
- * - options (Object): params of parser instance
- * - env (Object): additional data from parsed input (references, for example)
- *
- * Takes token stream and generates HTML. Probably, you will never need to call
- * this method directly.
- **/
- Renderer.prototype.render = function (tokens, options, env) {
- var i, len, type,
- result = '',
- rules = this.rules;
- for (i = 0, len = tokens.length; i < len; i++) {
- type = tokens[i].type;
- if (type === 'inline') {
- result += this.renderInline(tokens[i].children, options, env);
- } else if (typeof rules[type] !== 'undefined') {
- result += rules[tokens[i].type](tokens, i, options, env, this);
- } else {
- result += this.renderToken(tokens, i, options, env);
- }
- }
- return result;
- };
- module.exports = Renderer;
- },{"./common/utils":144}],157:[function(require,module,exports){
- /**
- * class Ruler
- *
- * Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and
- * [[MarkdownIt#inline]] to manage sequences of functions (rules):
- *
- * - keep rules in defined order
- * - assign the name to each rule
- * - enable/disable rules
- * - add/replace rules
- * - allow assign rules to additional named chains (in the same)
- * - cacheing lists of active rules
- *
- * You will not need use this class directly until write plugins. For simple
- * rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and
- * [[MarkdownIt.use]].
- **/
- 'use strict';
- /**
- * new Ruler()
- **/
- function Ruler() {
- // List of added rules. Each element is:
- //
- // {
- // name: XXX,
- // enabled: Boolean,
- // fn: Function(),
- // alt: [ name2, name3 ]
- // }
- //
- this.__rules__ = [];
- // Cached rule chains.
- //
- // First level - chain name, '' for default.
- // Second level - diginal anchor for fast filtering by charcodes.
- //
- this.__cache__ = null;
- }
- ////////////////////////////////////////////////////////////////////////////////
- // Helper methods, should not be used directly
- // Find rule index by name
- //
- Ruler.prototype.__find__ = function (name) {
- for (var i = 0; i < this.__rules__.length; i++) {
- if (this.__rules__[i].name === name) {
- return i;
- }
- }
- return -1;
- };
- // Build rules lookup cache
- //
- Ruler.prototype.__compile__ = function () {
- var self = this;
- var chains = [ '' ];
- // collect unique names
- self.__rules__.forEach(function (rule) {
- if (!rule.enabled) { return; }
- rule.alt.forEach(function (altName) {
- if (chains.indexOf(altName) < 0) {
- chains.push(altName);
- }
- });
- });
- self.__cache__ = {};
- chains.forEach(function (chain) {
- self.__cache__[chain] = [];
- self.__rules__.forEach(function (rule) {
- if (!rule.enabled) { return; }
- if (chain && rule.alt.indexOf(chain) < 0) { return; }
- self.__cache__[chain].push(rule.fn);
- });
- });
- };
- /**
- * Ruler.at(name, fn [, options])
- * - name (String): rule name to replace.
- * - fn (Function): new rule function.
- * - options (Object): new rule options (not mandatory).
- *
- * Replace rule by name with new function & options. Throws error if name not
- * found.
- *
- * ##### Options:
- *
- * - __alt__ - array with names of "alternate" chains.
- *
- * ##### Example
- *
- * Replace existing typographer replacement rule with new one:
- *
- * ```javascript
- * var md = require('markdown-it')();
- *
- * md.core.ruler.at('replacements', function replace(state) {
- * //...
- * });
- * ```
- **/
- Ruler.prototype.at = function (name, fn, options) {
- var index = this.__find__(name);
- var opt = options || {};
- if (index === -1) { throw new Error('Parser rule not found: ' + name); }
- this.__rules__[index].fn = fn;
- this.__rules__[index].alt = opt.alt || [];
- this.__cache__ = null;
- };
- /**
- * Ruler.before(beforeName, ruleName, fn [, options])
- * - beforeName (String): new rule will be added before this one.
- * - ruleName (String): name of added rule.
- * - fn (Function): rule function.
- * - options (Object): rule options (not mandatory).
- *
- * Add new rule to chain before one with given name. See also
- * [[Ruler.after]], [[Ruler.push]].
- *
- * ##### Options:
- *
- * - __alt__ - array with names of "alternate" chains.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')();
- *
- * md.block.ruler.before('paragraph', 'my_rule', function replace(state) {
- * //...
- * });
- * ```
- **/
- Ruler.prototype.before = function (beforeName, ruleName, fn, options) {
- var index = this.__find__(beforeName);
- var opt = options || {};
- if (index === -1) { throw new Error('Parser rule not found: ' + beforeName); }
- this.__rules__.splice(index, 0, {
- name: ruleName,
- enabled: true,
- fn: fn,
- alt: opt.alt || []
- });
- this.__cache__ = null;
- };
- /**
- * Ruler.after(afterName, ruleName, fn [, options])
- * - afterName (String): new rule will be added after this one.
- * - ruleName (String): name of added rule.
- * - fn (Function): rule function.
- * - options (Object): rule options (not mandatory).
- *
- * Add new rule to chain after one with given name. See also
- * [[Ruler.before]], [[Ruler.push]].
- *
- * ##### Options:
- *
- * - __alt__ - array with names of "alternate" chains.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')();
- *
- * md.inline.ruler.after('text', 'my_rule', function replace(state) {
- * //...
- * });
- * ```
- **/
- Ruler.prototype.after = function (afterName, ruleName, fn, options) {
- var index = this.__find__(afterName);
- var opt = options || {};
- if (index === -1) { throw new Error('Parser rule not found: ' + afterName); }
- this.__rules__.splice(index + 1, 0, {
- name: ruleName,
- enabled: true,
- fn: fn,
- alt: opt.alt || []
- });
- this.__cache__ = null;
- };
- /**
- * Ruler.push(ruleName, fn [, options])
- * - ruleName (String): name of added rule.
- * - fn (Function): rule function.
- * - options (Object): rule options (not mandatory).
- *
- * Push new rule to the end of chain. See also
- * [[Ruler.before]], [[Ruler.after]].
- *
- * ##### Options:
- *
- * - __alt__ - array with names of "alternate" chains.
- *
- * ##### Example
- *
- * ```javascript
- * var md = require('markdown-it')();
- *
- * md.core.ruler.push('my_rule', function replace(state) {
- * //...
- * });
- * ```
- **/
- Ruler.prototype.push = function (ruleName, fn, options) {
- var opt = options || {};
- this.__rules__.push({
- name: ruleName,
- enabled: true,
- fn: fn,
- alt: opt.alt || []
- });
- this.__cache__ = null;
- };
- /**
- * Ruler.enable(list [, ignoreInvalid]) -> Array
- * - list (String|Array): list of rule names to enable.
- * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
- *
- * Enable rules with given names. If any rule name not found - throw Error.
- * Errors can be disabled by second param.
- *
- * Returns list of found rule names (if no exception happened).
- *
- * See also [[Ruler.disable]], [[Ruler.enableOnly]].
- **/
- Ruler.prototype.enable = function (list, ignoreInvalid) {
- if (!Array.isArray(list)) { list = [ list ]; }
- var result = [];
- // Search by name and enable
- list.forEach(function (name) {
- var idx = this.__find__(name);
- if (idx < 0) {
- if (ignoreInvalid) { return; }
- throw new Error('Rules manager: invalid rule name ' + name);
- }
- this.__rules__[idx].enabled = true;
- result.push(name);
- }, this);
- this.__cache__ = null;
- return result;
- };
- /**
- * Ruler.enableOnly(list [, ignoreInvalid])
- * - list (String|Array): list of rule names to enable (whitelist).
- * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
- *
- * Enable rules with given names, and disable everything else. If any rule name
- * not found - throw Error. Errors can be disabled by second param.
- *
- * See also [[Ruler.disable]], [[Ruler.enable]].
- **/
- Ruler.prototype.enableOnly = function (list, ignoreInvalid) {
- if (!Array.isArray(list)) { list = [ list ]; }
- this.__rules__.forEach(function (rule) { rule.enabled = false; });
- this.enable(list, ignoreInvalid);
- };
- /**
- * Ruler.disable(list [, ignoreInvalid]) -> Array
- * - list (String|Array): list of rule names to disable.
- * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
- *
- * Disable rules with given names. If any rule name not found - throw Error.
- * Errors can be disabled by second param.
- *
- * Returns list of found rule names (if no exception happened).
- *
- * See also [[Ruler.enable]], [[Ruler.enableOnly]].
- **/
- Ruler.prototype.disable = function (list, ignoreInvalid) {
- if (!Array.isArray(list)) { list = [ list ]; }
- var result = [];
- // Search by name and disable
- list.forEach(function (name) {
- var idx = this.__find__(name);
- if (idx < 0) {
- if (ignoreInvalid) { return; }
- throw new Error('Rules manager: invalid rule name ' + name);
- }
- this.__rules__[idx].enabled = false;
- result.push(name);
- }, this);
- this.__cache__ = null;
- return result;
- };
- /**
- * Ruler.getRules(chainName) -> Array
- *
- * Return array of active functions (rules) for given chain name. It analyzes
- * rules configuration, compiles caches if not exists and returns result.
- *
- * Default chain name is `''` (empty string). It can't be skipped. That's
- * done intentionally, to keep signature monomorphic for high speed.
- **/
- Ruler.prototype.getRules = function (chainName) {
- if (this.__cache__ === null) {
- this.__compile__();
- }
- // Chain can be empty, if rules disabled. But we still have to return Array.
- return this.__cache__[chainName] || [];
- };
- module.exports = Ruler;
- },{}],158:[function(require,module,exports){
- // Block quotes
- 'use strict';
- var isSpace = require('../common/utils').isSpace;
- module.exports = function blockquote(state, startLine, endLine, silent) {
- var adjustTab,
- ch,
- i,
- initial,
- l,
- lastLineEmpty,
- lines,
- nextLine,
- offset,
- oldBMarks,
- oldBSCount,
- oldIndent,
- oldParentType,
- oldSCount,
- oldTShift,
- spaceAfterMarker,
- terminate,
- terminatorRules,
- token,
- wasOutdented,
- oldLineMax = state.lineMax,
- pos = state.bMarks[startLine] + state.tShift[startLine],
- max = state.eMarks[startLine];
- // if it's indented more than 3 spaces, it should be a code block
- if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
- // check the block quote marker
- if (state.src.charCodeAt(pos++) !== 0x3E/* > */) { return false; }
- // we know that it's going to be a valid blockquote,
- // so no point trying to find the end of it in silent mode
- if (silent) { return true; }
- // skip spaces after ">" and re-calculate offset
- initial = offset = state.sCount[startLine] + pos - (state.bMarks[startLine] + state.tShift[startLine]);
- // skip one optional space after '>'
- if (state.src.charCodeAt(pos) === 0x20 /* space */) {
- // ' > test '
- // ^ -- position start of line here:
- pos++;
- initial++;
- offset++;
- adjustTab = false;
- spaceAfterMarker = true;
- } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) {
- spaceAfterMarker = true;
- if ((state.bsCount[startLine] + offset) % 4 === 3) {
- // ' >\t test '
- // ^ -- position start of line here (tab has width===1)
- pos++;
- initial++;
- offset++;
- adjustTab = false;
- } else {
- // ' >\t test '
- // ^ -- position start of line here + shift bsCount slightly
- // to make extra space appear
- adjustTab = true;
- }
- } else {
- spaceAfterMarker = false;
- }
- oldBMarks = [ state.bMarks[startLine] ];
- state.bMarks[startLine] = pos;
- while (pos < max) {
- ch = state.src.charCodeAt(pos);
- if (isSpace(ch)) {
- if (ch === 0x09) {
- offset += 4 - (offset + state.bsCount[startLine] + (adjustTab ? 1 : 0)) % 4;
- } else {
- offset++;
- }
- } else {
- break;
- }
- pos++;
- }
- oldBSCount = [ state.bsCount[startLine] ];
- state.bsCount[startLine] = state.sCount[startLine] + 1 + (spaceAfterMarker ? 1 : 0);
- lastLineEmpty = pos >= max;
- oldSCount = [ state.sCount[startLine] ];
- state.sCount[startLine] = offset - initial;
- oldTShift = [ state.tShift[startLine] ];
- state.tShift[startLine] = pos - state.bMarks[startLine];
- terminatorRules = state.md.block.ruler.getRules('blockquote');
- oldParentType = state.parentType;
- state.parentType = 'blockquote';
- wasOutdented = false;
- // Search the end of the block
- //
- // Block ends with either:
- // 1. an empty line outside:
- // ```
- // > test
- //
- // ```
- // 2. an empty line inside:
- // ```
- // >
- // test
- // ```
- // 3. another tag:
- // ```
- // > test
- // - - -
- // ```
- for (nextLine = startLine + 1; nextLine < endLine; nextLine++) {
- // check if it's outdented, i.e. it's inside list item and indented
- // less than said list item:
- //
- // ```
- // 1. anything
- // > current blockquote
- // 2. checking this line
- // ```
- if (state.sCount[nextLine] < state.blkIndent) wasOutdented = true;
- pos = state.bMarks[nextLine] + state.tShift[nextLine];
- max = state.eMarks[nextLine];
- if (pos >= max) {
- // Case 1: line is not inside the blockquote, and this line is empty.
- break;
- }
- if (state.src.charCodeAt(pos++) === 0x3E/* > */ && !wasOutdented) {
- // This line is inside the blockquote.
- // skip spaces after ">" and re-calculate offset
- initial = offset = state.sCount[nextLine] + pos - (state.bMarks[nextLine] + state.tShift[nextLine]);
- // skip one optional space after '>'
- if (state.src.charCodeAt(pos) === 0x20 /* space */) {
- // ' > test '
- // ^ -- position start of line here:
- pos++;
- initial++;
- offset++;
- adjustTab = false;
- spaceAfterMarker = true;
- } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) {
- spaceAfterMarker = true;
- if ((state.bsCount[nextLine] + offset) % 4 === 3) {
- // ' >\t test '
- // ^ -- position start of line here (tab has width===1)
- pos++;
- initial++;
- offset++;
- adjustTab = false;
- } else {
- // ' >\t test '
- // ^ -- position start of line here + shift bsCount slightly
- // to make extra space appear
- adjustTab = true;
- }
- } else {
- spaceAfterMarker = false;
- }
- oldBMarks.push(state.bMarks[nextLine]);
- state.bMarks[nextLine] = pos;
- while (pos < max) {
- ch = state.src.charCodeAt(pos);
- if (isSpace(ch)) {
- if (ch === 0x09) {
- offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4;
- } else {
- offset++;
- }
- } else {
- break;
- }
- pos++;
- }
- lastLineEmpty = pos >= max;
- oldBSCount.push(state.bsCount[nextLine]);
- state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0);
- oldSCount.push(state.sCount[nextLine]);
- state.sCount[nextLine] = offset - initial;
- oldTShift.push(state.tShift[nextLine]);
- state.tShift[nextLine] = pos - state.bMarks[nextLine];
- continue;
- }
- // Case 2: line is not inside the blockquote, and the last line was empty.
- if (lastLineEmpty) { break; }
- // Case 3: another tag found.
- terminate = false;
- for (i = 0, l = terminatorRules.length; i < l; i++) {
- if (terminatorRules[i](state, nextLine, endLine, true)) {
- terminate = true;
- break;
- }
- }
- if (terminate) {
- // Quirk to enforce "hard termination mode" for paragraphs;
- // normally if you call `tokenize(state, startLine, nextLine)`,
- // paragraphs will look below nextLine for paragraph continuation,
- // but if blockquote is terminated by another tag, they shouldn't
- state.lineMax = nextLine;
- if (state.blkIndent !== 0) {
- // state.blkIndent was non-zero, we now set it to zero,
- // so we need to re-calculate all offsets to appear as
- // if indent wasn't changed
- oldBMarks.push(state.bMarks[nextLine]);
- oldBSCount.push(state.bsCount[nextLine]);
- oldTShift.push(state.tShift[nextLine]);
- oldSCount.push(state.sCount[nextLine]);
- state.sCount[nextLine] -= state.blkIndent;
- }
- break;
- }
- oldBMarks.push(state.bMarks[nextLine]);
- oldBSCount.push(state.bsCount[nextLine]);
- oldTShift.push(state.tShift[nextLine]);
- oldSCount.push(state.sCount[nextLine]);
- // A negative indentation means that this is a paragraph continuation
- //
- state.sCount[nextLine] = -1;
- }
- oldIndent = state.blkIndent;
- state.blkIndent = 0;
- token = state.push('blockquote_open', 'blockquote', 1);
- token.markup = '>';
- token.map = lines = [ startLine, 0 ];
- state.md.block.tokenize(state, startLine, nextLine);
- token = state.push('blockquote_close', 'blockquote', -1);
- token.markup = '>';
- state.lineMax = oldLineMax;
- state.parentType = oldParentType;
- lines[1] = state.line;
- // Restore original tShift; this might not be necessary since the parser
- // has already been here, but just to make sure we can do that.
- for (i = 0; i < oldTShift.length; i++) {
- state.bMarks[i + startLine] = oldBMarks[i];
- state.tShift[i + startLine] = oldTShift[i];
- state.sCount[i + startLine] = oldSCount[i];
- state.bsCount[i + startLine] = oldBSCount[i];
- }
- state.blkIndent = oldIndent;
- return true;
- };
- },{"../common/utils":144}],159:[function(require,module,exports){
- // Code block (4 spaces padded)
- 'use strict';
- module.exports = function code(state, startLine, endLine/*, silent*/) {
- var nextLine, last, token;
- if (state.sCount[startLine] - state.blkIndent < 4) { return false; }
- last = nextLine = startLine + 1;
- while (nextLine < endLine) {
- if (state.isEmpty(nextLine)) {
- nextLine++;
- continue;
- }
- if (state.sCount[nextLine] - state.blkIndent >= 4) {
- nextLine++;
- last = nextLine;
- continue;
- }
- break;
- }
- state.line = last;
- token = state.push('code_block', 'code', 0);
- token.content = state.getLines(startLine, last, 4 + state.blkIndent, true);
- token.map = [ startLine, state.line ];
- return true;
- };
- },{}],160:[function(require,module,exports){
- // fences (``` lang, ~~~ lang)
- 'use strict';
- module.exports = function fence(state, startLine, endLine, silent) {
- var marker, len, params, nextLine, mem, token, markup,
- haveEndMarker = false,
- pos = state.bMarks[startLine] + state.tShift[startLine],
- max = state.eMarks[startLine];
- // if it's indented more than 3 spaces, it should be a code block
- if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
- if (pos + 3 > max) { return false; }
- marker = state.src.charCodeAt(pos);
- if (marker !== 0x7E/* ~ */ && marker !== 0x60 /* ` */) {
- return false;
- }
- // scan marker length
- mem = pos;
- pos = state.skipChars(pos, marker);
- len = pos - mem;
- if (len < 3) { return false; }
- markup = state.src.slice(mem, pos);
- params = state.src.slice(pos, max);
- if (params.indexOf(String.fromCharCode(marker)) >= 0) { return false; }
- // Since start is found, we can report success here in validation mode
- if (silent) { return true; }
- // search end of block
- nextLine = startLine;
- for (;;) {
- nextLine++;
- if (nextLine >= endLine) {
- // unclosed block should be autoclosed by end of document.
- // also block seems to be autoclosed by end of parent
- break;
- }
- pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
- max = state.eMarks[nextLine];
- if (pos < max && state.sCount[nextLine] < state.blkIndent) {
- // non-empty line with negative indent should stop the list:
- // - ```
- // test
- break;
- }
- if (state.src.charCodeAt(pos) !== marker) { continue; }
- if (state.sCount[nextLine] - state.blkIndent >= 4) {
- // closing fence should be indented less than 4 spaces
- continue;
- }
- pos = state.skipChars(pos, marker);
- // closing code fence must be at least as long as the opening one
- if (pos - mem < len) { continue; }
- // make sure tail has spaces only
- pos = state.skipSpaces(pos);
- if (pos < max) { continue; }
- haveEndMarker = true;
- // found!
- break;
- }
- // If a fence has heading spaces, they should be removed from its inner block
- len = state.sCount[startLine];
- state.line = nextLine + (haveEndMarker ? 1 : 0);
- token = state.push('fence', 'code', 0);
- token.info = params;
- token.content = state.getLines(startLine + 1, nextLine, len, true);
- token.markup = markup;
- token.map = [ startLine, state.line ];
- return true;
- };
- },{}],161:[function(require,module,exports){
- // heading (#, ##, ...)
- 'use strict';
- var isSpace = require('../common/utils').isSpace;
- module.exports = function heading(state, startLine, endLine, silent) {
- var ch, level, tmp, token,
- pos = state.bMarks[startLine] + state.tShift[startLine],
- max = state.eMarks[startLine];
- // if it's indented more than 3 spaces, it should be a code block
- if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
- ch = state.src.charCodeAt(pos);
- if (ch !== 0x23/* # */ || pos >= max) { return false; }
- // count heading level
- level = 1;
- ch = state.src.charCodeAt(++pos);
- while (ch === 0x23/* # */ && pos < max && level <= 6) {
- level++;
- ch = state.src.charCodeAt(++pos);
- }
- if (level > 6 || (pos < max && !isSpace(ch))) { return false; }
- if (silent) { return true; }
- // Let's cut tails like ' ### ' from the end of string
- max = state.skipSpacesBack(max, pos);
- tmp = state.skipCharsBack(max, 0x23, pos); // #
- if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) {
- max = tmp;
- }
- state.line = startLine + 1;
- token = state.push('heading_open', 'h' + String(level), 1);
- token.markup = '########'.slice(0, level);
- token.map = [ startLine, state.line ];
- token = state.push('inline', '', 0);
- token.content = state.src.slice(pos, max).trim();
- token.map = [ startLine, state.line ];
- token.children = [];
- token = state.push('heading_close', 'h' + String(level), -1);
- token.markup = '########'.slice(0, level);
- return true;
- };
- },{"../common/utils":144}],162:[function(require,module,exports){
- // Horizontal rule
- 'use strict';
- var isSpace = require('../common/utils').isSpace;
- module.exports = function hr(state, startLine, endLine, silent) {
- var marker, cnt, ch, token,
- pos = state.bMarks[startLine] + state.tShift[startLine],
- max = state.eMarks[startLine];
- // if it's indented more than 3 spaces, it should be a code block
- if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
- marker = state.src.charCodeAt(pos++);
- // Check hr marker
- if (marker !== 0x2A/* * */ &&
- marker !== 0x2D/* - */ &&
- marker !== 0x5F/* _ */) {
- return false;
- }
- // markers can be mixed with spaces, but there should be at least 3 of them
- cnt = 1;
- while (pos < max) {
- ch = state.src.charCodeAt(pos++);
- if (ch !== marker && !isSpace(ch)) { return false; }
- if (ch === marker) { cnt++; }
- }
- if (cnt < 3) { return false; }
- if (silent) { return true; }
- state.line = startLine + 1;
- token = state.push('hr', 'hr', 0);
- token.map = [ startLine, state.line ];
- token.markup = Array(cnt + 1).join(String.fromCharCode(marker));
- return true;
- };
- },{"../common/utils":144}],163:[function(require,module,exports){
- // HTML block
- 'use strict';
- var block_names = require('../common/html_blocks');
- var HTML_OPEN_CLOSE_TAG_RE = require('../common/html_re').HTML_OPEN_CLOSE_TAG_RE;
- // An array of opening and corresponding closing sequences for html tags,
- // last argument defines whether it can terminate a paragraph or not
- //
- var HTML_SEQUENCES = [
- [ /^<(script|pre|style)(?=(\s|>|$))/i, /<\/(script|pre|style)>/i, true ],
- [ /^<!--/, /-->/, true ],
- [ /^<\?/, /\?>/, true ],
- [ /^<![A-Z]/, />/, true ],
- [ /^<!\[CDATA\[/, /\]\]>/, true ],
- [ new RegExp('^</?(' + block_names.join('|') + ')(?=(\\s|/?>|$))', 'i'), /^$/, true ],
- [ new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + '\\s*$'), /^$/, false ]
- ];
- module.exports = function html_block(state, startLine, endLine, silent) {
- var i, nextLine, token, lineText,
- pos = state.bMarks[startLine] + state.tShift[startLine],
- max = state.eMarks[startLine];
- // if it's indented more than 3 spaces, it should be a code block
- if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
- if (!state.md.options.html) { return false; }
- if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; }
- lineText = state.src.slice(pos, max);
- for (i = 0; i < HTML_SEQUENCES.length; i++) {
- if (HTML_SEQUENCES[i][0].test(lineText)) { break; }
- }
- if (i === HTML_SEQUENCES.length) { return false; }
- if (silent) {
- // true if this sequence can be a terminator, false otherwise
- return HTML_SEQUENCES[i][2];
- }
- nextLine = startLine + 1;
- // If we are here - we detected HTML block.
- // Let's roll down till block end.
- if (!HTML_SEQUENCES[i][1].test(lineText)) {
- for (; nextLine < endLine; nextLine++) {
- if (state.sCount[nextLine] < state.blkIndent) { break; }
- pos = state.bMarks[nextLine] + state.tShift[nextLine];
- max = state.eMarks[nextLine];
- lineText = state.src.slice(pos, max);
- if (HTML_SEQUENCES[i][1].test(lineText)) {
- if (lineText.length !== 0) { nextLine++; }
- break;
- }
- }
- }
- state.line = nextLine;
- token = state.push('html_block', '', 0);
- token.map = [ startLine, nextLine ];
- token.content = state.getLines(startLine, nextLine, state.blkIndent, true);
- return true;
- };
- },{"../common/html_blocks":142,"../common/html_re":143}],164:[function(require,module,exports){
- // lheading (---, ===)
- 'use strict';
- module.exports = function lheading(state, startLine, endLine/*, silent*/) {
- var content, terminate, i, l, token, pos, max, level, marker,
- nextLine = startLine + 1, oldParentType,
- terminatorRules = state.md.block.ruler.getRules('paragraph');
- // if it's indented more than 3 spaces, it should be a code block
- if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
- oldParentType = state.parentType;
- state.parentType = 'paragraph'; // use paragraph to match terminatorRules
- // jump line-by-line until empty one or EOF
- for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
- // this would be a code block normally, but after paragraph
- // it's considered a lazy continuation regardless of what's there
- if (state.sCount[nextLine] - state.blkIndent > 3) { continue; }
- //
- // Check for underline in setext header
- //
- if (state.sCount[nextLine] >= state.blkIndent) {
- pos = state.bMarks[nextLine] + state.tShift[nextLine];
- max = state.eMarks[nextLine];
- if (pos < max) {
- marker = state.src.charCodeAt(pos);
- if (marker === 0x2D/* - */ || marker === 0x3D/* = */) {
- pos = state.skipChars(pos, marker);
- pos = state.skipSpaces(pos);
- if (pos >= max) {
- level = (marker === 0x3D/* = */ ? 1 : 2);
- break;
- }
- }
- }
- }
- // quirk for blockquotes, this line should already be checked by that rule
- if (state.sCount[nextLine] < 0) { continue; }
- // Some tags can terminate paragraph without empty line.
- terminate = false;
- for (i = 0, l = terminatorRules.length; i < l; i++) {
- if (terminatorRules[i](state, nextLine, endLine, true)) {
- terminate = true;
- break;
- }
- }
- if (terminate) { break; }
- }
- if (!level) {
- // Didn't find valid underline
- return false;
- }
- content = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
- state.line = nextLine + 1;
- token = state.push('heading_open', 'h' + String(level), 1);
- token.markup = String.fromCharCode(marker);
- token.map = [ startLine, state.line ];
- token = state.push('inline', '', 0);
- token.content = content;
- token.map = [ startLine, state.line - 1 ];
- token.children = [];
- token = state.push('heading_close', 'h' + String(level), -1);
- token.markup = String.fromCharCode(marker);
- state.parentType = oldParentType;
- return true;
- };
- },{}],165:[function(require,module,exports){
- // Lists
- 'use strict';
- var isSpace = require('../common/utils').isSpace;
- // Search `[-+*][\n ]`, returns next pos after marker on success
- // or -1 on fail.
- function skipBulletListMarker(state, startLine) {
- var marker, pos, max, ch;
- pos = state.bMarks[startLine] + state.tShift[startLine];
- max = state.eMarks[startLine];
- marker = state.src.charCodeAt(pos++);
- // Check bullet
- if (marker !== 0x2A/* * */ &&
- marker !== 0x2D/* - */ &&
- marker !== 0x2B/* + */) {
- return -1;
- }
- if (pos < max) {
- ch = state.src.charCodeAt(pos);
- if (!isSpace(ch)) {
- // " -test " - is not a list item
- return -1;
- }
- }
- return pos;
- }
- // Search `\d+[.)][\n ]`, returns next pos after marker on success
- // or -1 on fail.
- function skipOrderedListMarker(state, startLine) {
- var ch,
- start = state.bMarks[startLine] + state.tShift[startLine],
- pos = start,
- max = state.eMarks[startLine];
- // List marker should have at least 2 chars (digit + dot)
- if (pos + 1 >= max) { return -1; }
- ch = state.src.charCodeAt(pos++);
- if (ch < 0x30/* 0 */ || ch > 0x39/* 9 */) { return -1; }
- for (;;) {
- // EOL -> fail
- if (pos >= max) { return -1; }
- ch = state.src.charCodeAt(pos++);
- if (ch >= 0x30/* 0 */ && ch <= 0x39/* 9 */) {
- // List marker should have no more than 9 digits
- // (prevents integer overflow in browsers)
- if (pos - start >= 10) { return -1; }
- continue;
- }
- // found valid marker
- if (ch === 0x29/* ) */ || ch === 0x2e/* . */) {
- break;
- }
- return -1;
- }
- if (pos < max) {
- ch = state.src.charCodeAt(pos);
- if (!isSpace(ch)) {
- // " 1.test " - is not a list item
- return -1;
- }
- }
- return pos;
- }
- function markTightParagraphs(state, idx) {
- var i, l,
- level = state.level + 2;
- for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) {
- if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') {
- state.tokens[i + 2].hidden = true;
- state.tokens[i].hidden = true;
- i += 2;
- }
- }
- }
- module.exports = function list(state, startLine, endLine, silent) {
- var ch,
- contentStart,
- i,
- indent,
- indentAfterMarker,
- initial,
- isOrdered,
- itemLines,
- l,
- listLines,
- listTokIdx,
- markerCharCode,
- markerValue,
- max,
- nextLine,
- offset,
- oldIndent,
- oldLIndent,
- oldParentType,
- oldTShift,
- oldTight,
- pos,
- posAfterMarker,
- prevEmptyEnd,
- start,
- terminate,
- terminatorRules,
- token,
- isTerminatingParagraph = false,
- tight = true;
- // if it's indented more than 3 spaces, it should be a code block
- if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
- // limit conditions when list can interrupt
- // a paragraph (validation mode only)
- if (silent && state.parentType === 'paragraph') {
- // Next list item should still terminate previous list item;
- //
- // This code can fail if plugins use blkIndent as well as lists,
- // but I hope the spec gets fixed long before that happens.
- //
- if (state.tShift[startLine] >= state.blkIndent) {
- isTerminatingParagraph = true;
- }
- }
- // Detect list type and position after marker
- if ((posAfterMarker = skipOrderedListMarker(state, startLine)) >= 0) {
- isOrdered = true;
- start = state.bMarks[startLine] + state.tShift[startLine];
- markerValue = Number(state.src.substr(start, posAfterMarker - start - 1));
- // If we're starting a new ordered list right after
- // a paragraph, it should start with 1.
- if (isTerminatingParagraph && markerValue !== 1) return false;
- } else if ((posAfterMarker = skipBulletListMarker(state, startLine)) >= 0) {
- isOrdered = false;
- } else {
- return false;
- }
- // If we're starting a new unordered list right after
- // a paragraph, first line should not be empty.
- if (isTerminatingParagraph) {
- if (state.skipSpaces(posAfterMarker) >= state.eMarks[startLine]) return false;
- }
- // We should terminate list on style change. Remember first one to compare.
- markerCharCode = state.src.charCodeAt(posAfterMarker - 1);
- // For validation mode we can terminate immediately
- if (silent) { return true; }
- // Start list
- listTokIdx = state.tokens.length;
- if (isOrdered) {
- token = state.push('ordered_list_open', 'ol', 1);
- if (markerValue !== 1) {
- token.attrs = [ [ 'start', markerValue ] ];
- }
- } else {
- token = state.push('bullet_list_open', 'ul', 1);
- }
- token.map = listLines = [ startLine, 0 ];
- token.markup = String.fromCharCode(markerCharCode);
- //
- // Iterate list items
- //
- nextLine = startLine;
- prevEmptyEnd = false;
- terminatorRules = state.md.block.ruler.getRules('list');
- oldParentType = state.parentType;
- state.parentType = 'list';
- while (nextLine < endLine) {
- pos = posAfterMarker;
- max = state.eMarks[nextLine];
- initial = offset = state.sCount[nextLine] + posAfterMarker - (state.bMarks[startLine] + state.tShift[startLine]);
- while (pos < max) {
- ch = state.src.charCodeAt(pos);
- if (ch === 0x09) {
- offset += 4 - (offset + state.bsCount[nextLine]) % 4;
- } else if (ch === 0x20) {
- offset++;
- } else {
- break;
- }
- pos++;
- }
- contentStart = pos;
- if (contentStart >= max) {
- // trimming space in "- \n 3" case, indent is 1 here
- indentAfterMarker = 1;
- } else {
- indentAfterMarker = offset - initial;
- }
- // If we have more than 4 spaces, the indent is 1
- // (the rest is just indented code block)
- if (indentAfterMarker > 4) { indentAfterMarker = 1; }
- // " - test"
- // ^^^^^ - calculating total length of this thing
- indent = initial + indentAfterMarker;
- // Run subparser & write tokens
- token = state.push('list_item_open', 'li', 1);
- token.markup = String.fromCharCode(markerCharCode);
- token.map = itemLines = [ startLine, 0 ];
- oldIndent = state.blkIndent;
- oldTight = state.tight;
- oldTShift = state.tShift[startLine];
- oldLIndent = state.sCount[startLine];
- state.blkIndent = indent;
- state.tight = true;
- state.tShift[startLine] = contentStart - state.bMarks[startLine];
- state.sCount[startLine] = offset;
- if (contentStart >= max && state.isEmpty(startLine + 1)) {
- // workaround for this case
- // (list item is empty, list terminates before "foo"):
- // ~~~~~~~~
- // -
- //
- // foo
- // ~~~~~~~~
- state.line = Math.min(state.line + 2, endLine);
- } else {
- state.md.block.tokenize(state, startLine, endLine, true);
- }
- // If any of list item is tight, mark list as tight
- if (!state.tight || prevEmptyEnd) {
- tight = false;
- }
- // Item become loose if finish with empty line,
- // but we should filter last element, because it means list finish
- prevEmptyEnd = (state.line - startLine) > 1 && state.isEmpty(state.line - 1);
- state.blkIndent = oldIndent;
- state.tShift[startLine] = oldTShift;
- state.sCount[startLine] = oldLIndent;
- state.tight = oldTight;
- token = state.push('list_item_close', 'li', -1);
- token.markup = String.fromCharCode(markerCharCode);
- nextLine = startLine = state.line;
- itemLines[1] = nextLine;
- contentStart = state.bMarks[startLine];
- if (nextLine >= endLine) { break; }
- //
- // Try to check if list is terminated or continued.
- //
- if (state.sCount[nextLine] < state.blkIndent) { break; }
- // fail if terminating block found
- terminate = false;
- for (i = 0, l = terminatorRules.length; i < l; i++) {
- if (terminatorRules[i](state, nextLine, endLine, true)) {
- terminate = true;
- break;
- }
- }
- if (terminate) { break; }
- // fail if list has another type
- if (isOrdered) {
- posAfterMarker = skipOrderedListMarker(state, nextLine);
- if (posAfterMarker < 0) { break; }
- } else {
- posAfterMarker = skipBulletListMarker(state, nextLine);
- if (posAfterMarker < 0) { break; }
- }
- if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { break; }
- }
- // Finalize list
- if (isOrdered) {
- token = state.push('ordered_list_close', 'ol', -1);
- } else {
- token = state.push('bullet_list_close', 'ul', -1);
- }
- token.markup = String.fromCharCode(markerCharCode);
- listLines[1] = nextLine;
- state.line = nextLine;
- state.parentType = oldParentType;
- // mark paragraphs tight if needed
- if (tight) {
- markTightParagraphs(state, listTokIdx);
- }
- return true;
- };
- },{"../common/utils":144}],166:[function(require,module,exports){
- // Paragraph
- 'use strict';
- module.exports = function paragraph(state, startLine/*, endLine*/) {
- var content, terminate, i, l, token, oldParentType,
- nextLine = startLine + 1,
- terminatorRules = state.md.block.ruler.getRules('paragraph'),
- endLine = state.lineMax;
- oldParentType = state.parentType;
- state.parentType = 'paragraph';
- // jump line-by-line until empty one or EOF
- for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
- // this would be a code block normally, but after paragraph
- // it's considered a lazy continuation regardless of what's there
- if (state.sCount[nextLine] - state.blkIndent > 3) { continue; }
- // quirk for blockquotes, this line should already be checked by that rule
- if (state.sCount[nextLine] < 0) { continue; }
- // Some tags can terminate paragraph without empty line.
- terminate = false;
- for (i = 0, l = terminatorRules.length; i < l; i++) {
- if (terminatorRules[i](state, nextLine, endLine, true)) {
- terminate = true;
- break;
- }
- }
- if (terminate) { break; }
- }
- content = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
- state.line = nextLine;
- token = state.push('paragraph_open', 'p', 1);
- token.map = [ startLine, state.line ];
- token = state.push('inline', '', 0);
- token.content = content;
- token.map = [ startLine, state.line ];
- token.children = [];
- token = state.push('paragraph_close', 'p', -1);
- state.parentType = oldParentType;
- return true;
- };
- },{}],167:[function(require,module,exports){
- 'use strict';
- var normalizeReference = require('../common/utils').normalizeReference;
- var isSpace = require('../common/utils').isSpace;
- module.exports = function reference(state, startLine, _endLine, silent) {
- var ch,
- destEndPos,
- destEndLineNo,
- endLine,
- href,
- i,
- l,
- label,
- labelEnd,
- oldParentType,
- res,
- start,
- str,
- terminate,
- terminatorRules,
- title,
- lines = 0,
- pos = state.bMarks[startLine] + state.tShift[startLine],
- max = state.eMarks[startLine],
- nextLine = startLine + 1;
- // if it's indented more than 3 spaces, it should be a code block
- if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
- if (state.src.charCodeAt(pos) !== 0x5B/* [ */) { return false; }
- // Simple check to quickly interrupt scan on [link](url) at the start of line.
- // Can be useful on practice: https://github.com/markdown-it/markdown-it/issues/54
- while (++pos < max) {
- if (state.src.charCodeAt(pos) === 0x5D /* ] */ &&
- state.src.charCodeAt(pos - 1) !== 0x5C/* \ */) {
- if (pos + 1 === max) { return false; }
- if (state.src.charCodeAt(pos + 1) !== 0x3A/* : */) { return false; }
- break;
- }
- }
- endLine = state.lineMax;
- // jump line-by-line until empty one or EOF
- terminatorRules = state.md.block.ruler.getRules('reference');
- oldParentType = state.parentType;
- state.parentType = 'reference';
- for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {
- // this would be a code block normally, but after paragraph
- // it's considered a lazy continuation regardless of what's there
- if (state.sCount[nextLine] - state.blkIndent > 3) { continue; }
- // quirk for blockquotes, this line should already be checked by that rule
- if (state.sCount[nextLine] < 0) { continue; }
- // Some tags can terminate paragraph without empty line.
- terminate = false;
- for (i = 0, l = terminatorRules.length; i < l; i++) {
- if (terminatorRules[i](state, nextLine, endLine, true)) {
- terminate = true;
- break;
- }
- }
- if (terminate) { break; }
- }
- str = state.getLines(startLine, nextLine, state.blkIndent, false).trim();
- max = str.length;
- for (pos = 1; pos < max; pos++) {
- ch = str.charCodeAt(pos);
- if (ch === 0x5B /* [ */) {
- return false;
- } else if (ch === 0x5D /* ] */) {
- labelEnd = pos;
- break;
- } else if (ch === 0x0A /* \n */) {
- lines++;
- } else if (ch === 0x5C /* \ */) {
- pos++;
- if (pos < max && str.charCodeAt(pos) === 0x0A) {
- lines++;
- }
- }
- }
- if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A/* : */) { return false; }
- // [label]: destination 'title'
- // ^^^ skip optional whitespace here
- for (pos = labelEnd + 2; pos < max; pos++) {
- ch = str.charCodeAt(pos);
- if (ch === 0x0A) {
- lines++;
- } else if (isSpace(ch)) {
- /*eslint no-empty:0*/
- } else {
- break;
- }
- }
- // [label]: destination 'title'
- // ^^^^^^^^^^^ parse this
- res = state.md.helpers.parseLinkDestination(str, pos, max);
- if (!res.ok) { return false; }
- href = state.md.normalizeLink(res.str);
- if (!state.md.validateLink(href)) { return false; }
- pos = res.pos;
- lines += res.lines;
- // save cursor state, we could require to rollback later
- destEndPos = pos;
- destEndLineNo = lines;
- // [label]: destination 'title'
- // ^^^ skipping those spaces
- start = pos;
- for (; pos < max; pos++) {
- ch = str.charCodeAt(pos);
- if (ch === 0x0A) {
- lines++;
- } else if (isSpace(ch)) {
- /*eslint no-empty:0*/
- } else {
- break;
- }
- }
- // [label]: destination 'title'
- // ^^^^^^^ parse this
- res = state.md.helpers.parseLinkTitle(str, pos, max);
- if (pos < max && start !== pos && res.ok) {
- title = res.str;
- pos = res.pos;
- lines += res.lines;
- } else {
- title = '';
- pos = destEndPos;
- lines = destEndLineNo;
- }
- // skip trailing spaces until the rest of the line
- while (pos < max) {
- ch = str.charCodeAt(pos);
- if (!isSpace(ch)) { break; }
- pos++;
- }
- if (pos < max && str.charCodeAt(pos) !== 0x0A) {
- if (title) {
- // garbage at the end of the line after title,
- // but it could still be a valid reference if we roll back
- title = '';
- pos = destEndPos;
- lines = destEndLineNo;
- while (pos < max) {
- ch = str.charCodeAt(pos);
- if (!isSpace(ch)) { break; }
- pos++;
- }
- }
- }
- if (pos < max && str.charCodeAt(pos) !== 0x0A) {
- // garbage at the end of the line
- return false;
- }
- label = normalizeReference(str.slice(1, labelEnd));
- if (!label) {
- // CommonMark 0.20 disallows empty labels
- return false;
- }
- // Reference can not terminate anything. This check is for safety only.
- /*istanbul ignore if*/
- if (silent) { return true; }
- if (typeof state.env.references === 'undefined') {
- state.env.references = {};
- }
- if (typeof state.env.references[label] === 'undefined') {
- state.env.references[label] = { title: title, href: href };
- }
- state.parentType = oldParentType;
- state.line = startLine + lines + 1;
- return true;
- };
- },{"../common/utils":144}],168:[function(require,module,exports){
- // Parser state class
- 'use strict';
- var Token = require('../token');
- var isSpace = require('../common/utils').isSpace;
- function StateBlock(src, md, env, tokens) {
- var ch, s, start, pos, len, indent, offset, indent_found;
- this.src = src;
- // link to parser instance
- this.md = md;
- this.env = env;
- //
- // Internal state vartiables
- //
- this.tokens = tokens;
- this.bMarks = []; // line begin offsets for fast jumps
- this.eMarks = []; // line end offsets for fast jumps
- this.tShift = []; // offsets of the first non-space characters (tabs not expanded)
- this.sCount = []; // indents for each line (tabs expanded)
- // An amount of virtual spaces (tabs expanded) between beginning
- // of each line (bMarks) and real beginning of that line.
- //
- // It exists only as a hack because blockquotes override bMarks
- // losing information in the process.
- //
- // It's used only when expanding tabs, you can think about it as
- // an initial tab length, e.g. bsCount=21 applied to string `\t123`
- // means first tab should be expanded to 4-21%4 === 3 spaces.
- //
- this.bsCount = [];
- // block parser variables
- this.blkIndent = 0; // required block content indent
- // (for example, if we are in list)
- this.line = 0; // line index in src
- this.lineMax = 0; // lines count
- this.tight = false; // loose/tight mode for lists
- this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any)
- // can be 'blockquote', 'list', 'root', 'paragraph' or 'reference'
- // used in lists to determine if they interrupt a paragraph
- this.parentType = 'root';
- this.level = 0;
- // renderer
- this.result = '';
- // Create caches
- // Generate markers.
- s = this.src;
- indent_found = false;
- for (start = pos = indent = offset = 0, len = s.length; pos < len; pos++) {
- ch = s.charCodeAt(pos);
- if (!indent_found) {
- if (isSpace(ch)) {
- indent++;
- if (ch === 0x09) {
- offset += 4 - offset % 4;
- } else {
- offset++;
- }
- continue;
- } else {
- indent_found = true;
- }
- }
- if (ch === 0x0A || pos === len - 1) {
- if (ch !== 0x0A) { pos++; }
- this.bMarks.push(start);
- this.eMarks.push(pos);
- this.tShift.push(indent);
- this.sCount.push(offset);
- this.bsCount.push(0);
- indent_found = false;
- indent = 0;
- offset = 0;
- start = pos + 1;
- }
- }
- // Push fake entry to simplify cache bounds checks
- this.bMarks.push(s.length);
- this.eMarks.push(s.length);
- this.tShift.push(0);
- this.sCount.push(0);
- this.bsCount.push(0);
- this.lineMax = this.bMarks.length - 1; // don't count last fake line
- }
- // Push new token to "stream".
- //
- StateBlock.prototype.push = function (type, tag, nesting) {
- var token = new Token(type, tag, nesting);
- token.block = true;
- if (nesting < 0) { this.level--; }
- token.level = this.level;
- if (nesting > 0) { this.level++; }
- this.tokens.push(token);
- return token;
- };
- StateBlock.prototype.isEmpty = function isEmpty(line) {
- return this.bMarks[line] + this.tShift[line] >= this.eMarks[line];
- };
- StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) {
- for (var max = this.lineMax; from < max; from++) {
- if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) {
- break;
- }
- }
- return from;
- };
- // Skip spaces from given position.
- StateBlock.prototype.skipSpaces = function skipSpaces(pos) {
- var ch;
- for (var max = this.src.length; pos < max; pos++) {
- ch = this.src.charCodeAt(pos);
- if (!isSpace(ch)) { break; }
- }
- return pos;
- };
- // Skip spaces from given position in reverse.
- StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos, min) {
- if (pos <= min) { return pos; }
- while (pos > min) {
- if (!isSpace(this.src.charCodeAt(--pos))) { return pos + 1; }
- }
- return pos;
- };
- // Skip char codes from given position
- StateBlock.prototype.skipChars = function skipChars(pos, code) {
- for (var max = this.src.length; pos < max; pos++) {
- if (this.src.charCodeAt(pos) !== code) { break; }
- }
- return pos;
- };
- // Skip char codes reverse from given position - 1
- StateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code, min) {
- if (pos <= min) { return pos; }
- while (pos > min) {
- if (code !== this.src.charCodeAt(--pos)) { return pos + 1; }
- }
- return pos;
- };
- // cut lines range from source.
- StateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) {
- var i, lineIndent, ch, first, last, queue, lineStart,
- line = begin;
- if (begin >= end) {
- return '';
- }
- queue = new Array(end - begin);
- for (i = 0; line < end; line++, i++) {
- lineIndent = 0;
- lineStart = first = this.bMarks[line];
- if (line + 1 < end || keepLastLF) {
- // No need for bounds check because we have fake entry on tail.
- last = this.eMarks[line] + 1;
- } else {
- last = this.eMarks[line];
- }
- while (first < last && lineIndent < indent) {
- ch = this.src.charCodeAt(first);
- if (isSpace(ch)) {
- if (ch === 0x09) {
- lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4;
- } else {
- lineIndent++;
- }
- } else if (first - lineStart < this.tShift[line]) {
- // patched tShift masked characters to look like spaces (blockquotes, list markers)
- lineIndent++;
- } else {
- break;
- }
- first++;
- }
- if (lineIndent > indent) {
- // partially expanding tabs in code blocks, e.g '\t\tfoobar'
- // with indent=2 becomes ' \tfoobar'
- queue[i] = new Array(lineIndent - indent + 1).join(' ') + this.src.slice(first, last);
- } else {
- queue[i] = this.src.slice(first, last);
- }
- }
- return queue.join('');
- };
- // re-export Token class to use in block rules
- StateBlock.prototype.Token = Token;
- module.exports = StateBlock;
- },{"../common/utils":144,"../token":191}],169:[function(require,module,exports){
- // GFM table, non-standard
- 'use strict';
- var isSpace = require('../common/utils').isSpace;
- function getLine(state, line) {
- var pos = state.bMarks[line] + state.blkIndent,
- max = state.eMarks[line];
- return state.src.substr(pos, max - pos);
- }
- function escapedSplit(str) {
- var result = [],
- pos = 0,
- max = str.length,
- ch,
- escapes = 0,
- lastPos = 0,
- backTicked = false,
- lastBackTick = 0;
- ch = str.charCodeAt(pos);
- while (pos < max) {
- if (ch === 0x60/* ` */) {
- if (backTicked) {
- // make \` close code sequence, but not open it;
- // the reason is: `\` is correct code block
- backTicked = false;
- lastBackTick = pos;
- } else if (escapes % 2 === 0) {
- backTicked = true;
- lastBackTick = pos;
- }
- } else if (ch === 0x7c/* | */ && (escapes % 2 === 0) && !backTicked) {
- result.push(str.substring(lastPos, pos));
- lastPos = pos + 1;
- }
- if (ch === 0x5c/* \ */) {
- escapes++;
- } else {
- escapes = 0;
- }
- pos++;
- // If there was an un-closed backtick, go back to just after
- // the last backtick, but as if it was a normal character
- if (pos === max && backTicked) {
- backTicked = false;
- pos = lastBackTick + 1;
- }
- ch = str.charCodeAt(pos);
- }
- result.push(str.substring(lastPos));
- return result;
- }
- module.exports = function table(state, startLine, endLine, silent) {
- var ch, lineText, pos, i, nextLine, columns, columnCount, token,
- aligns, t, tableLines, tbodyLines;
- // should have at least two lines
- if (startLine + 2 > endLine) { return false; }
- nextLine = startLine + 1;
- if (state.sCount[nextLine] < state.blkIndent) { return false; }
- // if it's indented more than 3 spaces, it should be a code block
- if (state.sCount[nextLine] - state.blkIndent >= 4) { return false; }
- // first character of the second line should be '|', '-', ':',
- // and no other characters are allowed but spaces;
- // basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp
- pos = state.bMarks[nextLine] + state.tShift[nextLine];
- if (pos >= state.eMarks[nextLine]) { return false; }
- ch = state.src.charCodeAt(pos++);
- if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */) { return false; }
- while (pos < state.eMarks[nextLine]) {
- ch = state.src.charCodeAt(pos);
- if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */ && !isSpace(ch)) { return false; }
- pos++;
- }
- lineText = getLine(state, startLine + 1);
- columns = lineText.split('|');
- aligns = [];
- for (i = 0; i < columns.length; i++) {
- t = columns[i].trim();
- if (!t) {
- // allow empty columns before and after table, but not in between columns;
- // e.g. allow ` |---| `, disallow ` ---||--- `
- if (i === 0 || i === columns.length - 1) {
- continue;
- } else {
- return false;
- }
- }
- if (!/^:?-+:?$/.test(t)) { return false; }
- if (t.charCodeAt(t.length - 1) === 0x3A/* : */) {
- aligns.push(t.charCodeAt(0) === 0x3A/* : */ ? 'center' : 'right');
- } else if (t.charCodeAt(0) === 0x3A/* : */) {
- aligns.push('left');
- } else {
- aligns.push('');
- }
- }
- lineText = getLine(state, startLine).trim();
- if (lineText.indexOf('|') === -1) { return false; }
- if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
- columns = escapedSplit(lineText.replace(/^\||\|$/g, ''));
- // header row will define an amount of columns in the entire table,
- // and align row shouldn't be smaller than that (the rest of the rows can)
- columnCount = columns.length;
- if (columnCount > aligns.length) { return false; }
- if (silent) { return true; }
- token = state.push('table_open', 'table', 1);
- token.map = tableLines = [ startLine, 0 ];
- token = state.push('thead_open', 'thead', 1);
- token.map = [ startLine, startLine + 1 ];
- token = state.push('tr_open', 'tr', 1);
- token.map = [ startLine, startLine + 1 ];
- for (i = 0; i < columns.length; i++) {
- token = state.push('th_open', 'th', 1);
- token.map = [ startLine, startLine + 1 ];
- if (aligns[i]) {
- token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
- }
- token = state.push('inline', '', 0);
- token.content = columns[i].trim();
- token.map = [ startLine, startLine + 1 ];
- token.children = [];
- token = state.push('th_close', 'th', -1);
- }
- token = state.push('tr_close', 'tr', -1);
- token = state.push('thead_close', 'thead', -1);
- token = state.push('tbody_open', 'tbody', 1);
- token.map = tbodyLines = [ startLine + 2, 0 ];
- for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
- if (state.sCount[nextLine] < state.blkIndent) { break; }
- lineText = getLine(state, nextLine).trim();
- if (lineText.indexOf('|') === -1) { break; }
- if (state.sCount[nextLine] - state.blkIndent >= 4) { break; }
- columns = escapedSplit(lineText.replace(/^\||\|$/g, ''));
- token = state.push('tr_open', 'tr', 1);
- for (i = 0; i < columnCount; i++) {
- token = state.push('td_open', 'td', 1);
- if (aligns[i]) {
- token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ];
- }
- token = state.push('inline', '', 0);
- token.content = columns[i] ? columns[i].trim() : '';
- token.children = [];
- token = state.push('td_close', 'td', -1);
- }
- token = state.push('tr_close', 'tr', -1);
- }
- token = state.push('tbody_close', 'tbody', -1);
- token = state.push('table_close', 'table', -1);
- tableLines[1] = tbodyLines[1] = nextLine;
- state.line = nextLine;
- return true;
- };
- },{"../common/utils":144}],170:[function(require,module,exports){
- 'use strict';
- module.exports = function block(state) {
- var token;
- if (state.inlineMode) {
- token = new state.Token('inline', '', 0);
- token.content = state.src;
- token.map = [ 0, 1 ];
- token.children = [];
- state.tokens.push(token);
- } else {
- state.md.block.parse(state.src, state.md, state.env, state.tokens);
- }
- };
- },{}],171:[function(require,module,exports){
- 'use strict';
- module.exports = function inline(state) {
- var tokens = state.tokens, tok, i, l;
- // Parse inlines
- for (i = 0, l = tokens.length; i < l; i++) {
- tok = tokens[i];
- if (tok.type === 'inline') {
- state.md.inline.parse(tok.content, state.md, state.env, tok.children);
- }
- }
- };
- },{}],172:[function(require,module,exports){
- // Replace link-like texts with link nodes.
- //
- // Currently restricted by `md.validateLink()` to http/https/ftp
- //
- 'use strict';
- var arrayReplaceAt = require('../common/utils').arrayReplaceAt;
- function isLinkOpen(str) {
- return /^<a[>\s]/i.test(str);
- }
- function isLinkClose(str) {
- return /^<\/a\s*>/i.test(str);
- }
- module.exports = function linkify(state) {
- var i, j, l, tokens, token, currentToken, nodes, ln, text, pos, lastPos,
- level, htmlLinkLevel, url, fullUrl, urlText,
- blockTokens = state.tokens,
- links;
- if (!state.md.options.linkify) { return; }
- for (j = 0, l = blockTokens.length; j < l; j++) {
- if (blockTokens[j].type !== 'inline' ||
- !state.md.linkify.pretest(blockTokens[j].content)) {
- continue;
- }
- tokens = blockTokens[j].children;
- htmlLinkLevel = 0;
- // We scan from the end, to keep position when new tags added.
- // Use reversed logic in links start/end match
- for (i = tokens.length - 1; i >= 0; i--) {
- currentToken = tokens[i];
- // Skip content of markdown links
- if (currentToken.type === 'link_close') {
- i--;
- while (tokens[i].level !== currentToken.level && tokens[i].type !== 'link_open') {
- i--;
- }
- continue;
- }
- // Skip content of html tag links
- if (currentToken.type === 'html_inline') {
- if (isLinkOpen(currentToken.content) && htmlLinkLevel > 0) {
- htmlLinkLevel--;
- }
- if (isLinkClose(currentToken.content)) {
- htmlLinkLevel++;
- }
- }
- if (htmlLinkLevel > 0) { continue; }
- if (currentToken.type === 'text' && state.md.linkify.test(currentToken.content)) {
- text = currentToken.content;
- links = state.md.linkify.match(text);
- // Now split string to nodes
- nodes = [];
- level = currentToken.level;
- lastPos = 0;
- for (ln = 0; ln < links.length; ln++) {
- url = links[ln].url;
- fullUrl = state.md.normalizeLink(url);
- if (!state.md.validateLink(fullUrl)) { continue; }
- urlText = links[ln].text;
- // Linkifier might send raw hostnames like "example.com", where url
- // starts with domain name. So we prepend http:// in those cases,
- // and remove it afterwards.
- //
- if (!links[ln].schema) {
- urlText = state.md.normalizeLinkText('http://' + urlText).replace(/^http:\/\//, '');
- } else if (links[ln].schema === 'mailto:' && !/^mailto:/i.test(urlText)) {
- urlText = state.md.normalizeLinkText('mailto:' + urlText).replace(/^mailto:/, '');
- } else {
- urlText = state.md.normalizeLinkText(urlText);
- }
- pos = links[ln].index;
- if (pos > lastPos) {
- token = new state.Token('text', '', 0);
- token.content = text.slice(lastPos, pos);
- token.level = level;
- nodes.push(token);
- }
- token = new state.Token('link_open', 'a', 1);
- token.attrs = [ [ 'href', fullUrl ] ];
- token.level = level++;
- token.markup = 'linkify';
- token.info = 'auto';
- nodes.push(token);
- token = new state.Token('text', '', 0);
- token.content = urlText;
- token.level = level;
- nodes.push(token);
- token = new state.Token('link_close', 'a', -1);
- token.level = --level;
- token.markup = 'linkify';
- token.info = 'auto';
- nodes.push(token);
- lastPos = links[ln].lastIndex;
- }
- if (lastPos < text.length) {
- token = new state.Token('text', '', 0);
- token.content = text.slice(lastPos);
- token.level = level;
- nodes.push(token);
- }
- // replace current node
- blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, nodes);
- }
- }
- }
- };
- },{"../common/utils":144}],173:[function(require,module,exports){
- // Normalize input string
- 'use strict';
- var NEWLINES_RE = /\r[\n\u0085]?|[\u2424\u2028\u0085]/g;
- var NULL_RE = /\u0000/g;
- module.exports = function inline(state) {
- var str;
- // Normalize newlines
- str = state.src.replace(NEWLINES_RE, '\n');
- // Replace NULL characters
- str = str.replace(NULL_RE, '\uFFFD');
- state.src = str;
- };
- },{}],174:[function(require,module,exports){
- // Simple typographyc replacements
- //
- // (c) (C) → ©
- // (tm) (TM) → ™
- // (r) (R) → ®
- // +- → ±
- // (p) (P) -> §
- // ... → … (also ?.... → ?.., !.... → !..)
- // ???????? → ???, !!!!! → !!!, `,,` → `,`
- // -- → –, --- → —
- //
- 'use strict';
- // TODO:
- // - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾
- // - miltiplication 2 x 4 -> 2 × 4
- var RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
- // Workaround for phantomjs - need regex without /g flag,
- // or root check will fail every second time
- var SCOPED_ABBR_TEST_RE = /\((c|tm|r|p)\)/i;
- var SCOPED_ABBR_RE = /\((c|tm|r|p)\)/ig;
- var SCOPED_ABBR = {
- c: '©',
- r: '®',
- p: '§',
- tm: '™'
- };
- function replaceFn(match, name) {
- return SCOPED_ABBR[name.toLowerCase()];
- }
- function replace_scoped(inlineTokens) {
- var i, token, inside_autolink = 0;
- for (i = inlineTokens.length - 1; i >= 0; i--) {
- token = inlineTokens[i];
- if (token.type === 'text' && !inside_autolink) {
- token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn);
- }
- if (token.type === 'link_open' && token.info === 'auto') {
- inside_autolink--;
- }
- if (token.type === 'link_close' && token.info === 'auto') {
- inside_autolink++;
- }
- }
- }
- function replace_rare(inlineTokens) {
- var i, token, inside_autolink = 0;
- for (i = inlineTokens.length - 1; i >= 0; i--) {
- token = inlineTokens[i];
- if (token.type === 'text' && !inside_autolink) {
- if (RARE_RE.test(token.content)) {
- token.content = token.content
- .replace(/\+-/g, '±')
- // .., ..., ....... -> …
- // but ?..... & !..... -> ?.. & !..
- .replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..')
- .replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',')
- // em-dash
- .replace(/(^|[^-])---([^-]|$)/mg, '$1\u2014$2')
- // en-dash
- .replace(/(^|\s)--(\s|$)/mg, '$1\u2013$2')
- .replace(/(^|[^-\s])--([^-\s]|$)/mg, '$1\u2013$2');
- }
- }
- if (token.type === 'link_open' && token.info === 'auto') {
- inside_autolink--;
- }
- if (token.type === 'link_close' && token.info === 'auto') {
- inside_autolink++;
- }
- }
- }
- module.exports = function replace(state) {
- var blkIdx;
- if (!state.md.options.typographer) { return; }
- for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
- if (state.tokens[blkIdx].type !== 'inline') { continue; }
- if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) {
- replace_scoped(state.tokens[blkIdx].children);
- }
- if (RARE_RE.test(state.tokens[blkIdx].content)) {
- replace_rare(state.tokens[blkIdx].children);
- }
- }
- };
- },{}],175:[function(require,module,exports){
- // Convert straight quotation marks to typographic ones
- //
- 'use strict';
- var isWhiteSpace = require('../common/utils').isWhiteSpace;
- var isPunctChar = require('../common/utils').isPunctChar;
- var isMdAsciiPunct = require('../common/utils').isMdAsciiPunct;
- var QUOTE_TEST_RE = /['"]/;
- var QUOTE_RE = /['"]/g;
- var APOSTROPHE = '\u2019'; /* ’ */
- function replaceAt(str, index, ch) {
- return str.substr(0, index) + ch + str.substr(index + 1);
- }
- function process_inlines(tokens, state) {
- var i, token, text, t, pos, max, thisLevel, item, lastChar, nextChar,
- isLastPunctChar, isNextPunctChar, isLastWhiteSpace, isNextWhiteSpace,
- canOpen, canClose, j, isSingle, stack, openQuote, closeQuote;
- stack = [];
- for (i = 0; i < tokens.length; i++) {
- token = tokens[i];
- thisLevel = tokens[i].level;
- for (j = stack.length - 1; j >= 0; j--) {
- if (stack[j].level <= thisLevel) { break; }
- }
- stack.length = j + 1;
- if (token.type !== 'text') { continue; }
- text = token.content;
- pos = 0;
- max = text.length;
- /*eslint no-labels:0,block-scoped-var:0*/
- OUTER:
- while (pos < max) {
- QUOTE_RE.lastIndex = pos;
- t = QUOTE_RE.exec(text);
- if (!t) { break; }
- canOpen = canClose = true;
- pos = t.index + 1;
- isSingle = (t[0] === "'");
- // Find previous character,
- // default to space if it's the beginning of the line
- //
- lastChar = 0x20;
- if (t.index - 1 >= 0) {
- lastChar = text.charCodeAt(t.index - 1);
- } else {
- for (j = i - 1; j >= 0; j--) {
- if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // lastChar defaults to 0x20
- if (tokens[j].type !== 'text') continue;
- lastChar = tokens[j].content.charCodeAt(tokens[j].content.length - 1);
- break;
- }
- }
- // Find next character,
- // default to space if it's the end of the line
- //
- nextChar = 0x20;
- if (pos < max) {
- nextChar = text.charCodeAt(pos);
- } else {
- for (j = i + 1; j < tokens.length; j++) {
- if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // nextChar defaults to 0x20
- if (tokens[j].type !== 'text') continue;
- nextChar = tokens[j].content.charCodeAt(0);
- break;
- }
- }
- isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
- isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
- isLastWhiteSpace = isWhiteSpace(lastChar);
- isNextWhiteSpace = isWhiteSpace(nextChar);
- if (isNextWhiteSpace) {
- canOpen = false;
- } else if (isNextPunctChar) {
- if (!(isLastWhiteSpace || isLastPunctChar)) {
- canOpen = false;
- }
- }
- if (isLastWhiteSpace) {
- canClose = false;
- } else if (isLastPunctChar) {
- if (!(isNextWhiteSpace || isNextPunctChar)) {
- canClose = false;
- }
- }
- if (nextChar === 0x22 /* " */ && t[0] === '"') {
- if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) {
- // special case: 1"" - count first quote as an inch
- canClose = canOpen = false;
- }
- }
- if (canOpen && canClose) {
- // treat this as the middle of the word
- canOpen = false;
- canClose = isNextPunctChar;
- }
- if (!canOpen && !canClose) {
- // middle of word
- if (isSingle) {
- token.content = replaceAt(token.content, t.index, APOSTROPHE);
- }
- continue;
- }
- if (canClose) {
- // this could be a closing quote, rewind the stack to get a match
- for (j = stack.length - 1; j >= 0; j--) {
- item = stack[j];
- if (stack[j].level < thisLevel) { break; }
- if (item.single === isSingle && stack[j].level === thisLevel) {
- item = stack[j];
- if (isSingle) {
- openQuote = state.md.options.quotes[2];
- closeQuote = state.md.options.quotes[3];
- } else {
- openQuote = state.md.options.quotes[0];
- closeQuote = state.md.options.quotes[1];
- }
- // replace token.content *before* tokens[item.token].content,
- // because, if they are pointing at the same token, replaceAt
- // could mess up indices when quote length != 1
- token.content = replaceAt(token.content, t.index, closeQuote);
- tokens[item.token].content = replaceAt(
- tokens[item.token].content, item.pos, openQuote);
- pos += closeQuote.length - 1;
- if (item.token === i) { pos += openQuote.length - 1; }
- text = token.content;
- max = text.length;
- stack.length = j;
- continue OUTER;
- }
- }
- }
- if (canOpen) {
- stack.push({
- token: i,
- pos: t.index,
- single: isSingle,
- level: thisLevel
- });
- } else if (canClose && isSingle) {
- token.content = replaceAt(token.content, t.index, APOSTROPHE);
- }
- }
- }
- }
- module.exports = function smartquotes(state) {
- /*eslint max-depth:0*/
- var blkIdx;
- if (!state.md.options.typographer) { return; }
- for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
- if (state.tokens[blkIdx].type !== 'inline' ||
- !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) {
- continue;
- }
- process_inlines(state.tokens[blkIdx].children, state);
- }
- };
- },{"../common/utils":144}],176:[function(require,module,exports){
- // Core state object
- //
- 'use strict';
- var Token = require('../token');
- function StateCore(src, md, env) {
- this.src = src;
- this.env = env;
- this.tokens = [];
- this.inlineMode = false;
- this.md = md; // link to parser instance
- }
- // re-export Token class to use in core rules
- StateCore.prototype.Token = Token;
- module.exports = StateCore;
- },{"../token":191}],177:[function(require,module,exports){
- // Process autolinks '<protocol:...>'
- 'use strict';
- /*eslint max-len:0*/
- var EMAIL_RE = /^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/;
- var AUTOLINK_RE = /^<([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)>/;
- module.exports = function autolink(state, silent) {
- var tail, linkMatch, emailMatch, url, fullUrl, token,
- pos = state.pos;
- if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; }
- tail = state.src.slice(pos);
- if (tail.indexOf('>') < 0) { return false; }
- if (AUTOLINK_RE.test(tail)) {
- linkMatch = tail.match(AUTOLINK_RE);
- url = linkMatch[0].slice(1, -1);
- fullUrl = state.md.normalizeLink(url);
- if (!state.md.validateLink(fullUrl)) { return false; }
- if (!silent) {
- token = state.push('link_open', 'a', 1);
- token.attrs = [ [ 'href', fullUrl ] ];
- token.markup = 'autolink';
- token.info = 'auto';
- token = state.push('text', '', 0);
- token.content = state.md.normalizeLinkText(url);
- token = state.push('link_close', 'a', -1);
- token.markup = 'autolink';
- token.info = 'auto';
- }
- state.pos += linkMatch[0].length;
- return true;
- }
- if (EMAIL_RE.test(tail)) {
- emailMatch = tail.match(EMAIL_RE);
- url = emailMatch[0].slice(1, -1);
- fullUrl = state.md.normalizeLink('mailto:' + url);
- if (!state.md.validateLink(fullUrl)) { return false; }
- if (!silent) {
- token = state.push('link_open', 'a', 1);
- token.attrs = [ [ 'href', fullUrl ] ];
- token.markup = 'autolink';
- token.info = 'auto';
- token = state.push('text', '', 0);
- token.content = state.md.normalizeLinkText(url);
- token = state.push('link_close', 'a', -1);
- token.markup = 'autolink';
- token.info = 'auto';
- }
- state.pos += emailMatch[0].length;
- return true;
- }
- return false;
- };
- },{}],178:[function(require,module,exports){
- // Parse backticks
- 'use strict';
- module.exports = function backtick(state, silent) {
- var start, max, marker, matchStart, matchEnd, token,
- pos = state.pos,
- ch = state.src.charCodeAt(pos);
- if (ch !== 0x60/* ` */) { return false; }
- start = pos;
- pos++;
- max = state.posMax;
- while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; }
- marker = state.src.slice(start, pos);
- matchStart = matchEnd = pos;
- while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) {
- matchEnd = matchStart + 1;
- while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; }
- if (matchEnd - matchStart === marker.length) {
- if (!silent) {
- token = state.push('code_inline', 'code', 0);
- token.markup = marker;
- token.content = state.src.slice(pos, matchStart)
- .replace(/[ \n]+/g, ' ')
- .trim();
- }
- state.pos = matchEnd;
- return true;
- }
- }
- if (!silent) { state.pending += marker; }
- state.pos += marker.length;
- return true;
- };
- },{}],179:[function(require,module,exports){
- // For each opening emphasis-like marker find a matching closing one
- //
- 'use strict';
- module.exports = function link_pairs(state) {
- var i, j, lastDelim, currDelim,
- delimiters = state.delimiters,
- max = state.delimiters.length;
- for (i = 0; i < max; i++) {
- lastDelim = delimiters[i];
- if (!lastDelim.close) { continue; }
- j = i - lastDelim.jump - 1;
- while (j >= 0) {
- currDelim = delimiters[j];
- if (currDelim.open &&
- currDelim.marker === lastDelim.marker &&
- currDelim.end < 0 &&
- currDelim.level === lastDelim.level) {
- // typeofs are for backward compatibility with plugins
- var odd_match = (currDelim.close || lastDelim.open) &&
- typeof currDelim.length !== 'undefined' &&
- typeof lastDelim.length !== 'undefined' &&
- (currDelim.length + lastDelim.length) % 3 === 0;
- if (!odd_match) {
- lastDelim.jump = i - j;
- lastDelim.open = false;
- currDelim.end = i;
- currDelim.jump = 0;
- break;
- }
- }
- j -= currDelim.jump + 1;
- }
- }
- };
- },{}],180:[function(require,module,exports){
- // Process *this* and _that_
- //
- 'use strict';
- // Insert each marker as a separate text token, and add it to delimiter list
- //
- module.exports.tokenize = function emphasis(state, silent) {
- var i, scanned, token,
- start = state.pos,
- marker = state.src.charCodeAt(start);
- if (silent) { return false; }
- if (marker !== 0x5F /* _ */ && marker !== 0x2A /* * */) { return false; }
- scanned = state.scanDelims(state.pos, marker === 0x2A);
- for (i = 0; i < scanned.length; i++) {
- token = state.push('text', '', 0);
- token.content = String.fromCharCode(marker);
- state.delimiters.push({
- // Char code of the starting marker (number).
- //
- marker: marker,
- // Total length of these series of delimiters.
- //
- length: scanned.length,
- // An amount of characters before this one that's equivalent to
- // current one. In plain English: if this delimiter does not open
- // an emphasis, neither do previous `jump` characters.
- //
- // Used to skip sequences like "*****" in one step, for 1st asterisk
- // value will be 0, for 2nd it's 1 and so on.
- //
- jump: i,
- // A position of the token this delimiter corresponds to.
- //
- token: state.tokens.length - 1,
- // Token level.
- //
- level: state.level,
- // If this delimiter is matched as a valid opener, `end` will be
- // equal to its position, otherwise it's `-1`.
- //
- end: -1,
- // Boolean flags that determine if this delimiter could open or close
- // an emphasis.
- //
- open: scanned.can_open,
- close: scanned.can_close
- });
- }
- state.pos += scanned.length;
- return true;
- };
- // Walk through delimiter list and replace text tokens with tags
- //
- module.exports.postProcess = function emphasis(state) {
- var i,
- startDelim,
- endDelim,
- token,
- ch,
- isStrong,
- delimiters = state.delimiters,
- max = state.delimiters.length;
- for (i = max - 1; i >= 0; i--) {
- startDelim = delimiters[i];
- if (startDelim.marker !== 0x5F/* _ */ && startDelim.marker !== 0x2A/* * */) {
- continue;
- }
- // Process only opening markers
- if (startDelim.end === -1) {
- continue;
- }
- endDelim = delimiters[startDelim.end];
- // If the previous delimiter has the same marker and is adjacent to this one,
- // merge those into one strong delimiter.
- //
- // `<em><em>whatever</em></em>` -> `<strong>whatever</strong>`
- //
- isStrong = i > 0 &&
- delimiters[i - 1].end === startDelim.end + 1 &&
- delimiters[i - 1].token === startDelim.token - 1 &&
- delimiters[startDelim.end + 1].token === endDelim.token + 1 &&
- delimiters[i - 1].marker === startDelim.marker;
- ch = String.fromCharCode(startDelim.marker);
- token = state.tokens[startDelim.token];
- token.type = isStrong ? 'strong_open' : 'em_open';
- token.tag = isStrong ? 'strong' : 'em';
- token.nesting = 1;
- token.markup = isStrong ? ch + ch : ch;
- token.content = '';
- token = state.tokens[endDelim.token];
- token.type = isStrong ? 'strong_close' : 'em_close';
- token.tag = isStrong ? 'strong' : 'em';
- token.nesting = -1;
- token.markup = isStrong ? ch + ch : ch;
- token.content = '';
- if (isStrong) {
- state.tokens[delimiters[i - 1].token].content = '';
- state.tokens[delimiters[startDelim.end + 1].token].content = '';
- i--;
- }
- }
- };
- },{}],181:[function(require,module,exports){
- // Process html entity - {, ¯, ", ...
- 'use strict';
- var entities = require('../common/entities');
- var has = require('../common/utils').has;
- var isValidEntityCode = require('../common/utils').isValidEntityCode;
- var fromCodePoint = require('../common/utils').fromCodePoint;
- var DIGITAL_RE = /^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i;
- var NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;
- module.exports = function entity(state, silent) {
- var ch, code, match, pos = state.pos, max = state.posMax;
- if (state.src.charCodeAt(pos) !== 0x26/* & */) { return false; }
- if (pos + 1 < max) {
- ch = state.src.charCodeAt(pos + 1);
- if (ch === 0x23 /* # */) {
- match = state.src.slice(pos).match(DIGITAL_RE);
- if (match) {
- if (!silent) {
- code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10);
- state.pending += isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD);
- }
- state.pos += match[0].length;
- return true;
- }
- } else {
- match = state.src.slice(pos).match(NAMED_RE);
- if (match) {
- if (has(entities, match[1])) {
- if (!silent) { state.pending += entities[match[1]]; }
- state.pos += match[0].length;
- return true;
- }
- }
- }
- }
- if (!silent) { state.pending += '&'; }
- state.pos++;
- return true;
- };
- },{"../common/entities":141,"../common/utils":144}],182:[function(require,module,exports){
- // Process escaped chars and hardbreaks
- 'use strict';
- var isSpace = require('../common/utils').isSpace;
- var ESCAPED = [];
- for (var i = 0; i < 256; i++) { ESCAPED.push(0); }
- '\\!"#$%&\'()*+,./:;<=>?@[]^_`{|}~-'
- .split('').forEach(function (ch) { ESCAPED[ch.charCodeAt(0)] = 1; });
- module.exports = function escape(state, silent) {
- var ch, pos = state.pos, max = state.posMax;
- if (state.src.charCodeAt(pos) !== 0x5C/* \ */) { return false; }
- pos++;
- if (pos < max) {
- ch = state.src.charCodeAt(pos);
- if (ch < 256 && ESCAPED[ch] !== 0) {
- if (!silent) { state.pending += state.src[pos]; }
- state.pos += 2;
- return true;
- }
- if (ch === 0x0A) {
- if (!silent) {
- state.push('hardbreak', 'br', 0);
- }
- pos++;
- // skip leading whitespaces from next line
- while (pos < max) {
- ch = state.src.charCodeAt(pos);
- if (!isSpace(ch)) { break; }
- pos++;
- }
- state.pos = pos;
- return true;
- }
- }
- if (!silent) { state.pending += '\\'; }
- state.pos++;
- return true;
- };
- },{"../common/utils":144}],183:[function(require,module,exports){
- // Process html tags
- 'use strict';
- var HTML_TAG_RE = require('../common/html_re').HTML_TAG_RE;
- function isLetter(ch) {
- /*eslint no-bitwise:0*/
- var lc = ch | 0x20; // to lower case
- return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */);
- }
- module.exports = function html_inline(state, silent) {
- var ch, match, max, token,
- pos = state.pos;
- if (!state.md.options.html) { return false; }
- // Check start
- max = state.posMax;
- if (state.src.charCodeAt(pos) !== 0x3C/* < */ ||
- pos + 2 >= max) {
- return false;
- }
- // Quick fail on second char
- ch = state.src.charCodeAt(pos + 1);
- if (ch !== 0x21/* ! */ &&
- ch !== 0x3F/* ? */ &&
- ch !== 0x2F/* / */ &&
- !isLetter(ch)) {
- return false;
- }
- match = state.src.slice(pos).match(HTML_TAG_RE);
- if (!match) { return false; }
- if (!silent) {
- token = state.push('html_inline', '', 0);
- token.content = state.src.slice(pos, pos + match[0].length);
- }
- state.pos += match[0].length;
- return true;
- };
- },{"../common/html_re":143}],184:[function(require,module,exports){
- // Process ![image](<src> "title")
- 'use strict';
- var normalizeReference = require('../common/utils').normalizeReference;
- var isSpace = require('../common/utils').isSpace;
- module.exports = function image(state, silent) {
- var attrs,
- code,
- content,
- label,
- labelEnd,
- labelStart,
- pos,
- ref,
- res,
- title,
- token,
- tokens,
- start,
- href = '',
- oldPos = state.pos,
- max = state.posMax;
- if (state.src.charCodeAt(state.pos) !== 0x21/* ! */) { return false; }
- if (state.src.charCodeAt(state.pos + 1) !== 0x5B/* [ */) { return false; }
- labelStart = state.pos + 2;
- labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false);
- // parser failed to find ']', so it's not a valid link
- if (labelEnd < 0) { return false; }
- pos = labelEnd + 1;
- if (pos < max && state.src.charCodeAt(pos) === 0x28/* ( */) {
- //
- // Inline link
- //
- // [link]( <href> "title" )
- // ^^ skipping these spaces
- pos++;
- for (; pos < max; pos++) {
- code = state.src.charCodeAt(pos);
- if (!isSpace(code) && code !== 0x0A) { break; }
- }
- if (pos >= max) { return false; }
- // [link]( <href> "title" )
- // ^^^^^^ parsing link destination
- start = pos;
- res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
- if (res.ok) {
- href = state.md.normalizeLink(res.str);
- if (state.md.validateLink(href)) {
- pos = res.pos;
- } else {
- href = '';
- }
- }
- // [link]( <href> "title" )
- // ^^ skipping these spaces
- start = pos;
- for (; pos < max; pos++) {
- code = state.src.charCodeAt(pos);
- if (!isSpace(code) && code !== 0x0A) { break; }
- }
- // [link]( <href> "title" )
- // ^^^^^^^ parsing link title
- res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
- if (pos < max && start !== pos && res.ok) {
- title = res.str;
- pos = res.pos;
- // [link]( <href> "title" )
- // ^^ skipping these spaces
- for (; pos < max; pos++) {
- code = state.src.charCodeAt(pos);
- if (!isSpace(code) && code !== 0x0A) { break; }
- }
- } else {
- title = '';
- }
- if (pos >= max || state.src.charCodeAt(pos) !== 0x29/* ) */) {
- state.pos = oldPos;
- return false;
- }
- pos++;
- } else {
- //
- // Link reference
- //
- if (typeof state.env.references === 'undefined') { return false; }
- if (pos < max && state.src.charCodeAt(pos) === 0x5B/* [ */) {
- start = pos + 1;
- pos = state.md.helpers.parseLinkLabel(state, pos);
- if (pos >= 0) {
- label = state.src.slice(start, pos++);
- } else {
- pos = labelEnd + 1;
- }
- } else {
- pos = labelEnd + 1;
- }
- // covers label === '' and label === undefined
- // (collapsed reference link and shortcut reference link respectively)
- if (!label) { label = state.src.slice(labelStart, labelEnd); }
- ref = state.env.references[normalizeReference(label)];
- if (!ref) {
- state.pos = oldPos;
- return false;
- }
- href = ref.href;
- title = ref.title;
- }
- //
- // We found the end of the link, and know for a fact it's a valid link;
- // so all that's left to do is to call tokenizer.
- //
- if (!silent) {
- content = state.src.slice(labelStart, labelEnd);
- state.md.inline.parse(
- content,
- state.md,
- state.env,
- tokens = []
- );
- token = state.push('image', 'img', 0);
- token.attrs = attrs = [ [ 'src', href ], [ 'alt', '' ] ];
- token.children = tokens;
- token.content = content;
- if (title) {
- attrs.push([ 'title', title ]);
- }
- }
- state.pos = pos;
- state.posMax = max;
- return true;
- };
- },{"../common/utils":144}],185:[function(require,module,exports){
- // Process [link](<to> "stuff")
- 'use strict';
- var normalizeReference = require('../common/utils').normalizeReference;
- var isSpace = require('../common/utils').isSpace;
- module.exports = function link(state, silent) {
- var attrs,
- code,
- label,
- labelEnd,
- labelStart,
- pos,
- res,
- ref,
- title,
- token,
- href = '',
- oldPos = state.pos,
- max = state.posMax,
- start = state.pos,
- parseReference = true;
- if (state.src.charCodeAt(state.pos) !== 0x5B/* [ */) { return false; }
- labelStart = state.pos + 1;
- labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true);
- // parser failed to find ']', so it's not a valid link
- if (labelEnd < 0) { return false; }
- pos = labelEnd + 1;
- if (pos < max && state.src.charCodeAt(pos) === 0x28/* ( */) {
- //
- // Inline link
- //
- // might have found a valid shortcut link, disable reference parsing
- parseReference = false;
- // [link]( <href> "title" )
- // ^^ skipping these spaces
- pos++;
- for (; pos < max; pos++) {
- code = state.src.charCodeAt(pos);
- if (!isSpace(code) && code !== 0x0A) { break; }
- }
- if (pos >= max) { return false; }
- // [link]( <href> "title" )
- // ^^^^^^ parsing link destination
- start = pos;
- res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax);
- if (res.ok) {
- href = state.md.normalizeLink(res.str);
- if (state.md.validateLink(href)) {
- pos = res.pos;
- } else {
- href = '';
- }
- }
- // [link]( <href> "title" )
- // ^^ skipping these spaces
- start = pos;
- for (; pos < max; pos++) {
- code = state.src.charCodeAt(pos);
- if (!isSpace(code) && code !== 0x0A) { break; }
- }
- // [link]( <href> "title" )
- // ^^^^^^^ parsing link title
- res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax);
- if (pos < max && start !== pos && res.ok) {
- title = res.str;
- pos = res.pos;
- // [link]( <href> "title" )
- // ^^ skipping these spaces
- for (; pos < max; pos++) {
- code = state.src.charCodeAt(pos);
- if (!isSpace(code) && code !== 0x0A) { break; }
- }
- } else {
- title = '';
- }
- if (pos >= max || state.src.charCodeAt(pos) !== 0x29/* ) */) {
- // parsing a valid shortcut link failed, fallback to reference
- parseReference = true;
- }
- pos++;
- }
- if (parseReference) {
- //
- // Link reference
- //
- if (typeof state.env.references === 'undefined') { return false; }
- if (pos < max && state.src.charCodeAt(pos) === 0x5B/* [ */) {
- start = pos + 1;
- pos = state.md.helpers.parseLinkLabel(state, pos);
- if (pos >= 0) {
- label = state.src.slice(start, pos++);
- } else {
- pos = labelEnd + 1;
- }
- } else {
- pos = labelEnd + 1;
- }
- // covers label === '' and label === undefined
- // (collapsed reference link and shortcut reference link respectively)
- if (!label) { label = state.src.slice(labelStart, labelEnd); }
- ref = state.env.references[normalizeReference(label)];
- if (!ref) {
- state.pos = oldPos;
- return false;
- }
- href = ref.href;
- title = ref.title;
- }
- //
- // We found the end of the link, and know for a fact it's a valid link;
- // so all that's left to do is to call tokenizer.
- //
- if (!silent) {
- state.pos = labelStart;
- state.posMax = labelEnd;
- token = state.push('link_open', 'a', 1);
- token.attrs = attrs = [ [ 'href', href ] ];
- if (title) {
- attrs.push([ 'title', title ]);
- }
- state.md.inline.tokenize(state);
- token = state.push('link_close', 'a', -1);
- }
- state.pos = pos;
- state.posMax = max;
- return true;
- };
- },{"../common/utils":144}],186:[function(require,module,exports){
- // Proceess '\n'
- 'use strict';
- var isSpace = require('../common/utils').isSpace;
- module.exports = function newline(state, silent) {
- var pmax, max, pos = state.pos;
- if (state.src.charCodeAt(pos) !== 0x0A/* \n */) { return false; }
- pmax = state.pending.length - 1;
- max = state.posMax;
- // ' \n' -> hardbreak
- // Lookup in pending chars is bad practice! Don't copy to other rules!
- // Pending string is stored in concat mode, indexed lookups will cause
- // convertion to flat mode.
- if (!silent) {
- if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) {
- if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) {
- state.pending = state.pending.replace(/ +$/, '');
- state.push('hardbreak', 'br', 0);
- } else {
- state.pending = state.pending.slice(0, -1);
- state.push('softbreak', 'br', 0);
- }
- } else {
- state.push('softbreak', 'br', 0);
- }
- }
- pos++;
- // skip heading spaces for next line
- while (pos < max && isSpace(state.src.charCodeAt(pos))) { pos++; }
- state.pos = pos;
- return true;
- };
- },{"../common/utils":144}],187:[function(require,module,exports){
- // Inline parser state
- 'use strict';
- var Token = require('../token');
- var isWhiteSpace = require('../common/utils').isWhiteSpace;
- var isPunctChar = require('../common/utils').isPunctChar;
- var isMdAsciiPunct = require('../common/utils').isMdAsciiPunct;
- function StateInline(src, md, env, outTokens) {
- this.src = src;
- this.env = env;
- this.md = md;
- this.tokens = outTokens;
- this.pos = 0;
- this.posMax = this.src.length;
- this.level = 0;
- this.pending = '';
- this.pendingLevel = 0;
- this.cache = {}; // Stores { start: end } pairs. Useful for backtrack
- // optimization of pairs parse (emphasis, strikes).
- this.delimiters = []; // Emphasis-like delimiters
- }
- // Flush pending text
- //
- StateInline.prototype.pushPending = function () {
- var token = new Token('text', '', 0);
- token.content = this.pending;
- token.level = this.pendingLevel;
- this.tokens.push(token);
- this.pending = '';
- return token;
- };
- // Push new token to "stream".
- // If pending text exists - flush it as text token
- //
- StateInline.prototype.push = function (type, tag, nesting) {
- if (this.pending) {
- this.pushPending();
- }
- var token = new Token(type, tag, nesting);
- if (nesting < 0) { this.level--; }
- token.level = this.level;
- if (nesting > 0) { this.level++; }
- this.pendingLevel = this.level;
- this.tokens.push(token);
- return token;
- };
- // Scan a sequence of emphasis-like markers, and determine whether
- // it can start an emphasis sequence or end an emphasis sequence.
- //
- // - start - position to scan from (it should point at a valid marker);
- // - canSplitWord - determine if these markers can be found inside a word
- //
- StateInline.prototype.scanDelims = function (start, canSplitWord) {
- var pos = start, lastChar, nextChar, count, can_open, can_close,
- isLastWhiteSpace, isLastPunctChar,
- isNextWhiteSpace, isNextPunctChar,
- left_flanking = true,
- right_flanking = true,
- max = this.posMax,
- marker = this.src.charCodeAt(start);
- // treat beginning of the line as a whitespace
- lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 0x20;
- while (pos < max && this.src.charCodeAt(pos) === marker) { pos++; }
- count = pos - start;
- // treat end of the line as a whitespace
- nextChar = pos < max ? this.src.charCodeAt(pos) : 0x20;
- isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar));
- isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar));
- isLastWhiteSpace = isWhiteSpace(lastChar);
- isNextWhiteSpace = isWhiteSpace(nextChar);
- if (isNextWhiteSpace) {
- left_flanking = false;
- } else if (isNextPunctChar) {
- if (!(isLastWhiteSpace || isLastPunctChar)) {
- left_flanking = false;
- }
- }
- if (isLastWhiteSpace) {
- right_flanking = false;
- } else if (isLastPunctChar) {
- if (!(isNextWhiteSpace || isNextPunctChar)) {
- right_flanking = false;
- }
- }
- if (!canSplitWord) {
- can_open = left_flanking && (!right_flanking || isLastPunctChar);
- can_close = right_flanking && (!left_flanking || isNextPunctChar);
- } else {
- can_open = left_flanking;
- can_close = right_flanking;
- }
- return {
- can_open: can_open,
- can_close: can_close,
- length: count
- };
- };
- // re-export Token class to use in block rules
- StateInline.prototype.Token = Token;
- module.exports = StateInline;
- },{"../common/utils":144,"../token":191}],188:[function(require,module,exports){
- // ~~strike through~~
- //
- 'use strict';
- // Insert each marker as a separate text token, and add it to delimiter list
- //
- module.exports.tokenize = function strikethrough(state, silent) {
- var i, scanned, token, len, ch,
- start = state.pos,
- marker = state.src.charCodeAt(start);
- if (silent) { return false; }
- if (marker !== 0x7E/* ~ */) { return false; }
- scanned = state.scanDelims(state.pos, true);
- len = scanned.length;
- ch = String.fromCharCode(marker);
- if (len < 2) { return false; }
- if (len % 2) {
- token = state.push('text', '', 0);
- token.content = ch;
- len--;
- }
- for (i = 0; i < len; i += 2) {
- token = state.push('text', '', 0);
- token.content = ch + ch;
- state.delimiters.push({
- marker: marker,
- jump: i,
- token: state.tokens.length - 1,
- level: state.level,
- end: -1,
- open: scanned.can_open,
- close: scanned.can_close
- });
- }
- state.pos += scanned.length;
- return true;
- };
- // Walk through delimiter list and replace text tokens with tags
- //
- module.exports.postProcess = function strikethrough(state) {
- var i, j,
- startDelim,
- endDelim,
- token,
- loneMarkers = [],
- delimiters = state.delimiters,
- max = state.delimiters.length;
- for (i = 0; i < max; i++) {
- startDelim = delimiters[i];
- if (startDelim.marker !== 0x7E/* ~ */) {
- continue;
- }
- if (startDelim.end === -1) {
- continue;
- }
- endDelim = delimiters[startDelim.end];
- token = state.tokens[startDelim.token];
- token.type = 's_open';
- token.tag = 's';
- token.nesting = 1;
- token.markup = '~~';
- token.content = '';
- token = state.tokens[endDelim.token];
- token.type = 's_close';
- token.tag = 's';
- token.nesting = -1;
- token.markup = '~~';
- token.content = '';
- if (state.tokens[endDelim.token - 1].type === 'text' &&
- state.tokens[endDelim.token - 1].content === '~') {
- loneMarkers.push(endDelim.token - 1);
- }
- }
- // If a marker sequence has an odd number of characters, it's splitted
- // like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the
- // start of the sequence.
- //
- // So, we have to move all those markers after subsequent s_close tags.
- //
- while (loneMarkers.length) {
- i = loneMarkers.pop();
- j = i + 1;
- while (j < state.tokens.length && state.tokens[j].type === 's_close') {
- j++;
- }
- j--;
- if (i !== j) {
- token = state.tokens[j];
- state.tokens[j] = state.tokens[i];
- state.tokens[i] = token;
- }
- }
- };
- },{}],189:[function(require,module,exports){
- // Skip text characters for text token, place those to pending buffer
- // and increment current pos
- 'use strict';
- // Rule to skip pure text
- // '{}$%@~+=:' reserved for extentions
- // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~
- // !!!! Don't confuse with "Markdown ASCII Punctuation" chars
- // http://spec.commonmark.org/0.15/#ascii-punctuation-character
- function isTerminatorChar(ch) {
- switch (ch) {
- case 0x0A/* \n */:
- case 0x21/* ! */:
- case 0x23/* # */:
- case 0x24/* $ */:
- case 0x25/* % */:
- case 0x26/* & */:
- case 0x2A/* * */:
- case 0x2B/* + */:
- case 0x2D/* - */:
- case 0x3A/* : */:
- case 0x3C/* < */:
- case 0x3D/* = */:
- case 0x3E/* > */:
- case 0x40/* @ */:
- case 0x5B/* [ */:
- case 0x5C/* \ */:
- case 0x5D/* ] */:
- case 0x5E/* ^ */:
- case 0x5F/* _ */:
- case 0x60/* ` */:
- case 0x7B/* { */:
- case 0x7D/* } */:
- case 0x7E/* ~ */:
- return true;
- default:
- return false;
- }
- }
- module.exports = function text(state, silent) {
- var pos = state.pos;
- while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) {
- pos++;
- }
- if (pos === state.pos) { return false; }
- if (!silent) { state.pending += state.src.slice(state.pos, pos); }
- state.pos = pos;
- return true;
- };
- // Alternative implementation, for memory.
- //
- // It costs 10% of performance, but allows extend terminators list, if place it
- // to `ParcerInline` property. Probably, will switch to it sometime, such
- // flexibility required.
- /*
- var TERMINATOR_RE = /[\n!#$%&*+\-:<=>@[\\\]^_`{}~]/;
- module.exports = function text(state, silent) {
- var pos = state.pos,
- idx = state.src.slice(pos).search(TERMINATOR_RE);
- // first char is terminator -> empty text
- if (idx === 0) { return false; }
- // no terminator -> text till end of string
- if (idx < 0) {
- if (!silent) { state.pending += state.src.slice(pos); }
- state.pos = state.src.length;
- return true;
- }
- if (!silent) { state.pending += state.src.slice(pos, pos + idx); }
- state.pos += idx;
- return true;
- };*/
- },{}],190:[function(require,module,exports){
- // Merge adjacent text nodes into one, and re-calculate all token levels
- //
- 'use strict';
- module.exports = function text_collapse(state) {
- var curr, last,
- level = 0,
- tokens = state.tokens,
- max = state.tokens.length;
- for (curr = last = 0; curr < max; curr++) {
- // re-calculate levels
- level += tokens[curr].nesting;
- tokens[curr].level = level;
- if (tokens[curr].type === 'text' &&
- curr + 1 < max &&
- tokens[curr + 1].type === 'text') {
- // collapse two adjacent text nodes
- tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content;
- } else {
- if (curr !== last) { tokens[last] = tokens[curr]; }
- last++;
- }
- }
- if (curr !== last) {
- tokens.length = last;
- }
- };
- },{}],191:[function(require,module,exports){
- // Token class
- 'use strict';
- /**
- * class Token
- **/
- /**
- * new Token(type, tag, nesting)
- *
- * Create new token and fill passed properties.
- **/
- function Token(type, tag, nesting) {
- /**
- * Token#type -> String
- *
- * Type of the token (string, e.g. "paragraph_open")
- **/
- this.type = type;
- /**
- * Token#tag -> String
- *
- * html tag name, e.g. "p"
- **/
- this.tag = tag;
- /**
- * Token#attrs -> Array
- *
- * Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]`
- **/
- this.attrs = null;
- /**
- * Token#map -> Array
- *
- * Source map info. Format: `[ line_begin, line_end ]`
- **/
- this.map = null;
- /**
- * Token#nesting -> Number
- *
- * Level change (number in {-1, 0, 1} set), where:
- *
- * - `1` means the tag is opening
- * - `0` means the tag is self-closing
- * - `-1` means the tag is closing
- **/
- this.nesting = nesting;
- /**
- * Token#level -> Number
- *
- * nesting level, the same as `state.level`
- **/
- this.level = 0;
- /**
- * Token#children -> Array
- *
- * An array of child nodes (inline and img tokens)
- **/
- this.children = null;
- /**
- * Token#content -> String
- *
- * In a case of self-closing tag (code, html, fence, etc.),
- * it has contents of this tag.
- **/
- this.content = '';
- /**
- * Token#markup -> String
- *
- * '*' or '_' for emphasis, fence string for fence, etc.
- **/
- this.markup = '';
- /**
- * Token#info -> String
- *
- * fence infostring
- **/
- this.info = '';
- /**
- * Token#meta -> Object
- *
- * A place for plugins to store an arbitrary data
- **/
- this.meta = null;
- /**
- * Token#block -> Boolean
- *
- * True for block-level tokens, false for inline tokens.
- * Used in renderer to calculate line breaks
- **/
- this.block = false;
- /**
- * Token#hidden -> Boolean
- *
- * If it's true, ignore this element when rendering. Used for tight lists
- * to hide paragraphs.
- **/
- this.hidden = false;
- }
- /**
- * Token.attrIndex(name) -> Number
- *
- * Search attribute index by name.
- **/
- Token.prototype.attrIndex = function attrIndex(name) {
- var attrs, i, len;
- if (!this.attrs) { return -1; }
- attrs = this.attrs;
- for (i = 0, len = attrs.length; i < len; i++) {
- if (attrs[i][0] === name) { return i; }
- }
- return -1;
- };
- /**
- * Token.attrPush(attrData)
- *
- * Add `[ name, value ]` attribute to list. Init attrs if necessary
- **/
- Token.prototype.attrPush = function attrPush(attrData) {
- if (this.attrs) {
- this.attrs.push(attrData);
- } else {
- this.attrs = [ attrData ];
- }
- };
- /**
- * Token.attrSet(name, value)
- *
- * Set `name` attribute to `value`. Override old value if exists.
- **/
- Token.prototype.attrSet = function attrSet(name, value) {
- var idx = this.attrIndex(name),
- attrData = [ name, value ];
- if (idx < 0) {
- this.attrPush(attrData);
- } else {
- this.attrs[idx] = attrData;
- }
- };
- /**
- * Token.attrGet(name)
- *
- * Get the value of attribute `name`, or null if it does not exist.
- **/
- Token.prototype.attrGet = function attrGet(name) {
- var idx = this.attrIndex(name), value = null;
- if (idx >= 0) {
- value = this.attrs[idx][1];
- }
- return value;
- };
- /**
- * Token.attrJoin(name, value)
- *
- * Join value to existing attribute via space. Or create new attribute if not
- * exists. Useful to operate with token classes.
- **/
- Token.prototype.attrJoin = function attrJoin(name, value) {
- var idx = this.attrIndex(name);
- if (idx < 0) {
- this.attrPush([ name, value ]);
- } else {
- this.attrs[idx][1] = this.attrs[idx][1] + ' ' + value;
- }
- };
- module.exports = Token;
- },{}],192:[function(require,module,exports){
- 'use strict';
- /* eslint-disable no-bitwise */
- var decodeCache = {};
- function getDecodeCache(exclude) {
- var i, ch, cache = decodeCache[exclude];
- if (cache) { return cache; }
- cache = decodeCache[exclude] = [];
- for (i = 0; i < 128; i++) {
- ch = String.fromCharCode(i);
- cache.push(ch);
- }
- for (i = 0; i < exclude.length; i++) {
- ch = exclude.charCodeAt(i);
- cache[ch] = '%' + ('0' + ch.toString(16).toUpperCase()).slice(-2);
- }
- return cache;
- }
- // Decode percent-encoded string.
- //
- function decode(string, exclude) {
- var cache;
- if (typeof exclude !== 'string') {
- exclude = decode.defaultChars;
- }
- cache = getDecodeCache(exclude);
- return string.replace(/(%[a-f0-9]{2})+/gi, function(seq) {
- var i, l, b1, b2, b3, b4, chr,
- result = '';
- for (i = 0, l = seq.length; i < l; i += 3) {
- b1 = parseInt(seq.slice(i + 1, i + 3), 16);
- if (b1 < 0x80) {
- result += cache[b1];
- continue;
- }
- if ((b1 & 0xE0) === 0xC0 && (i + 3 < l)) {
- // 110xxxxx 10xxxxxx
- b2 = parseInt(seq.slice(i + 4, i + 6), 16);
- if ((b2 & 0xC0) === 0x80) {
- chr = ((b1 << 6) & 0x7C0) | (b2 & 0x3F);
- if (chr < 0x80) {
- result += '\ufffd\ufffd';
- } else {
- result += String.fromCharCode(chr);
- }
- i += 3;
- continue;
- }
- }
- if ((b1 & 0xF0) === 0xE0 && (i + 6 < l)) {
- // 1110xxxx 10xxxxxx 10xxxxxx
- b2 = parseInt(seq.slice(i + 4, i + 6), 16);
- b3 = parseInt(seq.slice(i + 7, i + 9), 16);
- if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
- chr = ((b1 << 12) & 0xF000) | ((b2 << 6) & 0xFC0) | (b3 & 0x3F);
- if (chr < 0x800 || (chr >= 0xD800 && chr <= 0xDFFF)) {
- result += '\ufffd\ufffd\ufffd';
- } else {
- result += String.fromCharCode(chr);
- }
- i += 6;
- continue;
- }
- }
- if ((b1 & 0xF8) === 0xF0 && (i + 9 < l)) {
- // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx
- b2 = parseInt(seq.slice(i + 4, i + 6), 16);
- b3 = parseInt(seq.slice(i + 7, i + 9), 16);
- b4 = parseInt(seq.slice(i + 10, i + 12), 16);
- if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80 && (b4 & 0xC0) === 0x80) {
- chr = ((b1 << 18) & 0x1C0000) | ((b2 << 12) & 0x3F000) | ((b3 << 6) & 0xFC0) | (b4 & 0x3F);
- if (chr < 0x10000 || chr > 0x10FFFF) {
- result += '\ufffd\ufffd\ufffd\ufffd';
- } else {
- chr -= 0x10000;
- result += String.fromCharCode(0xD800 + (chr >> 10), 0xDC00 + (chr & 0x3FF));
- }
- i += 9;
- continue;
- }
- }
- result += '\ufffd';
- }
- return result;
- });
- }
- decode.defaultChars = ';/?:@&=+$,#';
- decode.componentChars = '';
- module.exports = decode;
- },{}],193:[function(require,module,exports){
- 'use strict';
- var encodeCache = {};
- // Create a lookup array where anything but characters in `chars` string
- // and alphanumeric chars is percent-encoded.
- //
- function getEncodeCache(exclude) {
- var i, ch, cache = encodeCache[exclude];
- if (cache) { return cache; }
- cache = encodeCache[exclude] = [];
- for (i = 0; i < 128; i++) {
- ch = String.fromCharCode(i);
- if (/^[0-9a-z]$/i.test(ch)) {
- // always allow unencoded alphanumeric characters
- cache.push(ch);
- } else {
- cache.push('%' + ('0' + i.toString(16).toUpperCase()).slice(-2));
- }
- }
- for (i = 0; i < exclude.length; i++) {
- cache[exclude.charCodeAt(i)] = exclude[i];
- }
- return cache;
- }
- // Encode unsafe characters with percent-encoding, skipping already
- // encoded sequences.
- //
- // - string - string to encode
- // - exclude - list of characters to ignore (in addition to a-zA-Z0-9)
- // - keepEscaped - don't encode '%' in a correct escape sequence (default: true)
- //
- function encode(string, exclude, keepEscaped) {
- var i, l, code, nextCode, cache,
- result = '';
- if (typeof exclude !== 'string') {
- // encode(string, keepEscaped)
- keepEscaped = exclude;
- exclude = encode.defaultChars;
- }
- if (typeof keepEscaped === 'undefined') {
- keepEscaped = true;
- }
- cache = getEncodeCache(exclude);
- for (i = 0, l = string.length; i < l; i++) {
- code = string.charCodeAt(i);
- if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) {
- if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) {
- result += string.slice(i, i + 3);
- i += 2;
- continue;
- }
- }
- if (code < 128) {
- result += cache[code];
- continue;
- }
- if (code >= 0xD800 && code <= 0xDFFF) {
- if (code >= 0xD800 && code <= 0xDBFF && i + 1 < l) {
- nextCode = string.charCodeAt(i + 1);
- if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) {
- result += encodeURIComponent(string[i] + string[i + 1]);
- i++;
- continue;
- }
- }
- result += '%EF%BF%BD';
- continue;
- }
- result += encodeURIComponent(string[i]);
- }
- return result;
- }
- encode.defaultChars = ";/?:@&=+$,-_.!~*'()#";
- encode.componentChars = "-_.!~*'()";
- module.exports = encode;
- },{}],194:[function(require,module,exports){
- 'use strict';
- module.exports = function format(url) {
- var result = '';
- result += url.protocol || '';
- result += url.slashes ? '//' : '';
- result += url.auth ? url.auth + '@' : '';
- if (url.hostname && url.hostname.indexOf(':') !== -1) {
- // ipv6 address
- result += '[' + url.hostname + ']';
- } else {
- result += url.hostname || '';
- }
- result += url.port ? ':' + url.port : '';
- result += url.pathname || '';
- result += url.search || '';
- result += url.hash || '';
- return result;
- };
- },{}],195:[function(require,module,exports){
- 'use strict';
- module.exports.encode = require('./encode');
- module.exports.decode = require('./decode');
- module.exports.format = require('./format');
- module.exports.parse = require('./parse');
- },{"./decode":192,"./encode":193,"./format":194,"./parse":196}],196:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- 'use strict';
- //
- // Changes from joyent/node:
- //
- // 1. No leading slash in paths,
- // e.g. in `url.parse('http://foo?bar')` pathname is ``, not `/`
- //
- // 2. Backslashes are not replaced with slashes,
- // so `http:\\example.org\` is treated like a relative path
- //
- // 3. Trailing colon is treated like a part of the path,
- // i.e. in `http://example.org:foo` pathname is `:foo`
- //
- // 4. Nothing is URL-encoded in the resulting object,
- // (in joyent/node some chars in auth and paths are encoded)
- //
- // 5. `url.parse()` does not have `parseQueryString` argument
- //
- // 6. Removed extraneous result properties: `host`, `path`, `query`, etc.,
- // which can be constructed using other parts of the url.
- //
- function Url() {
- this.protocol = null;
- this.slashes = null;
- this.auth = null;
- this.port = null;
- this.hostname = null;
- this.hash = null;
- this.search = null;
- this.pathname = null;
- }
- // Reference: RFC 3986, RFC 1808, RFC 2396
- // define these here so at least they only have to be
- // compiled once on the first module load.
- var protocolPattern = /^([a-z0-9.+-]+:)/i,
- portPattern = /:[0-9]*$/,
- // Special case for a simple path URL
- simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
- // RFC 2396: characters reserved for delimiting URLs.
- // We actually just auto-escape these.
- delims = [ '<', '>', '"', '`', ' ', '\r', '\n', '\t' ],
- // RFC 2396: characters not allowed for various reasons.
- unwise = [ '{', '}', '|', '\\', '^', '`' ].concat(delims),
- // Allowed by RFCs, but cause of XSS attacks. Always escape these.
- autoEscape = [ '\'' ].concat(unwise),
- // Characters that are never ever allowed in a hostname.
- // Note that any invalid chars are also handled, but these
- // are the ones that are *expected* to be seen, so we fast-path
- // them.
- nonHostChars = [ '%', '/', '?', ';', '#' ].concat(autoEscape),
- hostEndingChars = [ '/', '?', '#' ],
- hostnameMaxLen = 255,
- hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
- hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
- // protocols that can allow "unsafe" and "unwise" chars.
- /* eslint-disable no-script-url */
- // protocols that never have a hostname.
- hostlessProtocol = {
- 'javascript': true,
- 'javascript:': true
- },
- // protocols that always contain a // bit.
- slashedProtocol = {
- 'http': true,
- 'https': true,
- 'ftp': true,
- 'gopher': true,
- 'file': true,
- 'http:': true,
- 'https:': true,
- 'ftp:': true,
- 'gopher:': true,
- 'file:': true
- };
- /* eslint-enable no-script-url */
- function urlParse(url, slashesDenoteHost) {
- if (url && url instanceof Url) { return url; }
- var u = new Url();
- u.parse(url, slashesDenoteHost);
- return u;
- }
- Url.prototype.parse = function(url, slashesDenoteHost) {
- var i, l, lowerProto, hec, slashes,
- rest = url;
- // trim before proceeding.
- // This is to support parse stuff like " http://foo.com \n"
- rest = rest.trim();
- if (!slashesDenoteHost && url.split('#').length === 1) {
- // Try fast path regexp
- var simplePath = simplePathPattern.exec(rest);
- if (simplePath) {
- this.pathname = simplePath[1];
- if (simplePath[2]) {
- this.search = simplePath[2];
- }
- return this;
- }
- }
- var proto = protocolPattern.exec(rest);
- if (proto) {
- proto = proto[0];
- lowerProto = proto.toLowerCase();
- this.protocol = proto;
- rest = rest.substr(proto.length);
- }
- // figure out if it's got a host
- // user@server is *always* interpreted as a hostname, and url
- // resolution will treat //foo/bar as host=foo,path=bar because that's
- // how the browser resolves relative URLs.
- if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
- slashes = rest.substr(0, 2) === '//';
- if (slashes && !(proto && hostlessProtocol[proto])) {
- rest = rest.substr(2);
- this.slashes = true;
- }
- }
- if (!hostlessProtocol[proto] &&
- (slashes || (proto && !slashedProtocol[proto]))) {
- // there's a hostname.
- // the first instance of /, ?, ;, or # ends the host.
- //
- // If there is an @ in the hostname, then non-host chars *are* allowed
- // to the left of the last @ sign, unless some host-ending character
- // comes *before* the @-sign.
- // URLs are obnoxious.
- //
- // ex:
- // http://a@b@c/ => user:a@b host:c
- // http://a@b?@c => user:a host:c path:/?@c
- // v0.12 TODO(isaacs): This is not quite how Chrome does things.
- // Review our test case against browsers more comprehensively.
- // find the first instance of any hostEndingChars
- var hostEnd = -1;
- for (i = 0; i < hostEndingChars.length; i++) {
- hec = rest.indexOf(hostEndingChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
- hostEnd = hec;
- }
- }
- // at this point, either we have an explicit point where the
- // auth portion cannot go past, or the last @ char is the decider.
- var auth, atSign;
- if (hostEnd === -1) {
- // atSign can be anywhere.
- atSign = rest.lastIndexOf('@');
- } else {
- // atSign must be in auth portion.
- // http://a@b/c@d => host:b auth:a path:/c@d
- atSign = rest.lastIndexOf('@', hostEnd);
- }
- // Now we have a portion which is definitely the auth.
- // Pull that off.
- if (atSign !== -1) {
- auth = rest.slice(0, atSign);
- rest = rest.slice(atSign + 1);
- this.auth = auth;
- }
- // the host is the remaining to the left of the first non-host char
- hostEnd = -1;
- for (i = 0; i < nonHostChars.length; i++) {
- hec = rest.indexOf(nonHostChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
- hostEnd = hec;
- }
- }
- // if we still have not hit it, then the entire thing is a host.
- if (hostEnd === -1) {
- hostEnd = rest.length;
- }
- if (rest[hostEnd - 1] === ':') { hostEnd--; }
- var host = rest.slice(0, hostEnd);
- rest = rest.slice(hostEnd);
- // pull out port.
- this.parseHost(host);
- // we've indicated that there is a hostname,
- // so even if it's empty, it has to be present.
- this.hostname = this.hostname || '';
- // if hostname begins with [ and ends with ]
- // assume that it's an IPv6 address.
- var ipv6Hostname = this.hostname[0] === '[' &&
- this.hostname[this.hostname.length - 1] === ']';
- // validate a little.
- if (!ipv6Hostname) {
- var hostparts = this.hostname.split(/\./);
- for (i = 0, l = hostparts.length; i < l; i++) {
- var part = hostparts[i];
- if (!part) { continue; }
- if (!part.match(hostnamePartPattern)) {
- var newpart = '';
- for (var j = 0, k = part.length; j < k; j++) {
- if (part.charCodeAt(j) > 127) {
- // we replace non-ASCII char with a temporary placeholder
- // we need this to make sure size of hostname is not
- // broken by replacing non-ASCII by nothing
- newpart += 'x';
- } else {
- newpart += part[j];
- }
- }
- // we test again with ASCII char only
- if (!newpart.match(hostnamePartPattern)) {
- var validParts = hostparts.slice(0, i);
- var notHost = hostparts.slice(i + 1);
- var bit = part.match(hostnamePartStart);
- if (bit) {
- validParts.push(bit[1]);
- notHost.unshift(bit[2]);
- }
- if (notHost.length) {
- rest = notHost.join('.') + rest;
- }
- this.hostname = validParts.join('.');
- break;
- }
- }
- }
- }
- if (this.hostname.length > hostnameMaxLen) {
- this.hostname = '';
- }
- // strip [ and ] from the hostname
- // the host field still retains them, though
- if (ipv6Hostname) {
- this.hostname = this.hostname.substr(1, this.hostname.length - 2);
- }
- }
- // chop off from the tail first.
- var hash = rest.indexOf('#');
- if (hash !== -1) {
- // got a fragment string.
- this.hash = rest.substr(hash);
- rest = rest.slice(0, hash);
- }
- var qm = rest.indexOf('?');
- if (qm !== -1) {
- this.search = rest.substr(qm);
- rest = rest.slice(0, qm);
- }
- if (rest) { this.pathname = rest; }
- if (slashedProtocol[lowerProto] &&
- this.hostname && !this.pathname) {
- this.pathname = '';
- }
- return this;
- };
- Url.prototype.parseHost = function(host) {
- var port = portPattern.exec(host);
- if (port) {
- port = port[0];
- if (port !== ':') {
- this.port = port.substr(1);
- }
- host = host.substr(0, host.length - port.length);
- }
- if (host) { this.hostname = host; }
- };
- module.exports = urlParse;
- },{}],197:[function(require,module,exports){
- /*
- object-assign
- (c) Sindre Sorhus
- @license MIT
- */
- 'use strict';
- /* eslint-disable no-unused-vars */
- var getOwnPropertySymbols = Object.getOwnPropertySymbols;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var propIsEnumerable = Object.prototype.propertyIsEnumerable;
- function toObject(val) {
- if (val === null || val === undefined) {
- throw new TypeError('Object.assign cannot be called with null or undefined');
- }
- return Object(val);
- }
- function shouldUseNative() {
- try {
- if (!Object.assign) {
- return false;
- }
- // Detect buggy property enumeration order in older V8 versions.
- // https://bugs.chromium.org/p/v8/issues/detail?id=4118
- var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
- test1[5] = 'de';
- if (Object.getOwnPropertyNames(test1)[0] === '5') {
- return false;
- }
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test2 = {};
- for (var i = 0; i < 10; i++) {
- test2['_' + String.fromCharCode(i)] = i;
- }
- var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
- return test2[n];
- });
- if (order2.join('') !== '0123456789') {
- return false;
- }
- // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test3 = {};
- 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
- test3[letter] = letter;
- });
- if (Object.keys(Object.assign({}, test3)).join('') !==
- 'abcdefghijklmnopqrst') {
- return false;
- }
- return true;
- } catch (err) {
- // We don't expect any of the above to throw, but better to be safe.
- return false;
- }
- }
- module.exports = shouldUseNative() ? Object.assign : function (target, source) {
- var from;
- var to = toObject(target);
- var symbols;
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
- for (var key in from) {
- if (hasOwnProperty.call(from, key)) {
- to[key] = from[key];
- }
- }
- if (getOwnPropertySymbols) {
- symbols = getOwnPropertySymbols(from);
- for (var i = 0; i < symbols.length; i++) {
- if (propIsEnumerable.call(from, symbols[i])) {
- to[symbols[i]] = from[symbols[i]];
- }
- }
- }
- }
- return to;
- };
- },{}],198:[function(require,module,exports){
- // shim for using process in browser
- var process = module.exports = {};
- // cached from whatever global is present so that test runners that stub it
- // don't break things. But we need to wrap it in a try catch in case it is
- // wrapped in strict mode code which doesn't define any globals. It's inside a
- // function because try/catches deoptimize in certain engines.
- var cachedSetTimeout;
- var cachedClearTimeout;
- function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
- }
- function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
- }
- (function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
- } ())
- function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // 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
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
- }
- function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // 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.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
- }
- var queue = [];
- var draining = false;
- var currentQueue;
- var queueIndex = -1;
- function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
- }
- function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
- }
- process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
- };
- // v8 likes predictible objects
- function Item(fun, array) {
- this.fun = fun;
- this.array = array;
- }
- Item.prototype.run = function () {
- this.fun.apply(null, this.array);
- };
- process.title = 'browser';
- process.browser = true;
- process.env = {};
- process.argv = [];
- process.version = ''; // empty string to avoid regexp issues
- process.versions = {};
- function noop() {}
- process.on = noop;
- process.addListener = noop;
- process.once = noop;
- process.off = noop;
- process.removeListener = noop;
- process.removeAllListeners = noop;
- process.emit = noop;
- process.prependListener = noop;
- process.prependOnceListener = noop;
- process.listeners = function (name) { return [] }
- process.binding = function (name) {
- throw new Error('process.binding is not supported');
- };
- process.cwd = function () { return '/' };
- process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
- };
- process.umask = function() { return 0; };
- },{}],199:[function(require,module,exports){
- (function (process){
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- 'use strict';
- var printWarning = function() {};
- if (process.env.NODE_ENV !== 'production') {
- var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
- var loggedTypeFailures = {};
- var has = Function.call.bind(Object.prototype.hasOwnProperty);
- printWarning = function(text) {
- var message = 'Warning: ' + text;
- if (typeof console !== 'undefined') {
- console.error(message);
- }
- try {
- // --- Welcome to debugging React ---
- // This error was thrown as a convenience so that you can use this stack
- // to find the callsite that caused this warning to fire.
- throw new Error(message);
- } catch (x) {}
- };
- }
- /**
- * Assert that the values match with the type specs.
- * Error messages are memorized and will only be shown once.
- *
- * @param {object} typeSpecs Map of name to a ReactPropType
- * @param {object} values Runtime values that need to be type-checked
- * @param {string} location e.g. "prop", "context", "child context"
- * @param {string} componentName Name of the component for error messages.
- * @param {?Function} getStack Returns the component stack.
- * @private
- */
- function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
- if (process.env.NODE_ENV !== 'production') {
- for (var typeSpecName in typeSpecs) {
- if (has(typeSpecs, typeSpecName)) {
- var error;
- // Prop type validation may throw. In case they do, we don't want to
- // fail the render phase where it didn't fail before. So we log it.
- // After these have been cleaned up, we'll let them throw.
- try {
- // This is intentionally an invariant that gets caught. It's the same
- // behavior as without this statement except with a better message.
- if (typeof typeSpecs[typeSpecName] !== 'function') {
- var err = Error(
- (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
- 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
- );
- err.name = 'Invariant Violation';
- throw err;
- }
- error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
- } catch (ex) {
- error = ex;
- }
- if (error && !(error instanceof Error)) {
- printWarning(
- (componentName || 'React class') + ': type specification of ' +
- location + ' `' + typeSpecName + '` is invalid; the type checker ' +
- 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
- 'You may have forgotten to pass an argument to the type checker ' +
- 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
- 'shape all require an argument).'
- );
- }
- if (error instanceof Error && !(error.message in loggedTypeFailures)) {
- // Only monitor this failure once because there tends to be a lot of the
- // same error.
- loggedTypeFailures[error.message] = true;
- var stack = getStack ? getStack() : '';
- printWarning(
- 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
- );
- }
- }
- }
- }
- }
- /**
- * Resets warning cache when testing.
- *
- * @private
- */
- checkPropTypes.resetWarningCache = function() {
- if (process.env.NODE_ENV !== 'production') {
- loggedTypeFailures = {};
- }
- }
- module.exports = checkPropTypes;
- }).call(this,require('_process'))
- },{"./lib/ReactPropTypesSecret":203,"_process":198}],200:[function(require,module,exports){
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- 'use strict';
- var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
- function emptyFunction() {}
- function emptyFunctionWithReset() {}
- emptyFunctionWithReset.resetWarningCache = emptyFunction;
- module.exports = function() {
- function shim(props, propName, componentName, location, propFullName, secret) {
- if (secret === ReactPropTypesSecret) {
- // It is still safe when called from React.
- return;
- }
- var err = new Error(
- 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
- 'Use PropTypes.checkPropTypes() to call them. ' +
- 'Read more at http://fb.me/use-check-prop-types'
- );
- err.name = 'Invariant Violation';
- throw err;
- };
- shim.isRequired = shim;
- function getShim() {
- return shim;
- };
- // Important!
- // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
- var ReactPropTypes = {
- array: shim,
- bool: shim,
- func: shim,
- number: shim,
- object: shim,
- string: shim,
- symbol: shim,
- any: shim,
- arrayOf: getShim,
- element: shim,
- elementType: shim,
- instanceOf: getShim,
- node: shim,
- objectOf: getShim,
- oneOf: getShim,
- oneOfType: getShim,
- shape: getShim,
- exact: getShim,
- checkPropTypes: emptyFunctionWithReset,
- resetWarningCache: emptyFunction
- };
- ReactPropTypes.PropTypes = ReactPropTypes;
- return ReactPropTypes;
- };
- },{"./lib/ReactPropTypesSecret":203}],201:[function(require,module,exports){
- (function (process){
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- 'use strict';
- var ReactIs = require('react-is');
- var assign = require('object-assign');
- var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
- var checkPropTypes = require('./checkPropTypes');
- var has = Function.call.bind(Object.prototype.hasOwnProperty);
- var printWarning = function() {};
- if (process.env.NODE_ENV !== 'production') {
- printWarning = function(text) {
- var message = 'Warning: ' + text;
- if (typeof console !== 'undefined') {
- console.error(message);
- }
- try {
- // --- Welcome to debugging React ---
- // This error was thrown as a convenience so that you can use this stack
- // to find the callsite that caused this warning to fire.
- throw new Error(message);
- } catch (x) {}
- };
- }
- function emptyFunctionThatReturnsNull() {
- return null;
- }
- module.exports = function(isValidElement, throwOnDirectAccess) {
- /* global Symbol */
- var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
- var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
- /**
- * Returns the iterator method function contained on the iterable object.
- *
- * Be sure to invoke the function with the iterable as context:
- *
- * var iteratorFn = getIteratorFn(myIterable);
- * if (iteratorFn) {
- * var iterator = iteratorFn.call(myIterable);
- * ...
- * }
- *
- * @param {?object} maybeIterable
- * @return {?function}
- */
- function getIteratorFn(maybeIterable) {
- var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
- if (typeof iteratorFn === 'function') {
- return iteratorFn;
- }
- }
- /**
- * Collection of methods that allow declaration and validation of props that are
- * supplied to React components. Example usage:
- *
- * var Props = require('ReactPropTypes');
- * var MyArticle = React.createClass({
- * propTypes: {
- * // An optional string prop named "description".
- * description: Props.string,
- *
- * // A required enum prop named "category".
- * category: Props.oneOf(['News','Photos']).isRequired,
- *
- * // A prop named "dialog" that requires an instance of Dialog.
- * dialog: Props.instanceOf(Dialog).isRequired
- * },
- * render: function() { ... }
- * });
- *
- * A more formal specification of how these methods are used:
- *
- * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
- * decl := ReactPropTypes.{type}(.isRequired)?
- *
- * Each and every declaration produces a function with the same signature. This
- * allows the creation of custom validation functions. For example:
- *
- * var MyLink = React.createClass({
- * propTypes: {
- * // An optional string or URI prop named "href".
- * href: function(props, propName, componentName) {
- * var propValue = props[propName];
- * if (propValue != null && typeof propValue !== 'string' &&
- * !(propValue instanceof URI)) {
- * return new Error(
- * 'Expected a string or an URI for ' + propName + ' in ' +
- * componentName
- * );
- * }
- * }
- * },
- * render: function() {...}
- * });
- *
- * @internal
- */
- var ANONYMOUS = '<<anonymous>>';
- // Important!
- // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
- var ReactPropTypes = {
- array: createPrimitiveTypeChecker('array'),
- bool: createPrimitiveTypeChecker('boolean'),
- func: createPrimitiveTypeChecker('function'),
- number: createPrimitiveTypeChecker('number'),
- object: createPrimitiveTypeChecker('object'),
- string: createPrimitiveTypeChecker('string'),
- symbol: createPrimitiveTypeChecker('symbol'),
- any: createAnyTypeChecker(),
- arrayOf: createArrayOfTypeChecker,
- element: createElementTypeChecker(),
- elementType: createElementTypeTypeChecker(),
- instanceOf: createInstanceTypeChecker,
- node: createNodeChecker(),
- objectOf: createObjectOfTypeChecker,
- oneOf: createEnumTypeChecker,
- oneOfType: createUnionTypeChecker,
- shape: createShapeTypeChecker,
- exact: createStrictShapeTypeChecker,
- };
- /**
- * inlined Object.is polyfill to avoid requiring consumers ship their own
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
- */
- /*eslint-disable no-self-compare*/
- function is(x, y) {
- // SameValue algorithm
- if (x === y) {
- // Steps 1-5, 7-10
- // Steps 6.b-6.e: +0 != -0
- return x !== 0 || 1 / x === 1 / y;
- } else {
- // Step 6.a: NaN == NaN
- return x !== x && y !== y;
- }
- }
- /*eslint-enable no-self-compare*/
- /**
- * We use an Error-like object for backward compatibility as people may call
- * PropTypes directly and inspect their output. However, we don't use real
- * Errors anymore. We don't inspect their stack anyway, and creating them
- * is prohibitively expensive if they are created too often, such as what
- * happens in oneOfType() for any type before the one that matched.
- */
- function PropTypeError(message) {
- this.message = message;
- this.stack = '';
- }
- // Make `instanceof Error` still work for returned errors.
- PropTypeError.prototype = Error.prototype;
- function createChainableTypeChecker(validate) {
- if (process.env.NODE_ENV !== 'production') {
- var manualPropTypeCallCache = {};
- var manualPropTypeWarningCount = 0;
- }
- function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
- componentName = componentName || ANONYMOUS;
- propFullName = propFullName || propName;
- if (secret !== ReactPropTypesSecret) {
- if (throwOnDirectAccess) {
- // New behavior only for users of `prop-types` package
- var err = new Error(
- 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
- 'Use `PropTypes.checkPropTypes()` to call them. ' +
- 'Read more at http://fb.me/use-check-prop-types'
- );
- err.name = 'Invariant Violation';
- throw err;
- } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') {
- // Old behavior for people using React.PropTypes
- var cacheKey = componentName + ':' + propName;
- if (
- !manualPropTypeCallCache[cacheKey] &&
- // Avoid spamming the console because they are often not actionable except for lib authors
- manualPropTypeWarningCount < 3
- ) {
- printWarning(
- 'You are manually calling a React.PropTypes validation ' +
- 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +
- 'and will throw in the standalone `prop-types` package. ' +
- 'You may be seeing this warning due to a third-party PropTypes ' +
- 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
- );
- manualPropTypeCallCache[cacheKey] = true;
- manualPropTypeWarningCount++;
- }
- }
- }
- if (props[propName] == null) {
- if (isRequired) {
- if (props[propName] === null) {
- return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
- }
- return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
- }
- return null;
- } else {
- return validate(props, propName, componentName, location, propFullName);
- }
- }
- var chainedCheckType = checkType.bind(null, false);
- chainedCheckType.isRequired = checkType.bind(null, true);
- return chainedCheckType;
- }
- function createPrimitiveTypeChecker(expectedType) {
- function validate(props, propName, componentName, location, propFullName, secret) {
- var propValue = props[propName];
- var propType = getPropType(propValue);
- if (propType !== expectedType) {
- // `propValue` being instance of, say, date/regexp, pass the 'object'
- // check, but we can offer a more precise error message here rather than
- // 'of type `object`'.
- var preciseType = getPreciseType(propValue);
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
- }
- return null;
- }
- return createChainableTypeChecker(validate);
- }
- function createAnyTypeChecker() {
- return createChainableTypeChecker(emptyFunctionThatReturnsNull);
- }
- function createArrayOfTypeChecker(typeChecker) {
- function validate(props, propName, componentName, location, propFullName) {
- if (typeof typeChecker !== 'function') {
- return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
- }
- var propValue = props[propName];
- if (!Array.isArray(propValue)) {
- var propType = getPropType(propValue);
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
- }
- for (var i = 0; i < propValue.length; i++) {
- var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
- if (error instanceof Error) {
- return error;
- }
- }
- return null;
- }
- return createChainableTypeChecker(validate);
- }
- function createElementTypeChecker() {
- function validate(props, propName, componentName, location, propFullName) {
- var propValue = props[propName];
- if (!isValidElement(propValue)) {
- var propType = getPropType(propValue);
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
- }
- return null;
- }
- return createChainableTypeChecker(validate);
- }
- function createElementTypeTypeChecker() {
- function validate(props, propName, componentName, location, propFullName) {
- var propValue = props[propName];
- if (!ReactIs.isValidElementType(propValue)) {
- var propType = getPropType(propValue);
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
- }
- return null;
- }
- return createChainableTypeChecker(validate);
- }
- function createInstanceTypeChecker(expectedClass) {
- function validate(props, propName, componentName, location, propFullName) {
- if (!(props[propName] instanceof expectedClass)) {
- var expectedClassName = expectedClass.name || ANONYMOUS;
- var actualClassName = getClassName(props[propName]);
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
- }
- return null;
- }
- return createChainableTypeChecker(validate);
- }
- function createEnumTypeChecker(expectedValues) {
- if (!Array.isArray(expectedValues)) {
- if (process.env.NODE_ENV !== 'production') {
- if (arguments.length > 1) {
- printWarning(
- 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
- 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
- );
- } else {
- printWarning('Invalid argument supplied to oneOf, expected an array.');
- }
- }
- return emptyFunctionThatReturnsNull;
- }
- function validate(props, propName, componentName, location, propFullName) {
- var propValue = props[propName];
- for (var i = 0; i < expectedValues.length; i++) {
- if (is(propValue, expectedValues[i])) {
- return null;
- }
- }
- var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
- var type = getPreciseType(value);
- if (type === 'symbol') {
- return String(value);
- }
- return value;
- });
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
- }
- return createChainableTypeChecker(validate);
- }
- function createObjectOfTypeChecker(typeChecker) {
- function validate(props, propName, componentName, location, propFullName) {
- if (typeof typeChecker !== 'function') {
- return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
- }
- var propValue = props[propName];
- var propType = getPropType(propValue);
- if (propType !== 'object') {
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
- }
- for (var key in propValue) {
- if (has(propValue, key)) {
- var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
- if (error instanceof Error) {
- return error;
- }
- }
- }
- return null;
- }
- return createChainableTypeChecker(validate);
- }
- function createUnionTypeChecker(arrayOfTypeCheckers) {
- if (!Array.isArray(arrayOfTypeCheckers)) {
- process.env.NODE_ENV !== 'production' ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
- return emptyFunctionThatReturnsNull;
- }
- for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
- var checker = arrayOfTypeCheckers[i];
- if (typeof checker !== 'function') {
- printWarning(
- 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
- 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
- );
- return emptyFunctionThatReturnsNull;
- }
- }
- function validate(props, propName, componentName, location, propFullName) {
- for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
- var checker = arrayOfTypeCheckers[i];
- if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
- return null;
- }
- }
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
- }
- return createChainableTypeChecker(validate);
- }
- function createNodeChecker() {
- function validate(props, propName, componentName, location, propFullName) {
- if (!isNode(props[propName])) {
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
- }
- return null;
- }
- return createChainableTypeChecker(validate);
- }
- function createShapeTypeChecker(shapeTypes) {
- function validate(props, propName, componentName, location, propFullName) {
- var propValue = props[propName];
- var propType = getPropType(propValue);
- if (propType !== 'object') {
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
- }
- for (var key in shapeTypes) {
- var checker = shapeTypes[key];
- if (!checker) {
- continue;
- }
- var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
- if (error) {
- return error;
- }
- }
- return null;
- }
- return createChainableTypeChecker(validate);
- }
- function createStrictShapeTypeChecker(shapeTypes) {
- function validate(props, propName, componentName, location, propFullName) {
- var propValue = props[propName];
- var propType = getPropType(propValue);
- if (propType !== 'object') {
- return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
- }
- // We need to check all keys in case some are required but missing from
- // props.
- var allKeys = assign({}, props[propName], shapeTypes);
- for (var key in allKeys) {
- var checker = shapeTypes[key];
- if (!checker) {
- return new PropTypeError(
- 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
- '\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
- '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
- );
- }
- var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
- if (error) {
- return error;
- }
- }
- return null;
- }
- return createChainableTypeChecker(validate);
- }
- function isNode(propValue) {
- switch (typeof propValue) {
- case 'number':
- case 'string':
- case 'undefined':
- return true;
- case 'boolean':
- return !propValue;
- case 'object':
- if (Array.isArray(propValue)) {
- return propValue.every(isNode);
- }
- if (propValue === null || isValidElement(propValue)) {
- return true;
- }
- var iteratorFn = getIteratorFn(propValue);
- if (iteratorFn) {
- var iterator = iteratorFn.call(propValue);
- var step;
- if (iteratorFn !== propValue.entries) {
- while (!(step = iterator.next()).done) {
- if (!isNode(step.value)) {
- return false;
- }
- }
- } else {
- // Iterator will provide entry [k,v] tuples rather than values.
- while (!(step = iterator.next()).done) {
- var entry = step.value;
- if (entry) {
- if (!isNode(entry[1])) {
- return false;
- }
- }
- }
- }
- } else {
- return false;
- }
- return true;
- default:
- return false;
- }
- }
- function isSymbol(propType, propValue) {
- // Native Symbol.
- if (propType === 'symbol') {
- return true;
- }
- // falsy value can't be a Symbol
- if (!propValue) {
- return false;
- }
- // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
- if (propValue['@@toStringTag'] === 'Symbol') {
- return true;
- }
- // Fallback for non-spec compliant Symbols which are polyfilled.
- if (typeof Symbol === 'function' && propValue instanceof Symbol) {
- return true;
- }
- return false;
- }
- // Equivalent of `typeof` but with special handling for array and regexp.
- function getPropType(propValue) {
- var propType = typeof propValue;
- if (Array.isArray(propValue)) {
- return 'array';
- }
- if (propValue instanceof RegExp) {
- // Old webkits (at least until Android 4.0) return 'function' rather than
- // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
- // passes PropTypes.object.
- return 'object';
- }
- if (isSymbol(propType, propValue)) {
- return 'symbol';
- }
- return propType;
- }
- // This handles more types than `getPropType`. Only used for error messages.
- // See `createPrimitiveTypeChecker`.
- function getPreciseType(propValue) {
- if (typeof propValue === 'undefined' || propValue === null) {
- return '' + propValue;
- }
- var propType = getPropType(propValue);
- if (propType === 'object') {
- if (propValue instanceof Date) {
- return 'date';
- } else if (propValue instanceof RegExp) {
- return 'regexp';
- }
- }
- return propType;
- }
- // Returns a string that is postfixed to a warning about an invalid type.
- // For example, "undefined" or "of type array"
- function getPostfixForTypeWarning(value) {
- var type = getPreciseType(value);
- switch (type) {
- case 'array':
- case 'object':
- return 'an ' + type;
- case 'boolean':
- case 'date':
- case 'regexp':
- return 'a ' + type;
- default:
- return type;
- }
- }
- // Returns class name of the object, if any.
- function getClassName(propValue) {
- if (!propValue.constructor || !propValue.constructor.name) {
- return ANONYMOUS;
- }
- return propValue.constructor.name;
- }
- ReactPropTypes.checkPropTypes = checkPropTypes;
- ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
- ReactPropTypes.PropTypes = ReactPropTypes;
- return ReactPropTypes;
- };
- }).call(this,require('_process'))
- },{"./checkPropTypes":199,"./lib/ReactPropTypesSecret":203,"_process":198,"object-assign":197,"react-is":206}],202:[function(require,module,exports){
- (function (process){
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- if (process.env.NODE_ENV !== 'production') {
- var ReactIs = require('react-is');
- // By explicitly using `prop-types` you are opting into new development behavior.
- // http://fb.me/prop-types-in-prod
- var throwOnDirectAccess = true;
- module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);
- } else {
- // By explicitly using `prop-types` you are opting into new production behavior.
- // http://fb.me/prop-types-in-prod
- module.exports = require('./factoryWithThrowingShims')();
- }
- }).call(this,require('_process'))
- },{"./factoryWithThrowingShims":200,"./factoryWithTypeCheckers":201,"_process":198,"react-is":206}],203:[function(require,module,exports){
- /**
- * Copyright (c) 2013-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- 'use strict';
- var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
- module.exports = ReactPropTypesSecret;
- },{}],204:[function(require,module,exports){
- (function (process){
- /** @license React v16.8.6
- * react-is.development.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- 'use strict';
- if (process.env.NODE_ENV !== "production") {
- (function() {
- 'use strict';
- Object.defineProperty(exports, '__esModule', { value: true });
- // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
- // nor polyfill, then a plain number is used for performance.
- var hasSymbol = typeof Symbol === 'function' && Symbol.for;
- var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
- var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
- var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
- var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
- var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
- var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
- var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
- var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
- var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
- var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
- var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
- var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
- var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
- function isValidElementType(type) {
- return typeof type === 'string' || typeof type === 'function' ||
- // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
- type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE);
- }
- /**
- * Forked from fbjs/warning:
- * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
- *
- * Only change is we use console.warn instead of console.error,
- * and do nothing when 'console' is not supported.
- * This really simplifies the code.
- * ---
- * Similar to invariant but only logs a warning if the condition is not met.
- * This can be used to log issues in development environments in critical
- * paths. Removing the logging code for production environments will keep the
- * same logic and follow the same code paths.
- */
- var lowPriorityWarning = function () {};
- {
- var printWarning = function (format) {
- for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
- var argIndex = 0;
- var message = 'Warning: ' + format.replace(/%s/g, function () {
- return args[argIndex++];
- });
- if (typeof console !== 'undefined') {
- console.warn(message);
- }
- try {
- // --- Welcome to debugging React ---
- // This error was thrown as a convenience so that you can use this stack
- // to find the callsite that caused this warning to fire.
- throw new Error(message);
- } catch (x) {}
- };
- lowPriorityWarning = function (condition, format) {
- if (format === undefined) {
- throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
- }
- if (!condition) {
- for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
- args[_key2 - 2] = arguments[_key2];
- }
- printWarning.apply(undefined, [format].concat(args));
- }
- };
- }
- var lowPriorityWarning$1 = lowPriorityWarning;
- function typeOf(object) {
- if (typeof object === 'object' && object !== null) {
- var $$typeof = object.$$typeof;
- switch ($$typeof) {
- case REACT_ELEMENT_TYPE:
- var type = object.type;
- switch (type) {
- case REACT_ASYNC_MODE_TYPE:
- case REACT_CONCURRENT_MODE_TYPE:
- case REACT_FRAGMENT_TYPE:
- case REACT_PROFILER_TYPE:
- case REACT_STRICT_MODE_TYPE:
- case REACT_SUSPENSE_TYPE:
- return type;
- default:
- var $$typeofType = type && type.$$typeof;
- switch ($$typeofType) {
- case REACT_CONTEXT_TYPE:
- case REACT_FORWARD_REF_TYPE:
- case REACT_PROVIDER_TYPE:
- return $$typeofType;
- default:
- return $$typeof;
- }
- }
- case REACT_LAZY_TYPE:
- case REACT_MEMO_TYPE:
- case REACT_PORTAL_TYPE:
- return $$typeof;
- }
- }
- return undefined;
- }
- // AsyncMode is deprecated along with isAsyncMode
- var AsyncMode = REACT_ASYNC_MODE_TYPE;
- var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
- var ContextConsumer = REACT_CONTEXT_TYPE;
- var ContextProvider = REACT_PROVIDER_TYPE;
- var Element = REACT_ELEMENT_TYPE;
- var ForwardRef = REACT_FORWARD_REF_TYPE;
- var Fragment = REACT_FRAGMENT_TYPE;
- var Lazy = REACT_LAZY_TYPE;
- var Memo = REACT_MEMO_TYPE;
- var Portal = REACT_PORTAL_TYPE;
- var Profiler = REACT_PROFILER_TYPE;
- var StrictMode = REACT_STRICT_MODE_TYPE;
- var Suspense = REACT_SUSPENSE_TYPE;
- var hasWarnedAboutDeprecatedIsAsyncMode = false;
- // AsyncMode should be deprecated
- function isAsyncMode(object) {
- {
- if (!hasWarnedAboutDeprecatedIsAsyncMode) {
- hasWarnedAboutDeprecatedIsAsyncMode = true;
- lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
- }
- }
- return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
- }
- function isConcurrentMode(object) {
- return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
- }
- function isContextConsumer(object) {
- return typeOf(object) === REACT_CONTEXT_TYPE;
- }
- function isContextProvider(object) {
- return typeOf(object) === REACT_PROVIDER_TYPE;
- }
- function isElement(object) {
- return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
- }
- function isForwardRef(object) {
- return typeOf(object) === REACT_FORWARD_REF_TYPE;
- }
- function isFragment(object) {
- return typeOf(object) === REACT_FRAGMENT_TYPE;
- }
- function isLazy(object) {
- return typeOf(object) === REACT_LAZY_TYPE;
- }
- function isMemo(object) {
- return typeOf(object) === REACT_MEMO_TYPE;
- }
- function isPortal(object) {
- return typeOf(object) === REACT_PORTAL_TYPE;
- }
- function isProfiler(object) {
- return typeOf(object) === REACT_PROFILER_TYPE;
- }
- function isStrictMode(object) {
- return typeOf(object) === REACT_STRICT_MODE_TYPE;
- }
- function isSuspense(object) {
- return typeOf(object) === REACT_SUSPENSE_TYPE;
- }
- exports.typeOf = typeOf;
- exports.AsyncMode = AsyncMode;
- exports.ConcurrentMode = ConcurrentMode;
- exports.ContextConsumer = ContextConsumer;
- exports.ContextProvider = ContextProvider;
- exports.Element = Element;
- exports.ForwardRef = ForwardRef;
- exports.Fragment = Fragment;
- exports.Lazy = Lazy;
- exports.Memo = Memo;
- exports.Portal = Portal;
- exports.Profiler = Profiler;
- exports.StrictMode = StrictMode;
- exports.Suspense = Suspense;
- exports.isValidElementType = isValidElementType;
- exports.isAsyncMode = isAsyncMode;
- exports.isConcurrentMode = isConcurrentMode;
- exports.isContextConsumer = isContextConsumer;
- exports.isContextProvider = isContextProvider;
- exports.isElement = isElement;
- exports.isForwardRef = isForwardRef;
- exports.isFragment = isFragment;
- exports.isLazy = isLazy;
- exports.isMemo = isMemo;
- exports.isPortal = isPortal;
- exports.isProfiler = isProfiler;
- exports.isStrictMode = isStrictMode;
- exports.isSuspense = isSuspense;
- })();
- }
- }).call(this,require('_process'))
- },{"_process":198}],205:[function(require,module,exports){
- /** @license React v16.8.6
- * react-is.production.min.js
- *
- * Copyright (c) Facebook, Inc. and its affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- 'use strict';Object.defineProperty(exports,"__esModule",{value:!0});
- var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?Symbol.for("react.memo"):
- 60115,r=b?Symbol.for("react.lazy"):60116;function t(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case h:return a;default:return u}}case r:case q:case d:return u}}}function v(a){return t(a)===m}exports.typeOf=t;exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;
- exports.Fragment=e;exports.Lazy=r;exports.Memo=q;exports.Portal=d;exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||"object"===typeof a&&null!==a&&(a.$$typeof===r||a.$$typeof===q||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n)};exports.isAsyncMode=function(a){return v(a)||t(a)===l};exports.isConcurrentMode=v;exports.isContextConsumer=function(a){return t(a)===k};
- exports.isContextProvider=function(a){return t(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return t(a)===n};exports.isFragment=function(a){return t(a)===e};exports.isLazy=function(a){return t(a)===r};exports.isMemo=function(a){return t(a)===q};exports.isPortal=function(a){return t(a)===d};exports.isProfiler=function(a){return t(a)===g};exports.isStrictMode=function(a){return t(a)===f};
- exports.isSuspense=function(a){return t(a)===p};
- },{}],206:[function(require,module,exports){
- (function (process){
- 'use strict';
- if (process.env.NODE_ENV === 'production') {
- module.exports = require('./cjs/react-is.production.min.js');
- } else {
- module.exports = require('./cjs/react-is.development.js');
- }
- }).call(this,require('_process'))
- },{"./cjs/react-is.development.js":204,"./cjs/react-is.production.min.js":205,"_process":198}],207:[function(require,module,exports){
- module.exports = function () {
- var selection = document.getSelection();
- if (!selection.rangeCount) {
- return function () {};
- }
- var active = document.activeElement;
- var ranges = [];
- for (var i = 0; i < selection.rangeCount; i++) {
- ranges.push(selection.getRangeAt(i));
- }
- switch (active.tagName.toUpperCase()) { // .toUpperCase handles XHTML
- case 'INPUT':
- case 'TEXTAREA':
- active.blur();
- break;
- default:
- active = null;
- break;
- }
- selection.removeAllRanges();
- return function () {
- selection.type === 'Caret' &&
- selection.removeAllRanges();
- if (!selection.rangeCount) {
- ranges.forEach(function(range) {
- selection.addRange(range);
- });
- }
- active &&
- active.focus();
- };
- };
- },{}],208:[function(require,module,exports){
- module.exports=/[\0-\x1F\x7F-\x9F]/
- },{}],209:[function(require,module,exports){
- module.exports=/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/
- },{}],210:[function(require,module,exports){
- module.exports=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDF55-\uDF59]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD806[\uDC3B\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/
- },{}],211:[function(require,module,exports){
- module.exports=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/
- },{}],212:[function(require,module,exports){
- 'use strict';
- exports.Any = require('./properties/Any/regex');
- exports.Cc = require('./categories/Cc/regex');
- exports.Cf = require('./categories/Cf/regex');
- exports.P = require('./categories/P/regex');
- exports.Z = require('./categories/Z/regex');
- },{"./categories/Cc/regex":208,"./categories/Cf/regex":209,"./categories/P/regex":210,"./categories/Z/regex":211,"./properties/Any/regex":213}],213:[function(require,module,exports){
- module.exports=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/
- },{}],214:[function(require,module,exports){
- if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
- } else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
- },{}],215:[function(require,module,exports){
- module.exports = function isBuffer(arg) {
- return arg && typeof arg === 'object'
- && typeof arg.copy === 'function'
- && typeof arg.fill === 'function'
- && typeof arg.readUInt8 === 'function';
- }
- },{}],216:[function(require,module,exports){
- (function (process,global){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- var formatRegExp = /%[sdj%]/g;
- exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
- };
- // Mark that a method should not be used.
- // Returns a modified function which warns once by default.
- // If --no-deprecation is set, then it is a no-op.
- exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
- if (process.noDeprecation === true) {
- return fn;
- }
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
- return deprecated;
- };
- var debugs = {};
- var debugEnviron;
- exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
- };
- /**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
- /* legacy: obj, showHidden, depth, colors*/
- function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
- }
- exports.inspect = inspect;
- // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
- inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
- };
- // Don't use 'blue' not visible on cmd.exe
- inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
- };
- function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
- }
- function stylizeNoColor(str, styleType) {
- return str;
- }
- function arrayToHash(array) {
- var hash = {};
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
- return hash;
- }
- function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
- }
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
- var base = '', array = false, braces = ['{', '}'];
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
- ctx.seen.push(value);
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
- ctx.seen.pop();
- return reduceToSingleString(output, base, braces);
- }
- function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
- }
- function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
- }
- function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
- }
- function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
- return name + ': ' + str;
- }
- function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
- }
- // NOTE: These type checking functions intentionally don't use `instanceof`
- // because it is fragile and can be easily faked with `Object.create()`.
- function isArray(ar) {
- return Array.isArray(ar);
- }
- exports.isArray = isArray;
- function isBoolean(arg) {
- return typeof arg === 'boolean';
- }
- exports.isBoolean = isBoolean;
- function isNull(arg) {
- return arg === null;
- }
- exports.isNull = isNull;
- function isNullOrUndefined(arg) {
- return arg == null;
- }
- exports.isNullOrUndefined = isNullOrUndefined;
- function isNumber(arg) {
- return typeof arg === 'number';
- }
- exports.isNumber = isNumber;
- function isString(arg) {
- return typeof arg === 'string';
- }
- exports.isString = isString;
- function isSymbol(arg) {
- return typeof arg === 'symbol';
- }
- exports.isSymbol = isSymbol;
- function isUndefined(arg) {
- return arg === void 0;
- }
- exports.isUndefined = isUndefined;
- function isRegExp(re) {
- return isObject(re) && objectToString(re) === '[object RegExp]';
- }
- exports.isRegExp = isRegExp;
- function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
- }
- exports.isObject = isObject;
- function isDate(d) {
- return isObject(d) && objectToString(d) === '[object Date]';
- }
- exports.isDate = isDate;
- function isError(e) {
- return isObject(e) &&
- (objectToString(e) === '[object Error]' || e instanceof Error);
- }
- exports.isError = isError;
- function isFunction(arg) {
- return typeof arg === 'function';
- }
- exports.isFunction = isFunction;
- function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
- }
- exports.isPrimitive = isPrimitive;
- exports.isBuffer = require('./support/isBuffer');
- function objectToString(o) {
- return Object.prototype.toString.call(o);
- }
- function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
- }
- var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
- // 26 Feb 16:19:34
- function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
- }
- // log is just a thin wrapper to console.log that prepends a timestamp
- exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
- };
- /**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
- exports.inherits = require('inherits');
- exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
- };
- function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./support/isBuffer":215,"_process":198,"inherits":214}],217:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.DocExplorer = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _graphql = require("graphql");
- var _FieldDoc = _interopRequireDefault(require("./DocExplorer/FieldDoc"));
- var _SchemaDoc = _interopRequireDefault(require("./DocExplorer/SchemaDoc"));
- var _SearchBox = _interopRequireDefault(require("./DocExplorer/SearchBox"));
- var _SearchResults = _interopRequireDefault(require("./DocExplorer/SearchResults"));
- var _TypeDoc = _interopRequireDefault(require("./DocExplorer/TypeDoc"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var initialNav = {
- name: 'Schema',
- title: 'Documentation Explorer'
- };
- /**
- * DocExplorer
- *
- * Shows documentations for GraphQL definitions from the schema.
- *
- * Props:
- *
- * - schema: A required GraphQLSchema instance that provides GraphQL document
- * definitions.
- *
- * Children:
- *
- * - Any provided children will be positioned in the right-hand-side of the
- * top bar. Typically this will be a "close" button for temporary explorer.
- *
- */
- var DocExplorer =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(DocExplorer, _React$Component);
- function DocExplorer() {
- var _this;
- _classCallCheck(this, DocExplorer);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(DocExplorer).call(this));
- _defineProperty(_assertThisInitialized(_this), "handleNavBackClick", function () {
- if (_this.state.navStack.length > 1) {
- _this.setState({
- navStack: _this.state.navStack.slice(0, -1)
- });
- }
- });
- _defineProperty(_assertThisInitialized(_this), "handleClickTypeOrField", function (typeOrField) {
- _this.showDoc(typeOrField);
- });
- _defineProperty(_assertThisInitialized(_this), "handleSearch", function (value) {
- _this.showSearch(value);
- });
- _this.state = {
- navStack: [initialNav]
- };
- return _this;
- }
- _createClass(DocExplorer, [{
- key: "shouldComponentUpdate",
- value: function shouldComponentUpdate(nextProps, nextState) {
- return this.props.schema !== nextProps.schema || this.state.navStack !== nextState.navStack;
- }
- }, {
- key: "render",
- value: function render() {
- var schema = this.props.schema;
- var navStack = this.state.navStack;
- var navItem = navStack[navStack.length - 1];
- var content;
- if (schema === undefined) {
- // Schema is undefined when it is being loaded via introspection.
- content = _react.default.createElement("div", {
- className: "spinner-container"
- }, _react.default.createElement("div", {
- className: "spinner"
- }));
- } else if (!schema) {
- // Schema is null when it explicitly does not exist, typically due to
- // an error during introspection.
- content = _react.default.createElement("div", {
- className: "error-container"
- }, 'No Schema Available');
- } else if (navItem.search) {
- content = _react.default.createElement(_SearchResults.default, {
- searchValue: navItem.search,
- withinType: navItem.def,
- schema: schema,
- onClickType: this.handleClickTypeOrField,
- onClickField: this.handleClickTypeOrField
- });
- } else if (navStack.length === 1) {
- content = _react.default.createElement(_SchemaDoc.default, {
- schema: schema,
- onClickType: this.handleClickTypeOrField
- });
- } else if ((0, _graphql.isType)(navItem.def)) {
- content = _react.default.createElement(_TypeDoc.default, {
- schema: schema,
- type: navItem.def,
- onClickType: this.handleClickTypeOrField,
- onClickField: this.handleClickTypeOrField
- });
- } else {
- content = _react.default.createElement(_FieldDoc.default, {
- field: navItem.def,
- onClickType: this.handleClickTypeOrField
- });
- }
- var shouldSearchBoxAppear = navStack.length === 1 || (0, _graphql.isType)(navItem.def) && navItem.def.getFields;
- var prevName;
- if (navStack.length > 1) {
- prevName = navStack[navStack.length - 2].name;
- }
- return _react.default.createElement("div", {
- className: "doc-explorer",
- key: navItem.name
- }, _react.default.createElement("div", {
- className: "doc-explorer-title-bar"
- }, prevName && _react.default.createElement("div", {
- className: "doc-explorer-back",
- onClick: this.handleNavBackClick
- }, prevName), _react.default.createElement("div", {
- className: "doc-explorer-title"
- }, navItem.title || navItem.name), _react.default.createElement("div", {
- className: "doc-explorer-rhs"
- }, this.props.children)), _react.default.createElement("div", {
- className: "doc-explorer-contents"
- }, shouldSearchBoxAppear && _react.default.createElement(_SearchBox.default, {
- value: navItem.search,
- placeholder: "Search ".concat(navItem.name, "..."),
- onSearch: this.handleSearch
- }), content));
- } // Public API
- }, {
- key: "showDoc",
- value: function showDoc(typeOrField) {
- var navStack = this.state.navStack;
- var topNav = navStack[navStack.length - 1];
- if (topNav.def !== typeOrField) {
- this.setState({
- navStack: navStack.concat([{
- name: typeOrField.name,
- def: typeOrField
- }])
- });
- }
- } // Public API
- }, {
- key: "showDocForReference",
- value: function showDocForReference(reference) {
- if (reference.kind === 'Type') {
- this.showDoc(reference.type);
- } else if (reference.kind === 'Field') {
- this.showDoc(reference.field);
- } else if (reference.kind === 'Argument' && reference.field) {
- this.showDoc(reference.field);
- } else if (reference.kind === 'EnumValue' && reference.type) {
- this.showDoc(reference.type);
- }
- } // Public API
- }, {
- key: "showSearch",
- value: function showSearch(search) {
- var navStack = this.state.navStack.slice();
- var topNav = navStack[navStack.length - 1];
- navStack[navStack.length - 1] = _objectSpread({}, topNav, {
- search: search
- });
- this.setState({
- navStack: navStack
- });
- }
- }, {
- key: "reset",
- value: function reset() {
- this.setState({
- navStack: [initialNav]
- });
- }
- }]);
- return DocExplorer;
- }(_react.default.Component);
- exports.DocExplorer = DocExplorer;
- _defineProperty(DocExplorer, "propTypes", {
- schema: _propTypes.default.instanceOf(_graphql.GraphQLSchema)
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./DocExplorer/FieldDoc":220,"./DocExplorer/SchemaDoc":222,"./DocExplorer/SearchBox":223,"./DocExplorer/SearchResults":224,"./DocExplorer/TypeDoc":225,"graphql":29,"prop-types":202}],218:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = Argument;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _TypeLink = _interopRequireDefault(require("./TypeLink"));
- var _DefaultValue = _interopRequireDefault(require("./DefaultValue"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- function Argument(_ref) {
- var arg = _ref.arg,
- onClickType = _ref.onClickType,
- showDefaultValue = _ref.showDefaultValue;
- return _react.default.createElement("span", {
- className: "arg"
- }, _react.default.createElement("span", {
- className: "arg-name"
- }, arg.name), ': ', _react.default.createElement(_TypeLink.default, {
- type: arg.type,
- onClick: onClickType
- }), showDefaultValue !== false && _react.default.createElement(_DefaultValue.default, {
- field: arg
- }));
- }
- Argument.propTypes = {
- arg: _propTypes.default.object.isRequired,
- onClickType: _propTypes.default.func.isRequired,
- showDefaultValue: _propTypes.default.bool
- };
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./DefaultValue":219,"./TypeLink":226,"prop-types":202}],219:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = DefaultValue;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _graphql = require("graphql");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- function DefaultValue(_ref) {
- var field = _ref.field;
- var type = field.type,
- defaultValue = field.defaultValue;
- if (defaultValue !== undefined) {
- return _react.default.createElement("span", null, ' = ', _react.default.createElement("span", {
- className: "arg-default-value"
- }, (0, _graphql.print)((0, _graphql.astFromValue)(defaultValue, type))));
- }
- return null;
- }
- DefaultValue.propTypes = {
- field: _propTypes.default.object.isRequired
- };
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"graphql":29,"prop-types":202}],220:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _Argument = _interopRequireDefault(require("./Argument"));
- var _MarkdownContent = _interopRequireDefault(require("./MarkdownContent"));
- var _TypeLink = _interopRequireDefault(require("./TypeLink"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var FieldDoc =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(FieldDoc, _React$Component);
- function FieldDoc() {
- _classCallCheck(this, FieldDoc);
- return _possibleConstructorReturn(this, _getPrototypeOf(FieldDoc).apply(this, arguments));
- }
- _createClass(FieldDoc, [{
- key: "shouldComponentUpdate",
- value: function shouldComponentUpdate(nextProps) {
- return this.props.field !== nextProps.field;
- }
- }, {
- key: "render",
- value: function render() {
- var _this = this;
- var field = this.props.field;
- var argsDef;
- if (field.args && field.args.length > 0) {
- argsDef = _react.default.createElement("div", {
- className: "doc-category"
- }, _react.default.createElement("div", {
- className: "doc-category-title"
- }, 'arguments'), field.args.map(function (arg) {
- return _react.default.createElement("div", {
- key: arg.name,
- className: "doc-category-item"
- }, _react.default.createElement("div", null, _react.default.createElement(_Argument.default, {
- arg: arg,
- onClickType: _this.props.onClickType
- })), _react.default.createElement(_MarkdownContent.default, {
- className: "doc-value-description",
- markdown: arg.description
- }));
- }));
- }
- return _react.default.createElement("div", null, _react.default.createElement(_MarkdownContent.default, {
- className: "doc-type-description",
- markdown: field.description || 'No Description'
- }), field.deprecationReason && _react.default.createElement(_MarkdownContent.default, {
- className: "doc-deprecation",
- markdown: field.deprecationReason
- }), _react.default.createElement("div", {
- className: "doc-category"
- }, _react.default.createElement("div", {
- className: "doc-category-title"
- }, 'type'), _react.default.createElement(_TypeLink.default, {
- type: field.type,
- onClick: this.props.onClickType
- })), argsDef);
- }
- }]);
- return FieldDoc;
- }(_react.default.Component);
- exports.default = FieldDoc;
- _defineProperty(FieldDoc, "propTypes", {
- field: _propTypes.default.object,
- onClickType: _propTypes.default.func
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./Argument":218,"./MarkdownContent":221,"./TypeLink":226,"prop-types":202}],221:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _markdownIt = _interopRequireDefault(require("markdown-it"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var md = new _markdownIt.default();
- var MarkdownContent =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(MarkdownContent, _React$Component);
- function MarkdownContent() {
- _classCallCheck(this, MarkdownContent);
- return _possibleConstructorReturn(this, _getPrototypeOf(MarkdownContent).apply(this, arguments));
- }
- _createClass(MarkdownContent, [{
- key: "shouldComponentUpdate",
- value: function shouldComponentUpdate(nextProps) {
- return this.props.markdown !== nextProps.markdown;
- }
- }, {
- key: "render",
- value: function render() {
- var markdown = this.props.markdown;
- if (!markdown) {
- return _react.default.createElement("div", null);
- }
- return _react.default.createElement("div", {
- className: this.props.className,
- dangerouslySetInnerHTML: {
- __html: md.render(markdown)
- }
- });
- }
- }]);
- return MarkdownContent;
- }(_react.default.Component);
- exports.default = MarkdownContent;
- _defineProperty(MarkdownContent, "propTypes", {
- markdown: _propTypes.default.string,
- className: _propTypes.default.string
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"markdown-it":140,"prop-types":202}],222:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _TypeLink = _interopRequireDefault(require("./TypeLink"));
- var _MarkdownContent = _interopRequireDefault(require("./MarkdownContent"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- // Render the top level Schema
- var SchemaDoc =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(SchemaDoc, _React$Component);
- function SchemaDoc() {
- _classCallCheck(this, SchemaDoc);
- return _possibleConstructorReturn(this, _getPrototypeOf(SchemaDoc).apply(this, arguments));
- }
- _createClass(SchemaDoc, [{
- key: "shouldComponentUpdate",
- value: function shouldComponentUpdate(nextProps) {
- return this.props.schema !== nextProps.schema;
- }
- }, {
- key: "render",
- value: function render() {
- var schema = this.props.schema;
- var queryType = schema.getQueryType();
- var mutationType = schema.getMutationType && schema.getMutationType();
- var subscriptionType = schema.getSubscriptionType && schema.getSubscriptionType();
- return _react.default.createElement("div", null, _react.default.createElement(_MarkdownContent.default, {
- className: "doc-type-description",
- markdown: 'A GraphQL schema provides a root type for each kind of operation.'
- }), _react.default.createElement("div", {
- className: "doc-category"
- }, _react.default.createElement("div", {
- className: "doc-category-title"
- }, 'root types'), _react.default.createElement("div", {
- className: "doc-category-item"
- }, _react.default.createElement("span", {
- className: "keyword"
- }, 'query'), ': ', _react.default.createElement(_TypeLink.default, {
- type: queryType,
- onClick: this.props.onClickType
- })), mutationType && _react.default.createElement("div", {
- className: "doc-category-item"
- }, _react.default.createElement("span", {
- className: "keyword"
- }, 'mutation'), ': ', _react.default.createElement(_TypeLink.default, {
- type: mutationType,
- onClick: this.props.onClickType
- })), subscriptionType && _react.default.createElement("div", {
- className: "doc-category-item"
- }, _react.default.createElement("span", {
- className: "keyword"
- }, 'subscription'), ': ', _react.default.createElement(_TypeLink.default, {
- type: subscriptionType,
- onClick: this.props.onClickType
- }))));
- }
- }]);
- return SchemaDoc;
- }(_react.default.Component);
- exports.default = SchemaDoc;
- _defineProperty(SchemaDoc, "propTypes", {
- schema: _propTypes.default.object,
- onClickType: _propTypes.default.func
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./MarkdownContent":221,"./TypeLink":226,"prop-types":202}],223:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _debounce = _interopRequireDefault(require("../../utility/debounce"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var SearchBox =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(SearchBox, _React$Component);
- function SearchBox(props) {
- var _this;
- _classCallCheck(this, SearchBox);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(SearchBox).call(this, props));
- _defineProperty(_assertThisInitialized(_this), "handleChange", function (event) {
- var value = event.target.value;
- _this.setState({
- value: value
- });
- _this.debouncedOnSearch(value);
- });
- _defineProperty(_assertThisInitialized(_this), "handleClear", function () {
- _this.setState({
- value: ''
- });
- _this.props.onSearch('');
- });
- _this.state = {
- value: props.value || ''
- };
- _this.debouncedOnSearch = (0, _debounce.default)(200, _this.props.onSearch);
- return _this;
- }
- _createClass(SearchBox, [{
- key: "render",
- value: function render() {
- return _react.default.createElement("label", {
- className: "search-box"
- }, _react.default.createElement("input", {
- value: this.state.value,
- onChange: this.handleChange,
- type: "text",
- placeholder: this.props.placeholder
- }), this.state.value && _react.default.createElement("div", {
- className: "search-box-clear",
- onClick: this.handleClear
- }, "\u2715"));
- }
- }]);
- return SearchBox;
- }(_react.default.Component);
- exports.default = SearchBox;
- _defineProperty(SearchBox, "propTypes", {
- value: _propTypes.default.string,
- placeholder: _propTypes.default.string,
- onSearch: _propTypes.default.func
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"../../utility/debounce":243,"prop-types":202}],224:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _Argument = _interopRequireDefault(require("./Argument"));
- var _TypeLink = _interopRequireDefault(require("./TypeLink"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var SearchResults =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(SearchResults, _React$Component);
- function SearchResults() {
- _classCallCheck(this, SearchResults);
- return _possibleConstructorReturn(this, _getPrototypeOf(SearchResults).apply(this, arguments));
- }
- _createClass(SearchResults, [{
- key: "shouldComponentUpdate",
- value: function shouldComponentUpdate(nextProps) {
- return this.props.schema !== nextProps.schema || this.props.searchValue !== nextProps.searchValue;
- }
- }, {
- key: "render",
- value: function render() {
- var searchValue = this.props.searchValue;
- var withinType = this.props.withinType;
- var schema = this.props.schema;
- var onClickType = this.props.onClickType;
- var onClickField = this.props.onClickField;
- var matchedWithin = [];
- var matchedTypes = [];
- var matchedFields = [];
- var typeMap = schema.getTypeMap();
- var typeNames = Object.keys(typeMap); // Move the within type name to be the first searched.
- if (withinType) {
- typeNames = typeNames.filter(function (n) {
- return n !== withinType.name;
- });
- typeNames.unshift(withinType.name);
- }
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- var _loop = function _loop() {
- var typeName = _step.value;
- if (matchedWithin.length + matchedTypes.length + matchedFields.length >= 100) {
- return "break";
- }
- var type = typeMap[typeName];
- if (withinType !== type && isMatch(typeName, searchValue)) {
- matchedTypes.push(_react.default.createElement("div", {
- className: "doc-category-item",
- key: typeName
- }, _react.default.createElement(_TypeLink.default, {
- type: type,
- onClick: onClickType
- })));
- }
- if (type.getFields) {
- var fields = type.getFields();
- Object.keys(fields).forEach(function (fieldName) {
- var field = fields[fieldName];
- var matchingArgs;
- if (!isMatch(fieldName, searchValue)) {
- if (field.args && field.args.length) {
- matchingArgs = field.args.filter(function (arg) {
- return isMatch(arg.name, searchValue);
- });
- if (matchingArgs.length === 0) {
- return;
- }
- } else {
- return;
- }
- }
- var match = _react.default.createElement("div", {
- className: "doc-category-item",
- key: typeName + '.' + fieldName
- }, withinType !== type && [_react.default.createElement(_TypeLink.default, {
- key: "type",
- type: type,
- onClick: onClickType
- }), '.'], _react.default.createElement("a", {
- className: "field-name",
- onClick: function onClick(event) {
- return onClickField(field, type, event);
- }
- }, field.name), matchingArgs && ['(', _react.default.createElement("span", {
- key: "args"
- }, matchingArgs.map(function (arg) {
- return _react.default.createElement(_Argument.default, {
- key: arg.name,
- arg: arg,
- onClickType: onClickType,
- showDefaultValue: false
- });
- })), ')']);
- if (withinType === type) {
- matchedWithin.push(match);
- } else {
- matchedFields.push(match);
- }
- });
- }
- };
- for (var _iterator = typeNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ret = _loop();
- if (_ret === "break") break;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- if (matchedWithin.length + matchedTypes.length + matchedFields.length === 0) {
- return _react.default.createElement("span", {
- className: "doc-alert-text"
- }, 'No results found.');
- }
- if (withinType && matchedTypes.length + matchedFields.length > 0) {
- return _react.default.createElement("div", null, matchedWithin, _react.default.createElement("div", {
- className: "doc-category"
- }, _react.default.createElement("div", {
- className: "doc-category-title"
- }, 'other results'), matchedTypes, matchedFields));
- }
- return _react.default.createElement("div", null, matchedWithin, matchedTypes, matchedFields);
- }
- }]);
- return SearchResults;
- }(_react.default.Component);
- exports.default = SearchResults;
- _defineProperty(SearchResults, "propTypes", {
- schema: _propTypes.default.object,
- withinType: _propTypes.default.object,
- searchValue: _propTypes.default.string,
- onClickType: _propTypes.default.func,
- onClickField: _propTypes.default.func
- });
- function isMatch(sourceText, searchValue) {
- try {
- var escaped = searchValue.replace(/[^_0-9A-Za-z]/g, function (ch) {
- return '\\' + ch;
- });
- return sourceText.search(new RegExp(escaped, 'i')) !== -1;
- } catch (e) {
- return sourceText.toLowerCase().indexOf(searchValue.toLowerCase()) !== -1;
- }
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./Argument":218,"./TypeLink":226,"prop-types":202}],225:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _graphql = require("graphql");
- var _Argument = _interopRequireDefault(require("./Argument"));
- var _MarkdownContent = _interopRequireDefault(require("./MarkdownContent"));
- var _TypeLink = _interopRequireDefault(require("./TypeLink"));
- var _DefaultValue = _interopRequireDefault(require("./DefaultValue"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var TypeDoc =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(TypeDoc, _React$Component);
- function TypeDoc(props) {
- var _this;
- _classCallCheck(this, TypeDoc);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(TypeDoc).call(this, props));
- _defineProperty(_assertThisInitialized(_this), "handleShowDeprecated", function () {
- return _this.setState({
- showDeprecated: true
- });
- });
- _this.state = {
- showDeprecated: false
- };
- return _this;
- }
- _createClass(TypeDoc, [{
- key: "shouldComponentUpdate",
- value: function shouldComponentUpdate(nextProps, nextState) {
- return this.props.type !== nextProps.type || this.props.schema !== nextProps.schema || this.state.showDeprecated !== nextState.showDeprecated;
- }
- }, {
- key: "render",
- value: function render() {
- var schema = this.props.schema;
- var type = this.props.type;
- var onClickType = this.props.onClickType;
- var onClickField = this.props.onClickField;
- var typesTitle;
- var types;
- if (type instanceof _graphql.GraphQLUnionType) {
- typesTitle = 'possible types';
- types = schema.getPossibleTypes(type);
- } else if (type instanceof _graphql.GraphQLInterfaceType) {
- typesTitle = 'implementations';
- types = schema.getPossibleTypes(type);
- } else if (type instanceof _graphql.GraphQLObjectType) {
- typesTitle = 'implements';
- types = type.getInterfaces();
- }
- var typesDef;
- if (types && types.length > 0) {
- typesDef = _react.default.createElement("div", {
- className: "doc-category"
- }, _react.default.createElement("div", {
- className: "doc-category-title"
- }, typesTitle), types.map(function (subtype) {
- return _react.default.createElement("div", {
- key: subtype.name,
- className: "doc-category-item"
- }, _react.default.createElement(_TypeLink.default, {
- type: subtype,
- onClick: onClickType
- }));
- }));
- } // InputObject and Object
- var fieldsDef;
- var deprecatedFieldsDef;
- if (type.getFields) {
- var fieldMap = type.getFields();
- var fields = Object.keys(fieldMap).map(function (name) {
- return fieldMap[name];
- });
- fieldsDef = _react.default.createElement("div", {
- className: "doc-category"
- }, _react.default.createElement("div", {
- className: "doc-category-title"
- }, 'fields'), fields.filter(function (field) {
- return !field.isDeprecated;
- }).map(function (field) {
- return _react.default.createElement(Field, {
- key: field.name,
- type: type,
- field: field,
- onClickType: onClickType,
- onClickField: onClickField
- });
- }));
- var deprecatedFields = fields.filter(function (field) {
- return field.isDeprecated;
- });
- if (deprecatedFields.length > 0) {
- deprecatedFieldsDef = _react.default.createElement("div", {
- className: "doc-category"
- }, _react.default.createElement("div", {
- className: "doc-category-title"
- }, 'deprecated fields'), !this.state.showDeprecated ? _react.default.createElement("button", {
- className: "show-btn",
- onClick: this.handleShowDeprecated
- }, 'Show deprecated fields...') : deprecatedFields.map(function (field) {
- return _react.default.createElement(Field, {
- key: field.name,
- type: type,
- field: field,
- onClickType: onClickType,
- onClickField: onClickField
- });
- }));
- }
- }
- var valuesDef;
- var deprecatedValuesDef;
- if (type instanceof _graphql.GraphQLEnumType) {
- var values = type.getValues();
- valuesDef = _react.default.createElement("div", {
- className: "doc-category"
- }, _react.default.createElement("div", {
- className: "doc-category-title"
- }, 'values'), values.filter(function (value) {
- return !value.isDeprecated;
- }).map(function (value) {
- return _react.default.createElement(EnumValue, {
- key: value.name,
- value: value
- });
- }));
- var deprecatedValues = values.filter(function (value) {
- return value.isDeprecated;
- });
- if (deprecatedValues.length > 0) {
- deprecatedValuesDef = _react.default.createElement("div", {
- className: "doc-category"
- }, _react.default.createElement("div", {
- className: "doc-category-title"
- }, 'deprecated values'), !this.state.showDeprecated ? _react.default.createElement("button", {
- className: "show-btn",
- onClick: this.handleShowDeprecated
- }, 'Show deprecated values...') : deprecatedValues.map(function (value) {
- return _react.default.createElement(EnumValue, {
- key: value.name,
- value: value
- });
- }));
- }
- }
- return _react.default.createElement("div", null, _react.default.createElement(_MarkdownContent.default, {
- className: "doc-type-description",
- markdown: type.description || 'No Description'
- }), type instanceof _graphql.GraphQLObjectType && typesDef, fieldsDef, deprecatedFieldsDef, valuesDef, deprecatedValuesDef, !(type instanceof _graphql.GraphQLObjectType) && typesDef);
- }
- }]);
- return TypeDoc;
- }(_react.default.Component);
- exports.default = TypeDoc;
- _defineProperty(TypeDoc, "propTypes", {
- schema: _propTypes.default.instanceOf(_graphql.GraphQLSchema),
- type: _propTypes.default.object,
- onClickType: _propTypes.default.func,
- onClickField: _propTypes.default.func
- });
- function Field(_ref) {
- var type = _ref.type,
- field = _ref.field,
- onClickType = _ref.onClickType,
- onClickField = _ref.onClickField;
- return _react.default.createElement("div", {
- className: "doc-category-item"
- }, _react.default.createElement("a", {
- className: "field-name",
- onClick: function onClick(event) {
- return onClickField(field, type, event);
- }
- }, field.name), field.args && field.args.length > 0 && ['(', _react.default.createElement("span", {
- key: "args"
- }, field.args.map(function (arg) {
- return _react.default.createElement(_Argument.default, {
- key: arg.name,
- arg: arg,
- onClickType: onClickType
- });
- })), ')'], ': ', _react.default.createElement(_TypeLink.default, {
- type: field.type,
- onClick: onClickType
- }), _react.default.createElement(_DefaultValue.default, {
- field: field
- }), field.description && _react.default.createElement(_MarkdownContent.default, {
- className: "field-short-description",
- markdown: field.description
- }), field.deprecationReason && _react.default.createElement(_MarkdownContent.default, {
- className: "doc-deprecation",
- markdown: field.deprecationReason
- }));
- }
- Field.propTypes = {
- type: _propTypes.default.object,
- field: _propTypes.default.object,
- onClickType: _propTypes.default.func,
- onClickField: _propTypes.default.func
- };
- function EnumValue(_ref2) {
- var value = _ref2.value;
- return _react.default.createElement("div", {
- className: "doc-category-item"
- }, _react.default.createElement("div", {
- className: "enum-value"
- }, value.name), _react.default.createElement(_MarkdownContent.default, {
- className: "doc-value-description",
- markdown: value.description
- }), value.deprecationReason && _react.default.createElement(_MarkdownContent.default, {
- className: "doc-deprecation",
- markdown: value.deprecationReason
- }));
- }
- EnumValue.propTypes = {
- value: _propTypes.default.object
- };
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./Argument":218,"./DefaultValue":219,"./MarkdownContent":221,"./TypeLink":226,"graphql":29,"prop-types":202}],226:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _graphql = require("graphql");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var TypeLink =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(TypeLink, _React$Component);
- function TypeLink() {
- _classCallCheck(this, TypeLink);
- return _possibleConstructorReturn(this, _getPrototypeOf(TypeLink).apply(this, arguments));
- }
- _createClass(TypeLink, [{
- key: "shouldComponentUpdate",
- value: function shouldComponentUpdate(nextProps) {
- return this.props.type !== nextProps.type;
- }
- }, {
- key: "render",
- value: function render() {
- return renderType(this.props.type, this.props.onClick);
- }
- }]);
- return TypeLink;
- }(_react.default.Component);
- exports.default = TypeLink;
- _defineProperty(TypeLink, "propTypes", {
- type: _propTypes.default.object,
- onClick: _propTypes.default.func
- });
- function renderType(type, _onClick) {
- if (type instanceof _graphql.GraphQLNonNull) {
- return _react.default.createElement("span", null, renderType(type.ofType, _onClick), '!');
- }
- if (type instanceof _graphql.GraphQLList) {
- return _react.default.createElement("span", null, '[', renderType(type.ofType, _onClick), ']');
- }
- return _react.default.createElement("a", {
- className: "type-name",
- onClick: function onClick(event) {
- return _onClick(type, event);
- }
- }, type.name);
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"graphql":29,"prop-types":202}],227:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ExecuteButton = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * ExecuteButton
- *
- * What a nice round shiny button. Shows a drop-down when there are multiple
- * queries to run.
- */
- var ExecuteButton =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(ExecuteButton, _React$Component);
- function ExecuteButton(props) {
- var _this;
- _classCallCheck(this, ExecuteButton);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(ExecuteButton).call(this, props));
- _defineProperty(_assertThisInitialized(_this), "_onClick", function () {
- if (_this.props.isRunning) {
- _this.props.onStop();
- } else {
- _this.props.onRun();
- }
- });
- _defineProperty(_assertThisInitialized(_this), "_onOptionSelected", function (operation) {
- _this.setState({
- optionsOpen: false
- });
- _this.props.onRun(operation.name && operation.name.value);
- });
- _defineProperty(_assertThisInitialized(_this), "_onOptionsOpen", function (downEvent) {
- var initialPress = true;
- var downTarget = downEvent.target;
- _this.setState({
- highlight: null,
- optionsOpen: true
- });
- var _onMouseUp = function onMouseUp(upEvent) {
- if (initialPress && upEvent.target === downTarget) {
- initialPress = false;
- } else {
- document.removeEventListener('mouseup', _onMouseUp);
- _onMouseUp = null;
- var isOptionsMenuClicked = downTarget.parentNode.compareDocumentPosition(upEvent.target) & Node.DOCUMENT_POSITION_CONTAINED_BY;
- if (!isOptionsMenuClicked) {
- // menu calls setState if it was clicked
- _this.setState({
- optionsOpen: false
- });
- }
- }
- };
- document.addEventListener('mouseup', _onMouseUp);
- });
- _this.state = {
- optionsOpen: false,
- highlight: null
- };
- return _this;
- }
- _createClass(ExecuteButton, [{
- key: "render",
- value: function render() {
- var _this2 = this;
- var operations = this.props.operations;
- var optionsOpen = this.state.optionsOpen;
- var hasOptions = operations && operations.length > 1;
- var options = null;
- if (hasOptions && optionsOpen) {
- var highlight = this.state.highlight;
- options = _react.default.createElement("ul", {
- className: "execute-options"
- }, operations.map(function (operation) {
- return _react.default.createElement("li", {
- key: operation.name ? operation.name.value : '*',
- className: operation === highlight ? 'selected' : undefined,
- onMouseOver: function onMouseOver() {
- return _this2.setState({
- highlight: operation
- });
- },
- onMouseOut: function onMouseOut() {
- return _this2.setState({
- highlight: null
- });
- },
- onMouseUp: function onMouseUp() {
- return _this2._onOptionSelected(operation);
- }
- }, operation.name ? operation.name.value : '<Unnamed>');
- }));
- } // Allow click event if there is a running query or if there are not options
- // for which operation to run.
- var onClick;
- if (this.props.isRunning || !hasOptions) {
- onClick = this._onClick;
- } // Allow mouse down if there is no running query, there are options for
- // which operation to run, and the dropdown is currently closed.
- var onMouseDown;
- if (!this.props.isRunning && hasOptions && !optionsOpen) {
- onMouseDown = this._onOptionsOpen;
- }
- var pathJSX = this.props.isRunning ? _react.default.createElement("path", {
- d: "M 10 10 L 23 10 L 23 23 L 10 23 z"
- }) : _react.default.createElement("path", {
- d: "M 11 9 L 24 16 L 11 23 z"
- });
- return _react.default.createElement("div", {
- className: "execute-button-wrap"
- }, _react.default.createElement("button", {
- type: "button",
- className: "execute-button",
- onMouseDown: onMouseDown,
- onClick: onClick,
- title: "Execute Query (Ctrl-Enter)"
- }, _react.default.createElement("svg", {
- width: "34",
- height: "34"
- }, pathJSX)), options);
- }
- }]);
- return ExecuteButton;
- }(_react.default.Component);
- exports.ExecuteButton = ExecuteButton;
- _defineProperty(ExecuteButton, "propTypes", {
- onRun: _propTypes.default.func,
- onStop: _propTypes.default.func,
- isRunning: _propTypes.default.bool,
- operations: _propTypes.default.array
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"prop-types":202}],228:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.GraphiQL = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _reactDom = _interopRequireDefault((typeof window !== "undefined" ? window['ReactDOM'] : typeof global !== "undefined" ? global['ReactDOM'] : null));
- var _graphql = require("graphql");
- var _copyToClipboard = _interopRequireDefault(require("copy-to-clipboard"));
- var _ExecuteButton = require("./ExecuteButton");
- var _ImagePreview = require("./ImagePreview");
- var _ToolbarButton = require("./ToolbarButton");
- var _ToolbarGroup = require("./ToolbarGroup");
- var _ToolbarMenu = require("./ToolbarMenu");
- var _ToolbarSelect = require("./ToolbarSelect");
- var _QueryEditor = require("./QueryEditor");
- var _VariableEditor = require("./VariableEditor");
- var _ResultViewer = require("./ResultViewer");
- var _DocExplorer = require("./DocExplorer");
- var _QueryHistory = require("./QueryHistory");
- var _CodeMirrorSizer = _interopRequireDefault(require("../utility/CodeMirrorSizer"));
- var _StorageAPI = _interopRequireDefault(require("../utility/StorageAPI"));
- var _getQueryFacts = _interopRequireDefault(require("../utility/getQueryFacts"));
- var _getSelectedOperationName = _interopRequireDefault(require("../utility/getSelectedOperationName"));
- var _debounce = _interopRequireDefault(require("../utility/debounce"));
- var _find = _interopRequireDefault(require("../utility/find"));
- var _fillLeafs2 = require("../utility/fillLeafs");
- var _elementPosition = require("../utility/elementPosition");
- var _mergeAst = require("../utility/mergeAst");
- var _introspectionQueries = require("../utility/introspectionQueries");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var DEFAULT_DOC_EXPLORER_WIDTH = 350;
- /**
- * The top-level React component for GraphiQL, intended to encompass the entire
- * browser viewport.
- *
- * @see https://github.com/graphql/graphiql#usage
- */
- var GraphiQL =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(GraphiQL, _React$Component);
- function GraphiQL(props) {
- var _this;
- _classCallCheck(this, GraphiQL);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(GraphiQL).call(this, props)); // Ensure props are correct
- _defineProperty(_assertThisInitialized(_this), "handleClickReference", function (reference) {
- _this.setState({
- docExplorerOpen: true
- }, function () {
- _this.docExplorerComponent.showDocForReference(reference);
- });
- });
- _defineProperty(_assertThisInitialized(_this), "handleRunQuery", function (selectedOperationName) {
- _this._editorQueryID++;
- var queryID = _this._editorQueryID; // Use the edited query after autoCompleteLeafs() runs or,
- // in case autoCompletion fails (the function returns undefined),
- // the current query from the editor.
- var editedQuery = _this.autoCompleteLeafs() || _this.state.query;
- var variables = _this.state.variables;
- var operationName = _this.state.operationName; // If an operation was explicitly provided, different from the current
- // operation name, then report that it changed.
- if (selectedOperationName && selectedOperationName !== operationName) {
- operationName = selectedOperationName;
- _this.handleEditOperationName(operationName);
- }
- try {
- _this.setState({
- isWaitingForResponse: true,
- response: null,
- operationName: operationName
- }); // _fetchQuery may return a subscription.
- var subscription = _this._fetchQuery(editedQuery, variables, operationName, function (result) {
- if (queryID === _this._editorQueryID) {
- _this.setState({
- isWaitingForResponse: false,
- response: JSON.stringify(result, null, 2)
- });
- }
- });
- _this.setState({
- subscription: subscription
- });
- } catch (error) {
- _this.setState({
- isWaitingForResponse: false,
- response: error.message
- });
- }
- });
- _defineProperty(_assertThisInitialized(_this), "handleStopQuery", function () {
- var subscription = _this.state.subscription;
- _this.setState({
- isWaitingForResponse: false,
- subscription: null
- });
- if (subscription) {
- subscription.unsubscribe();
- }
- });
- _defineProperty(_assertThisInitialized(_this), "handlePrettifyQuery", function () {
- var editor = _this.getQueryEditor();
- editor.setValue((0, _graphql.print)((0, _graphql.parse)(editor.getValue())));
- });
- _defineProperty(_assertThisInitialized(_this), "handleMergeQuery", function () {
- var editor = _this.getQueryEditor();
- var query = editor.getValue();
- if (!query) {
- return;
- }
- var ast = (0, _graphql.parse)(query);
- editor.setValue((0, _graphql.print)((0, _mergeAst.mergeAst)(ast)));
- });
- _defineProperty(_assertThisInitialized(_this), "handleEditQuery", (0, _debounce.default)(100, function (value) {
- var queryFacts = _this._updateQueryFacts(value, _this.state.operationName, _this.state.operations, _this.state.schema);
- _this.setState(_objectSpread({
- query: value
- }, queryFacts));
- if (_this.props.onEditQuery) {
- return _this.props.onEditQuery(value);
- }
- }));
- _defineProperty(_assertThisInitialized(_this), "handleCopyQuery", function () {
- var editor = _this.getQueryEditor();
- var query = editor.getValue();
- if (!query) {
- return;
- }
- (0, _copyToClipboard.default)(query);
- if (_this.props.onCopyQuery) {
- return _this.props.onCopyQuery(query);
- }
- });
- _defineProperty(_assertThisInitialized(_this), "_updateQueryFacts", function (query, operationName, prevOperations, schema) {
- var queryFacts = (0, _getQueryFacts.default)(schema, query);
- if (queryFacts) {
- // Update operation name should any query names change.
- var updatedOperationName = (0, _getSelectedOperationName.default)(prevOperations, operationName, queryFacts.operations); // Report changing of operationName if it changed.
- var onEditOperationName = _this.props.onEditOperationName;
- if (onEditOperationName && operationName !== updatedOperationName) {
- onEditOperationName(updatedOperationName);
- }
- return _objectSpread({
- operationName: updatedOperationName
- }, queryFacts);
- }
- });
- _defineProperty(_assertThisInitialized(_this), "handleEditVariables", function (value) {
- _this.setState({
- variables: value
- });
- if (_this.props.onEditVariables) {
- _this.props.onEditVariables(value);
- }
- });
- _defineProperty(_assertThisInitialized(_this), "handleEditOperationName", function (operationName) {
- var onEditOperationName = _this.props.onEditOperationName;
- if (onEditOperationName) {
- onEditOperationName(operationName);
- }
- });
- _defineProperty(_assertThisInitialized(_this), "handleHintInformationRender", function (elem) {
- elem.addEventListener('click', _this._onClickHintInformation);
- var _onRemoveFn;
- elem.addEventListener('DOMNodeRemoved', _onRemoveFn = function onRemoveFn() {
- elem.removeEventListener('DOMNodeRemoved', _onRemoveFn);
- elem.removeEventListener('click', _this._onClickHintInformation);
- });
- });
- _defineProperty(_assertThisInitialized(_this), "handleEditorRunQuery", function () {
- _this._runQueryAtCursor();
- });
- _defineProperty(_assertThisInitialized(_this), "_onClickHintInformation", function (event) {
- if (event.target.className === 'typeName') {
- var typeName = event.target.innerHTML;
- var schema = _this.state.schema;
- if (schema) {
- var type = schema.getType(typeName);
- if (type) {
- _this.setState({
- docExplorerOpen: true
- }, function () {
- _this.docExplorerComponent.showDoc(type);
- });
- }
- }
- }
- });
- _defineProperty(_assertThisInitialized(_this), "handleToggleDocs", function () {
- if (typeof _this.props.onToggleDocs === 'function') {
- _this.props.onToggleDocs(!_this.state.docExplorerOpen);
- }
- _this.setState({
- docExplorerOpen: !_this.state.docExplorerOpen
- });
- });
- _defineProperty(_assertThisInitialized(_this), "handleToggleHistory", function () {
- if (typeof _this.props.onToggleHistory === 'function') {
- _this.props.onToggleHistory(!_this.state.historyPaneOpen);
- }
- _this.setState({
- historyPaneOpen: !_this.state.historyPaneOpen
- });
- });
- _defineProperty(_assertThisInitialized(_this), "handleSelectHistoryQuery", function (query, variables, operationName) {
- _this.handleEditQuery(query);
- _this.handleEditVariables(variables);
- _this.handleEditOperationName(operationName);
- });
- _defineProperty(_assertThisInitialized(_this), "handleResizeStart", function (downEvent) {
- if (!_this._didClickDragBar(downEvent)) {
- return;
- }
- downEvent.preventDefault();
- var offset = downEvent.clientX - (0, _elementPosition.getLeft)(downEvent.target);
- var onMouseMove = function onMouseMove(moveEvent) {
- if (moveEvent.buttons === 0) {
- return _onMouseUp();
- }
- var editorBar = _reactDom.default.findDOMNode(_this.editorBarComponent);
- var leftSize = moveEvent.clientX - (0, _elementPosition.getLeft)(editorBar) - offset;
- var rightSize = editorBar.clientWidth - leftSize;
- _this.setState({
- editorFlex: leftSize / rightSize
- });
- };
- var _onMouseUp = function onMouseUp() {
- document.removeEventListener('mousemove', onMouseMove);
- document.removeEventListener('mouseup', _onMouseUp);
- onMouseMove = null;
- _onMouseUp = null;
- };
- document.addEventListener('mousemove', onMouseMove);
- document.addEventListener('mouseup', _onMouseUp);
- });
- _defineProperty(_assertThisInitialized(_this), "handleResetResize", function () {
- _this.setState({
- editorFlex: 1
- });
- });
- _defineProperty(_assertThisInitialized(_this), "handleDocsResizeStart", function (downEvent) {
- downEvent.preventDefault();
- var hadWidth = _this.state.docExplorerWidth;
- var offset = downEvent.clientX - (0, _elementPosition.getLeft)(downEvent.target);
- var onMouseMove = function onMouseMove(moveEvent) {
- if (moveEvent.buttons === 0) {
- return _onMouseUp2();
- }
- var app = _reactDom.default.findDOMNode(_assertThisInitialized(_this));
- var cursorPos = moveEvent.clientX - (0, _elementPosition.getLeft)(app) - offset;
- var docsSize = app.clientWidth - cursorPos;
- if (docsSize < 100) {
- _this.setState({
- docExplorerOpen: false
- });
- } else {
- _this.setState({
- docExplorerOpen: true,
- docExplorerWidth: Math.min(docsSize, 650)
- });
- }
- };
- var _onMouseUp2 = function onMouseUp() {
- if (!_this.state.docExplorerOpen) {
- _this.setState({
- docExplorerWidth: hadWidth
- });
- }
- document.removeEventListener('mousemove', onMouseMove);
- document.removeEventListener('mouseup', _onMouseUp2);
- onMouseMove = null;
- _onMouseUp2 = null;
- };
- document.addEventListener('mousemove', onMouseMove);
- document.addEventListener('mouseup', _onMouseUp2);
- });
- _defineProperty(_assertThisInitialized(_this), "handleDocsResetResize", function () {
- _this.setState({
- docExplorerWidth: DEFAULT_DOC_EXPLORER_WIDTH
- });
- });
- _defineProperty(_assertThisInitialized(_this), "handleVariableResizeStart", function (downEvent) {
- downEvent.preventDefault();
- var didMove = false;
- var wasOpen = _this.state.variableEditorOpen;
- var hadHeight = _this.state.variableEditorHeight;
- var offset = downEvent.clientY - (0, _elementPosition.getTop)(downEvent.target);
- var onMouseMove = function onMouseMove(moveEvent) {
- if (moveEvent.buttons === 0) {
- return _onMouseUp3();
- }
- didMove = true;
- var editorBar = _reactDom.default.findDOMNode(_this.editorBarComponent);
- var topSize = moveEvent.clientY - (0, _elementPosition.getTop)(editorBar) - offset;
- var bottomSize = editorBar.clientHeight - topSize;
- if (bottomSize < 60) {
- _this.setState({
- variableEditorOpen: false,
- variableEditorHeight: hadHeight
- });
- } else {
- _this.setState({
- variableEditorOpen: true,
- variableEditorHeight: bottomSize
- });
- }
- };
- var _onMouseUp3 = function onMouseUp() {
- if (!didMove) {
- _this.setState({
- variableEditorOpen: !wasOpen
- });
- }
- document.removeEventListener('mousemove', onMouseMove);
- document.removeEventListener('mouseup', _onMouseUp3);
- onMouseMove = null;
- _onMouseUp3 = null;
- };
- document.addEventListener('mousemove', onMouseMove);
- document.addEventListener('mouseup', _onMouseUp3);
- });
- if (typeof props.fetcher !== 'function') {
- throw new TypeError('GraphiQL requires a fetcher function.');
- } // Cache the storage instance
- _this._storage = new _StorageAPI.default(props.storage); // Determine the initial query to display.
- var _query = props.query !== undefined ? props.query : _this._storage.get('query') !== null ? _this._storage.get('query') : props.defaultQuery !== undefined ? props.defaultQuery : defaultQuery; // Get the initial query facts.
- var _queryFacts = (0, _getQueryFacts.default)(props.schema, _query); // Determine the initial variables to display.
- var _variables = props.variables !== undefined ? props.variables : _this._storage.get('variables'); // Determine the initial operationName to use.
- var _operationName = props.operationName !== undefined ? props.operationName : (0, _getSelectedOperationName.default)(null, _this._storage.get('operationName'), _queryFacts && _queryFacts.operations); // prop can be supplied to open docExplorer initially
- var docExplorerOpen = props.docExplorerOpen || false; // but then local storage state overrides it
- if (_this._storage.get('docExplorerOpen')) {
- docExplorerOpen = _this._storage.get('docExplorerOpen') === 'true';
- } // Initialize state
- _this.state = _objectSpread({
- schema: props.schema,
- query: _query,
- variables: _variables,
- operationName: _operationName,
- docExplorerOpen: docExplorerOpen,
- response: props.response,
- editorFlex: Number(_this._storage.get('editorFlex')) || 1,
- variableEditorOpen: Boolean(_variables),
- variableEditorHeight: Number(_this._storage.get('variableEditorHeight')) || 200,
- historyPaneOpen: _this._storage.get('historyPaneOpen') === 'true' || false,
- docExplorerWidth: Number(_this._storage.get('docExplorerWidth')) || DEFAULT_DOC_EXPLORER_WIDTH,
- isWaitingForResponse: false,
- subscription: null
- }, _queryFacts); // Ensure only the last executed editor query is rendered.
- _this._editorQueryID = 0; // Subscribe to the browser window closing, treating it as an unmount.
- if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object') {
- window.addEventListener('beforeunload', function () {
- return _this.componentWillUnmount();
- });
- }
- return _this;
- }
- _createClass(GraphiQL, [{
- key: "componentDidMount",
- value: function componentDidMount() {
- // Only fetch schema via introspection if a schema has not been
- // provided, including if `null` was provided.
- if (this.state.schema === undefined) {
- this._fetchSchema();
- } // Utility for keeping CodeMirror correctly sized.
- this.codeMirrorSizer = new _CodeMirrorSizer.default();
- global.g = this;
- }
- }, {
- key: "componentWillReceiveProps",
- value: function componentWillReceiveProps(nextProps) {
- var _this2 = this;
- var nextSchema = this.state.schema;
- var nextQuery = this.state.query;
- var nextVariables = this.state.variables;
- var nextOperationName = this.state.operationName;
- var nextResponse = this.state.response;
- if (nextProps.schema !== undefined) {
- nextSchema = nextProps.schema;
- }
- if (nextProps.query !== undefined) {
- nextQuery = nextProps.query;
- }
- if (nextProps.variables !== undefined) {
- nextVariables = nextProps.variables;
- }
- if (nextProps.operationName !== undefined) {
- nextOperationName = nextProps.operationName;
- }
- if (nextProps.response !== undefined) {
- nextResponse = nextProps.response;
- }
- if (nextSchema !== this.state.schema || nextQuery !== this.state.query || nextOperationName !== this.state.operationName) {
- var updatedQueryAttributes = this._updateQueryFacts(nextQuery, nextOperationName, this.state.operations, nextSchema);
- if (updatedQueryAttributes !== undefined) {
- nextOperationName = updatedQueryAttributes.operationName;
- this.setState(updatedQueryAttributes);
- }
- } // If schema is not supplied via props and the fetcher changed, then
- // remove the schema so fetchSchema() will be called with the new fetcher.
- if (nextProps.schema === undefined && nextProps.fetcher !== this.props.fetcher) {
- nextSchema = undefined;
- }
- this.setState({
- schema: nextSchema,
- query: nextQuery,
- variables: nextVariables,
- operationName: nextOperationName,
- response: nextResponse
- }, function () {
- if (_this2.state.schema === undefined) {
- _this2.docExplorerComponent.reset();
- _this2._fetchSchema();
- }
- });
- }
- }, {
- key: "componentDidUpdate",
- value: function componentDidUpdate() {
- // If this update caused DOM nodes to have changed sizes, update the
- // corresponding CodeMirror instance sizes to match.
- this.codeMirrorSizer.updateSizes([this.queryEditorComponent, this.variableEditorComponent, this.resultComponent]);
- } // When the component is about to unmount, store any persistable state, such
- // that when the component is remounted, it will use the last used values.
- }, {
- key: "componentWillUnmount",
- value: function componentWillUnmount() {
- this._storage.set('query', this.state.query);
- this._storage.set('variables', this.state.variables);
- this._storage.set('operationName', this.state.operationName);
- this._storage.set('editorFlex', this.state.editorFlex);
- this._storage.set('variableEditorHeight', this.state.variableEditorHeight);
- this._storage.set('docExplorerWidth', this.state.docExplorerWidth);
- this._storage.set('docExplorerOpen', this.state.docExplorerOpen);
- this._storage.set('historyPaneOpen', this.state.historyPaneOpen);
- }
- }, {
- key: "render",
- value: function render() {
- var _this3 = this;
- var children = _react.default.Children.toArray(this.props.children);
- var logo = (0, _find.default)(children, function (child) {
- return child.type === GraphiQL.Logo;
- }) || _react.default.createElement(GraphiQL.Logo, null);
- var toolbar = (0, _find.default)(children, function (child) {
- return child.type === GraphiQL.Toolbar;
- }) || _react.default.createElement(GraphiQL.Toolbar, null, _react.default.createElement(_ToolbarButton.ToolbarButton, {
- onClick: this.handlePrettifyQuery,
- title: "Prettify Query (Shift-Ctrl-P)",
- label: "Prettify"
- }), _react.default.createElement(_ToolbarButton.ToolbarButton, {
- onClick: this.handleMergeQuery,
- title: "Merge Query (Shift-Ctrl-M)",
- label: "Merge"
- }), _react.default.createElement(_ToolbarButton.ToolbarButton, {
- onClick: this.handleCopyQuery,
- title: "Copy Query (Shift-Ctrl-C)",
- label: "Copy"
- }), _react.default.createElement(_ToolbarButton.ToolbarButton, {
- onClick: this.handleToggleHistory,
- title: "Show History",
- label: "History"
- }));
- var footer = (0, _find.default)(children, function (child) {
- return child.type === GraphiQL.Footer;
- });
- var queryWrapStyle = {
- WebkitFlex: this.state.editorFlex,
- flex: this.state.editorFlex
- };
- var docWrapStyle = {
- display: this.state.docExplorerOpen ? 'block' : 'none',
- width: this.state.docExplorerWidth
- };
- var docExplorerWrapClasses = 'docExplorerWrap' + (this.state.docExplorerWidth < 200 ? ' doc-explorer-narrow' : '');
- var historyPaneStyle = {
- display: this.state.historyPaneOpen ? 'block' : 'none',
- width: '230px',
- zIndex: '7'
- };
- var variableOpen = this.state.variableEditorOpen;
- var variableStyle = {
- height: variableOpen ? this.state.variableEditorHeight : null
- };
- return _react.default.createElement("div", {
- className: "graphiql-container"
- }, _react.default.createElement("div", {
- className: "historyPaneWrap",
- style: historyPaneStyle
- }, _react.default.createElement(_QueryHistory.QueryHistory, {
- operationName: this.state.operationName,
- query: this.state.query,
- variables: this.state.variables,
- onSelectQuery: this.handleSelectHistoryQuery,
- storage: this._storage,
- queryID: this._editorQueryID
- }, _react.default.createElement("div", {
- className: "docExplorerHide",
- onClick: this.handleToggleHistory
- }, "\u2715"))), _react.default.createElement("div", {
- className: "editorWrap"
- }, _react.default.createElement("div", {
- className: "topBarWrap"
- }, _react.default.createElement("div", {
- className: "topBar"
- }, logo, _react.default.createElement(_ExecuteButton.ExecuteButton, {
- isRunning: Boolean(this.state.subscription),
- onRun: this.handleRunQuery,
- onStop: this.handleStopQuery,
- operations: this.state.operations
- }), toolbar), !this.state.docExplorerOpen && _react.default.createElement("button", {
- className: "docExplorerShow",
- onClick: this.handleToggleDocs
- }, 'Docs')), _react.default.createElement("div", {
- ref: function ref(n) {
- _this3.editorBarComponent = n;
- },
- className: "editorBar",
- onDoubleClick: this.handleResetResize,
- onMouseDown: this.handleResizeStart
- }, _react.default.createElement("div", {
- className: "queryWrap",
- style: queryWrapStyle
- }, _react.default.createElement(_QueryEditor.QueryEditor, {
- ref: function ref(n) {
- _this3.queryEditorComponent = n;
- },
- schema: this.state.schema,
- value: this.state.query,
- onEdit: this.handleEditQuery,
- onHintInformationRender: this.handleHintInformationRender,
- onClickReference: this.handleClickReference,
- onCopyQuery: this.handleCopyQuery,
- onPrettifyQuery: this.handlePrettifyQuery,
- onMergeQuery: this.handleMergeQuery,
- onRunQuery: this.handleEditorRunQuery,
- editorTheme: this.props.editorTheme,
- readOnly: this.props.readOnly
- }), _react.default.createElement("div", {
- className: "variable-editor",
- style: variableStyle
- }, _react.default.createElement("div", {
- className: "variable-editor-title",
- style: {
- cursor: variableOpen ? 'row-resize' : 'n-resize'
- },
- onMouseDown: this.handleVariableResizeStart
- }, 'Query Variables'), _react.default.createElement(_VariableEditor.VariableEditor, {
- ref: function ref(n) {
- _this3.variableEditorComponent = n;
- },
- value: this.state.variables,
- variableToType: this.state.variableToType,
- onEdit: this.handleEditVariables,
- onHintInformationRender: this.handleHintInformationRender,
- onPrettifyQuery: this.handlePrettifyQuery,
- onMergeQuery: this.handleMergeQuery,
- onRunQuery: this.handleEditorRunQuery,
- editorTheme: this.props.editorTheme,
- readOnly: this.props.readOnly
- }))), _react.default.createElement("div", {
- className: "resultWrap"
- }, this.state.isWaitingForResponse && _react.default.createElement("div", {
- className: "spinner-container"
- }, _react.default.createElement("div", {
- className: "spinner"
- })), _react.default.createElement(_ResultViewer.ResultViewer, {
- ref: function ref(c) {
- _this3.resultComponent = c;
- },
- value: this.state.response,
- editorTheme: this.props.editorTheme,
- ResultsTooltip: this.props.ResultsTooltip,
- ImagePreview: _ImagePreview.ImagePreview
- }), footer))), _react.default.createElement("div", {
- className: docExplorerWrapClasses,
- style: docWrapStyle
- }, _react.default.createElement("div", {
- className: "docExplorerResizer",
- onDoubleClick: this.handleDocsResetResize,
- onMouseDown: this.handleDocsResizeStart
- }), _react.default.createElement(_DocExplorer.DocExplorer, {
- ref: function ref(c) {
- _this3.docExplorerComponent = c;
- },
- schema: this.state.schema
- }, _react.default.createElement("div", {
- className: "docExplorerHide",
- onClick: this.handleToggleDocs
- }, "\u2715"))));
- }
- /**
- * Get the query editor CodeMirror instance.
- *
- * @public
- */
- }, {
- key: "getQueryEditor",
- value: function getQueryEditor() {
- return this.queryEditorComponent.getCodeMirror();
- }
- /**
- * Get the variable editor CodeMirror instance.
- *
- * @public
- */
- }, {
- key: "getVariableEditor",
- value: function getVariableEditor() {
- return this.variableEditorComponent.getCodeMirror();
- }
- /**
- * Refresh all CodeMirror instances.
- *
- * @public
- */
- }, {
- key: "refresh",
- value: function refresh() {
- this.queryEditorComponent.getCodeMirror().refresh();
- this.variableEditorComponent.getCodeMirror().refresh();
- this.resultComponent.getCodeMirror().refresh();
- }
- /**
- * Inspect the query, automatically filling in selection sets for non-leaf
- * fields which do not yet have them.
- *
- * @public
- */
- }, {
- key: "autoCompleteLeafs",
- value: function autoCompleteLeafs() {
- var _fillLeafs = (0, _fillLeafs2.fillLeafs)(this.state.schema, this.state.query, this.props.getDefaultFieldNames),
- insertions = _fillLeafs.insertions,
- result = _fillLeafs.result;
- if (insertions && insertions.length > 0) {
- var editor = this.getQueryEditor();
- editor.operation(function () {
- var cursor = editor.getCursor();
- var cursorIndex = editor.indexFromPos(cursor);
- editor.setValue(result);
- var added = 0;
- var markers = insertions.map(function (_ref) {
- var index = _ref.index,
- string = _ref.string;
- return editor.markText(editor.posFromIndex(index + added), editor.posFromIndex(index + (added += string.length)), {
- className: 'autoInsertedLeaf',
- clearOnEnter: true,
- title: 'Automatically added leaf fields'
- });
- });
- setTimeout(function () {
- return markers.forEach(function (marker) {
- return marker.clear();
- });
- }, 7000);
- var newCursorIndex = cursorIndex;
- insertions.forEach(function (_ref2) {
- var index = _ref2.index,
- string = _ref2.string;
- if (index < cursorIndex) {
- newCursorIndex += string.length;
- }
- });
- editor.setCursor(editor.posFromIndex(newCursorIndex));
- });
- }
- return result;
- } // Private methods
- }, {
- key: "_fetchSchema",
- value: function _fetchSchema() {
- var _this4 = this;
- var fetcher = this.props.fetcher;
- var fetch = observableToPromise(fetcher({
- query: _introspectionQueries.introspectionQuery,
- operationName: _introspectionQueries.introspectionQueryName
- }));
- if (!isPromise(fetch)) {
- this.setState({
- response: 'Fetcher did not return a Promise for introspection.'
- });
- return;
- }
- fetch.then(function (result) {
- if (result.data) {
- return result;
- } // Try the stock introspection query first, falling back on the
- // sans-subscriptions query for services which do not yet support it.
- var fetch2 = observableToPromise(fetcher({
- query: _introspectionQueries.introspectionQuerySansSubscriptions,
- operationName: _introspectionQueries.introspectionQueryName
- }));
- if (!isPromise(fetch)) {
- throw new Error('Fetcher did not return a Promise for introspection.');
- }
- return fetch2;
- }).then(function (result) {
- // If a schema was provided while this fetch was underway, then
- // satisfy the race condition by respecting the already
- // provided schema.
- if (_this4.state.schema !== undefined) {
- return;
- }
- if (result && result.data) {
- var schema = (0, _graphql.buildClientSchema)(result.data);
- var queryFacts = (0, _getQueryFacts.default)(schema, _this4.state.query);
- _this4.setState(_objectSpread({
- schema: schema
- }, queryFacts));
- } else {
- var responseString = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
- _this4.setState({
- // Set schema to `null` to explicitly indicate that no schema exists.
- schema: null,
- response: responseString
- });
- }
- }).catch(function (error) {
- console.error("ERROR:", error);
- _this4.setState({
- schema: null,
- response: error && String(error.stack || error)
- });
- });
- }
- }, {
- key: "_fetchQuery",
- value: function _fetchQuery(query, variables, operationName, cb) {
- var _this5 = this;
- var fetcher = this.props.fetcher;
- var jsonVariables = null;
- try {
- jsonVariables = variables && variables.trim() !== '' ? JSON.parse(variables) : null;
- } catch (error) {
- throw new Error("Variables are invalid JSON: ".concat(error.message, "."));
- }
- if (_typeof(jsonVariables) !== 'object') {
- throw new Error('Variables are not a JSON object.');
- }
- var fetch = fetcher({
- query: query,
- variables: jsonVariables,
- operationName: operationName
- });
- if (isPromise(fetch)) {
- // If fetcher returned a Promise, then call the callback when the promise
- // resolves, otherwise handle the error.
- fetch.then(cb).catch(function (error) {
- _this5.setState({
- isWaitingForResponse: false,
- response: error && String(error.stack || error)
- });
- });
- } else if (isObservable(fetch)) {
- // If the fetcher returned an Observable, then subscribe to it, calling
- // the callback on each next value, and handling both errors and the
- // completion of the Observable. Returns a Subscription object.
- var subscription = fetch.subscribe({
- next: cb,
- error: function error(_error) {
- _this5.setState({
- isWaitingForResponse: false,
- response: _error && String(_error.stack || _error),
- subscription: null
- });
- },
- complete: function complete() {
- _this5.setState({
- isWaitingForResponse: false,
- subscription: null
- });
- }
- });
- return subscription;
- } else {
- throw new Error('Fetcher did not return Promise or Observable.');
- }
- }
- }, {
- key: "_runQueryAtCursor",
- value: function _runQueryAtCursor() {
- if (this.state.subscription) {
- this.handleStopQuery();
- return;
- }
- var operationName;
- var operations = this.state.operations;
- if (operations) {
- var editor = this.getQueryEditor();
- if (editor.hasFocus()) {
- var cursor = editor.getCursor();
- var cursorIndex = editor.indexFromPos(cursor); // Loop through all operations to see if one contains the cursor.
- for (var i = 0; i < operations.length; i++) {
- var operation = operations[i];
- if (operation.loc.start <= cursorIndex && operation.loc.end >= cursorIndex) {
- operationName = operation.name && operation.name.value;
- break;
- }
- }
- }
- }
- this.handleRunQuery(operationName);
- }
- }, {
- key: "_didClickDragBar",
- value: function _didClickDragBar(event) {
- // Only for primary unmodified clicks
- if (event.button !== 0 || event.ctrlKey) {
- return false;
- }
- var target = event.target; // We use codemirror's gutter as the drag bar.
- if (target.className.indexOf('CodeMirror-gutter') !== 0) {
- return false;
- } // Specifically the result window's drag bar.
- var resultWindow = _reactDom.default.findDOMNode(this.resultComponent);
- while (target) {
- if (target === resultWindow) {
- return true;
- }
- target = target.parentNode;
- }
- return false;
- }
- }]);
- return GraphiQL;
- }(_react.default.Component); // Configure the UI by providing this Component as a child of GraphiQL.
- exports.GraphiQL = GraphiQL;
- _defineProperty(GraphiQL, "propTypes", {
- fetcher: _propTypes.default.func.isRequired,
- schema: _propTypes.default.instanceOf(_graphql.GraphQLSchema),
- query: _propTypes.default.string,
- variables: _propTypes.default.string,
- operationName: _propTypes.default.string,
- response: _propTypes.default.string,
- storage: _propTypes.default.shape({
- getItem: _propTypes.default.func,
- setItem: _propTypes.default.func,
- removeItem: _propTypes.default.func
- }),
- defaultQuery: _propTypes.default.string,
- onCopyQuery: _propTypes.default.func,
- onEditQuery: _propTypes.default.func,
- onEditVariables: _propTypes.default.func,
- onEditOperationName: _propTypes.default.func,
- onToggleDocs: _propTypes.default.func,
- getDefaultFieldNames: _propTypes.default.func,
- editorTheme: _propTypes.default.string,
- onToggleHistory: _propTypes.default.func,
- ResultsTooltip: _propTypes.default.any,
- readOnly: _propTypes.default.bool,
- docExplorerOpen: _propTypes.default.bool
- });
- GraphiQL.Logo = function GraphiQLLogo(props) {
- return _react.default.createElement("div", {
- className: "title"
- }, props.children || _react.default.createElement("span", null, 'Graph', _react.default.createElement("em", null, 'i'), 'QL'));
- }; // Configure the UI by providing this Component as a child of GraphiQL.
- GraphiQL.Toolbar = function GraphiQLToolbar(props) {
- return _react.default.createElement("div", {
- className: "toolbar"
- }, props.children);
- }; // Export main windows/panes to be used separately if desired.
- GraphiQL.QueryEditor = _QueryEditor.QueryEditor;
- GraphiQL.VariableEditor = _VariableEditor.VariableEditor;
- GraphiQL.ResultViewer = _ResultViewer.ResultViewer; // Add a button to the Toolbar.
- GraphiQL.Button = _ToolbarButton.ToolbarButton;
- GraphiQL.ToolbarButton = _ToolbarButton.ToolbarButton; // Don't break existing API.
- // Add a group of buttons to the Toolbar
- GraphiQL.Group = _ToolbarGroup.ToolbarGroup; // Add a menu of items to the Toolbar.
- GraphiQL.Menu = _ToolbarMenu.ToolbarMenu;
- GraphiQL.MenuItem = _ToolbarMenu.ToolbarMenuItem; // Add a select-option input to the Toolbar.
- GraphiQL.Select = _ToolbarSelect.ToolbarSelect;
- GraphiQL.SelectOption = _ToolbarSelect.ToolbarSelectOption; // Configure the UI by providing this Component as a child of GraphiQL.
- GraphiQL.Footer = function GraphiQLFooter(props) {
- return _react.default.createElement("div", {
- className: "footer"
- }, props.children);
- };
- var defaultQuery = '# Welcome to GraphiQL on EliasDB\n#\n{\n Station(key : "13") {\n key\n name\n lines(traverse:":::Station") {\n key\n name\n kind\n }\n }\n}\n'
- function isPromise(value) {
- return _typeof(value) === 'object' && typeof value.then === 'function';
- } // Duck-type Observable.take(1).toPromise()
- function observableToPromise(observable) {
- if (!isObservable(observable)) {
- return observable;
- }
- return new Promise(function (resolve, reject) {
- var subscription = observable.subscribe(function (v) {
- resolve(v);
- subscription.unsubscribe();
- }, reject, function () {
- reject(new Error('no value resolved'));
- });
- });
- } // Duck-type observable detection.
- function isObservable(value) {
- return _typeof(value) === 'object' && typeof value.subscribe === 'function';
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"../utility/CodeMirrorSizer":240,"../utility/StorageAPI":242,"../utility/debounce":243,"../utility/elementPosition":244,"../utility/fillLeafs":245,"../utility/find":246,"../utility/getQueryFacts":247,"../utility/getSelectedOperationName":248,"../utility/introspectionQueries":249,"../utility/mergeAst":250,"./DocExplorer":217,"./ExecuteButton":227,"./ImagePreview":230,"./QueryEditor":231,"./QueryHistory":232,"./ResultViewer":233,"./ToolbarButton":234,"./ToolbarGroup":235,"./ToolbarMenu":236,"./ToolbarSelect":237,"./VariableEditor":238,"copy-to-clipboard":17,"graphql":29,"prop-types":202}],229:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var HistoryQuery =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(HistoryQuery, _React$Component);
- function HistoryQuery(props) {
- var _this;
- _classCallCheck(this, HistoryQuery);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(HistoryQuery).call(this, props));
- _defineProperty(_assertThisInitialized(_this), "editField", null);
- _this.state = {
- showButtons: false,
- editable: false
- };
- return _this;
- }
- _createClass(HistoryQuery, [{
- key: "render",
- value: function render() {
- var _this2 = this;
- var editStyles = {
- display: this.state.showButtons ? '' : 'none',
- marginLeft: '10px'
- };
- var starStyles = {
- display: this.props.favorite || this.state.showButtons ? '' : 'none',
- marginLeft: '10px'
- };
- var displayName = this.props.label || this.props.operationName || this.props.query.split('\n').filter(function (line) {
- return line.indexOf('#') !== 0;
- }).join('');
- var starIcon = this.props.favorite ? "\u2605" : "\u2606";
- return _react.default.createElement("p", {
- className: this.state.editable ? 'editable' : undefined,
- onClick: this.handleClick.bind(this),
- onMouseEnter: this.handleMouseEnter.bind(this),
- onMouseLeave: this.handleMouseLeave.bind(this)
- }, this.state.editable ? _react.default.createElement("input", {
- type: "text",
- defaultValue: this.props.label,
- ref: function ref(c) {
- return _this2.editField = c;
- },
- onBlur: this.handleFieldBlur.bind(this),
- onKeyDown: this.handleFieldKeyDown.bind(this),
- placeholder: "Type a label"
- }) : _react.default.createElement("span", {
- className: "history-label"
- }, displayName), _react.default.createElement("span", {
- onClick: this.handleEditClick.bind(this),
- style: editStyles
- }, "\u270E"), _react.default.createElement("span", {
- onClick: this.handleStarClick.bind(this),
- style: starStyles
- }, starIcon));
- }
- }, {
- key: "handleMouseEnter",
- value: function handleMouseEnter() {
- this.setState({
- showButtons: true
- });
- }
- }, {
- key: "handleMouseLeave",
- value: function handleMouseLeave() {
- this.setState({
- showButtons: false
- });
- }
- }, {
- key: "handleClick",
- value: function handleClick() {
- this.props.onSelect(this.props.query, this.props.variables, this.props.operationName, this.props.label);
- }
- }, {
- key: "handleStarClick",
- value: function handleStarClick(e) {
- e.stopPropagation();
- this.props.handleToggleFavorite(this.props.query, this.props.variables, this.props.operationName, this.props.label, this.props.favorite);
- }
- }, {
- key: "handleFieldBlur",
- value: function handleFieldBlur(e) {
- e.stopPropagation();
- this.setState({
- editable: false
- });
- this.props.handleEditLabel(this.props.query, this.props.variables, this.props.operationName, e.target.value, this.props.favorite);
- }
- }, {
- key: "handleFieldKeyDown",
- value: function handleFieldKeyDown(e) {
- if (e.keyCode === 13) {
- e.stopPropagation();
- this.setState({
- editable: false
- });
- this.props.handleEditLabel(this.props.query, this.props.variables, this.props.operationName, e.target.value, this.props.favorite);
- }
- }
- }, {
- key: "handleEditClick",
- value: function handleEditClick(e) {
- var _this3 = this;
- e.stopPropagation();
- this.setState({
- editable: true
- }, function () {
- if (_this3.editField) {
- _this3.editField.focus();
- }
- });
- }
- }]);
- return HistoryQuery;
- }(_react.default.Component);
- exports.default = HistoryQuery;
- _defineProperty(HistoryQuery, "propTypes", {
- favorite: _propTypes.default.bool,
- favoriteSize: _propTypes.default.number,
- handleEditLabel: _propTypes.default.func,
- handleToggleFavorite: _propTypes.default.func,
- operationName: _propTypes.default.string,
- onSelect: _propTypes.default.func,
- query: _propTypes.default.string,
- variables: _propTypes.default.string,
- label: _propTypes.default.string
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"prop-types":202}],230:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ImagePreview = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function tokenToURL(token) {
- if (token.type !== 'string') {
- return null;
- }
- var value = token.string.slice(1).slice(0, -1).trim();
- try {
- var location = window.location;
- return new URL(value, location.protocol + '//' + location.host);
- } catch (err) {
- return null;
- }
- }
- function isImageURL(url) {
- return /(bmp|gif|jpeg|jpg|png|svg)$/.test(url.pathname);
- }
- var ImagePreview =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(ImagePreview, _React$Component);
- _createClass(ImagePreview, null, [{
- key: "shouldRender",
- value: function shouldRender(token) {
- var url = tokenToURL(token);
- return url ? isImageURL(url) : false;
- }
- }]);
- function ImagePreview(props) {
- var _this;
- _classCallCheck(this, ImagePreview);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(ImagePreview).call(this, props));
- _defineProperty(_assertThisInitialized(_this), "state", {
- width: null,
- height: null,
- src: null,
- mime: null
- });
- return _this;
- }
- _createClass(ImagePreview, [{
- key: "componentDidMount",
- value: function componentDidMount() {
- this._updateMetadata();
- }
- }, {
- key: "componentDidUpdate",
- value: function componentDidUpdate() {
- this._updateMetadata();
- }
- }, {
- key: "render",
- value: function render() {
- var _this2 = this;
- var dims = null;
- if (this.state.width !== null && this.state.height !== null) {
- var dimensions = this.state.width + 'x' + this.state.height;
- if (this.state.mime !== null) {
- dimensions += ' ' + this.state.mime;
- }
- dims = _react.default.createElement("div", null, dimensions);
- }
- return _react.default.createElement("div", null, _react.default.createElement("img", {
- onLoad: function onLoad() {
- return _this2._updateMetadata();
- },
- ref: function ref(node) {
- _this2._node = node;
- },
- src: tokenToURL(this.props.token)
- }), dims);
- }
- }, {
- key: "_updateMetadata",
- value: function _updateMetadata() {
- var _this3 = this;
- if (!this._node) {
- return;
- }
- var width = this._node.naturalWidth;
- var height = this._node.naturalHeight;
- var src = this._node.src;
- if (src !== this.state.src) {
- this.setState({
- src: src
- });
- fetch(src, {
- method: 'HEAD'
- }).then(function (response) {
- _this3.setState({
- mime: response.headers.get('Content-Type')
- });
- });
- }
- if (width !== this.state.width || height !== this.state.height) {
- this.setState({
- height: height,
- width: width
- });
- }
- }
- }]);
- return ImagePreview;
- }(_react.default.Component);
- exports.ImagePreview = ImagePreview;
- _defineProperty(ImagePreview, "propTypes", {
- token: _propTypes.default.any
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"prop-types":202}],231:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.QueryEditor = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _graphql = require("graphql");
- var _markdownIt = _interopRequireDefault(require("markdown-it"));
- var _normalizeWhitespace = require("../utility/normalizeWhitespace");
- var _onHasCompletion = _interopRequireDefault(require("../utility/onHasCompletion"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var md = new _markdownIt.default();
- var AUTO_COMPLETE_AFTER_KEY = /^[a-zA-Z0-9_@(]$/;
- /**
- * QueryEditor
- *
- * Maintains an instance of CodeMirror responsible for editing a GraphQL query.
- *
- * Props:
- *
- * - schema: A GraphQLSchema instance enabling editor linting and hinting.
- * - value: The text of the editor.
- * - onEdit: A function called when the editor changes, given the edited text.
- * - readOnly: Turns the editor to read-only mode.
- *
- */
- var QueryEditor =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(QueryEditor, _React$Component);
- function QueryEditor(props) {
- var _this;
- _classCallCheck(this, QueryEditor);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(QueryEditor).call(this)); // Keep a cached version of the value, this cache will be updated when the
- // editor is updated, which can later be used to protect the editor from
- // unnecessary updates during the update lifecycle.
- _defineProperty(_assertThisInitialized(_this), "_onKeyUp", function (cm, event) {
- if (AUTO_COMPLETE_AFTER_KEY.test(event.key)) {
- _this.editor.execCommand('autocomplete');
- }
- });
- _defineProperty(_assertThisInitialized(_this), "_onEdit", function () {
- if (!_this.ignoreChangeEvent) {
- _this.cachedValue = _this.editor.getValue();
- if (_this.props.onEdit) {
- _this.props.onEdit(_this.cachedValue);
- }
- }
- });
- _defineProperty(_assertThisInitialized(_this), "_onHasCompletion", function (cm, data) {
- (0, _onHasCompletion.default)(cm, data, _this.props.onHintInformationRender);
- });
- _this.cachedValue = props.value || '';
- return _this;
- }
- _createClass(QueryEditor, [{
- key: "componentDidMount",
- value: function componentDidMount() {
- var _this2 = this;
- // Lazily require to ensure requiring GraphiQL outside of a Browser context
- // does not produce an error.
- var CodeMirror = require('codemirror');
- require('codemirror/addon/hint/show-hint');
- require('codemirror/addon/comment/comment');
- require('codemirror/addon/edit/matchbrackets');
- require('codemirror/addon/edit/closebrackets');
- require('codemirror/addon/fold/foldgutter');
- require('codemirror/addon/fold/brace-fold');
- require('codemirror/addon/search/search');
- require('codemirror/addon/search/searchcursor');
- require('codemirror/addon/search/jump-to-line');
- require('codemirror/addon/dialog/dialog');
- require('codemirror/addon/lint/lint');
- require('codemirror/keymap/sublime');
- require('codemirror-graphql/hint');
- require('codemirror-graphql/lint');
- require('codemirror-graphql/info');
- require('codemirror-graphql/jump');
- require('codemirror-graphql/mode');
- this.editor = CodeMirror(this._node, {
- value: this.props.value || '',
- lineNumbers: true,
- tabSize: 2,
- mode: 'graphql',
- theme: this.props.editorTheme || 'graphiql',
- keyMap: 'sublime',
- autoCloseBrackets: true,
- matchBrackets: true,
- showCursorWhenSelecting: true,
- readOnly: this.props.readOnly ? 'nocursor' : false,
- foldGutter: {
- minFoldSize: 4
- },
- lint: {
- schema: this.props.schema
- },
- hintOptions: {
- schema: this.props.schema,
- closeOnUnfocus: false,
- completeSingle: false,
- container: this._node
- },
- info: {
- schema: this.props.schema,
- renderDescription: function renderDescription(text) {
- return md.render(text);
- },
- onClick: function onClick(reference) {
- return _this2.props.onClickReference(reference);
- }
- },
- jump: {
- schema: this.props.schema,
- onClick: function onClick(reference) {
- return _this2.props.onClickReference(reference);
- }
- },
- gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
- extraKeys: {
- 'Cmd-Space': function CmdSpace() {
- return _this2.editor.showHint({
- completeSingle: true,
- container: _this2._node
- });
- },
- 'Ctrl-Space': function CtrlSpace() {
- return _this2.editor.showHint({
- completeSingle: true,
- container: _this2._node
- });
- },
- 'Alt-Space': function AltSpace() {
- return _this2.editor.showHint({
- completeSingle: true,
- container: _this2._node
- });
- },
- 'Shift-Space': function ShiftSpace() {
- return _this2.editor.showHint({
- completeSingle: true,
- container: _this2._node
- });
- },
- 'Shift-Alt-Space': function ShiftAltSpace() {
- return _this2.editor.showHint({
- completeSingle: true,
- container: _this2._node
- });
- },
- 'Cmd-Enter': function CmdEnter() {
- if (_this2.props.onRunQuery) {
- _this2.props.onRunQuery();
- }
- },
- 'Ctrl-Enter': function CtrlEnter() {
- if (_this2.props.onRunQuery) {
- _this2.props.onRunQuery();
- }
- },
- 'Shift-Ctrl-C': function ShiftCtrlC() {
- if (_this2.props.onCopyQuery) {
- _this2.props.onCopyQuery();
- }
- },
- 'Shift-Ctrl-P': function ShiftCtrlP() {
- if (_this2.props.onPrettifyQuery) {
- _this2.props.onPrettifyQuery();
- }
- },
- 'Shift-Ctrl-M': function ShiftCtrlM() {
- if (_this2.props.onMergeQuery) {
- _this2.props.onMergeQuery();
- }
- },
- // Persistent search box in Query Editor
- 'Cmd-F': 'findPersistent',
- 'Ctrl-F': 'findPersistent',
- 'Cmd-G': 'findPersistent',
- 'Ctrl-G': 'findPersistent',
- // Editor improvements
- 'Ctrl-Left': 'goSubwordLeft',
- 'Ctrl-Right': 'goSubwordRight',
- 'Alt-Left': 'goGroupLeft',
- 'Alt-Right': 'goGroupRight'
- }
- });
- this.editor.on('change', this._onEdit);
- this.editor.on('keyup', this._onKeyUp);
- this.editor.on('hasCompletion', this._onHasCompletion);
- this.editor.on('beforeChange', this._onBeforeChange);
- }
- }, {
- key: "componentDidUpdate",
- value: function componentDidUpdate(prevProps) {
- var CodeMirror = require('codemirror'); // Ensure the changes caused by this update are not interpretted as
- // user-input changes which could otherwise result in an infinite
- // event loop.
- this.ignoreChangeEvent = true;
- if (this.props.schema !== prevProps.schema) {
- this.editor.options.lint.schema = this.props.schema;
- this.editor.options.hintOptions.schema = this.props.schema;
- this.editor.options.info.schema = this.props.schema;
- this.editor.options.jump.schema = this.props.schema;
- CodeMirror.signal(this.editor, 'change', this.editor);
- }
- if (this.props.value !== prevProps.value && this.props.value !== this.cachedValue) {
- this.cachedValue = this.props.value;
- this.editor.setValue(this.props.value);
- }
- this.ignoreChangeEvent = false;
- }
- }, {
- key: "componentWillUnmount",
- value: function componentWillUnmount() {
- this.editor.off('change', this._onEdit);
- this.editor.off('keyup', this._onKeyUp);
- this.editor.off('hasCompletion', this._onHasCompletion);
- this.editor = null;
- }
- }, {
- key: "render",
- value: function render() {
- var _this3 = this;
- return _react.default.createElement("div", {
- className: "query-editor",
- ref: function ref(node) {
- _this3._node = node;
- }
- });
- }
- /**
- * Public API for retrieving the CodeMirror instance from this
- * React component.
- */
- }, {
- key: "getCodeMirror",
- value: function getCodeMirror() {
- return this.editor;
- }
- /**
- * Public API for retrieving the DOM client height for this component.
- */
- }, {
- key: "getClientHeight",
- value: function getClientHeight() {
- return this._node && this._node.clientHeight;
- }
- }, {
- key: "_onBeforeChange",
- value: function _onBeforeChange(instance, change) {
- // The update function is only present on non-redo, non-undo events.
- if (change.origin === 'paste') {
- var text = change.text.map(_normalizeWhitespace.normalizeWhitespace);
- change.update(change.from, change.to, text);
- }
- }
- }]);
- return QueryEditor;
- }(_react.default.Component);
- exports.QueryEditor = QueryEditor;
- _defineProperty(QueryEditor, "propTypes", {
- schema: _propTypes.default.instanceOf(_graphql.GraphQLSchema),
- value: _propTypes.default.string,
- onEdit: _propTypes.default.func,
- readOnly: _propTypes.default.bool,
- onHintInformationRender: _propTypes.default.func,
- onClickReference: _propTypes.default.func,
- onCopyQuery: _propTypes.default.func,
- onPrettifyQuery: _propTypes.default.func,
- onMergeQuery: _propTypes.default.func,
- onRunQuery: _propTypes.default.func,
- editorTheme: _propTypes.default.string
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"../utility/normalizeWhitespace":251,"../utility/onHasCompletion":252,"codemirror":16,"codemirror-graphql/hint":253,"codemirror-graphql/info":254,"codemirror-graphql/jump":255,"codemirror-graphql/lint":256,"codemirror-graphql/mode":257,"codemirror/addon/comment/comment":3,"codemirror/addon/dialog/dialog":4,"codemirror/addon/edit/closebrackets":5,"codemirror/addon/edit/matchbrackets":6,"codemirror/addon/fold/brace-fold":7,"codemirror/addon/fold/foldgutter":9,"codemirror/addon/hint/show-hint":10,"codemirror/addon/lint/lint":11,"codemirror/addon/search/jump-to-line":12,"codemirror/addon/search/search":13,"codemirror/addon/search/searchcursor":14,"codemirror/keymap/sublime":15,"graphql":29,"markdown-it":140,"prop-types":202}],232:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.QueryHistory = void 0;
- var _graphql = require("graphql");
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _QueryStore = _interopRequireDefault(require("../utility/QueryStore"));
- var _HistoryQuery = _interopRequireDefault(require("./HistoryQuery"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
- function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- var shouldSaveQuery = function shouldSaveQuery(nextProps, current, lastQuerySaved) {
- if (nextProps.queryID === current.queryID) {
- return false;
- }
- try {
- (0, _graphql.parse)(nextProps.query);
- } catch (e) {
- return false;
- }
- if (!lastQuerySaved) {
- return true;
- }
- if (JSON.stringify(nextProps.query) === JSON.stringify(lastQuerySaved.query)) {
- if (JSON.stringify(nextProps.variables) === JSON.stringify(lastQuerySaved.variables)) {
- return false;
- }
- if (!nextProps.variables && !lastQuerySaved.variables) {
- return false;
- }
- }
- return true;
- };
- var MAX_HISTORY_LENGTH = 20;
- var QueryHistory =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(QueryHistory, _React$Component);
- function QueryHistory(props) {
- var _this;
- _classCallCheck(this, QueryHistory);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(QueryHistory).call(this, props));
- _defineProperty(_assertThisInitialized(_this), "toggleFavorite", function (query, variables, operationName, label, favorite) {
- var item = {
- query: query,
- variables: variables,
- operationName: operationName,
- label: label
- };
- if (!_this.favoriteStore.contains(item)) {
- item.favorite = true;
- _this.favoriteStore.push(item);
- } else if (favorite) {
- item.favorite = false;
- _this.favoriteStore.delete(item);
- }
- _this.setState({
- queries: [].concat(_toConsumableArray(_this.historyStore.items), _toConsumableArray(_this.favoriteStore.items))
- });
- });
- _defineProperty(_assertThisInitialized(_this), "editLabel", function (query, variables, operationName, label, favorite) {
- var item = {
- query: query,
- variables: variables,
- operationName: operationName,
- label: label
- };
- if (favorite) {
- _this.favoriteStore.edit(_objectSpread({}, item, {
- favorite: favorite
- }));
- } else {
- _this.historyStore.edit(item);
- }
- _this.setState({
- queries: [].concat(_toConsumableArray(_this.historyStore.items), _toConsumableArray(_this.favoriteStore.items))
- });
- });
- _this.historyStore = new _QueryStore.default('queries', props.storage);
- _this.favoriteStore = new _QueryStore.default('favorites', props.storage);
- var historyQueries = _this.historyStore.fetchAll();
- var favoriteQueries = _this.favoriteStore.fetchAll();
- var queries = historyQueries.concat(favoriteQueries);
- _this.state = {
- queries: queries
- };
- return _this;
- }
- _createClass(QueryHistory, [{
- key: "componentWillReceiveProps",
- value: function componentWillReceiveProps(nextProps) {
- if (shouldSaveQuery(nextProps, this.props, this.historyStore.fetchRecent())) {
- var item = {
- query: nextProps.query,
- variables: nextProps.variables,
- operationName: nextProps.operationName
- };
- this.historyStore.push(item);
- if (this.historyStore.length > MAX_HISTORY_LENGTH) {
- this.historyStore.shift();
- }
- var historyQueries = this.historyStore.items;
- var favoriteQueries = this.favoriteStore.items;
- var queries = historyQueries.concat(favoriteQueries);
- this.setState({
- queries: queries
- });
- }
- }
- }, {
- key: "render",
- value: function render() {
- var _this2 = this;
- var queries = this.state.queries.slice().reverse();
- var queryNodes = queries.map(function (query, i) {
- return _react.default.createElement(_HistoryQuery.default, _extends({
- handleEditLabel: _this2.editLabel,
- handleToggleFavorite: _this2.toggleFavorite,
- key: i,
- onSelect: _this2.props.onSelectQuery
- }, query));
- });
- return _react.default.createElement("div", null, _react.default.createElement("div", {
- className: "history-title-bar"
- }, _react.default.createElement("div", {
- className: "history-title"
- }, 'History'), _react.default.createElement("div", {
- className: "doc-explorer-rhs"
- }, this.props.children)), _react.default.createElement("div", {
- className: "history-contents"
- }, queryNodes));
- }
- }]);
- return QueryHistory;
- }(_react.default.Component);
- exports.QueryHistory = QueryHistory;
- _defineProperty(QueryHistory, "propTypes", {
- query: _propTypes.default.string,
- variables: _propTypes.default.string,
- operationName: _propTypes.default.string,
- queryID: _propTypes.default.number,
- onSelectQuery: _propTypes.default.func,
- storage: _propTypes.default.object
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"../utility/QueryStore":241,"./HistoryQuery":229,"graphql":29,"prop-types":202}],233:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ResultViewer = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _reactDom = _interopRequireDefault((typeof window !== "undefined" ? window['ReactDOM'] : typeof global !== "undefined" ? global['ReactDOM'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * ResultViewer
- *
- * Maintains an instance of CodeMirror for viewing a GraphQL response.
- *
- * Props:
- *
- * - value: The text of the editor.
- *
- */
- var ResultViewer =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(ResultViewer, _React$Component);
- function ResultViewer() {
- _classCallCheck(this, ResultViewer);
- return _possibleConstructorReturn(this, _getPrototypeOf(ResultViewer).call(this));
- }
- _createClass(ResultViewer, [{
- key: "componentDidMount",
- value: function componentDidMount() {
- // Lazily require to ensure requiring GraphiQL outside of a Browser context
- // does not produce an error.
- var CodeMirror = require('codemirror');
- require('codemirror/addon/fold/foldgutter');
- require('codemirror/addon/fold/brace-fold');
- require('codemirror/addon/dialog/dialog');
- require('codemirror/addon/search/search');
- require('codemirror/addon/search/searchcursor');
- require('codemirror/addon/search/jump-to-line');
- require('codemirror/keymap/sublime');
- require('codemirror-graphql/results/mode');
- var Tooltip = this.props.ResultsTooltip;
- var ImagePreview = this.props.ImagePreview;
- if (Tooltip || ImagePreview) {
- require('codemirror-graphql/utils/info-addon');
- var tooltipDiv = document.createElement('div');
- CodeMirror.registerHelper('info', 'graphql-results', function (token, options, cm, pos) {
- var infoElements = [];
- if (Tooltip) {
- infoElements.push(_react.default.createElement(Tooltip, {
- pos: pos
- }));
- }
- if (ImagePreview && typeof ImagePreview.shouldRender === 'function' && ImagePreview.shouldRender(token)) {
- infoElements.push(_react.default.createElement(ImagePreview, {
- token: token
- }));
- }
- if (!infoElements.length) {
- _reactDom.default.unmountComponentAtNode(tooltipDiv);
- return null;
- }
- _reactDom.default.render(_react.default.createElement("div", null, infoElements), tooltipDiv);
- return tooltipDiv;
- });
- }
- this.viewer = CodeMirror(this._node, {
- lineWrapping: true,
- value: this.props.value || '',
- readOnly: true,
- theme: this.props.editorTheme || 'graphiql',
- mode: 'graphql-results',
- keyMap: 'sublime',
- foldGutter: {
- minFoldSize: 4
- },
- gutters: ['CodeMirror-foldgutter'],
- info: Boolean(this.props.ResultsTooltip || this.props.ImagePreview),
- extraKeys: {
- // Persistent search box in Query Editor
- 'Cmd-F': 'findPersistent',
- 'Ctrl-F': 'findPersistent',
- 'Cmd-G': 'findPersistent',
- 'Ctrl-G': 'findPersistent',
- // Editor improvements
- 'Ctrl-Left': 'goSubwordLeft',
- 'Ctrl-Right': 'goSubwordRight',
- 'Alt-Left': 'goGroupLeft',
- 'Alt-Right': 'goGroupRight'
- }
- });
- }
- }, {
- key: "shouldComponentUpdate",
- value: function shouldComponentUpdate(nextProps) {
- return this.props.value !== nextProps.value;
- }
- }, {
- key: "componentDidUpdate",
- value: function componentDidUpdate() {
- this.viewer.setValue(this.props.value || '');
- }
- }, {
- key: "componentWillUnmount",
- value: function componentWillUnmount() {
- this.viewer = null;
- }
- }, {
- key: "render",
- value: function render() {
- var _this = this;
- return _react.default.createElement("div", {
- className: "result-window",
- ref: function ref(node) {
- _this._node = node;
- }
- });
- }
- /**
- * Public API for retrieving the CodeMirror instance from this
- * React component.
- */
- }, {
- key: "getCodeMirror",
- value: function getCodeMirror() {
- return this.viewer;
- }
- /**
- * Public API for retrieving the DOM client height for this component.
- */
- }, {
- key: "getClientHeight",
- value: function getClientHeight() {
- return this._node && this._node.clientHeight;
- }
- }]);
- return ResultViewer;
- }(_react.default.Component);
- exports.ResultViewer = ResultViewer;
- _defineProperty(ResultViewer, "propTypes", {
- value: _propTypes.default.string,
- editorTheme: _propTypes.default.string,
- ResultsTooltip: _propTypes.default.any,
- ImagePreview: _propTypes.default.any
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"codemirror":16,"codemirror-graphql/results/mode":391,"codemirror-graphql/utils/info-addon":396,"codemirror/addon/dialog/dialog":4,"codemirror/addon/fold/brace-fold":7,"codemirror/addon/fold/foldgutter":9,"codemirror/addon/search/jump-to-line":12,"codemirror/addon/search/search":13,"codemirror/addon/search/searchcursor":14,"codemirror/keymap/sublime":15,"prop-types":202}],234:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ToolbarButton = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * ToolbarButton
- *
- * A button to use within the Toolbar.
- */
- var ToolbarButton =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(ToolbarButton, _React$Component);
- function ToolbarButton(props) {
- var _this;
- _classCallCheck(this, ToolbarButton);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(ToolbarButton).call(this, props));
- _defineProperty(_assertThisInitialized(_this), "handleClick", function (e) {
- e.preventDefault();
- try {
- _this.props.onClick();
- _this.setState({
- error: null
- });
- } catch (error) {
- _this.setState({
- error: error
- });
- }
- });
- _this.state = {
- error: null
- };
- return _this;
- }
- _createClass(ToolbarButton, [{
- key: "render",
- value: function render() {
- var error = this.state.error;
- return _react.default.createElement("a", {
- className: 'toolbar-button' + (error ? ' error' : ''),
- onMouseDown: preventDefault,
- onClick: this.handleClick,
- title: error ? error.message : this.props.title
- }, this.props.label);
- }
- }]);
- return ToolbarButton;
- }(_react.default.Component);
- exports.ToolbarButton = ToolbarButton;
- _defineProperty(ToolbarButton, "propTypes", {
- onClick: _propTypes.default.func,
- title: _propTypes.default.string,
- label: _propTypes.default.string
- });
- function preventDefault(e) {
- e.preventDefault();
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"prop-types":202}],235:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ToolbarGroup = ToolbarGroup;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- /**
- * ToolbarGroup
- *
- * A group of associated controls.
- */
- function ToolbarGroup(_ref) {
- var children = _ref.children;
- return _react.default.createElement("div", {
- className: "toolbar-button-group"
- }, children);
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],236:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ToolbarMenuItem = ToolbarMenuItem;
- exports.ToolbarMenu = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * ToolbarMenu
- *
- * A menu style button to use within the Toolbar.
- */
- var ToolbarMenu =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(ToolbarMenu, _React$Component);
- function ToolbarMenu(props) {
- var _this;
- _classCallCheck(this, ToolbarMenu);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(ToolbarMenu).call(this, props));
- _defineProperty(_assertThisInitialized(_this), "handleOpen", function (e) {
- preventDefault(e);
- _this.setState({
- visible: true
- });
- _this._subscribe();
- });
- _this.state = {
- visible: false
- };
- return _this;
- }
- _createClass(ToolbarMenu, [{
- key: "componentWillUnmount",
- value: function componentWillUnmount() {
- this._release();
- }
- }, {
- key: "render",
- value: function render() {
- var _this2 = this;
- var visible = this.state.visible;
- return _react.default.createElement("a", {
- className: "toolbar-menu toolbar-button",
- onClick: this.handleOpen.bind(this),
- onMouseDown: preventDefault,
- ref: function ref(node) {
- _this2._node = node;
- },
- title: this.props.title
- }, this.props.label, _react.default.createElement("svg", {
- width: "14",
- height: "8"
- }, _react.default.createElement("path", {
- fill: "#666",
- d: "M 5 1.5 L 14 1.5 L 9.5 7 z"
- })), _react.default.createElement("ul", {
- className: 'toolbar-menu-items' + (visible ? ' open' : '')
- }, this.props.children));
- }
- }, {
- key: "_subscribe",
- value: function _subscribe() {
- if (!this._listener) {
- this._listener = this.handleClick.bind(this);
- document.addEventListener('click', this._listener);
- }
- }
- }, {
- key: "_release",
- value: function _release() {
- if (this._listener) {
- document.removeEventListener('click', this._listener);
- this._listener = null;
- }
- }
- }, {
- key: "handleClick",
- value: function handleClick(e) {
- if (this._node !== e.target) {
- preventDefault(e);
- this.setState({
- visible: false
- });
- this._release();
- }
- }
- }]);
- return ToolbarMenu;
- }(_react.default.Component);
- exports.ToolbarMenu = ToolbarMenu;
- _defineProperty(ToolbarMenu, "propTypes", {
- title: _propTypes.default.string,
- label: _propTypes.default.string
- });
- function ToolbarMenuItem(_ref) {
- var onSelect = _ref.onSelect,
- title = _ref.title,
- label = _ref.label;
- return _react.default.createElement("li", {
- onMouseOver: function onMouseOver(e) {
- e.target.className = 'hover';
- },
- onMouseOut: function onMouseOut(e) {
- e.target.className = null;
- },
- onMouseDown: preventDefault,
- onMouseUp: onSelect,
- title: title
- }, label);
- }
- ToolbarMenuItem.propTypes = {
- onSelect: _propTypes.default.func,
- title: _propTypes.default.string,
- label: _propTypes.default.string
- };
- function preventDefault(e) {
- e.preventDefault();
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"prop-types":202}],237:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ToolbarSelectOption = ToolbarSelectOption;
- exports.ToolbarSelect = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * ToolbarSelect
- *
- * A select-option style button to use within the Toolbar.
- *
- */
- var ToolbarSelect =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(ToolbarSelect, _React$Component);
- function ToolbarSelect(props) {
- var _this;
- _classCallCheck(this, ToolbarSelect);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(ToolbarSelect).call(this, props));
- _defineProperty(_assertThisInitialized(_this), "handleOpen", function (e) {
- preventDefault(e);
- _this.setState({
- visible: true
- });
- _this._subscribe();
- });
- _this.state = {
- visible: false
- };
- return _this;
- }
- _createClass(ToolbarSelect, [{
- key: "componentWillUnmount",
- value: function componentWillUnmount() {
- this._release();
- }
- }, {
- key: "render",
- value: function render() {
- var _this2 = this;
- var selectedChild;
- var visible = this.state.visible;
- var optionChildren = _react.default.Children.map(this.props.children, function (child, i) {
- if (!selectedChild || child.props.selected) {
- selectedChild = child;
- }
- var onChildSelect = child.props.onSelect || _this2.props.onSelect && _this2.props.onSelect.bind(null, child.props.value, i);
- return _react.default.createElement(ToolbarSelectOption, _extends({}, child.props, {
- onSelect: onChildSelect
- }));
- });
- return _react.default.createElement("a", {
- className: "toolbar-select toolbar-button",
- onClick: this.handleOpen.bind(this),
- onMouseDown: preventDefault,
- ref: function ref(node) {
- _this2._node = node;
- },
- title: this.props.title
- }, selectedChild.props.label, _react.default.createElement("svg", {
- width: "13",
- height: "10"
- }, _react.default.createElement("path", {
- fill: "#666",
- d: "M 5 5 L 13 5 L 9 1 z"
- }), _react.default.createElement("path", {
- fill: "#666",
- d: "M 5 6 L 13 6 L 9 10 z"
- })), _react.default.createElement("ul", {
- className: 'toolbar-select-options' + (visible ? ' open' : '')
- }, optionChildren));
- }
- }, {
- key: "_subscribe",
- value: function _subscribe() {
- if (!this._listener) {
- this._listener = this.handleClick.bind(this);
- document.addEventListener('click', this._listener);
- }
- }
- }, {
- key: "_release",
- value: function _release() {
- if (this._listener) {
- document.removeEventListener('click', this._listener);
- this._listener = null;
- }
- }
- }, {
- key: "handleClick",
- value: function handleClick(e) {
- if (this._node !== e.target) {
- preventDefault(e);
- this.setState({
- visible: false
- });
- this._release();
- }
- }
- }]);
- return ToolbarSelect;
- }(_react.default.Component);
- exports.ToolbarSelect = ToolbarSelect;
- _defineProperty(ToolbarSelect, "propTypes", {
- title: _propTypes.default.string,
- label: _propTypes.default.string,
- onSelect: _propTypes.default.func
- });
- function ToolbarSelectOption(_ref) {
- var onSelect = _ref.onSelect,
- label = _ref.label,
- selected = _ref.selected;
- return _react.default.createElement("li", {
- onMouseOver: function onMouseOver(e) {
- e.target.className = 'hover';
- },
- onMouseOut: function onMouseOut(e) {
- e.target.className = null;
- },
- onMouseDown: preventDefault,
- onMouseUp: onSelect
- }, label, selected && _react.default.createElement("svg", {
- width: "13",
- height: "13"
- }, _react.default.createElement("polygon", {
- points: "4.851,10.462 0,5.611 2.314,3.297 4.851,5.835 10.686,0 13,2.314 4.851,10.462"
- })));
- }
- ToolbarSelectOption.propTypes = {
- onSelect: _propTypes.default.func,
- selected: _propTypes.default.bool,
- label: _propTypes.default.string,
- value: _propTypes.default.any
- };
- function preventDefault(e) {
- e.preventDefault();
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"prop-types":202}],238:[function(require,module,exports){
- (function (global){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.VariableEditor = void 0;
- var _react = _interopRequireDefault((typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null));
- var _propTypes = _interopRequireDefault(require("prop-types"));
- var _onHasCompletion = _interopRequireDefault(require("../utility/onHasCompletion"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * VariableEditor
- *
- * An instance of CodeMirror for editing variables defined in QueryEditor.
- *
- * Props:
- *
- * - variableToType: A mapping of variable name to GraphQLType.
- * - value: The text of the editor.
- * - onEdit: A function called when the editor changes, given the edited text.
- * - readOnly: Turns the editor to read-only mode.
- *
- */
- var VariableEditor =
- /*#__PURE__*/
- function (_React$Component) {
- _inherits(VariableEditor, _React$Component);
- function VariableEditor(props) {
- var _this;
- _classCallCheck(this, VariableEditor);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(VariableEditor).call(this)); // Keep a cached version of the value, this cache will be updated when the
- // editor is updated, which can later be used to protect the editor from
- // unnecessary updates during the update lifecycle.
- _defineProperty(_assertThisInitialized(_this), "_onKeyUp", function (cm, event) {
- var code = event.keyCode;
- if (code >= 65 && code <= 90 || // letters
- !event.shiftKey && code >= 48 && code <= 57 || // numbers
- event.shiftKey && code === 189 || // underscore
- event.shiftKey && code === 222 // "
- ) {
- _this.editor.execCommand('autocomplete');
- }
- });
- _defineProperty(_assertThisInitialized(_this), "_onEdit", function () {
- if (!_this.ignoreChangeEvent) {
- _this.cachedValue = _this.editor.getValue();
- if (_this.props.onEdit) {
- _this.props.onEdit(_this.cachedValue);
- }
- }
- });
- _defineProperty(_assertThisInitialized(_this), "_onHasCompletion", function (cm, data) {
- (0, _onHasCompletion.default)(cm, data, _this.props.onHintInformationRender);
- });
- _this.cachedValue = props.value || '';
- return _this;
- }
- _createClass(VariableEditor, [{
- key: "componentDidMount",
- value: function componentDidMount() {
- var _this2 = this;
- // Lazily require to ensure requiring GraphiQL outside of a Browser context
- // does not produce an error.
- var CodeMirror = require('codemirror');
- require('codemirror/addon/hint/show-hint');
- require('codemirror/addon/edit/matchbrackets');
- require('codemirror/addon/edit/closebrackets');
- require('codemirror/addon/fold/brace-fold');
- require('codemirror/addon/fold/foldgutter');
- require('codemirror/addon/lint/lint');
- require('codemirror/addon/search/searchcursor');
- require('codemirror/addon/search/jump-to-line');
- require('codemirror/addon/dialog/dialog');
- require('codemirror/keymap/sublime');
- require('codemirror-graphql/variables/hint');
- require('codemirror-graphql/variables/lint');
- require('codemirror-graphql/variables/mode');
- this.editor = CodeMirror(this._node, {
- value: this.props.value || '',
- lineNumbers: true,
- tabSize: 2,
- mode: 'graphql-variables',
- theme: this.props.editorTheme || 'graphiql',
- keyMap: 'sublime',
- autoCloseBrackets: true,
- matchBrackets: true,
- showCursorWhenSelecting: true,
- readOnly: this.props.readOnly ? 'nocursor' : false,
- foldGutter: {
- minFoldSize: 4
- },
- lint: {
- variableToType: this.props.variableToType
- },
- hintOptions: {
- variableToType: this.props.variableToType,
- closeOnUnfocus: false,
- completeSingle: false,
- container: this._node
- },
- gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
- extraKeys: {
- 'Cmd-Space': function CmdSpace() {
- return _this2.editor.showHint({
- completeSingle: false,
- container: _this2._node
- });
- },
- 'Ctrl-Space': function CtrlSpace() {
- return _this2.editor.showHint({
- completeSingle: false,
- container: _this2._node
- });
- },
- 'Alt-Space': function AltSpace() {
- return _this2.editor.showHint({
- completeSingle: false,
- container: _this2._node
- });
- },
- 'Shift-Space': function ShiftSpace() {
- return _this2.editor.showHint({
- completeSingle: false,
- container: _this2._node
- });
- },
- 'Cmd-Enter': function CmdEnter() {
- if (_this2.props.onRunQuery) {
- _this2.props.onRunQuery();
- }
- },
- 'Ctrl-Enter': function CtrlEnter() {
- if (_this2.props.onRunQuery) {
- _this2.props.onRunQuery();
- }
- },
- 'Shift-Ctrl-P': function ShiftCtrlP() {
- if (_this2.props.onPrettifyQuery) {
- _this2.props.onPrettifyQuery();
- }
- },
- 'Shift-Ctrl-M': function ShiftCtrlM() {
- if (_this2.props.onMergeQuery) {
- _this2.props.onMergeQuery();
- }
- },
- // Persistent search box in Query Editor
- 'Cmd-F': 'findPersistent',
- 'Ctrl-F': 'findPersistent',
- 'Cmd-G': 'findPersistent',
- 'Ctrl-G': 'findPersistent',
- // Editor improvements
- 'Ctrl-Left': 'goSubwordLeft',
- 'Ctrl-Right': 'goSubwordRight',
- 'Alt-Left': 'goGroupLeft',
- 'Alt-Right': 'goGroupRight'
- }
- });
- this.editor.on('change', this._onEdit);
- this.editor.on('keyup', this._onKeyUp);
- this.editor.on('hasCompletion', this._onHasCompletion);
- }
- }, {
- key: "componentDidUpdate",
- value: function componentDidUpdate(prevProps) {
- var CodeMirror = require('codemirror'); // Ensure the changes caused by this update are not interpretted as
- // user-input changes which could otherwise result in an infinite
- // event loop.
- this.ignoreChangeEvent = true;
- if (this.props.variableToType !== prevProps.variableToType) {
- this.editor.options.lint.variableToType = this.props.variableToType;
- this.editor.options.hintOptions.variableToType = this.props.variableToType;
- CodeMirror.signal(this.editor, 'change', this.editor);
- }
- if (this.props.value !== prevProps.value && this.props.value !== this.cachedValue) {
- var thisValue = this.props.value || '';
- this.cachedValue = thisValue;
- this.editor.setValue(thisValue);
- }
- this.ignoreChangeEvent = false;
- }
- }, {
- key: "componentWillUnmount",
- value: function componentWillUnmount() {
- this.editor.off('change', this._onEdit);
- this.editor.off('keyup', this._onKeyUp);
- this.editor.off('hasCompletion', this._onHasCompletion);
- this.editor = null;
- }
- }, {
- key: "render",
- value: function render() {
- var _this3 = this;
- return _react.default.createElement("div", {
- className: "codemirrorWrap",
- ref: function ref(node) {
- _this3._node = node;
- }
- });
- }
- /**
- * Public API for retrieving the CodeMirror instance from this
- * React component.
- */
- }, {
- key: "getCodeMirror",
- value: function getCodeMirror() {
- return this.editor;
- }
- /**
- * Public API for retrieving the DOM client height for this component.
- */
- }, {
- key: "getClientHeight",
- value: function getClientHeight() {
- return this._node && this._node.clientHeight;
- }
- }]);
- return VariableEditor;
- }(_react.default.Component);
- exports.VariableEditor = VariableEditor;
- _defineProperty(VariableEditor, "propTypes", {
- variableToType: _propTypes.default.object,
- value: _propTypes.default.string,
- onEdit: _propTypes.default.func,
- readOnly: _propTypes.default.bool,
- onHintInformationRender: _propTypes.default.func,
- onPrettifyQuery: _propTypes.default.func,
- onMergeQuery: _propTypes.default.func,
- onRunQuery: _propTypes.default.func,
- editorTheme: _propTypes.default.string
- });
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"../utility/onHasCompletion":252,"codemirror":16,"codemirror-graphql/variables/hint":399,"codemirror-graphql/variables/lint":400,"codemirror-graphql/variables/mode":401,"codemirror/addon/dialog/dialog":4,"codemirror/addon/edit/closebrackets":5,"codemirror/addon/edit/matchbrackets":6,"codemirror/addon/fold/brace-fold":7,"codemirror/addon/fold/foldgutter":9,"codemirror/addon/hint/show-hint":10,"codemirror/addon/lint/lint":11,"codemirror/addon/search/jump-to-line":12,"codemirror/addon/search/searchcursor":14,"codemirror/keymap/sublime":15,"prop-types":202}],239:[function(require,module,exports){
- "use strict";
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- // The primary React component to use.
- module.exports = require('./components/GraphiQL').GraphiQL;
- },{"./components/GraphiQL":228}],240:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- /**
- * When a containing DOM node's height has been altered, trigger a resize of
- * the related CodeMirror instance so that it is always correctly sized.
- */
- var CodeMirrorSizer =
- /*#__PURE__*/
- function () {
- function CodeMirrorSizer() {
- _classCallCheck(this, CodeMirrorSizer);
- this.sizes = [];
- }
- _createClass(CodeMirrorSizer, [{
- key: "updateSizes",
- value: function updateSizes(components) {
- var _this = this;
- components.forEach(function (component, i) {
- var size = component.getClientHeight();
- if (i <= _this.sizes.length && size !== _this.sizes[i]) {
- component.getCodeMirror().setSize();
- }
- _this.sizes[i] = size;
- });
- }
- }]);
- return CodeMirrorSizer;
- }();
- exports.default = CodeMirrorSizer;
- },{}],241:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- var QueryStore =
- /*#__PURE__*/
- function () {
- function QueryStore(key, storage) {
- _classCallCheck(this, QueryStore);
- this.key = key;
- this.storage = storage;
- this.items = this.fetchAll();
- }
- _createClass(QueryStore, [{
- key: "contains",
- value: function contains(item) {
- return this.items.some(function (x) {
- return x.query === item.query && x.variables === item.variables && x.operationName === item.operationName;
- });
- }
- }, {
- key: "edit",
- value: function edit(item) {
- var itemIndex = this.items.findIndex(function (x) {
- return x.query === item.query && x.variables === item.variables && x.operationName === item.operationName;
- });
- if (itemIndex !== -1) {
- this.items.splice(itemIndex, 1, item);
- this.save();
- }
- }
- }, {
- key: "delete",
- value: function _delete(item) {
- var itemIndex = this.items.findIndex(function (x) {
- return x.query === item.query && x.variables === item.variables && x.operationName === item.operationName;
- });
- if (itemIndex !== -1) {
- this.items.splice(itemIndex, 1);
- this.save();
- }
- }
- }, {
- key: "fetchRecent",
- value: function fetchRecent() {
- return this.items[this.items.length - 1];
- }
- }, {
- key: "fetchAll",
- value: function fetchAll() {
- var raw = this.storage.get(this.key);
- if (raw) {
- return JSON.parse(raw)[this.key];
- }
- return [];
- }
- }, {
- key: "push",
- value: function push(item) {
- this.items.push(item);
- this.save();
- }
- }, {
- key: "shift",
- value: function shift() {
- this.items.shift();
- this.save();
- }
- }, {
- key: "save",
- value: function save() {
- this.storage.set(this.key, JSON.stringify(_defineProperty({}, this.key, this.items)));
- }
- }, {
- key: "length",
- get: function get() {
- return this.items.length;
- }
- }]);
- return QueryStore;
- }();
- exports.default = QueryStore;
- },{}],242:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- var StorageAPI =
- /*#__PURE__*/
- function () {
- function StorageAPI(storage) {
- _classCallCheck(this, StorageAPI);
- this.storage = storage || window.localStorage;
- }
- _createClass(StorageAPI, [{
- key: "get",
- value: function get(name) {
- if (this.storage) {
- var value = this.storage.getItem('graphiql:' + name); // Clean up any inadvertently saved null/undefined values.
- if (value === 'null' || value === 'undefined') {
- this.storage.removeItem('graphiql:' + name);
- } else {
- return value;
- }
- }
- }
- }, {
- key: "set",
- value: function set(name, value) {
- if (this.storage) {
- var key = "graphiql:".concat(name);
- if (value) {
- if (isStorageAvailable(this.storage, key, value)) {
- this.storage.setItem(key, value);
- }
- } else {
- // Clean up by removing the item if there's no value to set
- this.storage.removeItem(key);
- }
- }
- }
- }]);
- return StorageAPI;
- }();
- exports.default = StorageAPI;
- function isStorageAvailable(storage, key, value) {
- try {
- storage.setItem(key, value);
- return true;
- } catch (e) {
- return e instanceof DOMException && ( // everything except Firefox
- e.code === 22 || // Firefox
- e.code === 1014 || // test name field too, because code might not be present
- // everything except Firefox
- e.name === 'QuotaExceededError' || // Firefox
- e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && // acknowledge QuotaExceededError only if there's something already stored
- storage.length !== 0;
- }
- }
- },{}],243:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = debounce;
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- /**
- * Provided a duration and a function, returns a new function which is called
- * `duration` milliseconds after the last call.
- */
- function debounce(duration, fn) {
- var timeout;
- return function () {
- var _this = this,
- _arguments = arguments;
- clearTimeout(timeout);
- timeout = setTimeout(function () {
- timeout = null;
- fn.apply(_this, _arguments);
- }, duration);
- };
- }
- },{}],244:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getLeft = getLeft;
- exports.getTop = getTop;
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- /**
- * Utility functions to get a pixel distance from left/top of the window.
- */
- function getLeft(initialElem) {
- var pt = 0;
- var elem = initialElem;
- while (elem.offsetParent) {
- pt += elem.offsetLeft;
- elem = elem.offsetParent;
- }
- return pt;
- }
- function getTop(initialElem) {
- var pt = 0;
- var elem = initialElem;
- while (elem.offsetParent) {
- pt += elem.offsetTop;
- elem = elem.offsetParent;
- }
- return pt;
- }
- },{}],245:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.fillLeafs = fillLeafs;
- var _graphql = require("graphql");
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- /**
- * Given a document string which may not be valid due to terminal fields not
- * representing leaf values (Spec Section: "Leaf Field Selections"), and a
- * function which provides reasonable default field names for a given type,
- * this function will attempt to produce a schema which is valid after filling
- * in selection sets for the invalid fields.
- *
- * Note that there is no guarantee that the result will be a valid query, this
- * utility represents a "best effort" which may be useful within IDE tools.
- */
- function fillLeafs(schema, docString, getDefaultFieldNames) {
- var insertions = [];
- if (!schema) {
- return {
- insertions: insertions,
- result: docString
- };
- }
- var ast;
- try {
- ast = (0, _graphql.parse)(docString);
- } catch (error) {
- return {
- insertions: insertions,
- result: docString
- };
- }
- var fieldNameFn = getDefaultFieldNames || defaultGetDefaultFieldNames;
- var typeInfo = new _graphql.TypeInfo(schema);
- (0, _graphql.visit)(ast, {
- leave: function leave(node) {
- typeInfo.leave(node);
- },
- enter: function enter(node) {
- typeInfo.enter(node);
- if (node.kind === 'Field' && !node.selectionSet) {
- var fieldType = typeInfo.getType();
- var selectionSet = buildSelectionSet(fieldType, fieldNameFn);
- if (selectionSet) {
- var indent = getIndentation(docString, node.loc.start);
- insertions.push({
- index: node.loc.end,
- string: ' ' + (0, _graphql.print)(selectionSet).replace(/\n/g, '\n' + indent)
- });
- }
- }
- }
- }); // Apply the insertions, but also return the insertions metadata.
- return {
- insertions: insertions,
- result: withInsertions(docString, insertions)
- };
- } // The default function to use for producing the default fields from a type.
- // This function first looks for some common patterns, and falls back to
- // including all leaf-type fields.
- function defaultGetDefaultFieldNames(type) {
- // If this type cannot access fields, then return an empty set.
- if (!type.getFields) {
- return [];
- }
- var fields = type.getFields(); // Is there an `id` field?
- if (fields['id']) {
- return ['id'];
- } // Is there an `edges` field?
- if (fields['edges']) {
- return ['edges'];
- } // Is there an `node` field?
- if (fields['node']) {
- return ['node'];
- } // Include all leaf-type fields.
- var leafFieldNames = [];
- Object.keys(fields).forEach(function (fieldName) {
- if ((0, _graphql.isLeafType)(fields[fieldName].type)) {
- leafFieldNames.push(fieldName);
- }
- });
- return leafFieldNames;
- } // Given a GraphQL type, and a function which produces field names, recursively
- // generate a SelectionSet which includes default fields.
- function buildSelectionSet(type, getDefaultFieldNames) {
- // Unwrap any non-null or list types.
- var namedType = (0, _graphql.getNamedType)(type); // Unknown types and leaf types do not have selection sets.
- if (!type || (0, _graphql.isLeafType)(type)) {
- return;
- } // Get an array of field names to use.
- var fieldNames = getDefaultFieldNames(namedType); // If there are no field names to use, return no selection set.
- if (!Array.isArray(fieldNames) || fieldNames.length === 0) {
- return;
- } // Build a selection set of each field, calling buildSelectionSet recursively.
- return {
- kind: 'SelectionSet',
- selections: fieldNames.map(function (fieldName) {
- var fieldDef = namedType.getFields()[fieldName];
- var fieldType = fieldDef ? fieldDef.type : null;
- return {
- kind: 'Field',
- name: {
- kind: 'Name',
- value: fieldName
- },
- selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames)
- };
- })
- };
- } // Given an initial string, and a list of "insertion" { index, string } objects,
- // return a new string with these insertions applied.
- function withInsertions(initial, insertions) {
- if (insertions.length === 0) {
- return initial;
- }
- var edited = '';
- var prevIndex = 0;
- insertions.forEach(function (_ref) {
- var index = _ref.index,
- string = _ref.string;
- edited += initial.slice(prevIndex, index) + string;
- prevIndex = index;
- });
- edited += initial.slice(prevIndex);
- return edited;
- } // Given a string and an index, look backwards to find the string of whitespace
- // following the next previous line break.
- function getIndentation(str, index) {
- var indentStart = index;
- var indentEnd = index;
- while (indentStart) {
- var c = str.charCodeAt(indentStart - 1); // line break
- if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) {
- break;
- }
- indentStart--; // not white space
- if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) {
- indentEnd = indentStart;
- }
- }
- return str.substring(indentStart, indentEnd);
- }
- },{"graphql":29}],246:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = find;
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- *
- */
- function find(list, predicate) {
- for (var i = 0; i < list.length; i++) {
- if (predicate(list[i])) {
- return list[i];
- }
- }
- }
- },{}],247:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = getQueryFacts;
- exports.collectVariables = collectVariables;
- var _graphql = require("graphql");
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- /**
- * Provided previous "queryFacts", a GraphQL schema, and a query document
- * string, return a set of facts about that query useful for GraphiQL features.
- *
- * If the query cannot be parsed, returns undefined.
- */
- function getQueryFacts(schema, documentStr) {
- if (!documentStr) {
- return;
- }
- var documentAST;
- try {
- documentAST = (0, _graphql.parse)(documentStr);
- } catch (e) {
- return;
- }
- var variableToType = schema ? collectVariables(schema, documentAST) : null; // Collect operations by their names.
- var operations = [];
- documentAST.definitions.forEach(function (def) {
- if (def.kind === 'OperationDefinition') {
- operations.push(def);
- }
- });
- return {
- variableToType: variableToType,
- operations: operations
- };
- }
- /**
- * Provided a schema and a document, produces a `variableToType` Object.
- */
- function collectVariables(schema, documentAST) {
- var variableToType = Object.create(null);
- documentAST.definitions.forEach(function (definition) {
- if (definition.kind === 'OperationDefinition') {
- var variableDefinitions = definition.variableDefinitions;
- if (variableDefinitions) {
- variableDefinitions.forEach(function (_ref) {
- var variable = _ref.variable,
- type = _ref.type;
- var inputType = (0, _graphql.typeFromAST)(schema, type);
- if (inputType) {
- variableToType[variable.name.value] = inputType;
- }
- });
- }
- }
- });
- return variableToType;
- }
- },{"graphql":29}],248:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = getSelectedOperationName;
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- /**
- * Provided optional previous operations and selected name, and a next list of
- * operations, determine what the next selected operation should be.
- */
- function getSelectedOperationName(prevOperations, prevSelectedOperationName, operations) {
- // If there are not enough operations to bother with, return nothing.
- if (!operations || operations.length < 1) {
- return;
- } // If a previous selection still exists, continue to use it.
- var names = operations.map(function (op) {
- return op.name && op.name.value;
- });
- if (prevSelectedOperationName && names.indexOf(prevSelectedOperationName) !== -1) {
- return prevSelectedOperationName;
- } // If a previous selection was the Nth operation, use the same Nth.
- if (prevSelectedOperationName && prevOperations) {
- var prevNames = prevOperations.map(function (op) {
- return op.name && op.name.value;
- });
- var prevIndex = prevNames.indexOf(prevSelectedOperationName);
- if (prevIndex !== -1 && prevIndex < names.length) {
- return names[prevIndex];
- }
- } // Use the first operation.
- return names[0];
- }
- },{}],249:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "introspectionQuery", {
- enumerable: true,
- get: function get() {
- return _graphql.introspectionQuery;
- }
- });
- exports.introspectionQuerySansSubscriptions = exports.introspectionQueryName = void 0;
- var _graphql = require("graphql");
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- var introspectionQueryName = (0, _graphql.getOperationAST)((0, _graphql.parse)(_graphql.introspectionQuery)).name.value; // Some GraphQL services do not support subscriptions and fail an introspection
- // query which includes the `subscriptionType` field as the stock introspection
- // query does. This backup query removes that field.
- exports.introspectionQueryName = introspectionQueryName;
- var introspectionQuerySansSubscriptions = "\n query ".concat(introspectionQueryName, " {\n __schema {\n queryType { name }\n mutationType { name }\n types {\n ...FullType\n }\n directives {\n name\n description\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n");
- exports.introspectionQuerySansSubscriptions = introspectionQuerySansSubscriptions;
- },{"graphql":29}],250:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.mergeAst = mergeAst;
- var _kinds = require("graphql/language/kinds");
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- function resolveDefinition(fragments, obj) {
- var definition = obj;
- if (definition.kind === _kinds.Kind.FRAGMENT_SPREAD) {
- definition = fragments[definition.name.value];
- }
- if (definition.selectionSet) {
- definition.selectionSet.selections = definition.selectionSet.selections.filter(function (selection, idx, self) {
- return selection.kind !== _kinds.Kind.FRAGMENT_SPREAD || idx === self.findIndex(function (_selection) {
- return _selection.kind === _kinds.Kind.FRAGMENT_SPREAD && selection.name.value === _selection.name.value;
- });
- }).map(function (selection) {
- return resolveDefinition(fragments, selection);
- });
- }
- return definition;
- }
- function mergeAst(queryAst) {
- var fragments = {};
- queryAst.definitions.filter(function (elem) {
- return elem.kind === _kinds.Kind.FRAGMENT_DEFINITION;
- }).forEach(function (frag) {
- var copyFragment = Object.assign({}, frag);
- copyFragment.kind = _kinds.Kind.INLINE_FRAGMENT;
- fragments[frag.name.value] = copyFragment;
- });
- var copyAst = Object.assign({}, queryAst);
- copyAst.definitions = queryAst.definitions.filter(function (elem) {
- return elem.kind !== _kinds.Kind.FRAGMENT_DEFINITION;
- }).map(function (op) {
- return resolveDefinition(fragments, op);
- });
- return copyAst;
- }
- },{"graphql/language/kinds":51}],251:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.normalizeWhitespace = normalizeWhitespace;
- exports.invalidCharacters = void 0;
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- // Unicode whitespace characters that break the interface.
- var invalidCharacters = Array.from({
- length: 11
- }, function (x, i) {
- // \u2000 -> \u200a
- return String.fromCharCode(0x2000 + i);
- }).concat(["\u2028", "\u2029", "\u202F", "\xA0"]);
- exports.invalidCharacters = invalidCharacters;
- var sanitizeRegex = new RegExp('[' + invalidCharacters.join('') + ']', 'g');
- function normalizeWhitespace(line) {
- return line.replace(sanitizeRegex, ' ');
- }
- },{}],252:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = onHasCompletion;
- var _graphql = require("graphql");
- var _markdownIt = _interopRequireDefault(require("markdown-it"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2019 GraphQL Contributors.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
- var md = new _markdownIt.default();
- /**
- * Render a custom UI for CodeMirror's hint which includes additional info
- * about the type and description for the selected context.
- */
- function onHasCompletion(cm, data, onHintInformationRender) {
- var CodeMirror = require('codemirror');
- var information;
- var deprecation; // When a hint result is selected, we augment the UI with information.
- CodeMirror.on(data, 'select', function (ctx, el) {
- // Only the first time (usually when the hint UI is first displayed)
- // do we create the information nodes.
- if (!information) {
- var hintsUl = el.parentNode; // This "information" node will contain the additional info about the
- // highlighted typeahead option.
- information = document.createElement('div');
- information.className = 'CodeMirror-hint-information';
- hintsUl.appendChild(information); // This "deprecation" node will contain info about deprecated usage.
- deprecation = document.createElement('div');
- deprecation.className = 'CodeMirror-hint-deprecation';
- hintsUl.appendChild(deprecation); // When CodeMirror attempts to remove the hint UI, we detect that it was
- // removed and in turn remove the information nodes.
- var _onRemoveFn;
- hintsUl.addEventListener('DOMNodeRemoved', _onRemoveFn = function onRemoveFn(event) {
- if (event.target === hintsUl) {
- hintsUl.removeEventListener('DOMNodeRemoved', _onRemoveFn);
- information = null;
- deprecation = null;
- _onRemoveFn = null;
- }
- });
- } // Now that the UI has been set up, add info to information.
- var description = ctx.description ? md.render(ctx.description) : 'Self descriptive.';
- var type = ctx.type ? '<span class="infoType">' + renderType(ctx.type) + '</span>' : '';
- information.innerHTML = '<div class="content">' + (description.slice(0, 3) === '<p>' ? '<p>' + type + description.slice(3) : type + description) + '</div>';
- if (ctx.isDeprecated) {
- var reason = ctx.deprecationReason ? md.render(ctx.deprecationReason) : '';
- deprecation.innerHTML = '<span class="deprecation-label">Deprecated</span>' + reason;
- deprecation.style.display = 'block';
- } else {
- deprecation.style.display = 'none';
- } // Additional rendering?
- if (onHintInformationRender) {
- onHintInformationRender(information);
- }
- });
- }
- function renderType(type) {
- if (type instanceof _graphql.GraphQLNonNull) {
- return "".concat(renderType(type.ofType), "!");
- }
- if (type instanceof _graphql.GraphQLList) {
- return "[".concat(renderType(type.ofType), "]");
- }
- return "<a class=\"typeName\">".concat(type.name, "</a>");
- }
- },{"codemirror":16,"graphql":29,"markdown-it":140}],253:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- var _graphqlLanguageServiceInterface = require('graphql-language-service-interface');
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Registers a "hint" helper for CodeMirror.
- *
- * Using CodeMirror's "hint" addon: https://codemirror.net/demo/complete.html
- * Given an editor, this helper will take the token at the cursor and return a
- * list of suggested tokens.
- *
- * Options:
- *
- * - schema: GraphQLSchema provides the hinter with positionally relevant info
- *
- * Additional Events:
- *
- * - hasCompletion (codemirror, data, token) - signaled when the hinter has a
- * new list of completion suggestions.
- *
- */
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- _codemirror2.default.registerHelper('hint', 'graphql', function (editor, options) {
- var schema = options.schema;
- if (!schema) {
- return;
- }
- var cur = editor.getCursor();
- var token = editor.getTokenAt(cur);
- var rawResults = (0, _graphqlLanguageServiceInterface.getAutocompleteSuggestions)(schema, editor.getValue(), cur, token);
- /**
- * GraphQL language service responds to the autocompletion request with
- * a different format:
- * type CompletionItem = {
- * label: string,
- * kind?: number,
- * detail?: string,
- * documentation?: string,
- * // GraphQL Deprecation information
- * isDeprecated?: ?string,
- * deprecationReason?: ?string,
- * };
- *
- * Switch to codemirror-compliant format before returning results.
- */
- var tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end;
- var results = {
- list: rawResults.map(function (item) {
- return {
- text: item.label,
- type: schema.getType(item.detail),
- description: item.documentation,
- isDeprecated: item.isDeprecated,
- deprecationReason: item.deprecationReason
- };
- }),
- from: { line: cur.line, column: tokenStart },
- to: { line: cur.line, column: token.end }
- };
- if (results && results.list && results.list.length > 0) {
- results.from = _codemirror2.default.Pos(results.from.line, results.from.column);
- results.to = _codemirror2.default.Pos(results.to.line, results.to.column);
- _codemirror2.default.signal(editor, 'hasCompletion', editor, results, token);
- }
- return results;
- });
- },{"codemirror":16,"graphql-language-service-interface":265}],254:[function(require,module,exports){
- 'use strict';
- var _graphql = require('graphql');
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- var _getTypeInfo = require('./utils/getTypeInfo');
- var _getTypeInfo2 = _interopRequireDefault(_getTypeInfo);
- var _SchemaReference = require('./utils/SchemaReference');
- require('./utils/info-addon');
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Registers GraphQL "info" tooltips for CodeMirror.
- *
- * When hovering over a token, this presents a tooltip explaining it.
- *
- * Options:
- *
- * - schema: GraphQLSchema provides positionally relevant info.
- * - hoverTime: The number of ms to wait before showing info. (Default 500)
- * - renderDescription: Convert a description to some HTML, Useful since
- * descriptions are often Markdown formatted.
- * - onClick: A function called when a named thing is clicked.
- *
- */
- _codemirror2.default.registerHelper('info', 'graphql', function (token, options) {
- if (!options.schema || !token.state) {
- return;
- }
- var state = token.state;
- var kind = state.kind;
- var step = state.step;
- var typeInfo = (0, _getTypeInfo2.default)(options.schema, token.state);
- // Given a Schema and a Token, produce the contents of an info tooltip.
- // To do this, create a div element that we will render "into" and then pass
- // it to various rendering functions.
- if (kind === 'Field' && step === 0 && typeInfo.fieldDef || kind === 'AliasedField' && step === 2 && typeInfo.fieldDef) {
- var into = document.createElement('div');
- renderField(into, typeInfo, options);
- renderDescription(into, options, typeInfo.fieldDef);
- return into;
- } else if (kind === 'Directive' && step === 1 && typeInfo.directiveDef) {
- var _into = document.createElement('div');
- renderDirective(_into, typeInfo, options);
- renderDescription(_into, options, typeInfo.directiveDef);
- return _into;
- } else if (kind === 'Argument' && step === 0 && typeInfo.argDef) {
- var _into2 = document.createElement('div');
- renderArg(_into2, typeInfo, options);
- renderDescription(_into2, options, typeInfo.argDef);
- return _into2;
- } else if (kind === 'EnumValue' && typeInfo.enumValue && typeInfo.enumValue.description) {
- var _into3 = document.createElement('div');
- renderEnumValue(_into3, typeInfo, options);
- renderDescription(_into3, options, typeInfo.enumValue);
- return _into3;
- } else if (kind === 'NamedType' && typeInfo.type && typeInfo.type.description) {
- var _into4 = document.createElement('div');
- renderType(_into4, typeInfo, options, typeInfo.type);
- renderDescription(_into4, options, typeInfo.type);
- return _into4;
- }
- });
- /**
- * Copyright (c) 2017, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- function renderField(into, typeInfo, options) {
- renderQualifiedField(into, typeInfo, options);
- renderTypeAnnotation(into, typeInfo, options, typeInfo.type);
- }
- function renderQualifiedField(into, typeInfo, options) {
- var fieldName = typeInfo.fieldDef.name;
- if (fieldName.slice(0, 2) !== '__') {
- renderType(into, typeInfo, options, typeInfo.parentType);
- text(into, '.');
- }
- text(into, fieldName, 'field-name', options, (0, _SchemaReference.getFieldReference)(typeInfo));
- }
- function renderDirective(into, typeInfo, options) {
- var name = '@' + typeInfo.directiveDef.name;
- text(into, name, 'directive-name', options, (0, _SchemaReference.getDirectiveReference)(typeInfo));
- }
- function renderArg(into, typeInfo, options) {
- if (typeInfo.directiveDef) {
- renderDirective(into, typeInfo, options);
- } else if (typeInfo.fieldDef) {
- renderQualifiedField(into, typeInfo, options);
- }
- var name = typeInfo.argDef.name;
- text(into, '(');
- text(into, name, 'arg-name', options, (0, _SchemaReference.getArgumentReference)(typeInfo));
- renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType);
- text(into, ')');
- }
- function renderTypeAnnotation(into, typeInfo, options, t) {
- text(into, ': ');
- renderType(into, typeInfo, options, t);
- }
- function renderEnumValue(into, typeInfo, options) {
- var name = typeInfo.enumValue.name;
- renderType(into, typeInfo, options, typeInfo.inputType);
- text(into, '.');
- text(into, name, 'enum-value', options, (0, _SchemaReference.getEnumValueReference)(typeInfo));
- }
- function renderType(into, typeInfo, options, t) {
- if (t instanceof _graphql.GraphQLNonNull) {
- renderType(into, typeInfo, options, t.ofType);
- text(into, '!');
- } else if (t instanceof _graphql.GraphQLList) {
- text(into, '[');
- renderType(into, typeInfo, options, t.ofType);
- text(into, ']');
- } else {
- text(into, t.name, 'type-name', options, (0, _SchemaReference.getTypeReference)(typeInfo, t));
- }
- }
- function renderDescription(into, options, def) {
- var description = def.description;
- if (description) {
- var descriptionDiv = document.createElement('div');
- descriptionDiv.className = 'info-description';
- if (options.renderDescription) {
- descriptionDiv.innerHTML = options.renderDescription(description);
- } else {
- descriptionDiv.appendChild(document.createTextNode(description));
- }
- into.appendChild(descriptionDiv);
- }
- renderDeprecation(into, options, def);
- }
- function renderDeprecation(into, options, def) {
- var reason = def.deprecationReason;
- if (reason) {
- var deprecationDiv = document.createElement('div');
- deprecationDiv.className = 'info-deprecation';
- if (options.renderDescription) {
- deprecationDiv.innerHTML = options.renderDescription(reason);
- } else {
- deprecationDiv.appendChild(document.createTextNode(reason));
- }
- var label = document.createElement('span');
- label.className = 'info-deprecation-label';
- label.appendChild(document.createTextNode('Deprecated: '));
- deprecationDiv.insertBefore(label, deprecationDiv.firstChild);
- into.appendChild(deprecationDiv);
- }
- }
- function text(into, content, className, options, ref) {
- if (className) {
- var onClick = options.onClick;
- var node = document.createElement(onClick ? 'a' : 'span');
- if (onClick) {
- // Providing a href forces proper a tag behavior, though we don't actually
- // want clicking the node to navigate anywhere.
- node.href = 'javascript:void 0'; // eslint-disable-line no-script-url
- node.addEventListener('click', function (e) {
- onClick(ref, e);
- });
- }
- node.className = className;
- node.appendChild(document.createTextNode(content));
- into.appendChild(node);
- } else {
- into.appendChild(document.createTextNode(content));
- }
- }
- },{"./utils/SchemaReference":392,"./utils/getTypeInfo":394,"./utils/info-addon":396,"codemirror":16,"graphql":285}],255:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- var _getTypeInfo = require('./utils/getTypeInfo');
- var _getTypeInfo2 = _interopRequireDefault(_getTypeInfo);
- var _SchemaReference = require('./utils/SchemaReference');
- require('./utils/jump-addon');
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Registers GraphQL "jump" links for CodeMirror.
- *
- * When command-hovering over a token, this converts it to a link, which when
- * pressed will call the provided onClick handler.
- *
- * Options:
- *
- * - schema: GraphQLSchema provides positionally relevant info.
- * - onClick: A function called when a named thing is clicked.
- *
- */
- /**
- * Copyright (c) 2017, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- _codemirror2.default.registerHelper('jump', 'graphql', function (token, options) {
- if (!options.schema || !options.onClick || !token.state) {
- return;
- }
- // Given a Schema and a Token, produce a "SchemaReference" which refers to
- // the particular artifact from the schema (such as a type, field, argument,
- // or directive) that token references.
- var state = token.state;
- var kind = state.kind;
- var step = state.step;
- var typeInfo = (0, _getTypeInfo2.default)(options.schema, state);
- if (kind === 'Field' && step === 0 && typeInfo.fieldDef || kind === 'AliasedField' && step === 2 && typeInfo.fieldDef) {
- return (0, _SchemaReference.getFieldReference)(typeInfo);
- } else if (kind === 'Directive' && step === 1 && typeInfo.directiveDef) {
- return (0, _SchemaReference.getDirectiveReference)(typeInfo);
- } else if (kind === 'Argument' && step === 0 && typeInfo.argDef) {
- return (0, _SchemaReference.getArgumentReference)(typeInfo);
- } else if (kind === 'EnumValue' && typeInfo.enumValue) {
- return (0, _SchemaReference.getEnumValueReference)(typeInfo);
- } else if (kind === 'NamedType' && typeInfo.type) {
- return (0, _SchemaReference.getTypeReference)(typeInfo);
- }
- });
- },{"./utils/SchemaReference":392,"./utils/getTypeInfo":394,"./utils/jump-addon":398,"codemirror":16}],256:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- var _graphqlLanguageServiceInterface = require('graphql-language-service-interface');
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- var SEVERITY = ['error', 'warning', 'information', 'hint'];
- var TYPE = {
- 'GraphQL: Validation': 'validation',
- 'GraphQL: Deprecation': 'deprecation',
- 'GraphQL: Syntax': 'syntax'
- };
- /**
- * Registers a "lint" helper for CodeMirror.
- *
- * Using CodeMirror's "lint" addon: https://codemirror.net/demo/lint.html
- * Given the text within an editor, this helper will take that text and return
- * a list of linter issues, derived from GraphQL's parse and validate steps.
- * Also, this uses `graphql-language-service-parser` to power the diagnostics
- * service.
- *
- * Options:
- *
- * - schema: GraphQLSchema provides the linter with positionally relevant info
- *
- */
- _codemirror2.default.registerHelper('lint', 'graphql', function (text, options) {
- var schema = options.schema;
- var rawResults = (0, _graphqlLanguageServiceInterface.getDiagnostics)(text, schema);
- var results = rawResults.map(function (error) {
- return {
- message: error.message,
- severity: SEVERITY[error.severity - 1],
- type: TYPE[error.source],
- from: _codemirror2.default.Pos(error.range.start.line, error.range.start.character),
- to: _codemirror2.default.Pos(error.range.end.line, error.range.end.character)
- };
- });
- return results;
- });
- },{"codemirror":16,"graphql-language-service-interface":265}],257:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- var _graphqlLanguageServiceParser = require('graphql-language-service-parser');
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * The GraphQL mode is defined as a tokenizer along with a list of rules, each
- * of which is either a function or an array.
- *
- * * Function: Provided a token and the stream, returns an expected next step.
- * * Array: A list of steps to take in order.
- *
- * A step is either another rule, or a terminal description of a token. If it
- * is a rule, that rule is pushed onto the stack and the parsing continues from
- * that point.
- *
- * If it is a terminal description, the token is checked against it using a
- * `match` function. If the match is successful, the token is colored and the
- * rule is stepped forward. If the match is unsuccessful, the remainder of the
- * rule is skipped and the previous rule is advanced.
- *
- * This parsing algorithm allows for incremental online parsing within various
- * levels of the syntax tree and results in a structured `state` linked-list
- * which contains the relevant information to produce valuable typeaheads.
- */
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- _codemirror2.default.defineMode('graphql', function (config) {
- var parser = (0, _graphqlLanguageServiceParser.onlineParser)({
- eatWhitespace: function eatWhitespace(stream) {
- return stream.eatWhile(_graphqlLanguageServiceParser.isIgnored);
- },
- lexRules: _graphqlLanguageServiceParser.LexRules,
- parseRules: _graphqlLanguageServiceParser.ParseRules,
- editorConfig: { tabSize: config.tabSize }
- });
- return {
- config: config,
- startState: parser.startState,
- token: parser.token,
- indent: indent,
- electricInput: /^\s*[})\]]/,
- fold: 'brace',
- lineComment: '#',
- closeBrackets: {
- pairs: '()[]{}""',
- explode: '()[]{}'
- }
- };
- });
- function indent(state, textAfter) {
- var levels = state.levels;
- // If there is no stack of levels, use the current level.
- // Otherwise, use the top level, pre-emptively dedenting for close braces.
- var level = !levels || levels.length === 0 ? state.indentLevel : levels[levels.length - 1] - (this.electricInput.test(textAfter) ? 1 : 0);
- return level * this.config.indentUnit;
- }
- },{"codemirror":16,"graphql-language-service-parser":269}],258:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.GraphQLLanguageService = undefined;
- var _graphql = require('graphql');
- var _getAutocompleteSuggestions2 = require('./getAutocompleteSuggestions');
- var _getHoverInformation2 = require('./getHoverInformation');
- var _getDiagnostics = require('./getDiagnostics');
- var _getDefinition = require('./getDefinition');
- var _graphqlLanguageServiceUtils = require('graphql-language-service-utils');
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var FRAGMENT_DEFINITION = _graphql.Kind.FRAGMENT_DEFINITION,
- OBJECT_TYPE_DEFINITION = _graphql.Kind.OBJECT_TYPE_DEFINITION,
- INTERFACE_TYPE_DEFINITION = _graphql.Kind.INTERFACE_TYPE_DEFINITION,
- ENUM_TYPE_DEFINITION = _graphql.Kind.ENUM_TYPE_DEFINITION,
- UNION_TYPE_DEFINITION = _graphql.Kind.UNION_TYPE_DEFINITION,
- SCALAR_TYPE_DEFINITION = _graphql.Kind.SCALAR_TYPE_DEFINITION,
- INPUT_OBJECT_TYPE_DEFINITION = _graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION,
- SCALAR_TYPE_EXTENSION = _graphql.Kind.SCALAR_TYPE_EXTENSION,
- OBJECT_TYPE_EXTENSION = _graphql.Kind.OBJECT_TYPE_EXTENSION,
- INTERFACE_TYPE_EXTENSION = _graphql.Kind.INTERFACE_TYPE_EXTENSION,
- UNION_TYPE_EXTENSION = _graphql.Kind.UNION_TYPE_EXTENSION,
- ENUM_TYPE_EXTENSION = _graphql.Kind.ENUM_TYPE_EXTENSION,
- INPUT_OBJECT_TYPE_EXTENSION = _graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION,
- DIRECTIVE_DEFINITION = _graphql.Kind.DIRECTIVE_DEFINITION,
- FRAGMENT_SPREAD = _graphql.Kind.FRAGMENT_SPREAD,
- OPERATION_DEFINITION = _graphql.Kind.OPERATION_DEFINITION,
- NAMED_TYPE = _graphql.Kind.NAMED_TYPE;
- var GraphQLLanguageService = exports.GraphQLLanguageService = function () {
- function GraphQLLanguageService(cache) {
- _classCallCheck(this, GraphQLLanguageService);
- this._graphQLCache = cache;
- this._graphQLConfig = cache.getGraphQLConfig();
- }
- GraphQLLanguageService.prototype.getDiagnostics = function getDiagnostics(query, uri, isRelayCompatMode) {
- var queryHasExtensions, projectConfig, schemaPath, queryAST, range, source, fragmentDefinitions, fragmentDependencies, dependenciesSource, validationAst, customRules, customRulesModulePath, rulesPath, schema;
- return regeneratorRuntime.async(function getDiagnostics$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- // Perform syntax diagnostics first, as this doesn't require
- // schema/fragment definitions, even the project configuration.
- queryHasExtensions = false;
- projectConfig = this._graphQLConfig.getConfigForFile(uri);
- schemaPath = projectConfig.schemaPath;
- _context.prev = 3;
- queryAST = (0, _graphql.parse)(query);
- if (!schemaPath || uri !== schemaPath) {
- queryHasExtensions = queryAST.definitions.some(function (definition) {
- switch (definition.kind) {
- case OBJECT_TYPE_DEFINITION:
- case INTERFACE_TYPE_DEFINITION:
- case ENUM_TYPE_DEFINITION:
- case UNION_TYPE_DEFINITION:
- case SCALAR_TYPE_DEFINITION:
- case INPUT_OBJECT_TYPE_DEFINITION:
- case SCALAR_TYPE_EXTENSION:
- case OBJECT_TYPE_EXTENSION:
- case INTERFACE_TYPE_EXTENSION:
- case UNION_TYPE_EXTENSION:
- case ENUM_TYPE_EXTENSION:
- case INPUT_OBJECT_TYPE_EXTENSION:
- case DIRECTIVE_DEFINITION:
- return true;
- }
- return false;
- });
- }
- _context.next = 12;
- break;
- case 8:
- _context.prev = 8;
- _context.t0 = _context['catch'](3);
- range = (0, _getDiagnostics.getRange)(_context.t0.locations[0], query);
- return _context.abrupt('return', [{
- severity: _getDiagnostics.SEVERITY.ERROR,
- message: _context.t0.message,
- source: 'GraphQL: Syntax',
- range: range
- }]);
- case 12:
- // If there's a matching config, proceed to prepare to run validation
- source = query;
- _context.next = 15;
- return regeneratorRuntime.awrap(this._graphQLCache.getFragmentDefinitions(projectConfig));
- case 15:
- fragmentDefinitions = _context.sent;
- _context.next = 18;
- return regeneratorRuntime.awrap(this._graphQLCache.getFragmentDependencies(query, fragmentDefinitions));
- case 18:
- fragmentDependencies = _context.sent;
- dependenciesSource = fragmentDependencies.reduce(function (prev, cur) {
- return prev + ' ' + (0, _graphql.print)(cur.definition);
- }, '');
- source = source + ' ' + dependenciesSource;
- validationAst = null;
- _context.prev = 22;
- validationAst = (0, _graphql.parse)(source);
- _context.next = 29;
- break;
- case 26:
- _context.prev = 26;
- _context.t1 = _context['catch'](22);
- return _context.abrupt('return', []);
- case 29:
- // Check if there are custom validation rules to be used
- customRules = void 0;
- customRulesModulePath = projectConfig.extensions.customValidationRules;
- if (customRulesModulePath) {
- /* eslint-disable no-implicit-coercion */
- rulesPath = require.resolve('' + customRulesModulePath);
- if (rulesPath) {
- customRules = require('' + rulesPath)(this._graphQLConfig);
- }
- /* eslint-enable no-implicit-coercion */
- }
- _context.next = 34;
- return regeneratorRuntime.awrap(this._graphQLCache.getSchema(projectConfig.projectName, queryHasExtensions).catch(function () {
- return null;
- }));
- case 34:
- schema = _context.sent;
- if (schema) {
- _context.next = 37;
- break;
- }
- return _context.abrupt('return', []);
- case 37:
- return _context.abrupt('return', (0, _getDiagnostics.validateQuery)(validationAst, schema, customRules, isRelayCompatMode));
- case 38:
- case 'end':
- return _context.stop();
- }
- }
- }, null, this, [[3, 8], [22, 26]]);
- };
- GraphQLLanguageService.prototype.getAutocompleteSuggestions = function getAutocompleteSuggestions(query, position, filePath) {
- var projectConfig, schema;
- return regeneratorRuntime.async(function getAutocompleteSuggestions$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- projectConfig = this._graphQLConfig.getConfigForFile(filePath);
- _context2.next = 3;
- return regeneratorRuntime.awrap(this._graphQLCache.getSchema(projectConfig.projectName).catch(function () {
- return null;
- }));
- case 3:
- schema = _context2.sent;
- if (!schema) {
- _context2.next = 6;
- break;
- }
- return _context2.abrupt('return', (0, _getAutocompleteSuggestions2.getAutocompleteSuggestions)(schema, query, position));
- case 6:
- return _context2.abrupt('return', []);
- case 7:
- case 'end':
- return _context2.stop();
- }
- }
- }, null, this);
- };
- GraphQLLanguageService.prototype.getHoverInformation = function getHoverInformation(query, position, filePath) {
- var projectConfig, schema;
- return regeneratorRuntime.async(function getHoverInformation$(_context3) {
- while (1) {
- switch (_context3.prev = _context3.next) {
- case 0:
- projectConfig = this._graphQLConfig.getConfigForFile(filePath);
- _context3.next = 3;
- return regeneratorRuntime.awrap(this._graphQLCache.getSchema(projectConfig.projectName).catch(function () {
- return null;
- }));
- case 3:
- schema = _context3.sent;
- if (!schema) {
- _context3.next = 6;
- break;
- }
- return _context3.abrupt('return', (0, _getHoverInformation2.getHoverInformation)(schema, query, position));
- case 6:
- return _context3.abrupt('return', '');
- case 7:
- case 'end':
- return _context3.stop();
- }
- }
- }, null, this);
- };
- GraphQLLanguageService.prototype.getDefinition = function getDefinition(query, position, filePath) {
- var projectConfig, ast, node;
- return regeneratorRuntime.async(function getDefinition$(_context4) {
- while (1) {
- switch (_context4.prev = _context4.next) {
- case 0:
- projectConfig = this._graphQLConfig.getConfigForFile(filePath);
- ast = void 0;
- _context4.prev = 2;
- ast = (0, _graphql.parse)(query);
- _context4.next = 9;
- break;
- case 6:
- _context4.prev = 6;
- _context4.t0 = _context4['catch'](2);
- return _context4.abrupt('return', null);
- case 9:
- node = (0, _graphqlLanguageServiceUtils.getASTNodeAtPosition)(query, ast, position);
- if (!node) {
- _context4.next = 17;
- break;
- }
- _context4.t1 = node.kind;
- _context4.next = _context4.t1 === FRAGMENT_SPREAD ? 14 : _context4.t1 === FRAGMENT_DEFINITION ? 15 : _context4.t1 === OPERATION_DEFINITION ? 15 : _context4.t1 === NAMED_TYPE ? 16 : 17;
- break;
- case 14:
- return _context4.abrupt('return', this._getDefinitionForFragmentSpread(query, ast, node, filePath, projectConfig));
- case 15:
- return _context4.abrupt('return', (0, _getDefinition.getDefinitionQueryResultForDefinitionNode)(filePath, query, node));
- case 16:
- return _context4.abrupt('return', this._getDefinitionForNamedType(query, ast, node, filePath, projectConfig));
- case 17:
- return _context4.abrupt('return', null);
- case 18:
- case 'end':
- return _context4.stop();
- }
- }
- }, null, this, [[2, 6]]);
- };
- GraphQLLanguageService.prototype._getDefinitionForNamedType = function _getDefinitionForNamedType(query, ast, node, filePath, projectConfig) {
- var objectTypeDefinitions, dependencies, localObjectTypeDefinitions, typeCastedDefs, localOperationDefinationInfos, result;
- return regeneratorRuntime.async(function _getDefinitionForNamedType$(_context5) {
- while (1) {
- switch (_context5.prev = _context5.next) {
- case 0:
- _context5.next = 2;
- return regeneratorRuntime.awrap(this._graphQLCache.getObjectTypeDefinitions(projectConfig));
- case 2:
- objectTypeDefinitions = _context5.sent;
- _context5.next = 5;
- return regeneratorRuntime.awrap(this._graphQLCache.getObjectTypeDependenciesForAST(ast, objectTypeDefinitions));
- case 5:
- dependencies = _context5.sent;
- localObjectTypeDefinitions = ast.definitions.filter(function (definition) {
- return definition.kind === OBJECT_TYPE_DEFINITION || definition.kind === INPUT_OBJECT_TYPE_DEFINITION || definition.kind === ENUM_TYPE_DEFINITION;
- });
- typeCastedDefs = localObjectTypeDefinitions;
- localOperationDefinationInfos = typeCastedDefs.map(function (definition) {
- return {
- filePath: filePath,
- content: query,
- definition: definition
- };
- });
- _context5.next = 11;
- return regeneratorRuntime.awrap((0, _getDefinition.getDefinitionQueryResultForNamedType)(query, node, dependencies.concat(localOperationDefinationInfos)));
- case 11:
- result = _context5.sent;
- return _context5.abrupt('return', result);
- case 13:
- case 'end':
- return _context5.stop();
- }
- }
- }, null, this);
- };
- GraphQLLanguageService.prototype._getDefinitionForFragmentSpread = function _getDefinitionForFragmentSpread(query, ast, node, filePath, projectConfig) {
- var fragmentDefinitions, dependencies, localFragDefinitions, typeCastedDefs, localFragInfos, result;
- return regeneratorRuntime.async(function _getDefinitionForFragmentSpread$(_context6) {
- while (1) {
- switch (_context6.prev = _context6.next) {
- case 0:
- _context6.next = 2;
- return regeneratorRuntime.awrap(this._graphQLCache.getFragmentDefinitions(projectConfig));
- case 2:
- fragmentDefinitions = _context6.sent;
- _context6.next = 5;
- return regeneratorRuntime.awrap(this._graphQLCache.getFragmentDependenciesForAST(ast, fragmentDefinitions));
- case 5:
- dependencies = _context6.sent;
- localFragDefinitions = ast.definitions.filter(function (definition) {
- return definition.kind === FRAGMENT_DEFINITION;
- });
- typeCastedDefs = localFragDefinitions;
- localFragInfos = typeCastedDefs.map(function (definition) {
- return {
- filePath: filePath,
- content: query,
- definition: definition
- };
- });
- _context6.next = 11;
- return regeneratorRuntime.awrap((0, _getDefinition.getDefinitionQueryResultForFragmentSpread)(query, node, dependencies.concat(localFragInfos)));
- case 11:
- result = _context6.sent;
- return _context6.abrupt('return', result);
- case 13:
- case 'end':
- return _context6.stop();
- }
- }
- }, null, this);
- };
- return GraphQLLanguageService;
- }();
- },{"./getAutocompleteSuggestions":260,"./getDefinition":261,"./getDiagnostics":262,"./getHoverInformation":263,"graphql":285,"graphql-language-service-utils":273}],259:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getDefinitionState = getDefinitionState;
- exports.getFieldDef = getFieldDef;
- exports.forEachState = forEachState;
- exports.objectValues = objectValues;
- exports.hintList = hintList;
- var _graphql = require('graphql');
- var _introspection = require('graphql/type/introspection');
- // Utility for returning the state representing the Definition this token state
- // is within, if any.
- function getDefinitionState(tokenState) {
- var definitionState = void 0;
- forEachState(tokenState, function (state) {
- switch (state.kind) {
- case 'Query':
- case 'ShortQuery':
- case 'Mutation':
- case 'Subscription':
- case 'FragmentDefinition':
- definitionState = state;
- break;
- }
- });
- return definitionState;
- }
- // Gets the field definition given a type and field name
- /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function getFieldDef(schema, type, fieldName) {
- if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === type) {
- return _introspection.SchemaMetaFieldDef;
- }
- if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === type) {
- return _introspection.TypeMetaFieldDef;
- }
- if (fieldName === _introspection.TypeNameMetaFieldDef.name && (0, _graphql.isCompositeType)(type)) {
- return _introspection.TypeNameMetaFieldDef;
- }
- if (type.getFields && typeof type.getFields === 'function') {
- return type.getFields()[fieldName];
- }
- return null;
- }
- // Utility for iterating through a CodeMirror parse state stack bottom-up.
- function forEachState(stack, fn) {
- var reverseStateStack = [];
- var state = stack;
- while (state && state.kind) {
- reverseStateStack.push(state);
- state = state.prevState;
- }
- for (var i = reverseStateStack.length - 1; i >= 0; i--) {
- fn(reverseStateStack[i]);
- }
- }
- function objectValues(object) {
- var keys = Object.keys(object);
- var len = keys.length;
- var values = new Array(len);
- for (var i = 0; i < len; ++i) {
- values[i] = object[keys[i]];
- }
- return values;
- }
- // Create the expected hint response given a possible list and a token
- function hintList(token, list) {
- return filterAndSortList(list, normalizeText(token.string));
- }
- // Given a list of hint entries and currently typed text, sort and filter to
- // provide a concise list.
- function filterAndSortList(list, text) {
- if (!text) {
- return filterNonEmpty(list, function (entry) {
- return !entry.isDeprecated;
- });
- }
- var byProximity = list.map(function (entry) {
- return {
- proximity: getProximity(normalizeText(entry.label), text),
- entry: entry
- };
- });
- var conciseMatches = filterNonEmpty(filterNonEmpty(byProximity, function (pair) {
- return pair.proximity <= 2;
- }), function (pair) {
- return !pair.entry.isDeprecated;
- });
- var sortedMatches = conciseMatches.sort(function (a, b) {
- return (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.label.length - b.entry.label.length;
- });
- return sortedMatches.map(function (pair) {
- return pair.entry;
- });
- }
- // Filters the array by the predicate, unless it results in an empty array,
- // in which case return the original array.
- function filterNonEmpty(array, predicate) {
- var filtered = array.filter(predicate);
- return filtered.length === 0 ? array : filtered;
- }
- function normalizeText(text) {
- return text.toLowerCase().replace(/\W/g, '');
- }
- // Determine a numeric proximity for a suggestion based on current text.
- function getProximity(suggestion, text) {
- // start with lexical distance
- var proximity = lexicalDistance(text, suggestion);
- if (suggestion.length > text.length) {
- // do not penalize long suggestions.
- proximity -= suggestion.length - text.length - 1;
- // penalize suggestions not starting with this phrase
- proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5;
- }
- return proximity;
- }
- /**
- * Computes the lexical distance between strings A and B.
- *
- * The "distance" between two strings is given by counting the minimum number
- * of edits needed to transform string A into string B. An edit can be an
- * insertion, deletion, or substitution of a single character, or a swap of two
- * adjacent characters.
- *
- * This distance can be useful for detecting typos in input or sorting
- *
- * @param {string} a
- * @param {string} b
- * @return {int} distance in number of edits
- */
- function lexicalDistance(a, b) {
- var i = void 0;
- var j = void 0;
- var d = [];
- var aLength = a.length;
- var bLength = b.length;
- for (i = 0; i <= aLength; i++) {
- d[i] = [i];
- }
- for (j = 1; j <= bLength; j++) {
- d[0][j] = j;
- }
- for (i = 1; i <= aLength; i++) {
- for (j = 1; j <= bLength; j++) {
- var cost = a[i - 1] === b[j - 1] ? 0 : 1;
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
- }
- }
- }
- return d[aLength][bLength];
- }
- },{"graphql":285,"graphql/type/introspection":326}],260:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- exports.getAutocompleteSuggestions = getAutocompleteSuggestions;
- exports.getTokenAtPosition = getTokenAtPosition;
- exports.getTypeInfo = getTypeInfo;
- var _graphql = require('graphql');
- var _graphqlLanguageServiceParser = require('graphql-language-service-parser');
- var _autocompleteUtils = require('./autocompleteUtils');
- /**
- * Given GraphQLSchema, queryText, and context of the current position within
- * the source text, provide a list of typeahead entries.
- */
- function getAutocompleteSuggestions(schema, queryText, cursor, contextToken) {
- var token = contextToken || getTokenAtPosition(queryText, cursor);
- var state = token.state.kind === 'Invalid' ? token.state.prevState : token.state;
- // relieve flow errors by checking if `state` exists
- if (!state) {
- return [];
- }
- var kind = state.kind;
- var step = state.step;
- var typeInfo = getTypeInfo(schema, token.state);
- // Definition kinds
- if (kind === 'Document') {
- return (0, _autocompleteUtils.hintList)(token, [{ label: 'query' }, { label: 'mutation' }, { label: 'subscription' }, { label: 'fragment' }, { label: '{' }]);
- }
- // Field names
- if (kind === 'SelectionSet' || kind === 'Field' || kind === 'AliasedField') {
- return getSuggestionsForFieldNames(token, typeInfo, schema);
- }
- // Argument names
- if (kind === 'Arguments' || kind === 'Argument' && step === 0) {
- var argDefs = typeInfo.argDefs;
- if (argDefs) {
- return (0, _autocompleteUtils.hintList)(token, argDefs.map(function (argDef) {
- return {
- label: argDef.name,
- detail: String(argDef.type),
- documentation: argDef.description
- };
- }));
- }
- }
- // Input Object fields
- if (kind === 'ObjectValue' || kind === 'ObjectField' && step === 0) {
- if (typeInfo.objectFieldDefs) {
- var objectFields = (0, _autocompleteUtils.objectValues)(typeInfo.objectFieldDefs);
- return (0, _autocompleteUtils.hintList)(token, objectFields.map(function (field) {
- return {
- label: field.name,
- detail: String(field.type),
- documentation: field.description
- };
- }));
- }
- }
- // Input values: Enum and Boolean
- if (kind === 'EnumValue' || kind === 'ListValue' && step === 1 || kind === 'ObjectField' && step === 2 || kind === 'Argument' && step === 2) {
- return getSuggestionsForInputValues(token, typeInfo);
- }
- // Fragment type conditions
- if (kind === 'TypeCondition' && step === 1 || kind === 'NamedType' && state.prevState != null && state.prevState.kind === 'TypeCondition') {
- return getSuggestionsForFragmentTypeConditions(token, typeInfo, schema);
- }
- // Fragment spread names
- if (kind === 'FragmentSpread' && step === 1) {
- return getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText);
- }
- // Variable definition types
- if (kind === 'VariableDefinition' && step === 2 || kind === 'ListType' && step === 1 || kind === 'NamedType' && state.prevState && (state.prevState.kind === 'VariableDefinition' || state.prevState.kind === 'ListType')) {
- return getSuggestionsForVariableDefinition(token, schema);
- }
- // Directive names
- if (kind === 'Directive') {
- return getSuggestionsForDirective(token, state, schema);
- }
- return [];
- }
- // Helper functions to get suggestions for each kinds
- function getSuggestionsForFieldNames(token, typeInfo, schema) {
- if (typeInfo.parentType) {
- var parentType = typeInfo.parentType;
- var fields = parentType.getFields instanceof Function ? (0, _autocompleteUtils.objectValues)(parentType.getFields()) : [];
- if ((0, _graphql.isAbstractType)(parentType)) {
- fields.push(_graphql.TypeNameMetaFieldDef);
- }
- if (parentType === schema.getQueryType()) {
- fields.push(_graphql.SchemaMetaFieldDef, _graphql.TypeMetaFieldDef);
- }
- return (0, _autocompleteUtils.hintList)(token, fields.map(function (field) {
- return {
- label: field.name,
- detail: String(field.type),
- documentation: field.description,
- isDeprecated: field.isDeprecated,
- deprecationReason: field.deprecationReason
- };
- }));
- }
- return [];
- }
- function getSuggestionsForInputValues(token, typeInfo) {
- var namedInputType = (0, _graphql.getNamedType)(typeInfo.inputType);
- if (namedInputType instanceof _graphql.GraphQLEnumType) {
- var values = namedInputType.getValues();
- return (0, _autocompleteUtils.hintList)(token, values.map(function (value) {
- return {
- label: value.name,
- detail: String(namedInputType),
- documentation: value.description,
- isDeprecated: value.isDeprecated,
- deprecationReason: value.deprecationReason
- };
- }));
- } else if (namedInputType === _graphql.GraphQLBoolean) {
- return (0, _autocompleteUtils.hintList)(token, [{
- label: 'true',
- detail: String(_graphql.GraphQLBoolean),
- documentation: 'Not false.'
- }, {
- label: 'false',
- detail: String(_graphql.GraphQLBoolean),
- documentation: 'Not true.'
- }]);
- }
- return [];
- }
- function getSuggestionsForFragmentTypeConditions(token, typeInfo, schema) {
- var possibleTypes = void 0;
- if (typeInfo.parentType) {
- if ((0, _graphql.isAbstractType)(typeInfo.parentType)) {
- var abstractType = (0, _graphql.assertAbstractType)(typeInfo.parentType);
- // Collect both the possible Object types as well as the interfaces
- // they implement.
- var possibleObjTypes = schema.getPossibleTypes(abstractType);
- var possibleIfaceMap = Object.create(null);
- possibleObjTypes.forEach(function (type) {
- type.getInterfaces().forEach(function (iface) {
- possibleIfaceMap[iface.name] = iface;
- });
- });
- possibleTypes = possibleObjTypes.concat((0, _autocompleteUtils.objectValues)(possibleIfaceMap));
- } else {
- // The parent type is a non-abstract Object type, so the only possible
- // type that can be used is that same type.
- possibleTypes = [typeInfo.parentType];
- }
- } else {
- var typeMap = schema.getTypeMap();
- possibleTypes = (0, _autocompleteUtils.objectValues)(typeMap).filter(_graphql.isCompositeType);
- }
- return (0, _autocompleteUtils.hintList)(token, possibleTypes.map(function (type) {
- var namedType = (0, _graphql.getNamedType)(type);
- return {
- label: String(type),
- documentation: namedType && namedType.description || ''
- };
- }));
- }
- function getSuggestionsForFragmentSpread(token, typeInfo, schema, queryText) {
- var typeMap = schema.getTypeMap();
- var defState = (0, _autocompleteUtils.getDefinitionState)(token.state);
- var fragments = getFragmentDefinitions(queryText);
- // Filter down to only the fragments which may exist here.
- var relevantFrags = fragments.filter(function (frag) {
- return (
- // Only include fragments with known types.
- typeMap[frag.typeCondition.name.value] &&
- // Only include fragments which are not cyclic.
- !(defState && defState.kind === 'FragmentDefinition' && defState.name === frag.name.value) &&
- // Only include fragments which could possibly be spread here.
- (0, _graphql.isCompositeType)(typeInfo.parentType) && (0, _graphql.isCompositeType)(typeMap[frag.typeCondition.name.value]) && (0, _graphql.doTypesOverlap)(schema, typeInfo.parentType, typeMap[frag.typeCondition.name.value])
- );
- });
- return (0, _autocompleteUtils.hintList)(token, relevantFrags.map(function (frag) {
- return {
- label: frag.name.value,
- detail: String(typeMap[frag.typeCondition.name.value]),
- documentation: 'fragment ' + frag.name.value + ' on ' + frag.typeCondition.name.value
- };
- }));
- }
- function getFragmentDefinitions(queryText) {
- var fragmentDefs = [];
- runOnlineParser(queryText, function (_, state) {
- if (state.kind === 'FragmentDefinition' && state.name && state.type) {
- fragmentDefs.push({
- kind: 'FragmentDefinition',
- name: {
- kind: 'Name',
- value: state.name
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: []
- },
- typeCondition: {
- kind: 'NamedType',
- name: {
- kind: 'Name',
- value: state.type
- }
- }
- });
- }
- });
- return fragmentDefs;
- }
- function getSuggestionsForVariableDefinition(token, schema) {
- var inputTypeMap = schema.getTypeMap();
- var inputTypes = (0, _autocompleteUtils.objectValues)(inputTypeMap).filter(_graphql.isInputType);
- return (0, _autocompleteUtils.hintList)(token, inputTypes.map(function (type) {
- return {
- label: type.name,
- documentation: type.description
- };
- }));
- }
- function getSuggestionsForDirective(token, state, schema) {
- if (state.prevState && state.prevState.kind) {
- var directives = schema.getDirectives().filter(function (directive) {
- return canUseDirective(state.prevState, directive);
- });
- return (0, _autocompleteUtils.hintList)(token, directives.map(function (directive) {
- return {
- label: directive.name,
- documentation: directive.description || ''
- };
- }));
- }
- return [];
- }
- function getTokenAtPosition(queryText, cursor) {
- var styleAtCursor = null;
- var stateAtCursor = null;
- var stringAtCursor = null;
- var token = runOnlineParser(queryText, function (stream, state, style, index) {
- if (index === cursor.line) {
- if (stream.getCurrentPosition() >= cursor.character) {
- styleAtCursor = style;
- stateAtCursor = _extends({}, state);
- stringAtCursor = stream.current();
- return 'BREAK';
- }
- }
- });
- // Return the state/style of parsed token in case those at cursor aren't
- // available.
- return {
- start: token.start,
- end: token.end,
- string: stringAtCursor || token.string,
- state: stateAtCursor || token.state,
- style: styleAtCursor || token.style
- };
- }
- /**
- * Provides an utility function to parse a given query text and construct a
- * `token` context object.
- * A token context provides useful information about the token/style that
- * CharacterStream currently possesses, as well as the end state and style
- * of the token.
- */
- function runOnlineParser(queryText, callback) {
- var lines = queryText.split('\n');
- var parser = (0, _graphqlLanguageServiceParser.onlineParser)();
- var state = parser.startState();
- var style = '';
- var stream = new _graphqlLanguageServiceParser.CharacterStream('');
- for (var i = 0; i < lines.length; i++) {
- stream = new _graphqlLanguageServiceParser.CharacterStream(lines[i]);
- while (!stream.eol()) {
- style = parser.token(stream, state);
- var code = callback(stream, state, style, i);
- if (code === 'BREAK') {
- break;
- }
- }
- // Above while loop won't run if there is an empty line.
- // Run the callback one more time to catch this.
- callback(stream, state, style, i);
- if (!state.kind) {
- state = parser.startState();
- }
- }
- return {
- start: stream.getStartOfToken(),
- end: stream.getCurrentPosition(),
- string: stream.current(),
- state: state,
- style: style
- };
- }
- function canUseDirective(state, directive) {
- if (!state || !state.kind) {
- return false;
- }
- var kind = state.kind;
- var locations = directive.locations;
- switch (kind) {
- case 'Query':
- return locations.indexOf('QUERY') !== -1;
- case 'Mutation':
- return locations.indexOf('MUTATION') !== -1;
- case 'Subscription':
- return locations.indexOf('SUBSCRIPTION') !== -1;
- case 'Field':
- case 'AliasedField':
- return locations.indexOf('FIELD') !== -1;
- case 'FragmentDefinition':
- return locations.indexOf('FRAGMENT_DEFINITION') !== -1;
- case 'FragmentSpread':
- return locations.indexOf('FRAGMENT_SPREAD') !== -1;
- case 'InlineFragment':
- return locations.indexOf('INLINE_FRAGMENT') !== -1;
- // Schema Definitions
- case 'SchemaDef':
- return locations.indexOf('SCHEMA') !== -1;
- case 'ScalarDef':
- return locations.indexOf('SCALAR') !== -1;
- case 'ObjectTypeDef':
- return locations.indexOf('OBJECT') !== -1;
- case 'FieldDef':
- return locations.indexOf('FIELD_DEFINITION') !== -1;
- case 'InterfaceDef':
- return locations.indexOf('INTERFACE') !== -1;
- case 'UnionDef':
- return locations.indexOf('UNION') !== -1;
- case 'EnumDef':
- return locations.indexOf('ENUM') !== -1;
- case 'EnumValue':
- return locations.indexOf('ENUM_VALUE') !== -1;
- case 'InputDef':
- return locations.indexOf('INPUT_OBJECT') !== -1;
- case 'InputValueDef':
- var prevStateKind = state.prevState && state.prevState.kind;
- switch (prevStateKind) {
- case 'ArgumentsDef':
- return locations.indexOf('ARGUMENT_DEFINITION') !== -1;
- case 'InputDef':
- return locations.indexOf('INPUT_FIELD_DEFINITION') !== -1;
- }
- }
- return false;
- }
- // Utility for collecting rich type information given any token's state
- // from the graphql-mode parser.
- function getTypeInfo(schema, tokenState) {
- var argDef = void 0;
- var argDefs = void 0;
- var directiveDef = void 0;
- var enumValue = void 0;
- var fieldDef = void 0;
- var inputType = void 0;
- var objectFieldDefs = void 0;
- var parentType = void 0;
- var type = void 0;
- (0, _autocompleteUtils.forEachState)(tokenState, function (state) {
- switch (state.kind) {
- case 'Query':
- case 'ShortQuery':
- type = schema.getQueryType();
- break;
- case 'Mutation':
- type = schema.getMutationType();
- break;
- case 'Subscription':
- type = schema.getSubscriptionType();
- break;
- case 'InlineFragment':
- case 'FragmentDefinition':
- if (state.type) {
- type = schema.getType(state.type);
- }
- break;
- case 'Field':
- case 'AliasedField':
- if (!type || !state.name) {
- fieldDef = null;
- } else {
- fieldDef = parentType ? (0, _autocompleteUtils.getFieldDef)(schema, parentType, state.name) : null;
- type = fieldDef ? fieldDef.type : null;
- }
- break;
- case 'SelectionSet':
- parentType = (0, _graphql.getNamedType)(type);
- break;
- case 'Directive':
- directiveDef = state.name ? schema.getDirective(state.name) : null;
- break;
- case 'Arguments':
- if (!state.prevState) {
- argDefs = null;
- } else {
- switch (state.prevState.kind) {
- case 'Field':
- argDefs = fieldDef && fieldDef.args;
- break;
- case 'Directive':
- argDefs = directiveDef && directiveDef.args;
- break;
- case 'AliasedField':
- var name = state.prevState && state.prevState.name;
- if (!name) {
- argDefs = null;
- break;
- }
- var field = parentType ? (0, _autocompleteUtils.getFieldDef)(schema, parentType, name) : null;
- if (!field) {
- argDefs = null;
- break;
- }
- argDefs = field.args;
- break;
- default:
- argDefs = null;
- break;
- }
- }
- break;
- case 'Argument':
- if (argDefs) {
- for (var i = 0; i < argDefs.length; i++) {
- if (argDefs[i].name === state.name) {
- argDef = argDefs[i];
- break;
- }
- }
- }
- inputType = argDef && argDef.type;
- break;
- case 'EnumValue':
- var enumType = (0, _graphql.getNamedType)(inputType);
- enumValue = enumType instanceof _graphql.GraphQLEnumType ? find(enumType.getValues(), function (val) {
- return val.value === state.name;
- }) : null;
- break;
- case 'ListValue':
- var nullableType = (0, _graphql.getNullableType)(inputType);
- inputType = nullableType instanceof _graphql.GraphQLList ? nullableType.ofType : null;
- break;
- case 'ObjectValue':
- var objectType = (0, _graphql.getNamedType)(inputType);
- objectFieldDefs = objectType instanceof _graphql.GraphQLInputObjectType ? objectType.getFields() : null;
- break;
- case 'ObjectField':
- var objectField = state.name && objectFieldDefs ? objectFieldDefs[state.name] : null;
- inputType = objectField && objectField.type;
- break;
- case 'NamedType':
- if (state.name) {
- type = schema.getType(state.name);
- }
- break;
- }
- });
- return {
- argDef: argDef,
- argDefs: argDefs,
- directiveDef: directiveDef,
- enumValue: enumValue,
- fieldDef: fieldDef,
- inputType: inputType,
- objectFieldDefs: objectFieldDefs,
- parentType: parentType,
- type: type
- };
- }
- // Returns the first item in the array which causes predicate to return truthy.
- function find(array, predicate) {
- for (var i = 0; i < array.length; i++) {
- if (predicate(array[i])) {
- return array[i];
- }
- }
- return null;
- }
- },{"./autocompleteUtils":259,"graphql":285,"graphql-language-service-parser":269}],261:[function(require,module,exports){
- (function (process){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.LANGUAGE = undefined;
- exports.getDefinitionQueryResultForNamedType = getDefinitionQueryResultForNamedType;
- exports.getDefinitionQueryResultForFragmentSpread = getDefinitionQueryResultForFragmentSpread;
- exports.getDefinitionQueryResultForDefinitionNode = getDefinitionQueryResultForDefinitionNode;
- var _graphqlLanguageServiceUtils = require('graphql-language-service-utils');
- var _assert = require('assert');
- var _assert2 = _interopRequireDefault(_assert);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var LANGUAGE = exports.LANGUAGE = 'GraphQL';
- function getRange(text, node) {
- var location = node.loc;
- (0, _assert2.default)(location, 'Expected ASTNode to have a location.');
- return (0, _graphqlLanguageServiceUtils.locToRange)(text, location);
- }
- function getPosition(text, node) {
- var location = node.loc;
- (0, _assert2.default)(location, 'Expected ASTNode to have a location.');
- return (0, _graphqlLanguageServiceUtils.offsetToPosition)(text, location.start);
- }
- function getDefinitionQueryResultForNamedType(text, node, dependencies) {
- var name, defNodes, definitions;
- return regeneratorRuntime.async(function getDefinitionQueryResultForNamedType$(_context) {
- while (1) {
- switch (_context.prev = _context.next) {
- case 0:
- name = node.name.value;
- defNodes = dependencies.filter(function (_ref) {
- var definition = _ref.definition;
- return definition.name && definition.name.value === name;
- });
- if (!(defNodes.length === 0)) {
- _context.next = 5;
- break;
- }
- process.stderr.write('Definition not found for GraphQL type ' + name);
- return _context.abrupt('return', { queryRange: [], definitions: [] });
- case 5:
- definitions = defNodes.map(function (_ref2) {
- var filePath = _ref2.filePath,
- content = _ref2.content,
- definition = _ref2.definition;
- return getDefinitionForNodeDefinition(filePath || '', content, definition);
- });
- return _context.abrupt('return', {
- definitions: definitions,
- queryRange: definitions.map(function (_) {
- return getRange(text, node);
- })
- });
- case 7:
- case 'end':
- return _context.stop();
- }
- }
- }, null, this);
- }
- function getDefinitionQueryResultForFragmentSpread(text, fragment, dependencies) {
- var name, defNodes, definitions;
- return regeneratorRuntime.async(function getDefinitionQueryResultForFragmentSpread$(_context2) {
- while (1) {
- switch (_context2.prev = _context2.next) {
- case 0:
- name = fragment.name.value;
- defNodes = dependencies.filter(function (_ref3) {
- var definition = _ref3.definition;
- return definition.name.value === name;
- });
- if (!(defNodes.length === 0)) {
- _context2.next = 5;
- break;
- }
- process.stderr.write('Definition not found for GraphQL fragment ' + name);
- return _context2.abrupt('return', { queryRange: [], definitions: [] });
- case 5:
- definitions = defNodes.map(function (_ref4) {
- var filePath = _ref4.filePath,
- content = _ref4.content,
- definition = _ref4.definition;
- return getDefinitionForFragmentDefinition(filePath || '', content, definition);
- });
- return _context2.abrupt('return', {
- definitions: definitions,
- queryRange: definitions.map(function (_) {
- return getRange(text, fragment);
- })
- });
- case 7:
- case 'end':
- return _context2.stop();
- }
- }
- }, null, this);
- }
- function getDefinitionQueryResultForDefinitionNode(path, text, definition) {
- return {
- definitions: [getDefinitionForFragmentDefinition(path, text, definition)],
- queryRange: definition.name ? [getRange(text, definition.name)] : []
- };
- }
- function getDefinitionForFragmentDefinition(path, text, definition) {
- var name = definition.name;
- (0, _assert2.default)(name, 'Expected ASTNode to have a Name.');
- return {
- path: path,
- position: getPosition(text, definition),
- range: getRange(text, definition),
- name: name.value || '',
- language: LANGUAGE,
- // This is a file inside the project root, good enough for now
- projectRoot: path
- };
- }
- function getDefinitionForNodeDefinition(path, text, definition) {
- var name = definition.name;
- (0, _assert2.default)(name, 'Expected ASTNode to have a Name.');
- return {
- path: path,
- position: getPosition(text, definition),
- range: getRange(text, definition),
- name: name.value || '',
- language: LANGUAGE,
- // This is a file inside the project root, good enough for now
- projectRoot: path
- };
- }
- }).call(this,require('_process'))
- },{"_process":198,"assert":1,"graphql-language-service-utils":273}],262:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.SEVERITY = undefined;
- exports.getDiagnostics = getDiagnostics;
- exports.validateQuery = validateQuery;
- exports.getRange = getRange;
- var _assert = require('assert');
- var _assert2 = _interopRequireDefault(_assert);
- var _graphql = require('graphql');
- var _graphqlLanguageServiceParser = require('graphql-language-service-parser');
- var _graphqlLanguageServiceUtils = require('graphql-language-service-utils');
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var SEVERITY = exports.SEVERITY = {
- ERROR: 1,
- WARNING: 2,
- INFORMATION: 3,
- HINT: 4
- };
- function getDiagnostics(query) {
- var schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
- var customRules = arguments[2];
- var isRelayCompatMode = arguments[3];
- var ast = null;
- try {
- ast = (0, _graphql.parse)(query);
- } catch (error) {
- var range = getRange(error.locations[0], query);
- return [{
- severity: SEVERITY.ERROR,
- message: error.message,
- source: 'GraphQL: Syntax',
- range: range
- }];
- }
- return validateQuery(ast, schema, customRules, isRelayCompatMode);
- }
- function validateQuery(ast) {
- var schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
- var customRules = arguments[2];
- var isRelayCompatMode = arguments[3];
- // We cannot validate the query unless a schema is provided.
- if (!schema) {
- return [];
- }
- var validationErrorAnnotations = mapCat((0, _graphqlLanguageServiceUtils.validateWithCustomRules)(schema, ast, customRules, isRelayCompatMode), function (error) {
- return annotations(error, SEVERITY.ERROR, 'Validation');
- });
- // Note: findDeprecatedUsages was added in graphql@0.9.0, but we want to
- // support older versions of graphql-js.
- var deprecationWarningAnnotations = !_graphql.findDeprecatedUsages ? [] : mapCat((0, _graphql.findDeprecatedUsages)(schema, ast), function (error) {
- return annotations(error, SEVERITY.WARNING, 'Deprecation');
- });
- return validationErrorAnnotations.concat(deprecationWarningAnnotations);
- }
- // General utility for map-cating (aka flat-mapping).
- function mapCat(array, mapper) {
- return Array.prototype.concat.apply([], array.map(mapper));
- }
- function annotations(error, severity, type) {
- if (!error.nodes) {
- return [];
- }
- return error.nodes.map(function (node) {
- var highlightNode = node.kind !== 'Variable' && node.name ? node.name : node.variable ? node.variable : node;
- (0, _assert2.default)(error.locations, 'GraphQL validation error requires locations.');
- var loc = error.locations[0];
- var highlightLoc = getLocation(highlightNode);
- var end = loc.column + (highlightLoc.end - highlightLoc.start);
- return {
- source: 'GraphQL: ' + type,
- message: error.message,
- severity: severity,
- range: new _graphqlLanguageServiceUtils.Range(new _graphqlLanguageServiceUtils.Position(loc.line - 1, loc.column - 1), new _graphqlLanguageServiceUtils.Position(loc.line - 1, end))
- };
- });
- }
- function getRange(location, queryText) {
- var parser = (0, _graphqlLanguageServiceParser.onlineParser)();
- var state = parser.startState();
- var lines = queryText.split('\n');
- (0, _assert2.default)(lines.length >= location.line, 'Query text must have more lines than where the error happened');
- var stream = null;
- for (var i = 0; i < location.line; i++) {
- stream = new _graphqlLanguageServiceParser.CharacterStream(lines[i]);
- while (!stream.eol()) {
- var style = parser.token(stream, state);
- if (style === 'invalidchar') {
- break;
- }
- }
- }
- (0, _assert2.default)(stream, 'Expected Parser stream to be available.');
- var line = location.line - 1;
- var start = stream.getStartOfToken();
- var end = stream.getCurrentPosition();
- return new _graphqlLanguageServiceUtils.Range(new _graphqlLanguageServiceUtils.Position(line, start), new _graphqlLanguageServiceUtils.Position(line, end));
- }
- /**
- * Get location info from a node in a type-safe way.
- *
- * The only way a node could not have a location is if we initialized the parser
- * (and therefore the lexer) with the `noLocation` option, but we always
- * call `parse` without options above.
- */
- function getLocation(node) {
- var typeCastedNode = node;
- var location = typeCastedNode.loc;
- (0, _assert2.default)(location, 'Expected ASTNode to have a location.');
- return location;
- }
- },{"assert":1,"graphql":285,"graphql-language-service-parser":269,"graphql-language-service-utils":273}],263:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getHoverInformation = getHoverInformation;
- var _getAutocompleteSuggestions = require('./getAutocompleteSuggestions');
- var _graphql = require('graphql');
- /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Ported from codemirror-graphql
- * https://github.com/graphql/codemirror-graphql/blob/master/src/info.js
- */
- function getHoverInformation(schema, queryText, cursor, contextToken) {
- var token = contextToken || (0, _getAutocompleteSuggestions.getTokenAtPosition)(queryText, cursor);
- if (!schema || !token || !token.state) {
- return [];
- }
- var state = token.state;
- var kind = state.kind;
- var step = state.step;
- var typeInfo = (0, _getAutocompleteSuggestions.getTypeInfo)(schema, token.state);
- var options = { schema: schema };
- // Given a Schema and a Token, produce the contents of an info tooltip.
- // To do this, create a div element that we will render "into" and then pass
- // it to various rendering functions.
- if (kind === 'Field' && step === 0 && typeInfo.fieldDef || kind === 'AliasedField' && step === 2 && typeInfo.fieldDef) {
- var into = [];
- renderField(into, typeInfo, options);
- renderDescription(into, options, typeInfo.fieldDef);
- return into.join('').trim();
- } else if (kind === 'Directive' && step === 1 && typeInfo.directiveDef) {
- var _into = [];
- renderDirective(_into, typeInfo, options);
- renderDescription(_into, options, typeInfo.directiveDef);
- return _into.join('').trim();
- } else if (kind === 'Argument' && step === 0 && typeInfo.argDef) {
- var _into2 = [];
- renderArg(_into2, typeInfo, options);
- renderDescription(_into2, options, typeInfo.argDef);
- return _into2.join('').trim();
- } else if (kind === 'EnumValue' && typeInfo.enumValue && typeInfo.enumValue.description) {
- var _into3 = [];
- renderEnumValue(_into3, typeInfo, options);
- renderDescription(_into3, options, typeInfo.enumValue);
- return _into3.join('').trim();
- } else if (kind === 'NamedType' && typeInfo.type && typeInfo.type.description) {
- var _into4 = [];
- renderType(_into4, typeInfo, options, typeInfo.type);
- renderDescription(_into4, options, typeInfo.type);
- return _into4.join('').trim();
- }
- }
- function renderField(into, typeInfo, options) {
- renderQualifiedField(into, typeInfo, options);
- renderTypeAnnotation(into, typeInfo, options, typeInfo.type);
- }
- function renderQualifiedField(into, typeInfo, options) {
- if (!typeInfo.fieldDef) {
- return;
- }
- var fieldName = typeInfo.fieldDef.name;
- if (fieldName.slice(0, 2) !== '__') {
- renderType(into, typeInfo, options, typeInfo.parentType);
- text(into, '.');
- }
- text(into, fieldName);
- }
- function renderDirective(into, typeInfo, options) {
- if (!typeInfo.directiveDef) {
- return;
- }
- var name = '@' + typeInfo.directiveDef.name;
- text(into, name);
- }
- function renderArg(into, typeInfo, options) {
- if (typeInfo.directiveDef) {
- renderDirective(into, typeInfo, options);
- } else if (typeInfo.fieldDef) {
- renderQualifiedField(into, typeInfo, options);
- }
- if (!typeInfo.argDef) {
- return;
- }
- var name = typeInfo.argDef.name;
- text(into, '(');
- text(into, name);
- renderTypeAnnotation(into, typeInfo, options, typeInfo.inputType);
- text(into, ')');
- }
- function renderTypeAnnotation(into, typeInfo, options, t) {
- text(into, ': ');
- renderType(into, typeInfo, options, t);
- }
- function renderEnumValue(into, typeInfo, options) {
- if (!typeInfo.enumValue) {
- return;
- }
- var name = typeInfo.enumValue.name;
- renderType(into, typeInfo, options, typeInfo.inputType);
- text(into, '.');
- text(into, name);
- }
- function renderType(into, typeInfo, options, t) {
- if (!t) {
- return;
- }
- if (t instanceof _graphql.GraphQLNonNull) {
- renderType(into, typeInfo, options, t.ofType);
- text(into, '!');
- } else if (t instanceof _graphql.GraphQLList) {
- text(into, '[');
- renderType(into, typeInfo, options, t.ofType);
- text(into, ']');
- } else {
- text(into, t.name);
- }
- }
- function renderDescription(into, options, def) {
- if (!def) {
- return;
- }
- var description = typeof def.description === 'string' ? def.description : null;
- if (description) {
- text(into, '\n\n');
- text(into, description);
- }
- renderDeprecation(into, options, def);
- }
- function renderDeprecation(into, options, def) {
- if (!def) {
- return;
- }
- var reason = typeof def.deprecationReason === 'string' ? def.deprecationReason : null;
- if (!reason) {
- return;
- }
- text(into, '\n\n');
- text(into, 'Deprecated: ');
- text(into, reason);
- }
- function text(into, content) {
- into.push(content);
- }
- },{"./getAutocompleteSuggestions":260,"graphql":285}],264:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- exports.getOutline = getOutline;
- var _graphql = require('graphql');
- var _graphqlLanguageServiceUtils = require('graphql-language-service-utils');
- var INLINE_FRAGMENT = _graphql.Kind.INLINE_FRAGMENT;
- var OUTLINEABLE_KINDS = {
- Field: true,
- OperationDefinition: true,
- Document: true,
- SelectionSet: true,
- Name: true,
- FragmentDefinition: true,
- FragmentSpread: true,
- InlineFragment: true
- };
- function getOutline(queryText) {
- var ast = void 0;
- try {
- ast = (0, _graphql.parse)(queryText);
- } catch (error) {
- return null;
- }
- var visitorFns = outlineTreeConverter(queryText);
- var outlineTrees = (0, _graphql.visit)(ast, {
- leave: function leave(node) {
- if (OUTLINEABLE_KINDS.hasOwnProperty(node.kind) && visitorFns[node.kind]) {
- return visitorFns[node.kind](node);
- }
- return null;
- }
- });
- return { outlineTrees: outlineTrees };
- }
- function outlineTreeConverter(docText) {
- var meta = function meta(node) {
- return {
- representativeName: node.name,
- startPosition: (0, _graphqlLanguageServiceUtils.offsetToPosition)(docText, node.loc.start),
- endPosition: (0, _graphqlLanguageServiceUtils.offsetToPosition)(docText, node.loc.end),
- children: node.selectionSet || []
- };
- };
- return {
- Field: function Field(node) {
- var tokenizedText = node.alias ? [buildToken('plain', node.alias), buildToken('plain', ': ')] : [];
- tokenizedText.push(buildToken('plain', node.name));
- return _extends({ tokenizedText: tokenizedText }, meta(node));
- },
- OperationDefinition: function OperationDefinition(node) {
- return _extends({
- tokenizedText: [buildToken('keyword', node.operation), buildToken('whitespace', ' '), buildToken('class-name', node.name)]
- }, meta(node));
- },
- Document: function Document(node) {
- return node.definitions;
- },
- SelectionSet: function SelectionSet(node) {
- return concatMap(node.selections, function (child) {
- return child.kind === INLINE_FRAGMENT ? child.selectionSet : child;
- });
- },
- Name: function Name(node) {
- return node.value;
- },
- FragmentDefinition: function FragmentDefinition(node) {
- return _extends({
- tokenizedText: [buildToken('keyword', 'fragment'), buildToken('whitespace', ' '), buildToken('class-name', node.name)]
- }, meta(node));
- },
- FragmentSpread: function FragmentSpread(node) {
- return _extends({
- tokenizedText: [buildToken('plain', '...'), buildToken('class-name', node.name)]
- }, meta(node));
- },
- InlineFragment: function InlineFragment(node) {
- return node.selectionSet;
- }
- };
- }
- function buildToken(kind, value) {
- return { kind: kind, value: value };
- }
- function concatMap(arr, fn) {
- var res = [];
- for (var i = 0; i < arr.length; i++) {
- var x = fn(arr[i], i);
- if (Array.isArray(x)) {
- res.push.apply(res, x);
- } else {
- res.push(x);
- }
- }
- return res;
- }
- },{"graphql":285,"graphql-language-service-utils":273}],265:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _autocompleteUtils = require('./autocompleteUtils');
- Object.defineProperty(exports, 'getDefinitionState', {
- enumerable: true,
- get: function get() {
- return _autocompleteUtils.getDefinitionState;
- }
- });
- Object.defineProperty(exports, 'getFieldDef', {
- enumerable: true,
- get: function get() {
- return _autocompleteUtils.getFieldDef;
- }
- });
- Object.defineProperty(exports, 'forEachState', {
- enumerable: true,
- get: function get() {
- return _autocompleteUtils.forEachState;
- }
- });
- Object.defineProperty(exports, 'objectValues', {
- enumerable: true,
- get: function get() {
- return _autocompleteUtils.objectValues;
- }
- });
- Object.defineProperty(exports, 'hintList', {
- enumerable: true,
- get: function get() {
- return _autocompleteUtils.hintList;
- }
- });
- var _getAutocompleteSuggestions = require('./getAutocompleteSuggestions');
- Object.defineProperty(exports, 'getAutocompleteSuggestions', {
- enumerable: true,
- get: function get() {
- return _getAutocompleteSuggestions.getAutocompleteSuggestions;
- }
- });
- var _getDefinition = require('./getDefinition');
- Object.defineProperty(exports, 'LANGUAGE', {
- enumerable: true,
- get: function get() {
- return _getDefinition.LANGUAGE;
- }
- });
- Object.defineProperty(exports, 'getDefinitionQueryResultForFragmentSpread', {
- enumerable: true,
- get: function get() {
- return _getDefinition.getDefinitionQueryResultForFragmentSpread;
- }
- });
- Object.defineProperty(exports, 'getDefinitionQueryResultForDefinitionNode', {
- enumerable: true,
- get: function get() {
- return _getDefinition.getDefinitionQueryResultForDefinitionNode;
- }
- });
- var _getDiagnostics = require('./getDiagnostics');
- Object.defineProperty(exports, 'getDiagnostics', {
- enumerable: true,
- get: function get() {
- return _getDiagnostics.getDiagnostics;
- }
- });
- Object.defineProperty(exports, 'validateQuery', {
- enumerable: true,
- get: function get() {
- return _getDiagnostics.validateQuery;
- }
- });
- var _getOutline = require('./getOutline');
- Object.defineProperty(exports, 'getOutline', {
- enumerable: true,
- get: function get() {
- return _getOutline.getOutline;
- }
- });
- var _getHoverInformation = require('./getHoverInformation');
- Object.defineProperty(exports, 'getHoverInformation', {
- enumerable: true,
- get: function get() {
- return _getHoverInformation.getHoverInformation;
- }
- });
- var _GraphQLLanguageService = require('./GraphQLLanguageService');
- Object.defineProperty(exports, 'GraphQLLanguageService', {
- enumerable: true,
- get: function get() {
- return _GraphQLLanguageService.GraphQLLanguageService;
- }
- });
- },{"./GraphQLLanguageService":258,"./autocompleteUtils":259,"./getAutocompleteSuggestions":260,"./getDefinition":261,"./getDiagnostics":262,"./getHoverInformation":263,"./getOutline":264}],266:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var CharacterStream = function () {
- function CharacterStream(sourceText) {
- var _this = this;
- _classCallCheck(this, CharacterStream);
- this.getStartOfToken = function () {
- return _this._start;
- };
- this.getCurrentPosition = function () {
- return _this._pos;
- };
- this.eol = function () {
- return _this._sourceText.length === _this._pos;
- };
- this.sol = function () {
- return _this._pos === 0;
- };
- this.peek = function () {
- return _this._sourceText.charAt(_this._pos) ? _this._sourceText.charAt(_this._pos) : null;
- };
- this.next = function () {
- var char = _this._sourceText.charAt(_this._pos);
- _this._pos++;
- return char;
- };
- this.eat = function (pattern) {
- var isMatched = _this._testNextCharacter(pattern);
- if (isMatched) {
- _this._start = _this._pos;
- _this._pos++;
- return _this._sourceText.charAt(_this._pos - 1);
- }
- return undefined;
- };
- this.eatWhile = function (match) {
- var isMatched = _this._testNextCharacter(match);
- var didEat = false;
- // If a match, treat the total upcoming matches as one token
- if (isMatched) {
- didEat = isMatched;
- _this._start = _this._pos;
- }
- while (isMatched) {
- _this._pos++;
- isMatched = _this._testNextCharacter(match);
- didEat = true;
- }
- return didEat;
- };
- this.eatSpace = function () {
- return _this.eatWhile(/[\s\u00a0]/);
- };
- this.skipToEnd = function () {
- _this._pos = _this._sourceText.length;
- };
- this.skipTo = function (position) {
- _this._pos = position;
- };
- this.match = function (pattern) {
- var consume = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
- var caseFold = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
- var token = null;
- var match = null;
- if (typeof pattern === 'string') {
- var regex = new RegExp(pattern, caseFold ? 'i' : 'g');
- match = regex.test(_this._sourceText.substr(_this._pos, pattern.length));
- token = pattern;
- } else if (pattern instanceof RegExp) {
- match = _this._sourceText.slice(_this._pos).match(pattern);
- token = match && match[0];
- }
- if (match != null) {
- if (typeof pattern === 'string' || match instanceof Array &&
- // String.match returns 'index' property, which flow fails to detect
- // for some reason. The below is a workaround, but an easier solution
- // is just checking if `match.index === 0`
- _this._sourceText.startsWith(match[0], _this._pos)) {
- if (consume) {
- _this._start = _this._pos;
- if (token && token.length) {
- _this._pos += token.length;
- }
- }
- return match;
- }
- }
- // No match available.
- return false;
- };
- this.backUp = function (num) {
- _this._pos -= num;
- };
- this.column = function () {
- return _this._pos;
- };
- this.indentation = function () {
- var match = _this._sourceText.match(/\s*/);
- var indent = 0;
- if (match && match.length === 0) {
- var whitespaces = match[0];
- var pos = 0;
- while (whitespaces.length > pos) {
- if (whitespaces.charCodeAt(pos) === 9) {
- indent += 2;
- } else {
- indent++;
- }
- pos++;
- }
- }
- return indent;
- };
- this.current = function () {
- return _this._sourceText.slice(_this._start, _this._pos);
- };
- this._start = 0;
- this._pos = 0;
- this._sourceText = sourceText;
- }
- CharacterStream.prototype._testNextCharacter = function _testNextCharacter(pattern) {
- var character = this._sourceText.charAt(this._pos);
- var isMatched = false;
- if (typeof pattern === 'string') {
- isMatched = character === pattern;
- } else {
- isMatched = pattern instanceof RegExp ? pattern.test(character) : pattern(character);
- }
- return isMatched;
- };
- return CharacterStream;
- }(); /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * CharacterStream implements a stream of character tokens given a source text.
- * The API design follows that of CodeMirror.StringStream.
- *
- * Required:
- *
- * sourceText: (string), A raw GraphQL source text. Works best if a line
- * is supplied.
- *
- */
- exports.default = CharacterStream;
- },{}],267:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.opt = opt;
- exports.list = list;
- exports.butNot = butNot;
- exports.t = t;
- exports.p = p;
- // An optional rule.
- function opt(ofRule) {
- return { ofRule: ofRule };
- }
- // A list of another rule.
- /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- // These functions help build matching rules for ParseRules.
- function list(ofRule, separator) {
- return { ofRule: ofRule, isList: true, separator: separator };
- }
- // An constraint described as `but not` in the GraphQL spec.
- function butNot(rule, exclusions) {
- var ruleMatch = rule.match;
- rule.match = function (token) {
- var check = false;
- if (ruleMatch) {
- check = ruleMatch(token);
- }
- return check && exclusions.every(function (exclusion) {
- return exclusion.match && !exclusion.match(token);
- });
- };
- return rule;
- }
- // Token of a kind
- function t(kind, style) {
- return { style: style, match: function match(token) {
- return token.kind === kind;
- } };
- }
- // Punctuator
- function p(value, style) {
- return {
- style: style || 'punctuation',
- match: function match(token) {
- return token.kind === 'Punctuation' && token.value === value;
- }
- };
- }
- },{}],268:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ParseRules = exports.LexRules = exports.isIgnored = undefined;
- var _RuleHelpers = require('./RuleHelpers');
- /**
- * Whitespace tokens defined in GraphQL spec.
- */
- /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var isIgnored = exports.isIgnored = function isIgnored(ch) {
- return ch === ' ' || ch === '\t' || ch === ',' || ch === '\n' || ch === '\r' || ch === '\uFEFF';
- };
- /**
- * The lexer rules. These are exactly as described by the spec.
- */
- var LexRules = exports.LexRules = {
- // The Name token.
- Name: /^[_A-Za-z][_0-9A-Za-z]*/,
- // All Punctuation used in GraphQL
- Punctuation: /^(?:!|\$|\(|\)|\.\.\.|:|=|@|\[|]|\{|\||\})/,
- // Combines the IntValue and FloatValue tokens.
- Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,
- // Note the closing quote is made optional as an IDE experience improvment.
- String: /^(?:"""(?:\\"""|[^"]|"[^"]|""[^"])*(?:""")?|"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?)/,
- // Comments consume entire lines.
- Comment: /^#.*/
- };
- /**
- * The parser rules. These are very close to, but not exactly the same as the
- * spec. Minor deviations allow for a simpler implementation. The resulting
- * parser can parse everything the spec declares possible.
- */
- var ParseRules = exports.ParseRules = {
- Document: [(0, _RuleHelpers.list)('Definition')],
- Definition: function Definition(token) {
- switch (token.value) {
- case '{':
- return 'ShortQuery';
- case 'query':
- return 'Query';
- case 'mutation':
- return 'Mutation';
- case 'subscription':
- return 'Subscription';
- case 'fragment':
- return 'FragmentDefinition';
- case 'schema':
- return 'SchemaDef';
- case 'scalar':
- return 'ScalarDef';
- case 'type':
- return 'ObjectTypeDef';
- case 'interface':
- return 'InterfaceDef';
- case 'union':
- return 'UnionDef';
- case 'enum':
- return 'EnumDef';
- case 'input':
- return 'InputDef';
- case 'extend':
- return 'ExtendDef';
- case 'directive':
- return 'DirectiveDef';
- }
- },
- // Note: instead of "Operation", these rules have been separated out.
- ShortQuery: ['SelectionSet'],
- Query: [word('query'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
- Mutation: [word('mutation'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
- Subscription: [word('subscription'), (0, _RuleHelpers.opt)(name('def')), (0, _RuleHelpers.opt)('VariableDefinitions'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
- VariableDefinitions: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('VariableDefinition'), (0, _RuleHelpers.p)(')')],
- VariableDefinition: ['Variable', (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue')],
- Variable: [(0, _RuleHelpers.p)('$', 'variable'), name('variable')],
- DefaultValue: [(0, _RuleHelpers.p)('='), 'Value'],
- SelectionSet: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('Selection'), (0, _RuleHelpers.p)('}')],
- Selection: function Selection(token, stream) {
- return token.value === '...' ? stream.match(/[\s\u00a0,]*(on\b|@|{)/, false) ? 'InlineFragment' : 'FragmentSpread' : stream.match(/[\s\u00a0,]*:/, false) ? 'AliasedField' : 'Field';
- },
- // Note: this minor deviation of "AliasedField" simplifies the lookahead.
- AliasedField: [name('property'), (0, _RuleHelpers.p)(':'), name('qualifier'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')],
- Field: [name('property'), (0, _RuleHelpers.opt)('Arguments'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.opt)('SelectionSet')],
- Arguments: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('Argument'), (0, _RuleHelpers.p)(')')],
- Argument: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'],
- FragmentSpread: [(0, _RuleHelpers.p)('...'), name('def'), (0, _RuleHelpers.list)('Directive')],
- InlineFragment: [(0, _RuleHelpers.p)('...'), (0, _RuleHelpers.opt)('TypeCondition'), (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
- FragmentDefinition: [word('fragment'), (0, _RuleHelpers.opt)((0, _RuleHelpers.butNot)(name('def'), [word('on')])), 'TypeCondition', (0, _RuleHelpers.list)('Directive'), 'SelectionSet'],
- TypeCondition: [word('on'), 'NamedType'],
- // Variables could be parsed in cases where only Const is expected by spec.
- Value: function Value(token) {
- switch (token.kind) {
- case 'Number':
- return 'NumberValue';
- case 'String':
- return 'StringValue';
- case 'Punctuation':
- switch (token.value) {
- case '[':
- return 'ListValue';
- case '{':
- return 'ObjectValue';
- case '$':
- return 'Variable';
- }
- return null;
- case 'Name':
- switch (token.value) {
- case 'true':
- case 'false':
- return 'BooleanValue';
- }
- if (token.value === 'null') {
- return 'NullValue';
- }
- return 'EnumValue';
- }
- },
- NumberValue: [(0, _RuleHelpers.t)('Number', 'number')],
- StringValue: [(0, _RuleHelpers.t)('String', 'string')],
- BooleanValue: [(0, _RuleHelpers.t)('Name', 'builtin')],
- NullValue: [(0, _RuleHelpers.t)('Name', 'keyword')],
- EnumValue: [name('string-2')],
- ListValue: [(0, _RuleHelpers.p)('['), (0, _RuleHelpers.list)('Value'), (0, _RuleHelpers.p)(']')],
- ObjectValue: [(0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('ObjectField'), (0, _RuleHelpers.p)('}')],
- ObjectField: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Value'],
- Type: function Type(token) {
- return token.value === '[' ? 'ListType' : 'NonNullType';
- },
- // NonNullType has been merged into ListType to simplify.
- ListType: [(0, _RuleHelpers.p)('['), 'Type', (0, _RuleHelpers.p)(']'), (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))],
- NonNullType: ['NamedType', (0, _RuleHelpers.opt)((0, _RuleHelpers.p)('!'))],
- NamedType: [type('atom')],
- Directive: [(0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('Arguments')],
- // GraphQL schema language
- SchemaDef: [word('schema'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('OperationTypeDef'), (0, _RuleHelpers.p)('}')],
- OperationTypeDef: [name('keyword'), (0, _RuleHelpers.p)(':'), name('atom')],
- ScalarDef: [word('scalar'), name('atom'), (0, _RuleHelpers.list)('Directive')],
- ObjectTypeDef: [word('type'), name('atom'), (0, _RuleHelpers.opt)('Implements'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')],
- Implements: [word('implements'), (0, _RuleHelpers.list)('NamedType')],
- FieldDef: [name('property'), (0, _RuleHelpers.opt)('ArgumentsDef'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.list)('Directive')],
- ArgumentsDef: [(0, _RuleHelpers.p)('('), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)(')')],
- InputValueDef: [name('attribute'), (0, _RuleHelpers.p)(':'), 'Type', (0, _RuleHelpers.opt)('DefaultValue'), (0, _RuleHelpers.list)('Directive')],
- InterfaceDef: [word('interface'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('FieldDef'), (0, _RuleHelpers.p)('}')],
- UnionDef: [word('union'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('='), (0, _RuleHelpers.list)('UnionMember', (0, _RuleHelpers.p)('|'))],
- UnionMember: ['NamedType'],
- EnumDef: [word('enum'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('EnumValueDef'), (0, _RuleHelpers.p)('}')],
- EnumValueDef: [name('string-2'), (0, _RuleHelpers.list)('Directive')],
- InputDef: [word('input'), name('atom'), (0, _RuleHelpers.list)('Directive'), (0, _RuleHelpers.p)('{'), (0, _RuleHelpers.list)('InputValueDef'), (0, _RuleHelpers.p)('}')],
- ExtendDef: [word('extend'), 'ObjectTypeDef'],
- DirectiveDef: [word('directive'), (0, _RuleHelpers.p)('@', 'meta'), name('meta'), (0, _RuleHelpers.opt)('ArgumentsDef'), word('on'), (0, _RuleHelpers.list)('DirectiveLocation', (0, _RuleHelpers.p)('|'))],
- DirectiveLocation: [name('string-2')]
- };
- // A keyword Token.
- function word(value) {
- return {
- style: 'keyword',
- match: function match(token) {
- return token.kind === 'Name' && token.value === value;
- }
- };
- }
- // A Name Token which will decorate the state with a `name`.
- function name(style) {
- return {
- style: style,
- match: function match(token) {
- return token.kind === 'Name';
- },
- update: function update(state, token) {
- state.name = token.value;
- }
- };
- }
- // A Name Token which will decorate the previous state with a `type`.
- function type(style) {
- return {
- style: style,
- match: function match(token) {
- return token.kind === 'Name';
- },
- update: function update(state, token) {
- if (state.prevState && state.prevState.prevState) {
- state.name = token.value;
- state.prevState.prevState.type = token.value;
- }
- }
- };
- }
- },{"./RuleHelpers":267}],269:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _CharacterStream = require('./CharacterStream');
- Object.defineProperty(exports, 'CharacterStream', {
- enumerable: true,
- get: function get() {
- return _interopRequireDefault(_CharacterStream).default;
- }
- });
- var _Rules = require('./Rules');
- Object.defineProperty(exports, 'LexRules', {
- enumerable: true,
- get: function get() {
- return _Rules.LexRules;
- }
- });
- Object.defineProperty(exports, 'ParseRules', {
- enumerable: true,
- get: function get() {
- return _Rules.ParseRules;
- }
- });
- Object.defineProperty(exports, 'isIgnored', {
- enumerable: true,
- get: function get() {
- return _Rules.isIgnored;
- }
- });
- var _RuleHelpers = require('./RuleHelpers');
- Object.defineProperty(exports, 'butNot', {
- enumerable: true,
- get: function get() {
- return _RuleHelpers.butNot;
- }
- });
- Object.defineProperty(exports, 'list', {
- enumerable: true,
- get: function get() {
- return _RuleHelpers.list;
- }
- });
- Object.defineProperty(exports, 'opt', {
- enumerable: true,
- get: function get() {
- return _RuleHelpers.opt;
- }
- });
- Object.defineProperty(exports, 'p', {
- enumerable: true,
- get: function get() {
- return _RuleHelpers.p;
- }
- });
- Object.defineProperty(exports, 't', {
- enumerable: true,
- get: function get() {
- return _RuleHelpers.t;
- }
- });
- var _onlineParser = require('./onlineParser');
- Object.defineProperty(exports, 'onlineParser', {
- enumerable: true,
- get: function get() {
- return _interopRequireDefault(_onlineParser).default;
- }
- });
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- },{"./CharacterStream":266,"./RuleHelpers":267,"./Rules":268,"./onlineParser":270}],270:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Builds an online immutable parser, designed to be used as part of a syntax
- * highlighting and code intelligence tools.
- *
- * Options:
- *
- * eatWhitespace: (
- * stream: Stream | CodeMirror.StringStream | CharacterStream
- * ) => boolean
- * Use CodeMirror API.
- *
- * LexRules: { [name: string]: RegExp }, Includes `Punctuation`, `Comment`.
- *
- * ParseRules: { [name: string]: Array<Rule> }, Includes `Document`.
- *
- * editorConfig: { [name: string]: any }, Provides an editor-specific
- * configurations set.
- *
- */
- exports.default = onlineParser;
- var _Rules = require('./Rules');
- function onlineParser() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
- eatWhitespace: function eatWhitespace(stream) {
- return stream.eatWhile(_Rules.isIgnored);
- },
- lexRules: _Rules.LexRules,
- parseRules: _Rules.ParseRules,
- editorConfig: {}
- };
- return {
- startState: function startState() {
- var initialState = {
- level: 0,
- step: 0,
- name: null,
- kind: null,
- type: null,
- rule: null,
- needsSeperator: false,
- prevState: null
- };
- pushRule(options.parseRules, initialState, 'Document');
- return initialState;
- },
- token: function token(stream, state) {
- return getToken(stream, state, options);
- }
- };
- }
- function getToken(stream, state, options) {
- var lexRules = options.lexRules,
- parseRules = options.parseRules,
- eatWhitespace = options.eatWhitespace,
- editorConfig = options.editorConfig;
- // Restore state after an empty-rule.
- if (state.rule && state.rule.length === 0) {
- popRule(state);
- } else if (state.needsAdvance) {
- state.needsAdvance = false;
- advanceRule(state, true);
- }
- // Remember initial indentation
- if (stream.sol()) {
- var tabSize = editorConfig && editorConfig.tabSize || 2;
- state.indentLevel = Math.floor(stream.indentation() / tabSize);
- }
- // Consume spaces and ignored characters
- if (eatWhitespace(stream)) {
- return 'ws';
- }
- // Get a matched token from the stream, using lex
- var token = lex(lexRules, stream);
- // If there's no matching token, skip ahead.
- if (!token) {
- stream.match(/\S+/);
- pushRule(SpecialParseRules, state, 'Invalid');
- return 'invalidchar';
- }
- // If the next token is a Comment, insert a Comment parsing rule.
- if (token.kind === 'Comment') {
- pushRule(SpecialParseRules, state, 'Comment');
- return 'comment';
- }
- // Save state before continuing.
- var backupState = assign({}, state);
- // Handle changes in expected indentation level
- if (token.kind === 'Punctuation') {
- if (/^[{([]/.test(token.value)) {
- // Push on the stack of levels one level deeper than the current level.
- state.levels = (state.levels || []).concat(state.indentLevel + 1);
- } else if (/^[})\]]/.test(token.value)) {
- // Pop from the stack of levels.
- // If the top of the stack is lower than the current level, lower the
- // current level to match.
- var levels = state.levels = (state.levels || []).slice(0, -1);
- if (state.indentLevel) {
- if (levels.length > 0 && levels[levels.length - 1] < state.indentLevel) {
- state.indentLevel = levels[levels.length - 1];
- }
- }
- }
- }
- while (state.rule) {
- // If this is a forking rule, determine what rule to use based on
- var expected = typeof state.rule === 'function' ? state.step === 0 ? state.rule(token, stream) : null : state.rule[state.step];
- // Seperator between list elements if necessary.
- if (state.needsSeperator) {
- expected = expected && expected.separator;
- }
- if (expected) {
- // Un-wrap optional/list parseRules.
- if (expected.ofRule) {
- expected = expected.ofRule;
- }
- // A string represents a Rule
- if (typeof expected === 'string') {
- pushRule(parseRules, state, expected);
- continue;
- }
- // Otherwise, match a Terminal.
- if (expected.match && expected.match(token)) {
- if (expected.update) {
- expected.update(state, token);
- }
- // If this token was a punctuator, advance the parse rule, otherwise
- // mark the state to be advanced before the next token. This ensures
- // that tokens which can be appended to keep the appropriate state.
- if (token.kind === 'Punctuation') {
- advanceRule(state, true);
- } else {
- state.needsAdvance = true;
- }
- return expected.style;
- }
- }
- unsuccessful(state);
- }
- // The parser does not know how to interpret this token, do not affect state.
- assign(state, backupState);
- pushRule(SpecialParseRules, state, 'Invalid');
- return 'invalidchar';
- }
- // Utility function to assign from object to another object.
- function assign(to, from) {
- var keys = Object.keys(from);
- for (var i = 0; i < keys.length; i++) {
- to[keys[i]] = from[keys[i]];
- }
- return to;
- }
- // A special rule set for parsing comment tokens.
- var SpecialParseRules = {
- Invalid: [],
- Comment: []
- };
- // Push a new rule onto the state.
- function pushRule(rules, state, ruleKind) {
- if (!rules[ruleKind]) {
- throw new TypeError('Unknown rule: ' + ruleKind);
- }
- state.prevState = _extends({}, state);
- state.kind = ruleKind;
- state.name = null;
- state.type = null;
- state.rule = rules[ruleKind];
- state.step = 0;
- state.needsSeperator = false;
- }
- // Pop the current rule from the state.
- function popRule(state) {
- // Check if there's anything to pop
- if (!state.prevState) {
- return;
- }
- state.kind = state.prevState.kind;
- state.name = state.prevState.name;
- state.type = state.prevState.type;
- state.rule = state.prevState.rule;
- state.step = state.prevState.step;
- state.needsSeperator = state.prevState.needsSeperator;
- state.prevState = state.prevState.prevState;
- }
- // Advance the step of the current rule.
- function advanceRule(state, successful) {
- // If this is advancing successfully and the current state is a list, give
- // it an opportunity to repeat itself.
- if (isList(state)) {
- if (state.rule && state.rule[state.step].separator) {
- var separator = state.rule[state.step].separator;
- state.needsSeperator = !state.needsSeperator;
- // If the separator was optional, then give it an opportunity to repeat.
- if (!state.needsSeperator && separator.ofRule) {
- return;
- }
- }
- // If this was a successful list parse, then allow it to repeat itself.
- if (successful) {
- return;
- }
- }
- // Advance the step in the rule. If the rule is completed, pop
- // the rule and advance the parent rule as well (recursively).
- state.needsSeperator = false;
- state.step++;
- // While the current rule is completed.
- while (state.rule && !(Array.isArray(state.rule) && state.step < state.rule.length)) {
- popRule(state);
- if (state.rule) {
- // Do not advance a List step so it has the opportunity to repeat itself.
- if (isList(state)) {
- if (state.rule && state.rule[state.step].separator) {
- state.needsSeperator = !state.needsSeperator;
- }
- } else {
- state.needsSeperator = false;
- state.step++;
- }
- }
- }
- }
- function isList(state) {
- return Array.isArray(state.rule) && typeof state.rule[state.step] !== 'string' && state.rule[state.step].isList;
- }
- // Unwind the state after an unsuccessful match.
- function unsuccessful(state) {
- // Fall back to the parent rule until you get to an optional or list rule or
- // until the entire stack of rules is empty.
- while (state.rule && !(Array.isArray(state.rule) && state.rule[state.step].ofRule)) {
- popRule(state);
- }
- // If there is still a rule, it must be an optional or list rule.
- // Consider this rule a success so that we may move past it.
- if (state.rule) {
- advanceRule(state, false);
- }
- }
- // Given a stream, returns a { kind, value } pair, or null.
- function lex(lexRules, stream) {
- var kinds = Object.keys(lexRules);
- for (var i = 0; i < kinds.length; i++) {
- var match = stream.match(lexRules[kinds[i]]);
- if (match && match instanceof Array) {
- return { kind: kinds[i], value: match[0] };
- }
- }
- }
- },{"./Rules":268}],271:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.offsetToPosition = offsetToPosition;
- exports.locToRange = locToRange;
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var Range = exports.Range = function () {
- function Range(start, end) {
- var _this = this;
- _classCallCheck(this, Range);
- this.containsPosition = function (position) {
- if (_this.start.line === position.line) {
- return _this.start.character <= position.character;
- } else if (_this.end.line === position.line) {
- return _this.end.character >= position.character;
- } else {
- return _this.start.line <= position.line && _this.end.line >= position.line;
- }
- };
- this.start = start;
- this.end = end;
- }
- Range.prototype.setStart = function setStart(line, character) {
- this.start = new Position(line, character);
- };
- Range.prototype.setEnd = function setEnd(line, character) {
- this.end = new Position(line, character);
- };
- return Range;
- }();
- var Position = exports.Position = function () {
- function Position(line, character) {
- var _this2 = this;
- _classCallCheck(this, Position);
- this.lessThanOrEqualTo = function (position) {
- return _this2.line < position.line || _this2.line === position.line && _this2.character <= position.character;
- };
- this.line = line;
- this.character = character;
- }
- Position.prototype.setLine = function setLine(line) {
- this.line = line;
- };
- Position.prototype.setCharacter = function setCharacter(character) {
- this.character = character;
- };
- return Position;
- }();
- function offsetToPosition(text, loc) {
- var EOL = '\n';
- var buf = text.slice(0, loc);
- var lines = buf.split(EOL).length - 1;
- var lastLineIndex = buf.lastIndexOf(EOL);
- return new Position(lines, loc - lastLineIndex - 1);
- }
- function locToRange(text, loc) {
- var start = offsetToPosition(text, loc.start);
- var end = offsetToPosition(text, loc.end);
- return new Range(start, end);
- }
- },{}],272:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getASTNodeAtPosition = getASTNodeAtPosition;
- exports.pointToOffset = pointToOffset;
- var _Range = require('./Range');
- var _graphql = require('graphql');
- function getASTNodeAtPosition(query, ast, point) {
- var offset = pointToOffset(query, point);
- var nodeContainingPosition = void 0;
- (0, _graphql.visit)(ast, {
- enter: function enter(node) {
- if (node.kind !== 'Name' && // We're usually interested in their parents
- node.loc && node.loc.start <= offset && offset <= node.loc.end) {
- nodeContainingPosition = node;
- } else {
- return false;
- }
- },
- leave: function leave(node) {
- if (node.loc && node.loc.start <= offset && offset <= node.loc.end) {
- return false;
- }
- }
- });
- return nodeContainingPosition;
- } /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function pointToOffset(text, point) {
- var linesUntilPosition = text.split('\n').slice(0, point.line);
- return point.character + linesUntilPosition.map(function (line) {
- return line.length + 1;
- } // count EOL
- ).reduce(function (a, b) {
- return a + b;
- }, 0);
- }
- },{"./Range":271,"graphql":285}],273:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _getASTNodeAtPosition = require('./getASTNodeAtPosition');
- Object.defineProperty(exports, 'getASTNodeAtPosition', {
- enumerable: true,
- get: function get() {
- return _getASTNodeAtPosition.getASTNodeAtPosition;
- }
- });
- Object.defineProperty(exports, 'pointToOffset', {
- enumerable: true,
- get: function get() {
- return _getASTNodeAtPosition.pointToOffset;
- }
- });
- var _Range = require('./Range');
- Object.defineProperty(exports, 'Position', {
- enumerable: true,
- get: function get() {
- return _Range.Position;
- }
- });
- Object.defineProperty(exports, 'Range', {
- enumerable: true,
- get: function get() {
- return _Range.Range;
- }
- });
- Object.defineProperty(exports, 'locToRange', {
- enumerable: true,
- get: function get() {
- return _Range.locToRange;
- }
- });
- Object.defineProperty(exports, 'offsetToPosition', {
- enumerable: true,
- get: function get() {
- return _Range.offsetToPosition;
- }
- });
- var _validateWithCustomRules = require('./validateWithCustomRules');
- Object.defineProperty(exports, 'validateWithCustomRules', {
- enumerable: true,
- get: function get() {
- return _validateWithCustomRules.validateWithCustomRules;
- }
- });
- },{"./Range":271,"./getASTNodeAtPosition":272,"./validateWithCustomRules":274}],274:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.validateWithCustomRules = validateWithCustomRules;
- var _graphql = require('graphql');
- /**
- * Validate a GraphQL Document optionally with custom validation rules.
- */
- function validateWithCustomRules(schema, ast, customRules, isRelayCompatMode) {
- // Because every fragment is considered for determing model subsets that may
- // be used anywhere in the codebase they're all technically "used" by clients
- // of graphql-data. So we remove this rule from the validators.
- var _require = require('graphql/validation/rules/NoUnusedFragments'),
- NoUnusedFragments = _require.NoUnusedFragments;
- var _require2 = require('graphql/validation/rules/ExecutableDefinitions'),
- ExecutableDefinitions = _require2.ExecutableDefinitions;
- var rulesToSkip = [NoUnusedFragments, ExecutableDefinitions];
- if (isRelayCompatMode) {
- var _require3 = require('graphql/validation/rules/KnownFragmentNames'),
- KnownFragmentNames = _require3.KnownFragmentNames;
- rulesToSkip.push(KnownFragmentNames);
- }
- var rules = _graphql.specifiedRules.filter(function (rule) {
- return !rulesToSkip.some(function (r) {
- return r === rule;
- });
- });
- var typeInfo = new _graphql.TypeInfo(schema);
- if (customRules) {
- Array.prototype.push.apply(rules, customRules);
- }
- var errors = (0, _graphql.validate)(schema, ast, rules, typeInfo);
- if (errors.length > 0) {
- return errors.filter(function (error) {
- if (error.message.indexOf('Unknown directive') === -1) {
- return true;
- }
- return !(error.nodes && error.nodes[0] && error.nodes[0].name && error.nodes[0].name.value === 'arguments' || error.nodes && error.nodes[0] && error.nodes[0].name && error.nodes[0].name.value && error.nodes[0].name.value === 'argumentDefinitions');
- });
- }
- return [];
- } /**
- * Copyright (c) Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- },{"graphql":285,"graphql/validation/rules/ExecutableDefinitions":356,"graphql/validation/rules/KnownFragmentNames":361,"graphql/validation/rules/NoUnusedFragments":367}],275:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.GraphQLError = GraphQLError;
- var _printError = require("./printError");
- var _location = require("../language/location");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function GraphQLError( // eslint-disable-line no-redeclare
- message, nodes, source, positions, path, originalError, extensions) {
- // Compute list of blame nodes.
- var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.
- var _source = source;
- if (!_source && _nodes) {
- var node = _nodes[0];
- _source = node && node.loc && node.loc.source;
- }
- var _positions = positions;
- if (!_positions && _nodes) {
- _positions = _nodes.reduce(function (list, node) {
- if (node.loc) {
- list.push(node.loc.start);
- }
- return list;
- }, []);
- }
- if (_positions && _positions.length === 0) {
- _positions = undefined;
- }
- var _locations;
- if (positions && source) {
- _locations = positions.map(function (pos) {
- return (0, _location.getLocation)(source, pos);
- });
- } else if (_nodes) {
- _locations = _nodes.reduce(function (list, node) {
- if (node.loc) {
- list.push((0, _location.getLocation)(node.loc.source, node.loc.start));
- }
- return list;
- }, []);
- }
- var _extensions = extensions || originalError && originalError.extensions;
- Object.defineProperties(this, {
- message: {
- value: message,
- // By being enumerable, JSON.stringify will include `message` in the
- // resulting output. This ensures that the simplest possible GraphQL
- // service adheres to the spec.
- enumerable: true,
- writable: true
- },
- locations: {
- // Coercing falsey values to undefined ensures they will not be included
- // in JSON.stringify() when not provided.
- value: _locations || undefined,
- // By being enumerable, JSON.stringify will include `locations` in the
- // resulting output. This ensures that the simplest possible GraphQL
- // service adheres to the spec.
- enumerable: Boolean(_locations)
- },
- path: {
- // Coercing falsey values to undefined ensures they will not be included
- // in JSON.stringify() when not provided.
- value: path || undefined,
- // By being enumerable, JSON.stringify will include `path` in the
- // resulting output. This ensures that the simplest possible GraphQL
- // service adheres to the spec.
- enumerable: Boolean(path)
- },
- nodes: {
- value: _nodes || undefined
- },
- source: {
- value: _source || undefined
- },
- positions: {
- value: _positions || undefined
- },
- originalError: {
- value: originalError
- },
- extensions: {
- // Coercing falsey values to undefined ensures they will not be included
- // in JSON.stringify() when not provided.
- value: _extensions || undefined,
- // By being enumerable, JSON.stringify will include `path` in the
- // resulting output. This ensures that the simplest possible GraphQL
- // service adheres to the spec.
- enumerable: Boolean(_extensions)
- }
- }); // Include (non-enumerable) stack trace.
- if (originalError && originalError.stack) {
- Object.defineProperty(this, 'stack', {
- value: originalError.stack,
- writable: true,
- configurable: true
- });
- } else if (Error.captureStackTrace) {
- Error.captureStackTrace(this, GraphQLError);
- } else {
- Object.defineProperty(this, 'stack', {
- value: Error().stack,
- writable: true,
- configurable: true
- });
- }
- }
- GraphQLError.prototype = Object.create(Error.prototype, {
- constructor: {
- value: GraphQLError
- },
- name: {
- value: 'GraphQLError'
- },
- toString: {
- value: function toString() {
- return (0, _printError.printError)(this);
- }
- }
- });
- },{"../language/location":309,"./printError":279}],276:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.formatError = formatError;
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given a GraphQLError, format it according to the rules described by the
- * Response Format, Errors section of the GraphQL Specification.
- */
- function formatError(error) {
- !error ? (0, _invariant.default)(0, 'Received null or undefined error.') : void 0;
- var message = error.message || 'An unknown error occurred.';
- var locations = error.locations;
- var path = error.path;
- var extensions = error.extensions;
- return extensions ? {
- message: message,
- locations: locations,
- path: path,
- extensions: extensions
- } : {
- message: message,
- locations: locations,
- path: path
- };
- }
- },{"../jsutils/invariant":290}],277:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "GraphQLError", {
- enumerable: true,
- get: function get() {
- return _GraphQLError.GraphQLError;
- }
- });
- Object.defineProperty(exports, "syntaxError", {
- enumerable: true,
- get: function get() {
- return _syntaxError.syntaxError;
- }
- });
- Object.defineProperty(exports, "locatedError", {
- enumerable: true,
- get: function get() {
- return _locatedError.locatedError;
- }
- });
- Object.defineProperty(exports, "printError", {
- enumerable: true,
- get: function get() {
- return _printError.printError;
- }
- });
- Object.defineProperty(exports, "formatError", {
- enumerable: true,
- get: function get() {
- return _formatError.formatError;
- }
- });
- var _GraphQLError = require("./GraphQLError");
- var _syntaxError = require("./syntaxError");
- var _locatedError = require("./locatedError");
- var _printError = require("./printError");
- var _formatError = require("./formatError");
- },{"./GraphQLError":275,"./formatError":276,"./locatedError":278,"./printError":279,"./syntaxError":280}],278:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.locatedError = locatedError;
- var _GraphQLError = require("./GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given an arbitrary Error, presumably thrown while attempting to execute a
- * GraphQL operation, produce a new GraphQLError aware of the location in the
- * document responsible for the original Error.
- */
- function locatedError(originalError, nodes, path) {
- // Note: this uses a brand-check to support GraphQL errors originating from
- // other contexts.
- if (originalError && Array.isArray(originalError.path)) {
- return originalError;
- }
- return new _GraphQLError.GraphQLError(originalError && originalError.message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError);
- }
- },{"./GraphQLError":275}],279:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.printError = printError;
- var _location = require("../language/location");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Prints a GraphQLError to a string, representing useful location information
- * about the error's position in the source.
- */
- function printError(error) {
- var printedLocations = [];
- if (error.nodes) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = error.nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var node = _step.value;
- if (node.loc) {
- printedLocations.push(highlightSourceAtLocation(node.loc.source, (0, _location.getLocation)(node.loc.source, node.loc.start)));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- } else if (error.source && error.locations) {
- var source = error.source;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = error.locations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var location = _step2.value;
- printedLocations.push(highlightSourceAtLocation(source, location));
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- }
- return printedLocations.length === 0 ? error.message : [error.message].concat(printedLocations).join('\n\n') + '\n';
- }
- /**
- * Render a helpful description of the location of the error in the GraphQL
- * Source document.
- */
- function highlightSourceAtLocation(source, location) {
- var firstLineColumnOffset = source.locationOffset.column - 1;
- var body = whitespace(firstLineColumnOffset) + source.body;
- var lineIndex = location.line - 1;
- var lineOffset = source.locationOffset.line - 1;
- var lineNum = location.line + lineOffset;
- var columnOffset = location.line === 1 ? firstLineColumnOffset : 0;
- var columnNum = location.column + columnOffset;
- var lines = body.split(/\r\n|[\n\r]/g);
- return "".concat(source.name, " (").concat(lineNum, ":").concat(columnNum, ")\n") + printPrefixedLines([// Lines specified like this: ["prefix", "string"],
- ["".concat(lineNum - 1, ": "), lines[lineIndex - 1]], ["".concat(lineNum, ": "), lines[lineIndex]], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1, ": "), lines[lineIndex + 1]]]);
- }
- function printPrefixedLines(lines) {
- var existingLines = lines.filter(function (_ref) {
- var _ = _ref[0],
- line = _ref[1];
- return line !== undefined;
- });
- var padLen = 0;
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = existingLines[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var _ref4 = _step3.value;
- var prefix = _ref4[0];
- padLen = Math.max(padLen, prefix.length);
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- return existingLines.map(function (_ref3) {
- var prefix = _ref3[0],
- line = _ref3[1];
- return lpad(padLen, prefix) + line;
- }).join('\n');
- }
- function whitespace(len) {
- return Array(len + 1).join(' ');
- }
- function lpad(len, str) {
- return whitespace(len - str.length) + str;
- }
- },{"../language/location":309}],280:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.syntaxError = syntaxError;
- var _GraphQLError = require("./GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Produces a GraphQLError representing a syntax error, containing useful
- * descriptive information about the syntax error's position in the source.
- */
- function syntaxError(source, position, description) {
- return new _GraphQLError.GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]);
- }
- },{"./GraphQLError":275}],281:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.execute = execute;
- exports.responsePathAsArray = responsePathAsArray;
- exports.addPath = addPath;
- exports.assertValidExecutionArguments = assertValidExecutionArguments;
- exports.buildExecutionContext = buildExecutionContext;
- exports.collectFields = collectFields;
- exports.buildResolveInfo = buildResolveInfo;
- exports.resolveFieldValueOrError = resolveFieldValueOrError;
- exports.getFieldDef = getFieldDef;
- exports.defaultFieldResolver = void 0;
- var _iterall = require("iterall");
- var _GraphQLError = require("../error/GraphQLError");
- var _locatedError = require("../error/locatedError");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _isNullish = _interopRequireDefault(require("../jsutils/isNullish"));
- var _isPromise = _interopRequireDefault(require("../jsutils/isPromise"));
- var _memoize = _interopRequireDefault(require("../jsutils/memoize3"));
- var _promiseForObject = _interopRequireDefault(require("../jsutils/promiseForObject"));
- var _promiseReduce = _interopRequireDefault(require("../jsutils/promiseReduce"));
- var _getOperationRootType = require("../utilities/getOperationRootType");
- var _typeFromAST = require("../utilities/typeFromAST");
- var _kinds = require("../language/kinds");
- var _values = require("./values");
- var _definition = require("../type/definition");
- var _introspection = require("../type/introspection");
- var _directives = require("../type/directives");
- var _validate = require("../type/validate");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {
- /* eslint-enable no-redeclare */
- // Extract arguments from object args if provided.
- return arguments.length === 1 ? executeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : executeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver);
- }
- function executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {
- // If arguments are missing or incorrect, throw an error.
- assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,
- // a "Response" with only errors is returned.
- var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed.
- if (Array.isArray(exeContext)) {
- return {
- errors: exeContext
- };
- } // Return a Promise that will eventually resolve to the data described by
- // The "Response" section of the GraphQL specification.
- //
- // If errors are encountered while executing a GraphQL field, only that
- // field and its descendants will be omitted, and sibling fields will still
- // be executed. An execution which encounters errors will still result in a
- // resolved Promise.
- var data = executeOperation(exeContext, exeContext.operation, rootValue);
- return buildResponse(exeContext, data);
- }
- /**
- * Given a completed execution context and data, build the { errors, data }
- * response defined by the "Response" section of the GraphQL specification.
- */
- function buildResponse(exeContext, data) {
- if ((0, _isPromise.default)(data)) {
- return data.then(function (resolved) {
- return buildResponse(exeContext, resolved);
- });
- }
- return exeContext.errors.length === 0 ? {
- data: data
- } : {
- errors: exeContext.errors,
- data: data
- };
- }
- /**
- * Given a ResponsePath (found in the `path` entry in the information provided
- * as the last argument to a field resolver), return an Array of the path keys.
- */
- function responsePathAsArray(path) {
- var flattened = [];
- var curr = path;
- while (curr) {
- flattened.push(curr.key);
- curr = curr.prev;
- }
- return flattened.reverse();
- }
- /**
- * Given a ResponsePath and a key, return a new ResponsePath containing the
- * new key.
- */
- function addPath(prev, key) {
- return {
- prev: prev,
- key: key
- };
- }
- /**
- * Essential assertions before executing to provide developer feedback for
- * improper use of the GraphQL library.
- */
- function assertValidExecutionArguments(schema, document, rawVariableValues) {
- !document ? (0, _invariant.default)(0, 'Must provide document') : void 0; // If the schema used for execution is invalid, throw an error.
- (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object.
- !(!rawVariableValues || _typeof(rawVariableValues) === 'object') ? (0, _invariant.default)(0, 'Variables must be provided as an Object where each property is a ' + 'variable value. Perhaps look to see if an unparsed JSON string ' + 'was provided.') : void 0;
- }
- /**
- * Constructs a ExecutionContext object from the arguments passed to
- * execute, which we will pass throughout the other execution methods.
- *
- * Throws a GraphQLError if a valid execution context cannot be created.
- */
- function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver) {
- var errors = [];
- var operation;
- var hasMultipleAssumedOperations = false;
- var fragments = Object.create(null);
- for (var i = 0; i < document.definitions.length; i++) {
- var definition = document.definitions[i];
- switch (definition.kind) {
- case _kinds.Kind.OPERATION_DEFINITION:
- if (!operationName && operation) {
- hasMultipleAssumedOperations = true;
- } else if (!operationName || definition.name && definition.name.value === operationName) {
- operation = definition;
- }
- break;
- case _kinds.Kind.FRAGMENT_DEFINITION:
- fragments[definition.name.value] = definition;
- break;
- }
- }
- if (!operation) {
- if (operationName) {
- errors.push(new _GraphQLError.GraphQLError("Unknown operation named \"".concat(operationName, "\".")));
- } else {
- errors.push(new _GraphQLError.GraphQLError('Must provide an operation.'));
- }
- } else if (hasMultipleAssumedOperations) {
- errors.push(new _GraphQLError.GraphQLError('Must provide operation name if query contains multiple operations.'));
- }
- var variableValues;
- if (operation) {
- var coercedVariableValues = (0, _values.getVariableValues)(schema, operation.variableDefinitions || [], rawVariableValues || {});
- if (coercedVariableValues.errors) {
- errors.push.apply(errors, coercedVariableValues.errors);
- } else {
- variableValues = coercedVariableValues.coerced;
- }
- }
- if (errors.length !== 0) {
- return errors;
- }
- !operation ? (0, _invariant.default)(0, 'Has operation if no errors.') : void 0;
- !variableValues ? (0, _invariant.default)(0, 'Has variables if no errors.') : void 0;
- return {
- schema: schema,
- fragments: fragments,
- rootValue: rootValue,
- contextValue: contextValue,
- operation: operation,
- variableValues: variableValues,
- fieldResolver: fieldResolver || defaultFieldResolver,
- errors: errors
- };
- }
- /**
- * Implements the "Evaluating operations" section of the spec.
- */
- function executeOperation(exeContext, operation, rootValue) {
- var type = (0, _getOperationRootType.getOperationRootType)(exeContext.schema, operation);
- var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null));
- var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level,
- // at which point we still log the error and null the parent field, which
- // in this case is the entire response.
- //
- // Similar to completeValueCatchingError.
- try {
- var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields);
- if ((0, _isPromise.default)(result)) {
- return result.then(undefined, function (error) {
- exeContext.errors.push(error);
- return Promise.resolve(null);
- });
- }
- return result;
- } catch (error) {
- exeContext.errors.push(error);
- return null;
- }
- }
- /**
- * Implements the "Evaluating selection sets" section of the spec
- * for "write" mode.
- */
- function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {
- return (0, _promiseReduce.default)(Object.keys(fields), function (results, responseName) {
- var fieldNodes = fields[responseName];
- var fieldPath = addPath(path, responseName);
- var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
- if (result === undefined) {
- return results;
- }
- if ((0, _isPromise.default)(result)) {
- return result.then(function (resolvedResult) {
- results[responseName] = resolvedResult;
- return results;
- });
- }
- results[responseName] = result;
- return results;
- }, Object.create(null));
- }
- /**
- * Implements the "Evaluating selection sets" section of the spec
- * for "read" mode.
- */
- function executeFields(exeContext, parentType, sourceValue, path, fields) {
- var results = Object.create(null);
- var containsPromise = false;
- for (var i = 0, keys = Object.keys(fields); i < keys.length; ++i) {
- var responseName = keys[i];
- var fieldNodes = fields[responseName];
- var fieldPath = addPath(path, responseName);
- var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);
- if (result !== undefined) {
- results[responseName] = result;
- if (!containsPromise && (0, _isPromise.default)(result)) {
- containsPromise = true;
- }
- }
- } // If there are no promises, we can just return the object
- if (!containsPromise) {
- return results;
- } // Otherwise, results is a map from field name to the result of resolving that
- // field, which is possibly a promise. Return a promise that will return this
- // same map, but with any promises replaced with the values they resolved to.
- return (0, _promiseForObject.default)(results);
- }
- /**
- * Given a selectionSet, adds all of the fields in that selection to
- * the passed in map of fields, and returns it at the end.
- *
- * CollectFields requires the "runtime type" of an object. For a field which
- * returns an Interface or Union type, the "runtime type" will be the actual
- * Object type returned by that field.
- */
- function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {
- for (var i = 0; i < selectionSet.selections.length; i++) {
- var selection = selectionSet.selections[i];
- switch (selection.kind) {
- case _kinds.Kind.FIELD:
- if (!shouldIncludeNode(exeContext, selection)) {
- continue;
- }
- var name = getFieldEntryKey(selection);
- if (!fields[name]) {
- fields[name] = [];
- }
- fields[name].push(selection);
- break;
- case _kinds.Kind.INLINE_FRAGMENT:
- if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {
- continue;
- }
- collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);
- break;
- case _kinds.Kind.FRAGMENT_SPREAD:
- var fragName = selection.name.value;
- if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) {
- continue;
- }
- visitedFragmentNames[fragName] = true;
- var fragment = exeContext.fragments[fragName];
- if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {
- continue;
- }
- collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);
- break;
- }
- }
- return fields;
- }
- /**
- * Determines if a field should be included based on the @include and @skip
- * directives, where @skip has higher precedence than @include.
- */
- function shouldIncludeNode(exeContext, node) {
- var skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, exeContext.variableValues);
- if (skip && skip.if === true) {
- return false;
- }
- var include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, exeContext.variableValues);
- if (include && include.if === false) {
- return false;
- }
- return true;
- }
- /**
- * Determines if a fragment is applicable to the given type.
- */
- function doesFragmentConditionMatch(exeContext, fragment, type) {
- var typeConditionNode = fragment.typeCondition;
- if (!typeConditionNode) {
- return true;
- }
- var conditionalType = (0, _typeFromAST.typeFromAST)(exeContext.schema, typeConditionNode);
- if (conditionalType === type) {
- return true;
- }
- if ((0, _definition.isAbstractType)(conditionalType)) {
- return exeContext.schema.isPossibleType(conditionalType, type);
- }
- return false;
- }
- /**
- * Implements the logic to compute the key of a given field's entry
- */
- function getFieldEntryKey(node) {
- return node.alias ? node.alias.value : node.name.value;
- }
- /**
- * Resolves the field on the given source object. In particular, this
- * figures out the value that the field returns by calling its resolve function,
- * then calls completeValue to complete promises, serialize scalars, or execute
- * the sub-selection-set for objects.
- */
- function resolveField(exeContext, parentType, source, fieldNodes, path) {
- var fieldNode = fieldNodes[0];
- var fieldName = fieldNode.name.value;
- var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName);
- if (!fieldDef) {
- return;
- }
- var resolveFn = fieldDef.resolve || exeContext.fieldResolver;
- var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal
- // or abrupt (error).
- var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info);
- return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result);
- }
- function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) {
- // The resolve function's optional fourth argument is a collection of
- // information about the current execution state.
- return {
- fieldName: fieldDef.name,
- fieldNodes: fieldNodes,
- returnType: fieldDef.type,
- parentType: parentType,
- path: path,
- schema: exeContext.schema,
- fragments: exeContext.fragments,
- rootValue: exeContext.rootValue,
- operation: exeContext.operation,
- variableValues: exeContext.variableValues
- };
- } // Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`
- // function. Returns the result of resolveFn or the abrupt-return Error object.
- function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) {
- try {
- // Build a JS object of arguments from the field.arguments AST, using the
- // variables scope to fulfill any variable references.
- // TODO: find a way to memoize, in case this field is within a List type.
- var args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that
- // is provided to every resolve function within an execution. It is commonly
- // used to represent an authenticated user, or request-specific caches.
- var _contextValue = exeContext.contextValue;
- var result = resolveFn(source, args, _contextValue, info);
- return (0, _isPromise.default)(result) ? result.then(undefined, asErrorInstance) : result;
- } catch (error) {
- return asErrorInstance(error);
- }
- } // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a
- // consistent Error interface.
- function asErrorInstance(error) {
- return error instanceof Error ? error : new Error(error || undefined);
- } // This is a small wrapper around completeValue which detects and logs errors
- // in the execution context.
- function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) {
- try {
- var completed;
- if ((0, _isPromise.default)(result)) {
- completed = result.then(function (resolved) {
- return completeValue(exeContext, returnType, fieldNodes, info, path, resolved);
- });
- } else {
- completed = completeValue(exeContext, returnType, fieldNodes, info, path, result);
- }
- if ((0, _isPromise.default)(completed)) {
- // Note: we don't rely on a `catch` method, but we do expect "thenable"
- // to take a second callback for the error case.
- return completed.then(undefined, function (error) {
- return handleFieldError(error, fieldNodes, path, returnType, exeContext);
- });
- }
- return completed;
- } catch (error) {
- return handleFieldError(error, fieldNodes, path, returnType, exeContext);
- }
- }
- function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) {
- var error = (0, _locatedError.locatedError)(asErrorInstance(rawError), fieldNodes, responsePathAsArray(path)); // If the field type is non-nullable, then it is resolved without any
- // protection from errors, however it still properly locates the error.
- if ((0, _definition.isNonNullType)(returnType)) {
- throw error;
- } // Otherwise, error protection is applied, logging the error and resolving
- // a null value for this field if one is encountered.
- exeContext.errors.push(error);
- return null;
- }
- /**
- * Implements the instructions for completeValue as defined in the
- * "Field entries" section of the spec.
- *
- * If the field type is Non-Null, then this recursively completes the value
- * for the inner type. It throws a field error if that completion returns null,
- * as per the "Nullability" section of the spec.
- *
- * If the field type is a List, then this recursively completes the value
- * for the inner type on each item in the list.
- *
- * If the field type is a Scalar or Enum, ensures the completed value is a legal
- * value of the type by calling the `serialize` method of GraphQL type
- * definition.
- *
- * If the field is an abstract type, determine the runtime type of the value
- * and then complete based on that type
- *
- * Otherwise, the field type expects a sub-selection set, and will complete the
- * value by evaluating all sub-selections.
- */
- function completeValue(exeContext, returnType, fieldNodes, info, path, result) {
- // If result is an Error, throw a located error.
- if (result instanceof Error) {
- throw result;
- } // If field type is NonNull, complete for inner type, and throw field error
- // if result is null.
- if ((0, _definition.isNonNullType)(returnType)) {
- var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result);
- if (completed === null) {
- throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, "."));
- }
- return completed;
- } // If result value is null-ish (null, undefined, or NaN) then return null.
- if ((0, _isNullish.default)(result)) {
- return null;
- } // If field type is List, complete each item in the list with the inner type
- if ((0, _definition.isListType)(returnType)) {
- return completeListValue(exeContext, returnType, fieldNodes, info, path, result);
- } // If field type is a leaf type, Scalar or Enum, serialize to a valid value,
- // returning null if serialization is not possible.
- if ((0, _definition.isLeafType)(returnType)) {
- return completeLeafValue(returnType, result);
- } // If field type is an abstract type, Interface or Union, determine the
- // runtime Object type and complete for that type.
- if ((0, _definition.isAbstractType)(returnType)) {
- return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result);
- } // If field type is Object, execute and complete all sub-selections.
- if ((0, _definition.isObjectType)(returnType)) {
- return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result);
- } // Not reachable. All possible output types have been considered.
- /* istanbul ignore next */
- throw new Error("Cannot complete value of unexpected type \"".concat((0, _inspect.default)(returnType), "\"."));
- }
- /**
- * Complete a list value by completing each item in the list with the
- * inner type
- */
- function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {
- !(0, _iterall.isCollection)(result) ? (0, _invariant.default)(0, "Expected Iterable, but did not find one for field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")) : void 0; // This is specified as a simple map, however we're optimizing the path
- // where the list contains no Promises by avoiding creating another Promise.
- var itemType = returnType.ofType;
- var containsPromise = false;
- var completedResults = [];
- (0, _iterall.forEach)(result, function (item, index) {
- // No need to modify the info object containing the path,
- // since from here on it is not ever accessed by resolver functions.
- var fieldPath = addPath(path, index);
- var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item);
- if (!containsPromise && (0, _isPromise.default)(completedItem)) {
- containsPromise = true;
- }
- completedResults.push(completedItem);
- });
- return containsPromise ? Promise.all(completedResults) : completedResults;
- }
- /**
- * Complete a Scalar or Enum by serializing to a valid value, returning
- * null if serialization is not possible.
- */
- function completeLeafValue(returnType, result) {
- !returnType.serialize ? (0, _invariant.default)(0, 'Missing serialize method on type') : void 0;
- var serializedResult = returnType.serialize(result);
- if ((0, _isInvalid.default)(serializedResult)) {
- throw new Error("Expected a value of type \"".concat((0, _inspect.default)(returnType), "\" but ") + "received: ".concat((0, _inspect.default)(result)));
- }
- return serializedResult;
- }
- /**
- * Complete a value of an abstract type by determining the runtime object type
- * of that value, then complete the value for that type.
- */
- function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {
- var runtimeType = returnType.resolveType ? returnType.resolveType(result, exeContext.contextValue, info) : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType);
- if ((0, _isPromise.default)(runtimeType)) {
- return runtimeType.then(function (resolvedRuntimeType) {
- return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
- });
- }
- return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);
- }
- function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) {
- var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName;
- if (!(0, _definition.isObjectType)(runtimeType)) {
- throw new _GraphQLError.GraphQLError("Abstract type ".concat(returnType.name, " must resolve to an Object type at ") + "runtime for field ".concat(info.parentType.name, ".").concat(info.fieldName, " with ") + "value ".concat((0, _inspect.default)(result), ", received \"").concat((0, _inspect.default)(runtimeType), "\". ") + "Either the ".concat(returnType.name, " type should provide a \"resolveType\" ") + 'function or each possible type should provide an "isTypeOf" function.', fieldNodes);
- }
- if (!exeContext.schema.isPossibleType(returnType, runtimeType)) {
- throw new _GraphQLError.GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type ") + "for \"".concat(returnType.name, "\"."), fieldNodes);
- }
- return runtimeType;
- }
- /**
- * Complete an Object value by executing all sub-selections.
- */
- function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {
- // If there is an isTypeOf predicate function, call it with the
- // current result. If isTypeOf returns false, then raise an error rather
- // than continuing execution.
- if (returnType.isTypeOf) {
- var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
- if ((0, _isPromise.default)(isTypeOf)) {
- return isTypeOf.then(function (resolvedIsTypeOf) {
- if (!resolvedIsTypeOf) {
- throw invalidReturnTypeError(returnType, result, fieldNodes);
- }
- return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
- });
- }
- if (!isTypeOf) {
- throw invalidReturnTypeError(returnType, result, fieldNodes);
- }
- }
- return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);
- }
- function invalidReturnTypeError(returnType, result, fieldNodes) {
- return new _GraphQLError.GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat((0, _inspect.default)(result), "."), fieldNodes);
- }
- function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) {
- // Collect sub-fields to execute to complete this value.
- var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);
- return executeFields(exeContext, returnType, result, path, subFieldNodes);
- }
- /**
- * A memoized collection of relevant subfields with regard to the return
- * type. Memoizing ensures the subfields are not repeatedly calculated, which
- * saves overhead when resolving lists of values.
- */
- var collectSubfields = (0, _memoize.default)(_collectSubfields);
- function _collectSubfields(exeContext, returnType, fieldNodes) {
- var subFieldNodes = Object.create(null);
- var visitedFragmentNames = Object.create(null);
- for (var i = 0; i < fieldNodes.length; i++) {
- var selectionSet = fieldNodes[i].selectionSet;
- if (selectionSet) {
- subFieldNodes = collectFields(exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames);
- }
- }
- return subFieldNodes;
- }
- /**
- * If a resolveType function is not given, then a default resolve behavior is
- * used which attempts two strategies:
- *
- * First, See if the provided value has a `__typename` field defined, if so, use
- * that value as name of the resolved type.
- *
- * Otherwise, test each possible type for the abstract type by calling
- * isTypeOf for the object being coerced, returning the first type that matches.
- */
- function defaultResolveTypeFn(value, contextValue, info, abstractType) {
- // First, look for `__typename`.
- if (value !== null && _typeof(value) === 'object' && typeof value.__typename === 'string') {
- return value.__typename;
- } // Otherwise, test each possible type.
- var possibleTypes = info.schema.getPossibleTypes(abstractType);
- var promisedIsTypeOfResults = [];
- for (var i = 0; i < possibleTypes.length; i++) {
- var type = possibleTypes[i];
- if (type.isTypeOf) {
- var isTypeOfResult = type.isTypeOf(value, contextValue, info);
- if ((0, _isPromise.default)(isTypeOfResult)) {
- promisedIsTypeOfResults[i] = isTypeOfResult;
- } else if (isTypeOfResult) {
- return type;
- }
- }
- }
- if (promisedIsTypeOfResults.length) {
- return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) {
- for (var _i = 0; _i < isTypeOfResults.length; _i++) {
- if (isTypeOfResults[_i]) {
- return possibleTypes[_i];
- }
- }
- });
- }
- }
- /**
- * If a resolve function is not given, then a default resolve behavior is used
- * which takes the property of the source object of the same name as the field
- * and returns it as the result, or if it's a function, returns the result
- * of calling that function while passing along args and context value.
- */
- var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) {
- // ensure source is a value for which property access is acceptable.
- if (_typeof(source) === 'object' || typeof source === 'function') {
- var property = source[info.fieldName];
- if (typeof property === 'function') {
- return source[info.fieldName](args, contextValue, info);
- }
- return property;
- }
- };
- /**
- * This method looks up the field on the given type definition.
- * It has special casing for the two introspection fields, __schema
- * and __typename. __typename is special because it can always be
- * queried as a field, even in situations where no other fields
- * are allowed, like on a Union. __schema could get automatically
- * added to the query type, but that would require mutating type
- * definitions, which would cause issues.
- */
- exports.defaultFieldResolver = defaultFieldResolver;
- function getFieldDef(schema, parentType, fieldName) {
- if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
- return _introspection.SchemaMetaFieldDef;
- } else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
- return _introspection.TypeMetaFieldDef;
- } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) {
- return _introspection.TypeNameMetaFieldDef;
- }
- return parentType.getFields()[fieldName];
- }
- },{"../error/GraphQLError":275,"../error/locatedError":278,"../jsutils/inspect":288,"../jsutils/invariant":290,"../jsutils/isInvalid":291,"../jsutils/isNullish":292,"../jsutils/isPromise":293,"../jsutils/memoize3":297,"../jsutils/promiseForObject":300,"../jsutils/promiseReduce":301,"../language/kinds":307,"../type/definition":323,"../type/directives":324,"../type/introspection":326,"../type/validate":329,"../utilities/getOperationRootType":341,"../utilities/typeFromAST":351,"./values":283,"iterall":137}],282:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "execute", {
- enumerable: true,
- get: function get() {
- return _execute.execute;
- }
- });
- Object.defineProperty(exports, "defaultFieldResolver", {
- enumerable: true,
- get: function get() {
- return _execute.defaultFieldResolver;
- }
- });
- Object.defineProperty(exports, "responsePathAsArray", {
- enumerable: true,
- get: function get() {
- return _execute.responsePathAsArray;
- }
- });
- Object.defineProperty(exports, "getDirectiveValues", {
- enumerable: true,
- get: function get() {
- return _values.getDirectiveValues;
- }
- });
- var _execute = require("./execute");
- var _values = require("./values");
- },{"./execute":281,"./values":283}],283:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getVariableValues = getVariableValues;
- exports.getArgumentValues = getArgumentValues;
- exports.getDirectiveValues = getDirectiveValues;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _GraphQLError = require("../error/GraphQLError");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- var _coerceValue = require("../utilities/coerceValue");
- var _typeFromAST = require("../utilities/typeFromAST");
- var _valueFromAST = require("../utilities/valueFromAST");
- var _kinds = require("../language/kinds");
- var _printer = require("../language/printer");
- var _definition = require("../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Prepares an object map of variableValues of the correct type based on the
- * provided variable definitions and arbitrary input. If the input cannot be
- * parsed to match the variable definitions, a GraphQLError will be thrown.
- *
- * Note: The returned value is a plain Object with a prototype, since it is
- * exposed to user code. Care should be taken to not pull values from the
- * Object prototype.
- */
- function getVariableValues(schema, varDefNodes, inputs) {
- var errors = [];
- var coercedValues = {};
- for (var i = 0; i < varDefNodes.length; i++) {
- var varDefNode = varDefNodes[i];
- var varName = varDefNode.variable.name.value;
- var varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type);
- if (!(0, _definition.isInputType)(varType)) {
- // Must use input types for variables. This should be caught during
- // validation, however is checked again here for safety.
- errors.push(new _GraphQLError.GraphQLError("Variable \"$".concat(varName, "\" expected value of type ") + "\"".concat((0, _printer.print)(varDefNode.type), "\" which cannot be used as an input type."), [varDefNode.type]));
- } else {
- var hasValue = hasOwnProperty(inputs, varName);
- var value = hasValue ? inputs[varName] : undefined;
- if (!hasValue && varDefNode.defaultValue) {
- // If no value was provided to a variable with a default value,
- // use the default value.
- coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType);
- } else if ((!hasValue || value === null) && (0, _definition.isNonNullType)(varType)) {
- // If no value or a nullish value was provided to a variable with a
- // non-null type (required), produce an error.
- errors.push(new _GraphQLError.GraphQLError(hasValue ? "Variable \"$".concat(varName, "\" of non-null type ") + "\"".concat((0, _inspect.default)(varType), "\" must not be null.") : "Variable \"$".concat(varName, "\" of required type ") + "\"".concat((0, _inspect.default)(varType), "\" was not provided."), [varDefNode]));
- } else if (hasValue) {
- if (value === null) {
- // If the explicit value `null` was provided, an entry in the coerced
- // values must exist as the value `null`.
- coercedValues[varName] = null;
- } else {
- // Otherwise, a non-null value was provided, coerce it to the expected
- // type or report an error if coercion fails.
- var coerced = (0, _coerceValue.coerceValue)(value, varType, varDefNode);
- var coercionErrors = coerced.errors;
- if (coercionErrors) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = coercionErrors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var error = _step.value;
- error.message = "Variable \"$".concat(varName, "\" got invalid value ").concat((0, _inspect.default)(value), "; ") + error.message;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- errors.push.apply(errors, coercionErrors);
- } else {
- coercedValues[varName] = coerced.value;
- }
- }
- }
- }
- }
- return errors.length === 0 ? {
- errors: undefined,
- coerced: coercedValues
- } : {
- errors: errors,
- coerced: undefined
- };
- }
- /**
- * Prepares an object map of argument values given a list of argument
- * definitions and list of argument AST nodes.
- *
- * Note: The returned value is a plain Object with a prototype, since it is
- * exposed to user code. Care should be taken to not pull values from the
- * Object prototype.
- */
- function getArgumentValues(def, node, variableValues) {
- var coercedValues = {};
- var argDefs = def.args;
- var argNodes = node.arguments;
- if (!argDefs || !argNodes) {
- return coercedValues;
- }
- var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) {
- return arg.name.value;
- });
- for (var i = 0; i < argDefs.length; i++) {
- var argDef = argDefs[i];
- var name = argDef.name;
- var argType = argDef.type;
- var argumentNode = argNodeMap[name];
- var hasValue = void 0;
- var isNull = void 0;
- if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) {
- var variableName = argumentNode.value.name.value;
- hasValue = variableValues && hasOwnProperty(variableValues, variableName);
- isNull = variableValues && variableValues[variableName] === null;
- } else {
- hasValue = argumentNode != null;
- isNull = argumentNode && argumentNode.value.kind === _kinds.Kind.NULL;
- }
- if (!hasValue && argDef.defaultValue !== undefined) {
- // If no argument was provided where the definition has a default value,
- // use the default value.
- coercedValues[name] = argDef.defaultValue;
- } else if ((!hasValue || isNull) && (0, _definition.isNonNullType)(argType)) {
- // If no argument or a null value was provided to an argument with a
- // non-null type (required), produce a field error.
- if (isNull) {
- throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat((0, _inspect.default)(argType), "\" ") + 'must not be null.', [argumentNode.value]);
- } else if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) {
- var _variableName = argumentNode.value.name.value;
- throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + "was provided the variable \"$".concat(_variableName, "\" ") + 'which was not provided a runtime value.', [argumentNode.value]);
- } else {
- throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + 'was not provided.', [node]);
- }
- } else if (hasValue) {
- if (argumentNode.value.kind === _kinds.Kind.NULL) {
- // If the explicit value `null` was provided, an entry in the coerced
- // values must exist as the value `null`.
- coercedValues[name] = null;
- } else if (argumentNode.value.kind === _kinds.Kind.VARIABLE) {
- var _variableName2 = argumentNode.value.name.value;
- !variableValues ? (0, _invariant.default)(0, 'Must exist for hasValue to be true.') : void 0; // Note: This does no further checking that this variable is correct.
- // This assumes that this query has been validated and the variable
- // usage here is of the correct type.
- coercedValues[name] = variableValues[_variableName2];
- } else {
- var valueNode = argumentNode.value;
- var coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues);
- if (coercedValue === undefined) {
- // Note: ValuesOfCorrectType validation should catch this before
- // execution. This is a runtime check to ensure execution does not
- // continue with an invalid argument value.
- throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat((0, _printer.print)(valueNode), "."), [argumentNode.value]);
- }
- coercedValues[name] = coercedValue;
- }
- }
- }
- return coercedValues;
- }
- /**
- * Prepares an object map of argument values given a directive definition
- * and a AST node which may contain directives. Optionally also accepts a map
- * of variable values.
- *
- * If the directive does not exist on the node, returns undefined.
- *
- * Note: The returned value is a plain Object with a prototype, since it is
- * exposed to user code. Care should be taken to not pull values from the
- * Object prototype.
- */
- function getDirectiveValues(directiveDef, node, variableValues) {
- var directiveNode = node.directives && (0, _find.default)(node.directives, function (directive) {
- return directive.name.value === directiveDef.name;
- });
- if (directiveNode) {
- return getArgumentValues(directiveDef, directiveNode, variableValues);
- }
- }
- function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
- },{"../error/GraphQLError":275,"../jsutils/inspect":288,"../jsutils/invariant":290,"../jsutils/keyMap":294,"../language/kinds":307,"../language/printer":312,"../polyfills/find":315,"../type/definition":323,"../utilities/coerceValue":335,"../utilities/typeFromAST":351,"../utilities/valueFromAST":352}],284:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.graphql = graphql;
- exports.graphqlSync = graphqlSync;
- var _validate = require("./type/validate");
- var _parser = require("./language/parser");
- var _validate2 = require("./validation/validate");
- var _execute = require("./execution/execute");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) {
- var _arguments = arguments;
- /* eslint-enable no-redeclare */
- // Always return a Promise for a consistent API.
- return new Promise(function (resolve) {
- return resolve( // Extract arguments from object args if provided.
- _arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver));
- });
- }
- /**
- * The graphqlSync function also fulfills GraphQL operations by parsing,
- * validating, and executing a GraphQL document along side a GraphQL schema.
- * However, it guarantees to complete synchronously (or throw an error) assuming
- * that all field resolvers are also synchronous.
- */
- function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) {
- /* eslint-enable no-redeclare */
- // Extract arguments from object args if provided.
- var result = arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver); // Assert that the execution was synchronous.
- if (result.then) {
- throw new Error('GraphQL execution failed to complete synchronously.');
- }
- return result;
- }
- function graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) {
- // Validate Schema
- var schemaValidationErrors = (0, _validate.validateSchema)(schema);
- if (schemaValidationErrors.length > 0) {
- return {
- errors: schemaValidationErrors
- };
- } // Parse
- var document;
- try {
- document = (0, _parser.parse)(source);
- } catch (syntaxError) {
- return {
- errors: [syntaxError]
- };
- } // Validate
- var validationErrors = (0, _validate2.validate)(schema, document);
- if (validationErrors.length > 0) {
- return {
- errors: validationErrors
- };
- } // Execute
- return (0, _execute.execute)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver);
- }
- },{"./execution/execute":281,"./language/parser":310,"./type/validate":329,"./validation/validate":390}],285:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "graphql", {
- enumerable: true,
- get: function get() {
- return _graphql.graphql;
- }
- });
- Object.defineProperty(exports, "graphqlSync", {
- enumerable: true,
- get: function get() {
- return _graphql.graphqlSync;
- }
- });
- Object.defineProperty(exports, "GraphQLSchema", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLSchema;
- }
- });
- Object.defineProperty(exports, "GraphQLScalarType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLScalarType;
- }
- });
- Object.defineProperty(exports, "GraphQLObjectType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLObjectType;
- }
- });
- Object.defineProperty(exports, "GraphQLInterfaceType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLInterfaceType;
- }
- });
- Object.defineProperty(exports, "GraphQLUnionType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLUnionType;
- }
- });
- Object.defineProperty(exports, "GraphQLEnumType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLEnumType;
- }
- });
- Object.defineProperty(exports, "GraphQLInputObjectType", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLInputObjectType;
- }
- });
- Object.defineProperty(exports, "GraphQLList", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLList;
- }
- });
- Object.defineProperty(exports, "GraphQLNonNull", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLNonNull;
- }
- });
- Object.defineProperty(exports, "GraphQLDirective", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLDirective;
- }
- });
- Object.defineProperty(exports, "TypeKind", {
- enumerable: true,
- get: function get() {
- return _type.TypeKind;
- }
- });
- Object.defineProperty(exports, "specifiedScalarTypes", {
- enumerable: true,
- get: function get() {
- return _type.specifiedScalarTypes;
- }
- });
- Object.defineProperty(exports, "GraphQLInt", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLInt;
- }
- });
- Object.defineProperty(exports, "GraphQLFloat", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLFloat;
- }
- });
- Object.defineProperty(exports, "GraphQLString", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLString;
- }
- });
- Object.defineProperty(exports, "GraphQLBoolean", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLBoolean;
- }
- });
- Object.defineProperty(exports, "GraphQLID", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLID;
- }
- });
- Object.defineProperty(exports, "specifiedDirectives", {
- enumerable: true,
- get: function get() {
- return _type.specifiedDirectives;
- }
- });
- Object.defineProperty(exports, "GraphQLIncludeDirective", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLIncludeDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLSkipDirective", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLSkipDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLDeprecatedDirective", {
- enumerable: true,
- get: function get() {
- return _type.GraphQLDeprecatedDirective;
- }
- });
- Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", {
- enumerable: true,
- get: function get() {
- return _type.DEFAULT_DEPRECATION_REASON;
- }
- });
- Object.defineProperty(exports, "SchemaMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _type.SchemaMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "TypeMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _type.TypeMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "TypeNameMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _type.TypeNameMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "introspectionTypes", {
- enumerable: true,
- get: function get() {
- return _type.introspectionTypes;
- }
- });
- Object.defineProperty(exports, "__Schema", {
- enumerable: true,
- get: function get() {
- return _type.__Schema;
- }
- });
- Object.defineProperty(exports, "__Directive", {
- enumerable: true,
- get: function get() {
- return _type.__Directive;
- }
- });
- Object.defineProperty(exports, "__DirectiveLocation", {
- enumerable: true,
- get: function get() {
- return _type.__DirectiveLocation;
- }
- });
- Object.defineProperty(exports, "__Type", {
- enumerable: true,
- get: function get() {
- return _type.__Type;
- }
- });
- Object.defineProperty(exports, "__Field", {
- enumerable: true,
- get: function get() {
- return _type.__Field;
- }
- });
- Object.defineProperty(exports, "__InputValue", {
- enumerable: true,
- get: function get() {
- return _type.__InputValue;
- }
- });
- Object.defineProperty(exports, "__EnumValue", {
- enumerable: true,
- get: function get() {
- return _type.__EnumValue;
- }
- });
- Object.defineProperty(exports, "__TypeKind", {
- enumerable: true,
- get: function get() {
- return _type.__TypeKind;
- }
- });
- Object.defineProperty(exports, "isSchema", {
- enumerable: true,
- get: function get() {
- return _type.isSchema;
- }
- });
- Object.defineProperty(exports, "isDirective", {
- enumerable: true,
- get: function get() {
- return _type.isDirective;
- }
- });
- Object.defineProperty(exports, "isType", {
- enumerable: true,
- get: function get() {
- return _type.isType;
- }
- });
- Object.defineProperty(exports, "isScalarType", {
- enumerable: true,
- get: function get() {
- return _type.isScalarType;
- }
- });
- Object.defineProperty(exports, "isObjectType", {
- enumerable: true,
- get: function get() {
- return _type.isObjectType;
- }
- });
- Object.defineProperty(exports, "isInterfaceType", {
- enumerable: true,
- get: function get() {
- return _type.isInterfaceType;
- }
- });
- Object.defineProperty(exports, "isUnionType", {
- enumerable: true,
- get: function get() {
- return _type.isUnionType;
- }
- });
- Object.defineProperty(exports, "isEnumType", {
- enumerable: true,
- get: function get() {
- return _type.isEnumType;
- }
- });
- Object.defineProperty(exports, "isInputObjectType", {
- enumerable: true,
- get: function get() {
- return _type.isInputObjectType;
- }
- });
- Object.defineProperty(exports, "isListType", {
- enumerable: true,
- get: function get() {
- return _type.isListType;
- }
- });
- Object.defineProperty(exports, "isNonNullType", {
- enumerable: true,
- get: function get() {
- return _type.isNonNullType;
- }
- });
- Object.defineProperty(exports, "isInputType", {
- enumerable: true,
- get: function get() {
- return _type.isInputType;
- }
- });
- Object.defineProperty(exports, "isOutputType", {
- enumerable: true,
- get: function get() {
- return _type.isOutputType;
- }
- });
- Object.defineProperty(exports, "isLeafType", {
- enumerable: true,
- get: function get() {
- return _type.isLeafType;
- }
- });
- Object.defineProperty(exports, "isCompositeType", {
- enumerable: true,
- get: function get() {
- return _type.isCompositeType;
- }
- });
- Object.defineProperty(exports, "isAbstractType", {
- enumerable: true,
- get: function get() {
- return _type.isAbstractType;
- }
- });
- Object.defineProperty(exports, "isWrappingType", {
- enumerable: true,
- get: function get() {
- return _type.isWrappingType;
- }
- });
- Object.defineProperty(exports, "isNullableType", {
- enumerable: true,
- get: function get() {
- return _type.isNullableType;
- }
- });
- Object.defineProperty(exports, "isNamedType", {
- enumerable: true,
- get: function get() {
- return _type.isNamedType;
- }
- });
- Object.defineProperty(exports, "isRequiredArgument", {
- enumerable: true,
- get: function get() {
- return _type.isRequiredArgument;
- }
- });
- Object.defineProperty(exports, "isRequiredInputField", {
- enumerable: true,
- get: function get() {
- return _type.isRequiredInputField;
- }
- });
- Object.defineProperty(exports, "isSpecifiedScalarType", {
- enumerable: true,
- get: function get() {
- return _type.isSpecifiedScalarType;
- }
- });
- Object.defineProperty(exports, "isIntrospectionType", {
- enumerable: true,
- get: function get() {
- return _type.isIntrospectionType;
- }
- });
- Object.defineProperty(exports, "isSpecifiedDirective", {
- enumerable: true,
- get: function get() {
- return _type.isSpecifiedDirective;
- }
- });
- Object.defineProperty(exports, "assertSchema", {
- enumerable: true,
- get: function get() {
- return _type.assertSchema;
- }
- });
- Object.defineProperty(exports, "assertDirective", {
- enumerable: true,
- get: function get() {
- return _type.assertDirective;
- }
- });
- Object.defineProperty(exports, "assertType", {
- enumerable: true,
- get: function get() {
- return _type.assertType;
- }
- });
- Object.defineProperty(exports, "assertScalarType", {
- enumerable: true,
- get: function get() {
- return _type.assertScalarType;
- }
- });
- Object.defineProperty(exports, "assertObjectType", {
- enumerable: true,
- get: function get() {
- return _type.assertObjectType;
- }
- });
- Object.defineProperty(exports, "assertInterfaceType", {
- enumerable: true,
- get: function get() {
- return _type.assertInterfaceType;
- }
- });
- Object.defineProperty(exports, "assertUnionType", {
- enumerable: true,
- get: function get() {
- return _type.assertUnionType;
- }
- });
- Object.defineProperty(exports, "assertEnumType", {
- enumerable: true,
- get: function get() {
- return _type.assertEnumType;
- }
- });
- Object.defineProperty(exports, "assertInputObjectType", {
- enumerable: true,
- get: function get() {
- return _type.assertInputObjectType;
- }
- });
- Object.defineProperty(exports, "assertListType", {
- enumerable: true,
- get: function get() {
- return _type.assertListType;
- }
- });
- Object.defineProperty(exports, "assertNonNullType", {
- enumerable: true,
- get: function get() {
- return _type.assertNonNullType;
- }
- });
- Object.defineProperty(exports, "assertInputType", {
- enumerable: true,
- get: function get() {
- return _type.assertInputType;
- }
- });
- Object.defineProperty(exports, "assertOutputType", {
- enumerable: true,
- get: function get() {
- return _type.assertOutputType;
- }
- });
- Object.defineProperty(exports, "assertLeafType", {
- enumerable: true,
- get: function get() {
- return _type.assertLeafType;
- }
- });
- Object.defineProperty(exports, "assertCompositeType", {
- enumerable: true,
- get: function get() {
- return _type.assertCompositeType;
- }
- });
- Object.defineProperty(exports, "assertAbstractType", {
- enumerable: true,
- get: function get() {
- return _type.assertAbstractType;
- }
- });
- Object.defineProperty(exports, "assertWrappingType", {
- enumerable: true,
- get: function get() {
- return _type.assertWrappingType;
- }
- });
- Object.defineProperty(exports, "assertNullableType", {
- enumerable: true,
- get: function get() {
- return _type.assertNullableType;
- }
- });
- Object.defineProperty(exports, "assertNamedType", {
- enumerable: true,
- get: function get() {
- return _type.assertNamedType;
- }
- });
- Object.defineProperty(exports, "getNullableType", {
- enumerable: true,
- get: function get() {
- return _type.getNullableType;
- }
- });
- Object.defineProperty(exports, "getNamedType", {
- enumerable: true,
- get: function get() {
- return _type.getNamedType;
- }
- });
- Object.defineProperty(exports, "validateSchema", {
- enumerable: true,
- get: function get() {
- return _type.validateSchema;
- }
- });
- Object.defineProperty(exports, "assertValidSchema", {
- enumerable: true,
- get: function get() {
- return _type.assertValidSchema;
- }
- });
- Object.defineProperty(exports, "Source", {
- enumerable: true,
- get: function get() {
- return _language.Source;
- }
- });
- Object.defineProperty(exports, "getLocation", {
- enumerable: true,
- get: function get() {
- return _language.getLocation;
- }
- });
- Object.defineProperty(exports, "parse", {
- enumerable: true,
- get: function get() {
- return _language.parse;
- }
- });
- Object.defineProperty(exports, "parseValue", {
- enumerable: true,
- get: function get() {
- return _language.parseValue;
- }
- });
- Object.defineProperty(exports, "parseType", {
- enumerable: true,
- get: function get() {
- return _language.parseType;
- }
- });
- Object.defineProperty(exports, "print", {
- enumerable: true,
- get: function get() {
- return _language.print;
- }
- });
- Object.defineProperty(exports, "visit", {
- enumerable: true,
- get: function get() {
- return _language.visit;
- }
- });
- Object.defineProperty(exports, "visitInParallel", {
- enumerable: true,
- get: function get() {
- return _language.visitInParallel;
- }
- });
- Object.defineProperty(exports, "visitWithTypeInfo", {
- enumerable: true,
- get: function get() {
- return _language.visitWithTypeInfo;
- }
- });
- Object.defineProperty(exports, "getVisitFn", {
- enumerable: true,
- get: function get() {
- return _language.getVisitFn;
- }
- });
- Object.defineProperty(exports, "Kind", {
- enumerable: true,
- get: function get() {
- return _language.Kind;
- }
- });
- Object.defineProperty(exports, "TokenKind", {
- enumerable: true,
- get: function get() {
- return _language.TokenKind;
- }
- });
- Object.defineProperty(exports, "DirectiveLocation", {
- enumerable: true,
- get: function get() {
- return _language.DirectiveLocation;
- }
- });
- Object.defineProperty(exports, "BREAK", {
- enumerable: true,
- get: function get() {
- return _language.BREAK;
- }
- });
- Object.defineProperty(exports, "isDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _language.isDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isExecutableDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _language.isExecutableDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isSelectionNode", {
- enumerable: true,
- get: function get() {
- return _language.isSelectionNode;
- }
- });
- Object.defineProperty(exports, "isValueNode", {
- enumerable: true,
- get: function get() {
- return _language.isValueNode;
- }
- });
- Object.defineProperty(exports, "isTypeNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeNode;
- }
- });
- Object.defineProperty(exports, "isTypeSystemDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeSystemDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isTypeDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isTypeSystemExtensionNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeSystemExtensionNode;
- }
- });
- Object.defineProperty(exports, "isTypeExtensionNode", {
- enumerable: true,
- get: function get() {
- return _language.isTypeExtensionNode;
- }
- });
- Object.defineProperty(exports, "execute", {
- enumerable: true,
- get: function get() {
- return _execution.execute;
- }
- });
- Object.defineProperty(exports, "defaultFieldResolver", {
- enumerable: true,
- get: function get() {
- return _execution.defaultFieldResolver;
- }
- });
- Object.defineProperty(exports, "responsePathAsArray", {
- enumerable: true,
- get: function get() {
- return _execution.responsePathAsArray;
- }
- });
- Object.defineProperty(exports, "getDirectiveValues", {
- enumerable: true,
- get: function get() {
- return _execution.getDirectiveValues;
- }
- });
- Object.defineProperty(exports, "subscribe", {
- enumerable: true,
- get: function get() {
- return _subscription.subscribe;
- }
- });
- Object.defineProperty(exports, "createSourceEventStream", {
- enumerable: true,
- get: function get() {
- return _subscription.createSourceEventStream;
- }
- });
- Object.defineProperty(exports, "validate", {
- enumerable: true,
- get: function get() {
- return _validation.validate;
- }
- });
- Object.defineProperty(exports, "ValidationContext", {
- enumerable: true,
- get: function get() {
- return _validation.ValidationContext;
- }
- });
- Object.defineProperty(exports, "specifiedRules", {
- enumerable: true,
- get: function get() {
- return _validation.specifiedRules;
- }
- });
- Object.defineProperty(exports, "FieldsOnCorrectTypeRule", {
- enumerable: true,
- get: function get() {
- return _validation.FieldsOnCorrectTypeRule;
- }
- });
- Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", {
- enumerable: true,
- get: function get() {
- return _validation.FragmentsOnCompositeTypesRule;
- }
- });
- Object.defineProperty(exports, "KnownArgumentNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.KnownArgumentNamesRule;
- }
- });
- Object.defineProperty(exports, "KnownDirectivesRule", {
- enumerable: true,
- get: function get() {
- return _validation.KnownDirectivesRule;
- }
- });
- Object.defineProperty(exports, "KnownFragmentNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.KnownFragmentNamesRule;
- }
- });
- Object.defineProperty(exports, "KnownTypeNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.KnownTypeNamesRule;
- }
- });
- Object.defineProperty(exports, "LoneAnonymousOperationRule", {
- enumerable: true,
- get: function get() {
- return _validation.LoneAnonymousOperationRule;
- }
- });
- Object.defineProperty(exports, "NoFragmentCyclesRule", {
- enumerable: true,
- get: function get() {
- return _validation.NoFragmentCyclesRule;
- }
- });
- Object.defineProperty(exports, "NoUndefinedVariablesRule", {
- enumerable: true,
- get: function get() {
- return _validation.NoUndefinedVariablesRule;
- }
- });
- Object.defineProperty(exports, "NoUnusedFragmentsRule", {
- enumerable: true,
- get: function get() {
- return _validation.NoUnusedFragmentsRule;
- }
- });
- Object.defineProperty(exports, "NoUnusedVariablesRule", {
- enumerable: true,
- get: function get() {
- return _validation.NoUnusedVariablesRule;
- }
- });
- Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", {
- enumerable: true,
- get: function get() {
- return _validation.OverlappingFieldsCanBeMergedRule;
- }
- });
- Object.defineProperty(exports, "PossibleFragmentSpreadsRule", {
- enumerable: true,
- get: function get() {
- return _validation.PossibleFragmentSpreadsRule;
- }
- });
- Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", {
- enumerable: true,
- get: function get() {
- return _validation.ProvidedRequiredArgumentsRule;
- }
- });
- Object.defineProperty(exports, "ScalarLeafsRule", {
- enumerable: true,
- get: function get() {
- return _validation.ScalarLeafsRule;
- }
- });
- Object.defineProperty(exports, "SingleFieldSubscriptionsRule", {
- enumerable: true,
- get: function get() {
- return _validation.SingleFieldSubscriptionsRule;
- }
- });
- Object.defineProperty(exports, "UniqueArgumentNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueArgumentNamesRule;
- }
- });
- Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueDirectivesPerLocationRule;
- }
- });
- Object.defineProperty(exports, "UniqueFragmentNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueFragmentNamesRule;
- }
- });
- Object.defineProperty(exports, "UniqueInputFieldNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueInputFieldNamesRule;
- }
- });
- Object.defineProperty(exports, "UniqueOperationNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueOperationNamesRule;
- }
- });
- Object.defineProperty(exports, "UniqueVariableNamesRule", {
- enumerable: true,
- get: function get() {
- return _validation.UniqueVariableNamesRule;
- }
- });
- Object.defineProperty(exports, "ValuesOfCorrectTypeRule", {
- enumerable: true,
- get: function get() {
- return _validation.ValuesOfCorrectTypeRule;
- }
- });
- Object.defineProperty(exports, "VariablesAreInputTypesRule", {
- enumerable: true,
- get: function get() {
- return _validation.VariablesAreInputTypesRule;
- }
- });
- Object.defineProperty(exports, "VariablesInAllowedPositionRule", {
- enumerable: true,
- get: function get() {
- return _validation.VariablesInAllowedPositionRule;
- }
- });
- Object.defineProperty(exports, "GraphQLError", {
- enumerable: true,
- get: function get() {
- return _error.GraphQLError;
- }
- });
- Object.defineProperty(exports, "formatError", {
- enumerable: true,
- get: function get() {
- return _error.formatError;
- }
- });
- Object.defineProperty(exports, "printError", {
- enumerable: true,
- get: function get() {
- return _error.printError;
- }
- });
- Object.defineProperty(exports, "getIntrospectionQuery", {
- enumerable: true,
- get: function get() {
- return _utilities.getIntrospectionQuery;
- }
- });
- Object.defineProperty(exports, "introspectionQuery", {
- enumerable: true,
- get: function get() {
- return _utilities.introspectionQuery;
- }
- });
- Object.defineProperty(exports, "getOperationAST", {
- enumerable: true,
- get: function get() {
- return _utilities.getOperationAST;
- }
- });
- Object.defineProperty(exports, "getOperationRootType", {
- enumerable: true,
- get: function get() {
- return _utilities.getOperationRootType;
- }
- });
- Object.defineProperty(exports, "introspectionFromSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.introspectionFromSchema;
- }
- });
- Object.defineProperty(exports, "buildClientSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.buildClientSchema;
- }
- });
- Object.defineProperty(exports, "buildASTSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.buildASTSchema;
- }
- });
- Object.defineProperty(exports, "buildSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.buildSchema;
- }
- });
- Object.defineProperty(exports, "getDescription", {
- enumerable: true,
- get: function get() {
- return _utilities.getDescription;
- }
- });
- Object.defineProperty(exports, "extendSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.extendSchema;
- }
- });
- Object.defineProperty(exports, "lexicographicSortSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.lexicographicSortSchema;
- }
- });
- Object.defineProperty(exports, "printSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.printSchema;
- }
- });
- Object.defineProperty(exports, "printIntrospectionSchema", {
- enumerable: true,
- get: function get() {
- return _utilities.printIntrospectionSchema;
- }
- });
- Object.defineProperty(exports, "printType", {
- enumerable: true,
- get: function get() {
- return _utilities.printType;
- }
- });
- Object.defineProperty(exports, "typeFromAST", {
- enumerable: true,
- get: function get() {
- return _utilities.typeFromAST;
- }
- });
- Object.defineProperty(exports, "valueFromAST", {
- enumerable: true,
- get: function get() {
- return _utilities.valueFromAST;
- }
- });
- Object.defineProperty(exports, "valueFromASTUntyped", {
- enumerable: true,
- get: function get() {
- return _utilities.valueFromASTUntyped;
- }
- });
- Object.defineProperty(exports, "astFromValue", {
- enumerable: true,
- get: function get() {
- return _utilities.astFromValue;
- }
- });
- Object.defineProperty(exports, "TypeInfo", {
- enumerable: true,
- get: function get() {
- return _utilities.TypeInfo;
- }
- });
- Object.defineProperty(exports, "coerceValue", {
- enumerable: true,
- get: function get() {
- return _utilities.coerceValue;
- }
- });
- Object.defineProperty(exports, "isValidJSValue", {
- enumerable: true,
- get: function get() {
- return _utilities.isValidJSValue;
- }
- });
- Object.defineProperty(exports, "isValidLiteralValue", {
- enumerable: true,
- get: function get() {
- return _utilities.isValidLiteralValue;
- }
- });
- Object.defineProperty(exports, "concatAST", {
- enumerable: true,
- get: function get() {
- return _utilities.concatAST;
- }
- });
- Object.defineProperty(exports, "separateOperations", {
- enumerable: true,
- get: function get() {
- return _utilities.separateOperations;
- }
- });
- Object.defineProperty(exports, "isEqualType", {
- enumerable: true,
- get: function get() {
- return _utilities.isEqualType;
- }
- });
- Object.defineProperty(exports, "isTypeSubTypeOf", {
- enumerable: true,
- get: function get() {
- return _utilities.isTypeSubTypeOf;
- }
- });
- Object.defineProperty(exports, "doTypesOverlap", {
- enumerable: true,
- get: function get() {
- return _utilities.doTypesOverlap;
- }
- });
- Object.defineProperty(exports, "assertValidName", {
- enumerable: true,
- get: function get() {
- return _utilities.assertValidName;
- }
- });
- Object.defineProperty(exports, "isValidNameError", {
- enumerable: true,
- get: function get() {
- return _utilities.isValidNameError;
- }
- });
- Object.defineProperty(exports, "findBreakingChanges", {
- enumerable: true,
- get: function get() {
- return _utilities.findBreakingChanges;
- }
- });
- Object.defineProperty(exports, "findDangerousChanges", {
- enumerable: true,
- get: function get() {
- return _utilities.findDangerousChanges;
- }
- });
- Object.defineProperty(exports, "BreakingChangeType", {
- enumerable: true,
- get: function get() {
- return _utilities.BreakingChangeType;
- }
- });
- Object.defineProperty(exports, "DangerousChangeType", {
- enumerable: true,
- get: function get() {
- return _utilities.DangerousChangeType;
- }
- });
- Object.defineProperty(exports, "findDeprecatedUsages", {
- enumerable: true,
- get: function get() {
- return _utilities.findDeprecatedUsages;
- }
- });
- var _graphql = require("./graphql");
- var _type = require("./type");
- var _language = require("./language");
- var _execution = require("./execution");
- var _subscription = require("./subscription");
- var _validation = require("./validation");
- var _error = require("./error");
- var _utilities = require("./utilities");
- },{"./error":277,"./execution":282,"./graphql":284,"./language":306,"./subscription":320,"./type":325,"./utilities":342,"./validation":355}],286:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = defineToJSON;
- var _nodejsCustomInspectSymbol = _interopRequireDefault(require("./nodejsCustomInspectSymbol"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * The `defineToJSON()` function defines toJSON() and inspect() prototype
- * methods, if no function provided they become aliases for toString().
- */
- function defineToJSON( // eslint-disable-next-line flowtype/no-weak-types
- classObject) {
- var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : classObject.prototype.toString;
- classObject.prototype.toJSON = fn;
- classObject.prototype.inspect = fn;
- if (_nodejsCustomInspectSymbol.default) {
- classObject.prototype[_nodejsCustomInspectSymbol.default] = fn;
- }
- }
- },{"./nodejsCustomInspectSymbol":298}],287:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = defineToStringTag;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * The `defineToStringTag()` function checks first to see if the runtime
- * supports the `Symbol` class and then if the `Symbol.toStringTag` constant
- * is defined as a `Symbol` instance. If both conditions are met, the
- * Symbol.toStringTag property is defined as a getter that returns the
- * supplied class constructor's name.
- *
- * @method defineToStringTag
- *
- * @param {Class<any>} classObject a class such as Object, String, Number but
- * typically one of your own creation through the class keyword; `class A {}`,
- * for example.
- */
- function defineToStringTag(classObject) {
- if (typeof Symbol === 'function' && Symbol.toStringTag) {
- Object.defineProperty(classObject.prototype, Symbol.toStringTag, {
- get: function get() {
- return this.constructor.name;
- }
- });
- }
- }
- },{}],288:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = inspect;
- var _nodejsCustomInspectSymbol = _interopRequireDefault(require("./nodejsCustomInspectSymbol"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- /**
- * Used to print values in error messages.
- */
- function inspect(value) {
- switch (_typeof(value)) {
- case 'string':
- return JSON.stringify(value);
- case 'function':
- return value.name ? "[function ".concat(value.name, "]") : '[function]';
- case 'object':
- if (value) {
- var customInspectFn = getCustomFn(value);
- if (customInspectFn) {
- // $FlowFixMe(>=0.90.0)
- var customValue = customInspectFn.call(value);
- return typeof customValue === 'string' ? customValue : inspect(customValue);
- } else if (Array.isArray(value)) {
- return '[' + value.map(inspect).join(', ') + ']';
- }
- var properties = Object.keys(value).map(function (k) {
- return "".concat(k, ": ").concat(inspect(value[k]));
- }).join(', ');
- return properties ? '{ ' + properties + ' }' : '{}';
- }
- return String(value);
- default:
- return String(value);
- }
- }
- function getCustomFn(object) {
- var customInspectFn = object[String(_nodejsCustomInspectSymbol.default)];
- if (typeof customInspectFn === 'function') {
- return customInspectFn;
- }
- if (typeof object.inspect === 'function') {
- return object.inspect;
- }
- }
- },{"./nodejsCustomInspectSymbol":298}],289:[function(require,module,exports){
- (function (process){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * A replacement for instanceof which includes an error warning when multi-realm
- * constructors are detected.
- */
- // See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
- // See: https://webpack.js.org/guides/production/
- var _default = process.env.NODE_ENV === 'production' ? // eslint-disable-next-line no-shadow
- function instanceOf(value, constructor) {
- return value instanceof constructor;
- } : // eslint-disable-next-line no-shadow
- function instanceOf(value, constructor) {
- if (value instanceof constructor) {
- return true;
- }
- if (value) {
- var valueClass = value.constructor;
- var className = constructor.name;
- if (className && valueClass && valueClass.name === className) {
- throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results."));
- }
- }
- return false;
- };
- exports.default = _default;
- }).call(this,require('_process'))
- },{"_process":198}],290:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = invariant;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function invariant(condition, message) {
- /* istanbul ignore else */
- if (!condition) {
- throw new Error(message);
- }
- }
- },{}],291:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = isInvalid;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Returns true if a value is undefined, or NaN.
- */
- function isInvalid(value) {
- return value === undefined || value !== value;
- }
- },{}],292:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = isNullish;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Returns true if a value is null, undefined, or NaN.
- */
- function isNullish(value) {
- return value === null || value === undefined || value !== value;
- }
- },{}],293:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = isPromise;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Returns true if the value acts like a Promise, i.e. has a "then" function,
- * otherwise returns false.
- */
- // eslint-disable-next-line no-redeclare
- function isPromise(value) {
- return Boolean(value && typeof value.then === 'function');
- }
- },{}],294:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = keyMap;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Creates a keyed JS object from an array, given a function to produce the keys
- * for each value in the array.
- *
- * This provides a convenient lookup for the array items if the key function
- * produces unique results.
- *
- * const phoneBook = [
- * { name: 'Jon', num: '555-1234' },
- * { name: 'Jenny', num: '867-5309' }
- * ]
- *
- * // { Jon: { name: 'Jon', num: '555-1234' },
- * // Jenny: { name: 'Jenny', num: '867-5309' } }
- * const entriesByName = keyMap(
- * phoneBook,
- * entry => entry.name
- * )
- *
- * // { name: 'Jenny', num: '857-6309' }
- * const jennyEntry = entriesByName['Jenny']
- *
- */
- function keyMap(list, keyFn) {
- return list.reduce(function (map, item) {
- return map[keyFn(item)] = item, map;
- }, Object.create(null));
- }
- },{}],295:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = keyValMap;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Creates a keyed JS object from an array, given a function to produce the keys
- * and a function to produce the values from each item in the array.
- *
- * const phoneBook = [
- * { name: 'Jon', num: '555-1234' },
- * { name: 'Jenny', num: '867-5309' }
- * ]
- *
- * // { Jon: '555-1234', Jenny: '867-5309' }
- * const phonesByName = keyValMap(
- * phoneBook,
- * entry => entry.name,
- * entry => entry.num
- * )
- *
- */
- function keyValMap(list, keyFn, valFn) {
- return list.reduce(function (map, item) {
- return map[keyFn(item)] = valFn(item), map;
- }, Object.create(null));
- }
- },{}],296:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = mapValue;
- var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2019-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Creates an object map with the same keys as `map` and values generated by
- * running each value of `map` thru `fn`.
- */
- function mapValue(map, fn) {
- var result = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectEntries.default)(map)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref2 = _step.value;
- var _key = _ref2[0];
- var _value = _ref2[1];
- result[_key] = fn(_value, _key);
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return result;
- }
- },{"../polyfills/objectEntries":318}],297:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = memoize3;
- /**
- * Copyright (c) 2017-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Memoizes the provided three-argument function.
- */
- function memoize3(fn) {
- var cache0;
- function memoized(a1, a2, a3) {
- if (!cache0) {
- cache0 = new WeakMap();
- }
- var cache1 = cache0.get(a1);
- var cache2;
- if (cache1) {
- cache2 = cache1.get(a2);
- if (cache2) {
- var cachedValue = cache2.get(a3);
- if (cachedValue !== undefined) {
- return cachedValue;
- }
- }
- } else {
- cache1 = new WeakMap();
- cache0.set(a1, cache1);
- }
- if (!cache2) {
- cache2 = new WeakMap();
- cache1.set(a2, cache2);
- }
- var newValue = fn.apply(this, arguments);
- cache2.set(a3, newValue);
- return newValue;
- }
- return memoized;
- }
- },{}],298:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var nodejsCustomInspectSymbol = typeof Symbol === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;
- var _default = nodejsCustomInspectSymbol;
- exports.default = _default;
- },{}],299:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = orList;
- var _invariant = _interopRequireDefault(require("./invariant"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var MAX_LENGTH = 5;
- /**
- * Given [ A, B, C ] return 'A, B, or C'.
- */
- function orList(items) {
- !(items.length !== 0) ? (0, _invariant.default)(0) : void 0;
- if (items.length === 1) {
- return items[0];
- }
- if (items.length === 2) {
- return items[0] + ' or ' + items[1];
- }
- var selected = items.slice(0, MAX_LENGTH);
- var lastItem = selected.pop();
- return selected.join(', ') + ', or ' + lastItem;
- }
- },{"./invariant":290}],300:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = promiseForObject;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * This function transforms a JS object `ObjMap<Promise<T>>` into
- * a `Promise<ObjMap<T>>`
- *
- * This is akin to bluebird's `Promise.props`, but implemented only using
- * `Promise.all` so it will work with any implementation of ES6 promises.
- */
- function promiseForObject(object) {
- var keys = Object.keys(object);
- var valuesAndPromises = keys.map(function (name) {
- return object[name];
- });
- return Promise.all(valuesAndPromises).then(function (values) {
- return values.reduce(function (resolvedObject, value, i) {
- resolvedObject[keys[i]] = value;
- return resolvedObject;
- }, Object.create(null));
- });
- }
- },{}],301:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = promiseReduce;
- var _isPromise = _interopRequireDefault(require("./isPromise"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Similar to Array.prototype.reduce(), however the reducing callback may return
- * a Promise, in which case reduction will continue after each promise resolves.
- *
- * If the callback does not return a Promise, then this function will also not
- * return a Promise.
- */
- function promiseReduce(values, callback, initialValue) {
- return values.reduce(function (previous, value) {
- return (0, _isPromise.default)(previous) ? previous.then(function (resolved) {
- return callback(resolved, value);
- }) : callback(previous, value);
- }, initialValue);
- }
- },{"./isPromise":293}],302:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = quotedOrList;
- var _orList = _interopRequireDefault(require("./orList"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given [ A, B, C ] return '"A", "B", or "C"'.
- */
- function quotedOrList(items) {
- return (0, _orList.default)(items.map(function (item) {
- return "\"".concat(item, "\"");
- }));
- }
- },{"./orList":299}],303:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = suggestionList;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given an invalid input string and a list of valid options, returns a filtered
- * list of valid options sorted based on their similarity with the input.
- */
- function suggestionList(input, options) {
- var optionsByDistance = Object.create(null);
- var oLength = options.length;
- var inputThreshold = input.length / 2;
- for (var i = 0; i < oLength; i++) {
- var distance = lexicalDistance(input, options[i]);
- var threshold = Math.max(inputThreshold, options[i].length / 2, 1);
- if (distance <= threshold) {
- optionsByDistance[options[i]] = distance;
- }
- }
- return Object.keys(optionsByDistance).sort(function (a, b) {
- return optionsByDistance[a] - optionsByDistance[b];
- });
- }
- /**
- * Computes the lexical distance between strings A and B.
- *
- * The "distance" between two strings is given by counting the minimum number
- * of edits needed to transform string A into string B. An edit can be an
- * insertion, deletion, or substitution of a single character, or a swap of two
- * adjacent characters.
- *
- * Includes a custom alteration from Damerau-Levenshtein to treat case changes
- * as a single edit which helps identify mis-cased values with an edit distance
- * of 1.
- *
- * This distance can be useful for detecting typos in input or sorting
- *
- * @param {string} a
- * @param {string} b
- * @return {int} distance in number of edits
- */
- function lexicalDistance(aStr, bStr) {
- if (aStr === bStr) {
- return 0;
- }
- var i;
- var j;
- var d = [];
- var a = aStr.toLowerCase();
- var b = bStr.toLowerCase();
- var aLength = a.length;
- var bLength = b.length; // Any case change counts as a single edit
- if (a === b) {
- return 1;
- }
- for (i = 0; i <= aLength; i++) {
- d[i] = [i];
- }
- for (j = 1; j <= bLength; j++) {
- d[0][j] = j;
- }
- for (i = 1; i <= aLength; i++) {
- for (j = 1; j <= bLength; j++) {
- var cost = a[i - 1] === b[j - 1] ? 0 : 1;
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
- }
- }
- }
- return d[aLength][bLength];
- }
- },{}],304:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = blockStringValue;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Produces the value of a block string from its parsed raw value, similar to
- * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.
- *
- * This implements the GraphQL spec's BlockStringValue() static algorithm.
- */
- function blockStringValue(rawString) {
- // Expand a block string's raw value into independent lines.
- var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first.
- var commonIndent = null;
- for (var i = 1; i < lines.length; i++) {
- var line = lines[i];
- var indent = leadingWhitespace(line);
- if (indent < line.length && (commonIndent === null || indent < commonIndent)) {
- commonIndent = indent;
- if (commonIndent === 0) {
- break;
- }
- }
- }
- if (commonIndent) {
- for (var _i = 1; _i < lines.length; _i++) {
- lines[_i] = lines[_i].slice(commonIndent);
- }
- } // Remove leading and trailing blank lines.
- while (lines.length > 0 && isBlank(lines[0])) {
- lines.shift();
- }
- while (lines.length > 0 && isBlank(lines[lines.length - 1])) {
- lines.pop();
- } // Return a string of the lines joined with U+000A.
- return lines.join('\n');
- }
- function leadingWhitespace(str) {
- var i = 0;
- while (i < str.length && (str[i] === ' ' || str[i] === '\t')) {
- i++;
- }
- return i;
- }
- function isBlank(str) {
- return leadingWhitespace(str) === str.length;
- }
- },{}],305:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.DirectiveLocation = void 0;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * The set of allowed directive location values.
- */
- var DirectiveLocation = Object.freeze({
- // Request Definitions
- QUERY: 'QUERY',
- MUTATION: 'MUTATION',
- SUBSCRIPTION: 'SUBSCRIPTION',
- FIELD: 'FIELD',
- FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION',
- FRAGMENT_SPREAD: 'FRAGMENT_SPREAD',
- INLINE_FRAGMENT: 'INLINE_FRAGMENT',
- VARIABLE_DEFINITION: 'VARIABLE_DEFINITION',
- // Type System Definitions
- SCHEMA: 'SCHEMA',
- SCALAR: 'SCALAR',
- OBJECT: 'OBJECT',
- FIELD_DEFINITION: 'FIELD_DEFINITION',
- ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION',
- INTERFACE: 'INTERFACE',
- UNION: 'UNION',
- ENUM: 'ENUM',
- ENUM_VALUE: 'ENUM_VALUE',
- INPUT_OBJECT: 'INPUT_OBJECT',
- INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'
- });
- /**
- * The enum type representing the directive location values.
- */
- exports.DirectiveLocation = DirectiveLocation;
- },{}],306:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "getLocation", {
- enumerable: true,
- get: function get() {
- return _location.getLocation;
- }
- });
- Object.defineProperty(exports, "Kind", {
- enumerable: true,
- get: function get() {
- return _kinds.Kind;
- }
- });
- Object.defineProperty(exports, "createLexer", {
- enumerable: true,
- get: function get() {
- return _lexer.createLexer;
- }
- });
- Object.defineProperty(exports, "TokenKind", {
- enumerable: true,
- get: function get() {
- return _lexer.TokenKind;
- }
- });
- Object.defineProperty(exports, "parse", {
- enumerable: true,
- get: function get() {
- return _parser.parse;
- }
- });
- Object.defineProperty(exports, "parseValue", {
- enumerable: true,
- get: function get() {
- return _parser.parseValue;
- }
- });
- Object.defineProperty(exports, "parseType", {
- enumerable: true,
- get: function get() {
- return _parser.parseType;
- }
- });
- Object.defineProperty(exports, "print", {
- enumerable: true,
- get: function get() {
- return _printer.print;
- }
- });
- Object.defineProperty(exports, "Source", {
- enumerable: true,
- get: function get() {
- return _source.Source;
- }
- });
- Object.defineProperty(exports, "visit", {
- enumerable: true,
- get: function get() {
- return _visitor.visit;
- }
- });
- Object.defineProperty(exports, "visitInParallel", {
- enumerable: true,
- get: function get() {
- return _visitor.visitInParallel;
- }
- });
- Object.defineProperty(exports, "visitWithTypeInfo", {
- enumerable: true,
- get: function get() {
- return _visitor.visitWithTypeInfo;
- }
- });
- Object.defineProperty(exports, "getVisitFn", {
- enumerable: true,
- get: function get() {
- return _visitor.getVisitFn;
- }
- });
- Object.defineProperty(exports, "BREAK", {
- enumerable: true,
- get: function get() {
- return _visitor.BREAK;
- }
- });
- Object.defineProperty(exports, "isDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isExecutableDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isExecutableDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isSelectionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isSelectionNode;
- }
- });
- Object.defineProperty(exports, "isValueNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isValueNode;
- }
- });
- Object.defineProperty(exports, "isTypeNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeNode;
- }
- });
- Object.defineProperty(exports, "isTypeSystemDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeSystemDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isTypeDefinitionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeDefinitionNode;
- }
- });
- Object.defineProperty(exports, "isTypeSystemExtensionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeSystemExtensionNode;
- }
- });
- Object.defineProperty(exports, "isTypeExtensionNode", {
- enumerable: true,
- get: function get() {
- return _predicates.isTypeExtensionNode;
- }
- });
- Object.defineProperty(exports, "DirectiveLocation", {
- enumerable: true,
- get: function get() {
- return _directiveLocation.DirectiveLocation;
- }
- });
- var _location = require("./location");
- var _kinds = require("./kinds");
- var _lexer = require("./lexer");
- var _parser = require("./parser");
- var _printer = require("./printer");
- var _source = require("./source");
- var _visitor = require("./visitor");
- var _predicates = require("./predicates");
- var _directiveLocation = require("./directiveLocation");
- },{"./directiveLocation":305,"./kinds":307,"./lexer":308,"./location":309,"./parser":310,"./predicates":311,"./printer":312,"./source":313,"./visitor":314}],307:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Kind = void 0;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * The set of allowed kind values for AST nodes.
- */
- var Kind = Object.freeze({
- // Name
- NAME: 'Name',
- // Document
- DOCUMENT: 'Document',
- OPERATION_DEFINITION: 'OperationDefinition',
- VARIABLE_DEFINITION: 'VariableDefinition',
- SELECTION_SET: 'SelectionSet',
- FIELD: 'Field',
- ARGUMENT: 'Argument',
- // Fragments
- FRAGMENT_SPREAD: 'FragmentSpread',
- INLINE_FRAGMENT: 'InlineFragment',
- FRAGMENT_DEFINITION: 'FragmentDefinition',
- // Values
- VARIABLE: 'Variable',
- INT: 'IntValue',
- FLOAT: 'FloatValue',
- STRING: 'StringValue',
- BOOLEAN: 'BooleanValue',
- NULL: 'NullValue',
- ENUM: 'EnumValue',
- LIST: 'ListValue',
- OBJECT: 'ObjectValue',
- OBJECT_FIELD: 'ObjectField',
- // Directives
- DIRECTIVE: 'Directive',
- // Types
- NAMED_TYPE: 'NamedType',
- LIST_TYPE: 'ListType',
- NON_NULL_TYPE: 'NonNullType',
- // Type System Definitions
- SCHEMA_DEFINITION: 'SchemaDefinition',
- OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',
- // Type Definitions
- SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',
- OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',
- FIELD_DEFINITION: 'FieldDefinition',
- INPUT_VALUE_DEFINITION: 'InputValueDefinition',
- INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',
- UNION_TYPE_DEFINITION: 'UnionTypeDefinition',
- ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',
- ENUM_VALUE_DEFINITION: 'EnumValueDefinition',
- INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',
- // Directive Definitions
- DIRECTIVE_DEFINITION: 'DirectiveDefinition',
- // Type System Extensions
- SCHEMA_EXTENSION: 'SchemaExtension',
- // Type Extensions
- SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',
- OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',
- INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',
- UNION_TYPE_EXTENSION: 'UnionTypeExtension',
- ENUM_TYPE_EXTENSION: 'EnumTypeExtension',
- INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'
- });
- /**
- * The enum type representing the possible kind values of AST nodes.
- */
- exports.Kind = Kind;
- },{}],308:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.createLexer = createLexer;
- exports.getTokenDesc = getTokenDesc;
- exports.TokenKind = void 0;
- var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON"));
- var _error = require("../error");
- var _blockStringValue = _interopRequireDefault(require("./blockStringValue"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given a Source object, this returns a Lexer for that source.
- * A Lexer is a stateful stream generator in that every time
- * it is advanced, it returns the next token in the Source. Assuming the
- * source lexes, the final Token emitted by the lexer will be of kind
- * EOF, after which the lexer will repeatedly return the same EOF token
- * whenever called.
- */
- function createLexer(source, options) {
- var startOfFileToken = new Tok(TokenKind.SOF, 0, 0, 0, 0, null);
- var lexer = {
- source: source,
- options: options,
- lastToken: startOfFileToken,
- token: startOfFileToken,
- line: 1,
- lineStart: 0,
- advance: advanceLexer,
- lookahead: lookahead
- };
- return lexer;
- }
- function advanceLexer() {
- this.lastToken = this.token;
- var token = this.token = this.lookahead();
- return token;
- }
- function lookahead() {
- var token = this.token;
- if (token.kind !== TokenKind.EOF) {
- do {
- // Note: next is only mutable during parsing, so we cast to allow this.
- token = token.next || (token.next = readToken(this, token));
- } while (token.kind === TokenKind.COMMENT);
- }
- return token;
- }
- /**
- * The return type of createLexer.
- */
- /**
- * An exported enum describing the different kinds of tokens that the
- * lexer emits.
- */
- var TokenKind = Object.freeze({
- SOF: '<SOF>',
- EOF: '<EOF>',
- BANG: '!',
- DOLLAR: '$',
- AMP: '&',
- PAREN_L: '(',
- PAREN_R: ')',
- SPREAD: '...',
- COLON: ':',
- EQUALS: '=',
- AT: '@',
- BRACKET_L: '[',
- BRACKET_R: ']',
- BRACE_L: '{',
- PIPE: '|',
- BRACE_R: '}',
- NAME: 'Name',
- INT: 'Int',
- FLOAT: 'Float',
- STRING: 'String',
- BLOCK_STRING: 'BlockString',
- COMMENT: 'Comment'
- });
- /**
- * The enum type representing the token kinds values.
- */
- exports.TokenKind = TokenKind;
- /**
- * A helper function to describe a token as a string for debugging
- */
- function getTokenDesc(token) {
- var value = token.value;
- return value ? "".concat(token.kind, " \"").concat(value, "\"") : token.kind;
- }
- var charCodeAt = String.prototype.charCodeAt;
- var slice = String.prototype.slice;
- /**
- * Helper function for constructing the Token object.
- */
- function Tok(kind, start, end, line, column, prev, value) {
- this.kind = kind;
- this.start = start;
- this.end = end;
- this.line = line;
- this.column = column;
- this.value = value;
- this.prev = prev;
- this.next = null;
- } // Print a simplified form when appearing in JSON/util.inspect.
- (0, _defineToJSON.default)(Tok, function () {
- return {
- kind: this.kind,
- value: this.value,
- line: this.line,
- column: this.column
- };
- });
- function printCharCode(code) {
- return (// NaN/undefined represents access beyond the end of the file.
- isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII.
- code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form.
- "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"")
- );
- }
- /**
- * Gets the next token from the source starting at the given position.
- *
- * This skips over whitespace until it finds the next lexable token, then lexes
- * punctuators immediately or calls the appropriate helper function for more
- * complicated tokens.
- */
- function readToken(lexer, prev) {
- var source = lexer.source;
- var body = source.body;
- var bodyLength = body.length;
- var pos = positionAfterWhitespace(body, prev.end, lexer);
- var line = lexer.line;
- var col = 1 + pos - lexer.lineStart;
- if (pos >= bodyLength) {
- return new Tok(TokenKind.EOF, bodyLength, bodyLength, line, col, prev);
- }
- var code = charCodeAt.call(body, pos); // SourceCharacter
- switch (code) {
- // !
- case 33:
- return new Tok(TokenKind.BANG, pos, pos + 1, line, col, prev);
- // #
- case 35:
- return readComment(source, pos, line, col, prev);
- // $
- case 36:
- return new Tok(TokenKind.DOLLAR, pos, pos + 1, line, col, prev);
- // &
- case 38:
- return new Tok(TokenKind.AMP, pos, pos + 1, line, col, prev);
- // (
- case 40:
- return new Tok(TokenKind.PAREN_L, pos, pos + 1, line, col, prev);
- // )
- case 41:
- return new Tok(TokenKind.PAREN_R, pos, pos + 1, line, col, prev);
- // .
- case 46:
- if (charCodeAt.call(body, pos + 1) === 46 && charCodeAt.call(body, pos + 2) === 46) {
- return new Tok(TokenKind.SPREAD, pos, pos + 3, line, col, prev);
- }
- break;
- // :
- case 58:
- return new Tok(TokenKind.COLON, pos, pos + 1, line, col, prev);
- // =
- case 61:
- return new Tok(TokenKind.EQUALS, pos, pos + 1, line, col, prev);
- // @
- case 64:
- return new Tok(TokenKind.AT, pos, pos + 1, line, col, prev);
- // [
- case 91:
- return new Tok(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev);
- // ]
- case 93:
- return new Tok(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev);
- // {
- case 123:
- return new Tok(TokenKind.BRACE_L, pos, pos + 1, line, col, prev);
- // |
- case 124:
- return new Tok(TokenKind.PIPE, pos, pos + 1, line, col, prev);
- // }
- case 125:
- return new Tok(TokenKind.BRACE_R, pos, pos + 1, line, col, prev);
- // A-Z _ a-z
- case 65:
- case 66:
- case 67:
- case 68:
- case 69:
- case 70:
- case 71:
- case 72:
- case 73:
- case 74:
- case 75:
- case 76:
- case 77:
- case 78:
- case 79:
- case 80:
- case 81:
- case 82:
- case 83:
- case 84:
- case 85:
- case 86:
- case 87:
- case 88:
- case 89:
- case 90:
- case 95:
- case 97:
- case 98:
- case 99:
- case 100:
- case 101:
- case 102:
- case 103:
- case 104:
- case 105:
- case 106:
- case 107:
- case 108:
- case 109:
- case 110:
- case 111:
- case 112:
- case 113:
- case 114:
- case 115:
- case 116:
- case 117:
- case 118:
- case 119:
- case 120:
- case 121:
- case 122:
- return readName(source, pos, line, col, prev);
- // - 0-9
- case 45:
- case 48:
- case 49:
- case 50:
- case 51:
- case 52:
- case 53:
- case 54:
- case 55:
- case 56:
- case 57:
- return readNumber(source, pos, code, line, col, prev);
- // "
- case 34:
- if (charCodeAt.call(body, pos + 1) === 34 && charCodeAt.call(body, pos + 2) === 34) {
- return readBlockString(source, pos, line, col, prev, lexer);
- }
- return readString(source, pos, line, col, prev);
- }
- throw (0, _error.syntaxError)(source, pos, unexpectedCharacterMessage(code));
- }
- /**
- * Report a message that an unexpected character was encountered.
- */
- function unexpectedCharacterMessage(code) {
- if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
- return "Cannot contain the invalid character ".concat(printCharCode(code), ".");
- }
- if (code === 39) {
- // '
- return "Unexpected single quote character ('), did you mean to use " + 'a double quote (")?';
- }
- return "Cannot parse the unexpected character ".concat(printCharCode(code), ".");
- }
- /**
- * Reads from body starting at startPosition until it finds a non-whitespace
- * character, then returns the position of that character for lexing.
- */
- function positionAfterWhitespace(body, startPosition, lexer) {
- var bodyLength = body.length;
- var position = startPosition;
- while (position < bodyLength) {
- var code = charCodeAt.call(body, position); // tab | space | comma | BOM
- if (code === 9 || code === 32 || code === 44 || code === 0xfeff) {
- ++position;
- } else if (code === 10) {
- // new line
- ++position;
- ++lexer.line;
- lexer.lineStart = position;
- } else if (code === 13) {
- // carriage return
- if (charCodeAt.call(body, position + 1) === 10) {
- position += 2;
- } else {
- ++position;
- }
- ++lexer.line;
- lexer.lineStart = position;
- } else {
- break;
- }
- }
- return position;
- }
- /**
- * Reads a comment token from the source file.
- *
- * #[\u0009\u0020-\uFFFF]*
- */
- function readComment(source, start, line, col, prev) {
- var body = source.body;
- var code;
- var position = start;
- do {
- code = charCodeAt.call(body, ++position);
- } while (code !== null && ( // SourceCharacter but not LineTerminator
- code > 0x001f || code === 0x0009));
- return new Tok(TokenKind.COMMENT, start, position, line, col, prev, slice.call(body, start + 1, position));
- }
- /**
- * Reads a number token from the source file, either a float
- * or an int depending on whether a decimal point appears.
- *
- * Int: -?(0|[1-9][0-9]*)
- * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?
- */
- function readNumber(source, start, firstCode, line, col, prev) {
- var body = source.body;
- var code = firstCode;
- var position = start;
- var isFloat = false;
- if (code === 45) {
- // -
- code = charCodeAt.call(body, ++position);
- }
- if (code === 48) {
- // 0
- code = charCodeAt.call(body, ++position);
- if (code >= 48 && code <= 57) {
- throw (0, _error.syntaxError)(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), "."));
- }
- } else {
- position = readDigits(source, position, code);
- code = charCodeAt.call(body, position);
- }
- if (code === 46) {
- // .
- isFloat = true;
- code = charCodeAt.call(body, ++position);
- position = readDigits(source, position, code);
- code = charCodeAt.call(body, position);
- }
- if (code === 69 || code === 101) {
- // E e
- isFloat = true;
- code = charCodeAt.call(body, ++position);
- if (code === 43 || code === 45) {
- // + -
- code = charCodeAt.call(body, ++position);
- }
- position = readDigits(source, position, code);
- }
- return new Tok(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, slice.call(body, start, position));
- }
- /**
- * Returns the new position in the source after reading digits.
- */
- function readDigits(source, start, firstCode) {
- var body = source.body;
- var position = start;
- var code = firstCode;
- if (code >= 48 && code <= 57) {
- // 0 - 9
- do {
- code = charCodeAt.call(body, ++position);
- } while (code >= 48 && code <= 57); // 0 - 9
- return position;
- }
- throw (0, _error.syntaxError)(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));
- }
- /**
- * Reads a string token from the source file.
- *
- * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
- */
- function readString(source, start, line, col, prev) {
- var body = source.body;
- var position = start + 1;
- var chunkStart = position;
- var code = 0;
- var value = '';
- while (position < body.length && (code = charCodeAt.call(body, position)) !== null && // not LineTerminator
- code !== 0x000a && code !== 0x000d) {
- // Closing Quote (")
- if (code === 34) {
- value += slice.call(body, chunkStart, position);
- return new Tok(TokenKind.STRING, start, position + 1, line, col, prev, value);
- } // SourceCharacter
- if (code < 0x0020 && code !== 0x0009) {
- throw (0, _error.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));
- }
- ++position;
- if (code === 92) {
- // \
- value += slice.call(body, chunkStart, position - 1);
- code = charCodeAt.call(body, position);
- switch (code) {
- case 34:
- value += '"';
- break;
- case 47:
- value += '/';
- break;
- case 92:
- value += '\\';
- break;
- case 98:
- value += '\b';
- break;
- case 102:
- value += '\f';
- break;
- case 110:
- value += '\n';
- break;
- case 114:
- value += '\r';
- break;
- case 116:
- value += '\t';
- break;
- case 117:
- // u
- var charCode = uniCharCode(charCodeAt.call(body, position + 1), charCodeAt.call(body, position + 2), charCodeAt.call(body, position + 3), charCodeAt.call(body, position + 4));
- if (charCode < 0) {
- throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: ' + "\\u".concat(body.slice(position + 1, position + 5), "."));
- }
- value += String.fromCharCode(charCode);
- position += 4;
- break;
- default:
- throw (0, _error.syntaxError)(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), "."));
- }
- ++position;
- chunkStart = position;
- }
- }
- throw (0, _error.syntaxError)(source, position, 'Unterminated string.');
- }
- /**
- * Reads a block string token from the source file.
- *
- * """("?"?(\\"""|\\(?!=""")|[^"\\]))*"""
- */
- function readBlockString(source, start, line, col, prev, lexer) {
- var body = source.body;
- var position = start + 3;
- var chunkStart = position;
- var code = 0;
- var rawValue = '';
- while (position < body.length && (code = charCodeAt.call(body, position)) !== null) {
- // Closing Triple-Quote (""")
- if (code === 34 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34) {
- rawValue += slice.call(body, chunkStart, position);
- return new Tok(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, (0, _blockStringValue.default)(rawValue));
- } // SourceCharacter
- if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {
- throw (0, _error.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));
- }
- if (code === 10) {
- // new line
- ++position;
- ++lexer.line;
- lexer.lineStart = position;
- } else if (code === 13) {
- // carriage return
- if (charCodeAt.call(body, position + 1) === 10) {
- position += 2;
- } else {
- ++position;
- }
- ++lexer.line;
- lexer.lineStart = position;
- } else if ( // Escape Triple-Quote (\""")
- code === 92 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34 && charCodeAt.call(body, position + 3) === 34) {
- rawValue += slice.call(body, chunkStart, position) + '"""';
- position += 4;
- chunkStart = position;
- } else {
- ++position;
- }
- }
- throw (0, _error.syntaxError)(source, position, 'Unterminated string.');
- }
- /**
- * Converts four hexadecimal chars to the integer that the
- * string represents. For example, uniCharCode('0','0','0','f')
- * will return 15, and uniCharCode('0','0','f','f') returns 255.
- *
- * Returns a negative number on error, if a char was invalid.
- *
- * This is implemented by noting that char2hex() returns -1 on error,
- * which means the result of ORing the char2hex() will also be negative.
- */
- function uniCharCode(a, b, c, d) {
- return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);
- }
- /**
- * Converts a hex character to its integer value.
- * '0' becomes 0, '9' becomes 9
- * 'A' becomes 10, 'F' becomes 15
- * 'a' becomes 10, 'f' becomes 15
- *
- * Returns -1 on error.
- */
- function char2hex(a) {
- return a >= 48 && a <= 57 ? a - 48 // 0-9
- : a >= 65 && a <= 70 ? a - 55 // A-F
- : a >= 97 && a <= 102 ? a - 87 // a-f
- : -1;
- }
- /**
- * Reads an alphanumeric + underscore name from the source.
- *
- * [_A-Za-z][_0-9A-Za-z]*
- */
- function readName(source, start, line, col, prev) {
- var body = source.body;
- var bodyLength = body.length;
- var position = start + 1;
- var code = 0;
- while (position !== bodyLength && (code = charCodeAt.call(body, position)) !== null && (code === 95 || // _
- code >= 48 && code <= 57 || // 0-9
- code >= 65 && code <= 90 || // A-Z
- code >= 97 && code <= 122) // a-z
- ) {
- ++position;
- }
- return new Tok(TokenKind.NAME, start, position, line, col, prev, slice.call(body, start, position));
- }
- },{"../error":277,"../jsutils/defineToJSON":286,"./blockStringValue":304}],309:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getLocation = getLocation;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Represents a location in a Source.
- */
- /**
- * Takes a Source and a UTF-8 character offset, and returns the corresponding
- * line and column as a SourceLocation.
- */
- function getLocation(source, position) {
- var lineRegexp = /\r\n|[\n\r]/g;
- var line = 1;
- var column = position + 1;
- var match;
- while ((match = lineRegexp.exec(source.body)) && match.index < position) {
- line += 1;
- column = position + 1 - (match.index + match[0].length);
- }
- return {
- line: line,
- column: column
- };
- }
- },{}],310:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.parse = parse;
- exports.parseValue = parseValue;
- exports.parseType = parseType;
- exports.parseConstValue = parseConstValue;
- exports.parseTypeReference = parseTypeReference;
- exports.parseNamedType = parseNamedType;
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON"));
- var _source = require("./source");
- var _error = require("../error");
- var _lexer = require("./lexer");
- var _kinds = require("./kinds");
- var _directiveLocation = require("./directiveLocation");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Given a GraphQL source, parses it into a Document.
- * Throws GraphQLError if a syntax error is encountered.
- */
- function parse(source, options) {
- var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
- if (!(sourceObj instanceof _source.Source)) {
- throw new TypeError("Must provide Source. Received: ".concat((0, _inspect.default)(sourceObj)));
- }
- var lexer = (0, _lexer.createLexer)(sourceObj, options || {});
- return parseDocument(lexer);
- }
- /**
- * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for
- * that value.
- * Throws GraphQLError if a syntax error is encountered.
- *
- * This is useful within tools that operate upon GraphQL Values directly and
- * in isolation of complete GraphQL documents.
- *
- * Consider providing the results to the utility function: valueFromAST().
- */
- function parseValue(source, options) {
- var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
- var lexer = (0, _lexer.createLexer)(sourceObj, options || {});
- expect(lexer, _lexer.TokenKind.SOF);
- var value = parseValueLiteral(lexer, false);
- expect(lexer, _lexer.TokenKind.EOF);
- return value;
- }
- /**
- * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for
- * that type.
- * Throws GraphQLError if a syntax error is encountered.
- *
- * This is useful within tools that operate upon GraphQL Types directly and
- * in isolation of complete GraphQL documents.
- *
- * Consider providing the results to the utility function: typeFromAST().
- */
- function parseType(source, options) {
- var sourceObj = typeof source === 'string' ? new _source.Source(source) : source;
- var lexer = (0, _lexer.createLexer)(sourceObj, options || {});
- expect(lexer, _lexer.TokenKind.SOF);
- var type = parseTypeReference(lexer);
- expect(lexer, _lexer.TokenKind.EOF);
- return type;
- }
- /**
- * Converts a name lex token into a name parse node.
- */
- function parseName(lexer) {
- var token = expect(lexer, _lexer.TokenKind.NAME);
- return {
- kind: _kinds.Kind.NAME,
- value: token.value,
- loc: loc(lexer, token)
- };
- } // Implements the parsing rules in the Document section.
- /**
- * Document : Definition+
- */
- function parseDocument(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.DOCUMENT,
- definitions: many(lexer, _lexer.TokenKind.SOF, parseDefinition, _lexer.TokenKind.EOF),
- loc: loc(lexer, start)
- };
- }
- /**
- * Definition :
- * - ExecutableDefinition
- * - TypeSystemDefinition
- * - TypeSystemExtension
- */
- function parseDefinition(lexer) {
- if (peek(lexer, _lexer.TokenKind.NAME)) {
- switch (lexer.token.value) {
- case 'query':
- case 'mutation':
- case 'subscription':
- case 'fragment':
- return parseExecutableDefinition(lexer);
- case 'schema':
- case 'scalar':
- case 'type':
- case 'interface':
- case 'union':
- case 'enum':
- case 'input':
- case 'directive':
- return parseTypeSystemDefinition(lexer);
- case 'extend':
- return parseTypeSystemExtension(lexer);
- }
- } else if (peek(lexer, _lexer.TokenKind.BRACE_L)) {
- return parseExecutableDefinition(lexer);
- } else if (peekDescription(lexer)) {
- return parseTypeSystemDefinition(lexer);
- }
- throw unexpected(lexer);
- }
- /**
- * ExecutableDefinition :
- * - OperationDefinition
- * - FragmentDefinition
- */
- function parseExecutableDefinition(lexer) {
- if (peek(lexer, _lexer.TokenKind.NAME)) {
- switch (lexer.token.value) {
- case 'query':
- case 'mutation':
- case 'subscription':
- return parseOperationDefinition(lexer);
- case 'fragment':
- return parseFragmentDefinition(lexer);
- }
- } else if (peek(lexer, _lexer.TokenKind.BRACE_L)) {
- return parseOperationDefinition(lexer);
- }
- throw unexpected(lexer);
- } // Implements the parsing rules in the Operations section.
- /**
- * OperationDefinition :
- * - SelectionSet
- * - OperationType Name? VariableDefinitions? Directives? SelectionSet
- */
- function parseOperationDefinition(lexer) {
- var start = lexer.token;
- if (peek(lexer, _lexer.TokenKind.BRACE_L)) {
- return {
- kind: _kinds.Kind.OPERATION_DEFINITION,
- operation: 'query',
- name: undefined,
- variableDefinitions: [],
- directives: [],
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- var operation = parseOperationType(lexer);
- var name;
- if (peek(lexer, _lexer.TokenKind.NAME)) {
- name = parseName(lexer);
- }
- return {
- kind: _kinds.Kind.OPERATION_DEFINITION,
- operation: operation,
- name: name,
- variableDefinitions: parseVariableDefinitions(lexer),
- directives: parseDirectives(lexer, false),
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- /**
- * OperationType : one of query mutation subscription
- */
- function parseOperationType(lexer) {
- var operationToken = expect(lexer, _lexer.TokenKind.NAME);
- switch (operationToken.value) {
- case 'query':
- return 'query';
- case 'mutation':
- return 'mutation';
- case 'subscription':
- return 'subscription';
- }
- throw unexpected(lexer, operationToken);
- }
- /**
- * VariableDefinitions : ( VariableDefinition+ )
- */
- function parseVariableDefinitions(lexer) {
- return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, parseVariableDefinition, _lexer.TokenKind.PAREN_R) : [];
- }
- /**
- * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
- */
- function parseVariableDefinition(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.VARIABLE_DEFINITION,
- variable: parseVariable(lexer),
- type: (expect(lexer, _lexer.TokenKind.COLON), parseTypeReference(lexer)),
- defaultValue: skip(lexer, _lexer.TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined,
- directives: parseDirectives(lexer, true),
- loc: loc(lexer, start)
- };
- }
- /**
- * Variable : $ Name
- */
- function parseVariable(lexer) {
- var start = lexer.token;
- expect(lexer, _lexer.TokenKind.DOLLAR);
- return {
- kind: _kinds.Kind.VARIABLE,
- name: parseName(lexer),
- loc: loc(lexer, start)
- };
- }
- /**
- * SelectionSet : { Selection+ }
- */
- function parseSelectionSet(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.SELECTION_SET,
- selections: many(lexer, _lexer.TokenKind.BRACE_L, parseSelection, _lexer.TokenKind.BRACE_R),
- loc: loc(lexer, start)
- };
- }
- /**
- * Selection :
- * - Field
- * - FragmentSpread
- * - InlineFragment
- */
- function parseSelection(lexer) {
- return peek(lexer, _lexer.TokenKind.SPREAD) ? parseFragment(lexer) : parseField(lexer);
- }
- /**
- * Field : Alias? Name Arguments? Directives? SelectionSet?
- *
- * Alias : Name :
- */
- function parseField(lexer) {
- var start = lexer.token;
- var nameOrAlias = parseName(lexer);
- var alias;
- var name;
- if (skip(lexer, _lexer.TokenKind.COLON)) {
- alias = nameOrAlias;
- name = parseName(lexer);
- } else {
- name = nameOrAlias;
- }
- return {
- kind: _kinds.Kind.FIELD,
- alias: alias,
- name: name,
- arguments: parseArguments(lexer, false),
- directives: parseDirectives(lexer, false),
- selectionSet: peek(lexer, _lexer.TokenKind.BRACE_L) ? parseSelectionSet(lexer) : undefined,
- loc: loc(lexer, start)
- };
- }
- /**
- * Arguments[Const] : ( Argument[?Const]+ )
- */
- function parseArguments(lexer, isConst) {
- var item = isConst ? parseConstArgument : parseArgument;
- return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, item, _lexer.TokenKind.PAREN_R) : [];
- }
- /**
- * Argument[Const] : Name : Value[?Const]
- */
- function parseArgument(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.ARGUMENT,
- name: parseName(lexer),
- value: (expect(lexer, _lexer.TokenKind.COLON), parseValueLiteral(lexer, false)),
- loc: loc(lexer, start)
- };
- }
- function parseConstArgument(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.ARGUMENT,
- name: parseName(lexer),
- value: (expect(lexer, _lexer.TokenKind.COLON), parseConstValue(lexer)),
- loc: loc(lexer, start)
- };
- } // Implements the parsing rules in the Fragments section.
- /**
- * Corresponds to both FragmentSpread and InlineFragment in the spec.
- *
- * FragmentSpread : ... FragmentName Directives?
- *
- * InlineFragment : ... TypeCondition? Directives? SelectionSet
- */
- function parseFragment(lexer) {
- var start = lexer.token;
- expect(lexer, _lexer.TokenKind.SPREAD);
- var hasTypeCondition = skipKeyword(lexer, 'on');
- if (!hasTypeCondition && peek(lexer, _lexer.TokenKind.NAME)) {
- return {
- kind: _kinds.Kind.FRAGMENT_SPREAD,
- name: parseFragmentName(lexer),
- directives: parseDirectives(lexer, false),
- loc: loc(lexer, start)
- };
- }
- return {
- kind: _kinds.Kind.INLINE_FRAGMENT,
- typeCondition: hasTypeCondition ? parseNamedType(lexer) : undefined,
- directives: parseDirectives(lexer, false),
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- /**
- * FragmentDefinition :
- * - fragment FragmentName on TypeCondition Directives? SelectionSet
- *
- * TypeCondition : NamedType
- */
- function parseFragmentDefinition(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'fragment'); // Experimental support for defining variables within fragments changes
- // the grammar of FragmentDefinition:
- // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet
- if (lexer.options.experimentalFragmentVariables) {
- return {
- kind: _kinds.Kind.FRAGMENT_DEFINITION,
- name: parseFragmentName(lexer),
- variableDefinitions: parseVariableDefinitions(lexer),
- typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)),
- directives: parseDirectives(lexer, false),
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- return {
- kind: _kinds.Kind.FRAGMENT_DEFINITION,
- name: parseFragmentName(lexer),
- typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)),
- directives: parseDirectives(lexer, false),
- selectionSet: parseSelectionSet(lexer),
- loc: loc(lexer, start)
- };
- }
- /**
- * FragmentName : Name but not `on`
- */
- function parseFragmentName(lexer) {
- if (lexer.token.value === 'on') {
- throw unexpected(lexer);
- }
- return parseName(lexer);
- } // Implements the parsing rules in the Values section.
- /**
- * Value[Const] :
- * - [~Const] Variable
- * - IntValue
- * - FloatValue
- * - StringValue
- * - BooleanValue
- * - NullValue
- * - EnumValue
- * - ListValue[?Const]
- * - ObjectValue[?Const]
- *
- * BooleanValue : one of `true` `false`
- *
- * NullValue : `null`
- *
- * EnumValue : Name but not `true`, `false` or `null`
- */
- function parseValueLiteral(lexer, isConst) {
- var token = lexer.token;
- switch (token.kind) {
- case _lexer.TokenKind.BRACKET_L:
- return parseList(lexer, isConst);
- case _lexer.TokenKind.BRACE_L:
- return parseObject(lexer, isConst);
- case _lexer.TokenKind.INT:
- lexer.advance();
- return {
- kind: _kinds.Kind.INT,
- value: token.value,
- loc: loc(lexer, token)
- };
- case _lexer.TokenKind.FLOAT:
- lexer.advance();
- return {
- kind: _kinds.Kind.FLOAT,
- value: token.value,
- loc: loc(lexer, token)
- };
- case _lexer.TokenKind.STRING:
- case _lexer.TokenKind.BLOCK_STRING:
- return parseStringLiteral(lexer);
- case _lexer.TokenKind.NAME:
- if (token.value === 'true' || token.value === 'false') {
- lexer.advance();
- return {
- kind: _kinds.Kind.BOOLEAN,
- value: token.value === 'true',
- loc: loc(lexer, token)
- };
- } else if (token.value === 'null') {
- lexer.advance();
- return {
- kind: _kinds.Kind.NULL,
- loc: loc(lexer, token)
- };
- }
- lexer.advance();
- return {
- kind: _kinds.Kind.ENUM,
- value: token.value,
- loc: loc(lexer, token)
- };
- case _lexer.TokenKind.DOLLAR:
- if (!isConst) {
- return parseVariable(lexer);
- }
- break;
- }
- throw unexpected(lexer);
- }
- function parseStringLiteral(lexer) {
- var token = lexer.token;
- lexer.advance();
- return {
- kind: _kinds.Kind.STRING,
- value: token.value,
- block: token.kind === _lexer.TokenKind.BLOCK_STRING,
- loc: loc(lexer, token)
- };
- }
- function parseConstValue(lexer) {
- return parseValueLiteral(lexer, true);
- }
- function parseValueValue(lexer) {
- return parseValueLiteral(lexer, false);
- }
- /**
- * ListValue[Const] :
- * - [ ]
- * - [ Value[?Const]+ ]
- */
- function parseList(lexer, isConst) {
- var start = lexer.token;
- var item = isConst ? parseConstValue : parseValueValue;
- return {
- kind: _kinds.Kind.LIST,
- values: any(lexer, _lexer.TokenKind.BRACKET_L, item, _lexer.TokenKind.BRACKET_R),
- loc: loc(lexer, start)
- };
- }
- /**
- * ObjectValue[Const] :
- * - { }
- * - { ObjectField[?Const]+ }
- */
- function parseObject(lexer, isConst) {
- var start = lexer.token;
- expect(lexer, _lexer.TokenKind.BRACE_L);
- var fields = [];
- while (!skip(lexer, _lexer.TokenKind.BRACE_R)) {
- fields.push(parseObjectField(lexer, isConst));
- }
- return {
- kind: _kinds.Kind.OBJECT,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * ObjectField[Const] : Name : Value[?Const]
- */
- function parseObjectField(lexer, isConst) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.OBJECT_FIELD,
- name: parseName(lexer),
- value: (expect(lexer, _lexer.TokenKind.COLON), parseValueLiteral(lexer, isConst)),
- loc: loc(lexer, start)
- };
- } // Implements the parsing rules in the Directives section.
- /**
- * Directives[Const] : Directive[?Const]+
- */
- function parseDirectives(lexer, isConst) {
- var directives = [];
- while (peek(lexer, _lexer.TokenKind.AT)) {
- directives.push(parseDirective(lexer, isConst));
- }
- return directives;
- }
- /**
- * Directive[Const] : @ Name Arguments[?Const]?
- */
- function parseDirective(lexer, isConst) {
- var start = lexer.token;
- expect(lexer, _lexer.TokenKind.AT);
- return {
- kind: _kinds.Kind.DIRECTIVE,
- name: parseName(lexer),
- arguments: parseArguments(lexer, isConst),
- loc: loc(lexer, start)
- };
- } // Implements the parsing rules in the Types section.
- /**
- * Type :
- * - NamedType
- * - ListType
- * - NonNullType
- */
- function parseTypeReference(lexer) {
- var start = lexer.token;
- var type;
- if (skip(lexer, _lexer.TokenKind.BRACKET_L)) {
- type = parseTypeReference(lexer);
- expect(lexer, _lexer.TokenKind.BRACKET_R);
- type = {
- kind: _kinds.Kind.LIST_TYPE,
- type: type,
- loc: loc(lexer, start)
- };
- } else {
- type = parseNamedType(lexer);
- }
- if (skip(lexer, _lexer.TokenKind.BANG)) {
- return {
- kind: _kinds.Kind.NON_NULL_TYPE,
- type: type,
- loc: loc(lexer, start)
- };
- }
- return type;
- }
- /**
- * NamedType : Name
- */
- function parseNamedType(lexer) {
- var start = lexer.token;
- return {
- kind: _kinds.Kind.NAMED_TYPE,
- name: parseName(lexer),
- loc: loc(lexer, start)
- };
- } // Implements the parsing rules in the Type Definition section.
- /**
- * TypeSystemDefinition :
- * - SchemaDefinition
- * - TypeDefinition
- * - DirectiveDefinition
- *
- * TypeDefinition :
- * - ScalarTypeDefinition
- * - ObjectTypeDefinition
- * - InterfaceTypeDefinition
- * - UnionTypeDefinition
- * - EnumTypeDefinition
- * - InputObjectTypeDefinition
- */
- function parseTypeSystemDefinition(lexer) {
- // Many definitions begin with a description and require a lookahead.
- var keywordToken = peekDescription(lexer) ? lexer.lookahead() : lexer.token;
- if (keywordToken.kind === _lexer.TokenKind.NAME) {
- switch (keywordToken.value) {
- case 'schema':
- return parseSchemaDefinition(lexer);
- case 'scalar':
- return parseScalarTypeDefinition(lexer);
- case 'type':
- return parseObjectTypeDefinition(lexer);
- case 'interface':
- return parseInterfaceTypeDefinition(lexer);
- case 'union':
- return parseUnionTypeDefinition(lexer);
- case 'enum':
- return parseEnumTypeDefinition(lexer);
- case 'input':
- return parseInputObjectTypeDefinition(lexer);
- case 'directive':
- return parseDirectiveDefinition(lexer);
- }
- }
- throw unexpected(lexer, keywordToken);
- }
- function peekDescription(lexer) {
- return peek(lexer, _lexer.TokenKind.STRING) || peek(lexer, _lexer.TokenKind.BLOCK_STRING);
- }
- /**
- * Description : StringValue
- */
- function parseDescription(lexer) {
- if (peekDescription(lexer)) {
- return parseStringLiteral(lexer);
- }
- }
- /**
- * SchemaDefinition : schema Directives[Const]? { OperationTypeDefinition+ }
- */
- function parseSchemaDefinition(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'schema');
- var directives = parseDirectives(lexer, true);
- var operationTypes = many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R);
- return {
- kind: _kinds.Kind.SCHEMA_DEFINITION,
- directives: directives,
- operationTypes: operationTypes,
- loc: loc(lexer, start)
- };
- }
- /**
- * OperationTypeDefinition : OperationType : NamedType
- */
- function parseOperationTypeDefinition(lexer) {
- var start = lexer.token;
- var operation = parseOperationType(lexer);
- expect(lexer, _lexer.TokenKind.COLON);
- var type = parseNamedType(lexer);
- return {
- kind: _kinds.Kind.OPERATION_TYPE_DEFINITION,
- operation: operation,
- type: type,
- loc: loc(lexer, start)
- };
- }
- /**
- * ScalarTypeDefinition : Description? scalar Name Directives[Const]?
- */
- function parseScalarTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'scalar');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- return {
- kind: _kinds.Kind.SCALAR_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * ObjectTypeDefinition :
- * Description?
- * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
- */
- function parseObjectTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'type');
- var name = parseName(lexer);
- var interfaces = parseImplementsInterfaces(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseFieldsDefinition(lexer);
- return {
- kind: _kinds.Kind.OBJECT_TYPE_DEFINITION,
- description: description,
- name: name,
- interfaces: interfaces,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * ImplementsInterfaces :
- * - implements `&`? NamedType
- * - ImplementsInterfaces & NamedType
- */
- function parseImplementsInterfaces(lexer) {
- var types = [];
- if (skipKeyword(lexer, 'implements')) {
- // Optional leading ampersand
- skip(lexer, _lexer.TokenKind.AMP);
- do {
- types.push(parseNamedType(lexer));
- } while (skip(lexer, _lexer.TokenKind.AMP) || // Legacy support for the SDL?
- lexer.options.allowLegacySDLImplementsInterfaces && peek(lexer, _lexer.TokenKind.NAME));
- }
- return types;
- }
- /**
- * FieldsDefinition : { FieldDefinition+ }
- */
- function parseFieldsDefinition(lexer) {
- // Legacy support for the SDL?
- if (lexer.options.allowLegacySDLEmptyFields && peek(lexer, _lexer.TokenKind.BRACE_L) && lexer.lookahead().kind === _lexer.TokenKind.BRACE_R) {
- lexer.advance();
- lexer.advance();
- return [];
- }
- return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R) : [];
- }
- /**
- * FieldDefinition :
- * - Description? Name ArgumentsDefinition? : Type Directives[Const]?
- */
- function parseFieldDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- var name = parseName(lexer);
- var args = parseArgumentDefs(lexer);
- expect(lexer, _lexer.TokenKind.COLON);
- var type = parseTypeReference(lexer);
- var directives = parseDirectives(lexer, true);
- return {
- kind: _kinds.Kind.FIELD_DEFINITION,
- description: description,
- name: name,
- arguments: args,
- type: type,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * ArgumentsDefinition : ( InputValueDefinition+ )
- */
- function parseArgumentDefs(lexer) {
- if (!peek(lexer, _lexer.TokenKind.PAREN_L)) {
- return [];
- }
- return many(lexer, _lexer.TokenKind.PAREN_L, parseInputValueDef, _lexer.TokenKind.PAREN_R);
- }
- /**
- * InputValueDefinition :
- * - Description? Name : Type DefaultValue? Directives[Const]?
- */
- function parseInputValueDef(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- var name = parseName(lexer);
- expect(lexer, _lexer.TokenKind.COLON);
- var type = parseTypeReference(lexer);
- var defaultValue;
- if (skip(lexer, _lexer.TokenKind.EQUALS)) {
- defaultValue = parseConstValue(lexer);
- }
- var directives = parseDirectives(lexer, true);
- return {
- kind: _kinds.Kind.INPUT_VALUE_DEFINITION,
- description: description,
- name: name,
- type: type,
- defaultValue: defaultValue,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * InterfaceTypeDefinition :
- * - Description? interface Name Directives[Const]? FieldsDefinition?
- */
- function parseInterfaceTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'interface');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseFieldsDefinition(lexer);
- return {
- kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * UnionTypeDefinition :
- * - Description? union Name Directives[Const]? UnionMemberTypes?
- */
- function parseUnionTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'union');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var types = parseUnionMemberTypes(lexer);
- return {
- kind: _kinds.Kind.UNION_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- types: types,
- loc: loc(lexer, start)
- };
- }
- /**
- * UnionMemberTypes :
- * - = `|`? NamedType
- * - UnionMemberTypes | NamedType
- */
- function parseUnionMemberTypes(lexer) {
- var types = [];
- if (skip(lexer, _lexer.TokenKind.EQUALS)) {
- // Optional leading pipe
- skip(lexer, _lexer.TokenKind.PIPE);
- do {
- types.push(parseNamedType(lexer));
- } while (skip(lexer, _lexer.TokenKind.PIPE));
- }
- return types;
- }
- /**
- * EnumTypeDefinition :
- * - Description? enum Name Directives[Const]? EnumValuesDefinition?
- */
- function parseEnumTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'enum');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var values = parseEnumValuesDefinition(lexer);
- return {
- kind: _kinds.Kind.ENUM_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- values: values,
- loc: loc(lexer, start)
- };
- }
- /**
- * EnumValuesDefinition : { EnumValueDefinition+ }
- */
- function parseEnumValuesDefinition(lexer) {
- return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseEnumValueDefinition, _lexer.TokenKind.BRACE_R) : [];
- }
- /**
- * EnumValueDefinition : Description? EnumValue Directives[Const]?
- *
- * EnumValue : Name
- */
- function parseEnumValueDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- return {
- kind: _kinds.Kind.ENUM_VALUE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * InputObjectTypeDefinition :
- * - Description? input Name Directives[Const]? InputFieldsDefinition?
- */
- function parseInputObjectTypeDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'input');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseInputFieldsDefinition(lexer);
- return {
- kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION,
- description: description,
- name: name,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * InputFieldsDefinition : { InputValueDefinition+ }
- */
- function parseInputFieldsDefinition(lexer) {
- return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseInputValueDef, _lexer.TokenKind.BRACE_R) : [];
- }
- /**
- * TypeSystemExtension :
- * - SchemaExtension
- * - TypeExtension
- *
- * TypeExtension :
- * - ScalarTypeExtension
- * - ObjectTypeExtension
- * - InterfaceTypeExtension
- * - UnionTypeExtension
- * - EnumTypeExtension
- * - InputObjectTypeDefinition
- */
- function parseTypeSystemExtension(lexer) {
- var keywordToken = lexer.lookahead();
- if (keywordToken.kind === _lexer.TokenKind.NAME) {
- switch (keywordToken.value) {
- case 'schema':
- return parseSchemaExtension(lexer);
- case 'scalar':
- return parseScalarTypeExtension(lexer);
- case 'type':
- return parseObjectTypeExtension(lexer);
- case 'interface':
- return parseInterfaceTypeExtension(lexer);
- case 'union':
- return parseUnionTypeExtension(lexer);
- case 'enum':
- return parseEnumTypeExtension(lexer);
- case 'input':
- return parseInputObjectTypeExtension(lexer);
- }
- }
- throw unexpected(lexer, keywordToken);
- }
- /**
- * SchemaExtension :
- * - extend schema Directives[Const]? { OperationTypeDefinition+ }
- * - extend schema Directives[Const]
- */
- function parseSchemaExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'schema');
- var directives = parseDirectives(lexer, true);
- var operationTypes = peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R) : [];
- if (directives.length === 0 && operationTypes.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.SCHEMA_EXTENSION,
- directives: directives,
- operationTypes: operationTypes,
- loc: loc(lexer, start)
- };
- }
- /**
- * ScalarTypeExtension :
- * - extend scalar Name Directives[Const]
- */
- function parseScalarTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'scalar');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- if (directives.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.SCALAR_TYPE_EXTENSION,
- name: name,
- directives: directives,
- loc: loc(lexer, start)
- };
- }
- /**
- * ObjectTypeExtension :
- * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
- * - extend type Name ImplementsInterfaces? Directives[Const]
- * - extend type Name ImplementsInterfaces
- */
- function parseObjectTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'type');
- var name = parseName(lexer);
- var interfaces = parseImplementsInterfaces(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseFieldsDefinition(lexer);
- if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.OBJECT_TYPE_EXTENSION,
- name: name,
- interfaces: interfaces,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * InterfaceTypeExtension :
- * - extend interface Name Directives[Const]? FieldsDefinition
- * - extend interface Name Directives[Const]
- */
- function parseInterfaceTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'interface');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseFieldsDefinition(lexer);
- if (directives.length === 0 && fields.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION,
- name: name,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * UnionTypeExtension :
- * - extend union Name Directives[Const]? UnionMemberTypes
- * - extend union Name Directives[Const]
- */
- function parseUnionTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'union');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var types = parseUnionMemberTypes(lexer);
- if (directives.length === 0 && types.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.UNION_TYPE_EXTENSION,
- name: name,
- directives: directives,
- types: types,
- loc: loc(lexer, start)
- };
- }
- /**
- * EnumTypeExtension :
- * - extend enum Name Directives[Const]? EnumValuesDefinition
- * - extend enum Name Directives[Const]
- */
- function parseEnumTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'enum');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var values = parseEnumValuesDefinition(lexer);
- if (directives.length === 0 && values.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.ENUM_TYPE_EXTENSION,
- name: name,
- directives: directives,
- values: values,
- loc: loc(lexer, start)
- };
- }
- /**
- * InputObjectTypeExtension :
- * - extend input Name Directives[Const]? InputFieldsDefinition
- * - extend input Name Directives[Const]
- */
- function parseInputObjectTypeExtension(lexer) {
- var start = lexer.token;
- expectKeyword(lexer, 'extend');
- expectKeyword(lexer, 'input');
- var name = parseName(lexer);
- var directives = parseDirectives(lexer, true);
- var fields = parseInputFieldsDefinition(lexer);
- if (directives.length === 0 && fields.length === 0) {
- throw unexpected(lexer);
- }
- return {
- kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION,
- name: name,
- directives: directives,
- fields: fields,
- loc: loc(lexer, start)
- };
- }
- /**
- * DirectiveDefinition :
- * - Description? directive @ Name ArgumentsDefinition? on DirectiveLocations
- */
- function parseDirectiveDefinition(lexer) {
- var start = lexer.token;
- var description = parseDescription(lexer);
- expectKeyword(lexer, 'directive');
- expect(lexer, _lexer.TokenKind.AT);
- var name = parseName(lexer);
- var args = parseArgumentDefs(lexer);
- expectKeyword(lexer, 'on');
- var locations = parseDirectiveLocations(lexer);
- return {
- kind: _kinds.Kind.DIRECTIVE_DEFINITION,
- description: description,
- name: name,
- arguments: args,
- locations: locations,
- loc: loc(lexer, start)
- };
- }
- /**
- * DirectiveLocations :
- * - `|`? DirectiveLocation
- * - DirectiveLocations | DirectiveLocation
- */
- function parseDirectiveLocations(lexer) {
- // Optional leading pipe
- skip(lexer, _lexer.TokenKind.PIPE);
- var locations = [];
- do {
- locations.push(parseDirectiveLocation(lexer));
- } while (skip(lexer, _lexer.TokenKind.PIPE));
- return locations;
- }
- /*
- * DirectiveLocation :
- * - ExecutableDirectiveLocation
- * - TypeSystemDirectiveLocation
- *
- * ExecutableDirectiveLocation : one of
- * `QUERY`
- * `MUTATION`
- * `SUBSCRIPTION`
- * `FIELD`
- * `FRAGMENT_DEFINITION`
- * `FRAGMENT_SPREAD`
- * `INLINE_FRAGMENT`
- *
- * TypeSystemDirectiveLocation : one of
- * `SCHEMA`
- * `SCALAR`
- * `OBJECT`
- * `FIELD_DEFINITION`
- * `ARGUMENT_DEFINITION`
- * `INTERFACE`
- * `UNION`
- * `ENUM`
- * `ENUM_VALUE`
- * `INPUT_OBJECT`
- * `INPUT_FIELD_DEFINITION`
- */
- function parseDirectiveLocation(lexer) {
- var start = lexer.token;
- var name = parseName(lexer);
- if (_directiveLocation.DirectiveLocation.hasOwnProperty(name.value)) {
- return name;
- }
- throw unexpected(lexer, start);
- } // Core parsing utility functions
- /**
- * Returns a location object, used to identify the place in
- * the source that created a given parsed object.
- */
- function loc(lexer, startToken) {
- if (!lexer.options.noLocation) {
- return new Loc(startToken, lexer.lastToken, lexer.source);
- }
- }
- function Loc(startToken, endToken, source) {
- this.start = startToken.start;
- this.end = endToken.end;
- this.startToken = startToken;
- this.endToken = endToken;
- this.source = source;
- } // Print a simplified form when appearing in JSON/util.inspect.
- (0, _defineToJSON.default)(Loc, function () {
- return {
- start: this.start,
- end: this.end
- };
- });
- /**
- * Determines if the next token is of a given kind
- */
- function peek(lexer, kind) {
- return lexer.token.kind === kind;
- }
- /**
- * If the next token is of the given kind, return true after advancing
- * the lexer. Otherwise, do not change the parser state and return false.
- */
- function skip(lexer, kind) {
- if (lexer.token.kind === kind) {
- lexer.advance();
- return true;
- }
- return false;
- }
- /**
- * If the next token is of the given kind, return that token after advancing
- * the lexer. Otherwise, do not change the parser state and throw an error.
- */
- function expect(lexer, kind) {
- var token = lexer.token;
- if (token.kind === kind) {
- lexer.advance();
- return token;
- }
- throw (0, _error.syntaxError)(lexer.source, token.start, "Expected ".concat(kind, ", found ").concat((0, _lexer.getTokenDesc)(token)));
- }
- /**
- * If the next token is a keyword with the given value, return true after advancing
- * the lexer. Otherwise, do not change the parser state and return false.
- */
- function skipKeyword(lexer, value) {
- var token = lexer.token;
- if (token.kind === _lexer.TokenKind.NAME && token.value === value) {
- lexer.advance();
- return true;
- }
- return false;
- }
- /**
- * If the next token is a keyword with the given value, return that token after
- * advancing the lexer. Otherwise, do not change the parser state and throw
- * an error.
- */
- function expectKeyword(lexer, value) {
- if (!skipKeyword(lexer, value)) {
- throw (0, _error.syntaxError)(lexer.source, lexer.token.start, "Expected \"".concat(value, "\", found ").concat((0, _lexer.getTokenDesc)(lexer.token)));
- }
- }
- /**
- * Helper function for creating an error when an unexpected lexed token
- * is encountered.
- */
- function unexpected(lexer, atToken) {
- var token = atToken || lexer.token;
- return (0, _error.syntaxError)(lexer.source, token.start, "Unexpected ".concat((0, _lexer.getTokenDesc)(token)));
- }
- /**
- * Returns a possibly empty list of parse nodes, determined by
- * the parseFn. This list begins with a lex token of openKind
- * and ends with a lex token of closeKind. Advances the parser
- * to the next lex token after the closing token.
- */
- function any(lexer, openKind, parseFn, closeKind) {
- expect(lexer, openKind);
- var nodes = [];
- while (!skip(lexer, closeKind)) {
- nodes.push(parseFn(lexer));
- }
- return nodes;
- }
- /**
- * Returns a non-empty list of parse nodes, determined by
- * the parseFn. This list begins with a lex token of openKind
- * and ends with a lex token of closeKind. Advances the parser
- * to the next lex token after the closing token.
- */
- function many(lexer, openKind, parseFn, closeKind) {
- expect(lexer, openKind);
- var nodes = [parseFn(lexer)];
- while (!skip(lexer, closeKind)) {
- nodes.push(parseFn(lexer));
- }
- return nodes;
- }
- },{"../error":277,"../jsutils/defineToJSON":286,"../jsutils/inspect":288,"./directiveLocation":305,"./kinds":307,"./lexer":308,"./source":313}],311:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isDefinitionNode = isDefinitionNode;
- exports.isExecutableDefinitionNode = isExecutableDefinitionNode;
- exports.isSelectionNode = isSelectionNode;
- exports.isValueNode = isValueNode;
- exports.isTypeNode = isTypeNode;
- exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode;
- exports.isTypeDefinitionNode = isTypeDefinitionNode;
- exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode;
- exports.isTypeExtensionNode = isTypeExtensionNode;
- var _kinds = require("./kinds");
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function isDefinitionNode(node) {
- return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node);
- }
- function isExecutableDefinitionNode(node) {
- return node.kind === _kinds.Kind.OPERATION_DEFINITION || node.kind === _kinds.Kind.FRAGMENT_DEFINITION;
- }
- function isSelectionNode(node) {
- return node.kind === _kinds.Kind.FIELD || node.kind === _kinds.Kind.FRAGMENT_SPREAD || node.kind === _kinds.Kind.INLINE_FRAGMENT;
- }
- function isValueNode(node) {
- return node.kind === _kinds.Kind.VARIABLE || node.kind === _kinds.Kind.INT || node.kind === _kinds.Kind.FLOAT || node.kind === _kinds.Kind.STRING || node.kind === _kinds.Kind.BOOLEAN || node.kind === _kinds.Kind.NULL || node.kind === _kinds.Kind.ENUM || node.kind === _kinds.Kind.LIST || node.kind === _kinds.Kind.OBJECT;
- }
- function isTypeNode(node) {
- return node.kind === _kinds.Kind.NAMED_TYPE || node.kind === _kinds.Kind.LIST_TYPE || node.kind === _kinds.Kind.NON_NULL_TYPE;
- }
- function isTypeSystemDefinitionNode(node) {
- return node.kind === _kinds.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === _kinds.Kind.DIRECTIVE_DEFINITION;
- }
- function isTypeDefinitionNode(node) {
- return node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION;
- }
- function isTypeSystemExtensionNode(node) {
- return node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node);
- }
- function isTypeExtensionNode(node) {
- return node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION;
- }
- },{"./kinds":307}],312:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.print = print;
- var _visitor = require("./visitor");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Converts an AST into a string, using one set of reasonable
- * formatting rules.
- */
- function print(ast) {
- return (0, _visitor.visit)(ast, {
- leave: printDocASTReducer
- });
- }
- var printDocASTReducer = {
- Name: function Name(node) {
- return node.value;
- },
- Variable: function Variable(node) {
- return '$' + node.name;
- },
- // Document
- Document: function Document(node) {
- return join(node.definitions, '\n\n') + '\n';
- },
- OperationDefinition: function OperationDefinition(node) {
- var op = node.operation;
- var name = node.name;
- var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')');
- var directives = join(node.directives, ' ');
- var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use
- // the query short form.
- return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' ');
- },
- VariableDefinition: function VariableDefinition(_ref) {
- var variable = _ref.variable,
- type = _ref.type,
- defaultValue = _ref.defaultValue,
- directives = _ref.directives;
- return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' '));
- },
- SelectionSet: function SelectionSet(_ref2) {
- var selections = _ref2.selections;
- return block(selections);
- },
- Field: function Field(_ref3) {
- var alias = _ref3.alias,
- name = _ref3.name,
- args = _ref3.arguments,
- directives = _ref3.directives,
- selectionSet = _ref3.selectionSet;
- return join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' ');
- },
- Argument: function Argument(_ref4) {
- var name = _ref4.name,
- value = _ref4.value;
- return name + ': ' + value;
- },
- // Fragments
- FragmentSpread: function FragmentSpread(_ref5) {
- var name = _ref5.name,
- directives = _ref5.directives;
- return '...' + name + wrap(' ', join(directives, ' '));
- },
- InlineFragment: function InlineFragment(_ref6) {
- var typeCondition = _ref6.typeCondition,
- directives = _ref6.directives,
- selectionSet = _ref6.selectionSet;
- return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ');
- },
- FragmentDefinition: function FragmentDefinition(_ref7) {
- var name = _ref7.name,
- typeCondition = _ref7.typeCondition,
- variableDefinitions = _ref7.variableDefinitions,
- directives = _ref7.directives,
- selectionSet = _ref7.selectionSet;
- return (// Note: fragment variable definitions are experimental and may be changed
- // or removed in the future.
- "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet
- );
- },
- // Value
- IntValue: function IntValue(_ref8) {
- var value = _ref8.value;
- return value;
- },
- FloatValue: function FloatValue(_ref9) {
- var value = _ref9.value;
- return value;
- },
- StringValue: function StringValue(_ref10, key) {
- var value = _ref10.value,
- isBlockString = _ref10.block;
- return isBlockString ? printBlockString(value, key === 'description') : JSON.stringify(value);
- },
- BooleanValue: function BooleanValue(_ref11) {
- var value = _ref11.value;
- return value ? 'true' : 'false';
- },
- NullValue: function NullValue() {
- return 'null';
- },
- EnumValue: function EnumValue(_ref12) {
- var value = _ref12.value;
- return value;
- },
- ListValue: function ListValue(_ref13) {
- var values = _ref13.values;
- return '[' + join(values, ', ') + ']';
- },
- ObjectValue: function ObjectValue(_ref14) {
- var fields = _ref14.fields;
- return '{' + join(fields, ', ') + '}';
- },
- ObjectField: function ObjectField(_ref15) {
- var name = _ref15.name,
- value = _ref15.value;
- return name + ': ' + value;
- },
- // Directive
- Directive: function Directive(_ref16) {
- var name = _ref16.name,
- args = _ref16.arguments;
- return '@' + name + wrap('(', join(args, ', '), ')');
- },
- // Type
- NamedType: function NamedType(_ref17) {
- var name = _ref17.name;
- return name;
- },
- ListType: function ListType(_ref18) {
- var type = _ref18.type;
- return '[' + type + ']';
- },
- NonNullType: function NonNullType(_ref19) {
- var type = _ref19.type;
- return type + '!';
- },
- // Type System Definitions
- SchemaDefinition: function SchemaDefinition(_ref20) {
- var directives = _ref20.directives,
- operationTypes = _ref20.operationTypes;
- return join(['schema', join(directives, ' '), block(operationTypes)], ' ');
- },
- OperationTypeDefinition: function OperationTypeDefinition(_ref21) {
- var operation = _ref21.operation,
- type = _ref21.type;
- return operation + ': ' + type;
- },
- ScalarTypeDefinition: addDescription(function (_ref22) {
- var name = _ref22.name,
- directives = _ref22.directives;
- return join(['scalar', name, join(directives, ' ')], ' ');
- }),
- ObjectTypeDefinition: addDescription(function (_ref23) {
- var name = _ref23.name,
- interfaces = _ref23.interfaces,
- directives = _ref23.directives,
- fields = _ref23.fields;
- return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
- }),
- FieldDefinition: addDescription(function (_ref24) {
- var name = _ref24.name,
- args = _ref24.arguments,
- type = _ref24.type,
- directives = _ref24.directives;
- return name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + type + wrap(' ', join(directives, ' '));
- }),
- InputValueDefinition: addDescription(function (_ref25) {
- var name = _ref25.name,
- type = _ref25.type,
- defaultValue = _ref25.defaultValue,
- directives = _ref25.directives;
- return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' ');
- }),
- InterfaceTypeDefinition: addDescription(function (_ref26) {
- var name = _ref26.name,
- directives = _ref26.directives,
- fields = _ref26.fields;
- return join(['interface', name, join(directives, ' '), block(fields)], ' ');
- }),
- UnionTypeDefinition: addDescription(function (_ref27) {
- var name = _ref27.name,
- directives = _ref27.directives,
- types = _ref27.types;
- return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
- }),
- EnumTypeDefinition: addDescription(function (_ref28) {
- var name = _ref28.name,
- directives = _ref28.directives,
- values = _ref28.values;
- return join(['enum', name, join(directives, ' '), block(values)], ' ');
- }),
- EnumValueDefinition: addDescription(function (_ref29) {
- var name = _ref29.name,
- directives = _ref29.directives;
- return join([name, join(directives, ' ')], ' ');
- }),
- InputObjectTypeDefinition: addDescription(function (_ref30) {
- var name = _ref30.name,
- directives = _ref30.directives,
- fields = _ref30.fields;
- return join(['input', name, join(directives, ' '), block(fields)], ' ');
- }),
- DirectiveDefinition: addDescription(function (_ref31) {
- var name = _ref31.name,
- args = _ref31.arguments,
- locations = _ref31.locations;
- return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ' on ' + join(locations, ' | ');
- }),
- SchemaExtension: function SchemaExtension(_ref32) {
- var directives = _ref32.directives,
- operationTypes = _ref32.operationTypes;
- return join(['extend schema', join(directives, ' '), block(operationTypes)], ' ');
- },
- ScalarTypeExtension: function ScalarTypeExtension(_ref33) {
- var name = _ref33.name,
- directives = _ref33.directives;
- return join(['extend scalar', name, join(directives, ' ')], ' ');
- },
- ObjectTypeExtension: function ObjectTypeExtension(_ref34) {
- var name = _ref34.name,
- interfaces = _ref34.interfaces,
- directives = _ref34.directives,
- fields = _ref34.fields;
- return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' ');
- },
- InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) {
- var name = _ref35.name,
- directives = _ref35.directives,
- fields = _ref35.fields;
- return join(['extend interface', name, join(directives, ' '), block(fields)], ' ');
- },
- UnionTypeExtension: function UnionTypeExtension(_ref36) {
- var name = _ref36.name,
- directives = _ref36.directives,
- types = _ref36.types;
- return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' ');
- },
- EnumTypeExtension: function EnumTypeExtension(_ref37) {
- var name = _ref37.name,
- directives = _ref37.directives,
- values = _ref37.values;
- return join(['extend enum', name, join(directives, ' '), block(values)], ' ');
- },
- InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) {
- var name = _ref38.name,
- directives = _ref38.directives,
- fields = _ref38.fields;
- return join(['extend input', name, join(directives, ' '), block(fields)], ' ');
- }
- };
- function addDescription(cb) {
- return function (node) {
- return join([node.description, cb(node)], '\n');
- };
- }
- /**
- * Given maybeArray, print an empty string if it is null or empty, otherwise
- * print all items together separated by separator if provided
- */
- function join(maybeArray, separator) {
- return maybeArray ? maybeArray.filter(function (x) {
- return x;
- }).join(separator || '') : '';
- }
- /**
- * Given array, print each item on its own line, wrapped in an
- * indented "{ }" block.
- */
- function block(array) {
- return array && array.length !== 0 ? '{\n' + indent(join(array, '\n')) + '\n}' : '';
- }
- /**
- * If maybeString is not null or empty, then wrap with start and end, otherwise
- * print an empty string.
- */
- function wrap(start, maybeString, end) {
- return maybeString ? start + maybeString + (end || '') : '';
- }
- function indent(maybeString) {
- return maybeString && ' ' + maybeString.replace(/\n/g, '\n ');
- }
- function isMultiline(string) {
- return string.indexOf('\n') !== -1;
- }
- function hasMultilineItems(maybeArray) {
- return maybeArray && maybeArray.some(isMultiline);
- }
- /**
- * Print a block string in the indented block form by adding a leading and
- * trailing blank line. However, if a block string starts with whitespace and is
- * a single-line, adding a leading blank line would strip that whitespace.
- */
- function printBlockString(value, isDescription) {
- var escaped = value.replace(/"""/g, '\\"""');
- return isMultiline(value) || value[0] !== ' ' && value[0] !== '\t' ? "\"\"\"\n".concat(isDescription ? escaped : indent(escaped), "\n\"\"\"") : "\"\"\"".concat(escaped.replace(/"$/, '"\n'), "\"\"\"");
- }
- },{"./visitor":314}],313:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.Source = void 0;
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * A representation of source input to GraphQL.
- * `name` and `locationOffset` are optional. They are useful for clients who
- * store GraphQL documents in source files; for example, if the GraphQL input
- * starts at line 40 in a file named Foo.graphql, it might be useful for name to
- * be "Foo.graphql" and location to be `{ line: 40, column: 0 }`.
- * line and column in locationOffset are 1-indexed
- */
- var Source = function Source(body, name, locationOffset) {
- this.body = body;
- this.name = name || 'GraphQL request';
- this.locationOffset = locationOffset || {
- line: 1,
- column: 1
- };
- !(this.locationOffset.line > 0) ? (0, _invariant.default)(0, 'line in locationOffset is 1-indexed and must be positive') : void 0;
- !(this.locationOffset.column > 0) ? (0, _invariant.default)(0, 'column in locationOffset is 1-indexed and must be positive') : void 0;
- }; // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.Source = Source;
- (0, _defineToStringTag.default)(Source);
- },{"../jsutils/defineToStringTag":287,"../jsutils/invariant":290}],314:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.visit = visit;
- exports.visitInParallel = visitInParallel;
- exports.visitWithTypeInfo = visitWithTypeInfo;
- exports.getVisitFn = getVisitFn;
- exports.BREAK = exports.QueryDocumentKeys = void 0;
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var QueryDocumentKeys = {
- Name: [],
- Document: ['definitions'],
- OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
- VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],
- Variable: ['name'],
- SelectionSet: ['selections'],
- Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
- Argument: ['name', 'value'],
- FragmentSpread: ['name', 'directives'],
- InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
- FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed
- // or removed in the future.
- 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'],
- IntValue: [],
- FloatValue: [],
- StringValue: [],
- BooleanValue: [],
- NullValue: [],
- EnumValue: [],
- ListValue: ['values'],
- ObjectValue: ['fields'],
- ObjectField: ['name', 'value'],
- Directive: ['name', 'arguments'],
- NamedType: ['name'],
- ListType: ['type'],
- NonNullType: ['type'],
- SchemaDefinition: ['directives', 'operationTypes'],
- OperationTypeDefinition: ['type'],
- ScalarTypeDefinition: ['description', 'name', 'directives'],
- ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
- FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],
- InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'],
- InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'],
- UnionTypeDefinition: ['description', 'name', 'directives', 'types'],
- EnumTypeDefinition: ['description', 'name', 'directives', 'values'],
- EnumValueDefinition: ['description', 'name', 'directives'],
- InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],
- DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],
- SchemaExtension: ['directives', 'operationTypes'],
- ScalarTypeExtension: ['name', 'directives'],
- ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
- InterfaceTypeExtension: ['name', 'directives', 'fields'],
- UnionTypeExtension: ['name', 'directives', 'types'],
- EnumTypeExtension: ['name', 'directives', 'values'],
- InputObjectTypeExtension: ['name', 'directives', 'fields']
- };
- exports.QueryDocumentKeys = QueryDocumentKeys;
- var BREAK = {};
- /**
- * visit() will walk through an AST using a depth first traversal, calling
- * the visitor's enter function at each node in the traversal, and calling the
- * leave function after visiting that node and all of its child nodes.
- *
- * By returning different values from the enter and leave functions, the
- * behavior of the visitor can be altered, including skipping over a sub-tree of
- * the AST (by returning false), editing the AST by returning a value or null
- * to remove the value, or to stop the whole traversal by returning BREAK.
- *
- * When using visit() to edit an AST, the original AST will not be modified, and
- * a new version of the AST with the changes applied will be returned from the
- * visit function.
- *
- * const editedAST = visit(ast, {
- * enter(node, key, parent, path, ancestors) {
- * // @return
- * // undefined: no action
- * // false: skip visiting this node
- * // visitor.BREAK: stop visiting altogether
- * // null: delete this node
- * // any value: replace this node with the returned value
- * },
- * leave(node, key, parent, path, ancestors) {
- * // @return
- * // undefined: no action
- * // false: no action
- * // visitor.BREAK: stop visiting altogether
- * // null: delete this node
- * // any value: replace this node with the returned value
- * }
- * });
- *
- * Alternatively to providing enter() and leave() functions, a visitor can
- * instead provide functions named the same as the kinds of AST nodes, or
- * enter/leave visitors at a named key, leading to four permutations of
- * visitor API:
- *
- * 1) Named visitors triggered when entering a node a specific kind.
- *
- * visit(ast, {
- * Kind(node) {
- * // enter the "Kind" node
- * }
- * })
- *
- * 2) Named visitors that trigger upon entering and leaving a node of
- * a specific kind.
- *
- * visit(ast, {
- * Kind: {
- * enter(node) {
- * // enter the "Kind" node
- * }
- * leave(node) {
- * // leave the "Kind" node
- * }
- * }
- * })
- *
- * 3) Generic visitors that trigger upon entering and leaving any node.
- *
- * visit(ast, {
- * enter(node) {
- * // enter any node
- * },
- * leave(node) {
- * // leave any node
- * }
- * })
- *
- * 4) Parallel visitors for entering and leaving nodes of a specific kind.
- *
- * visit(ast, {
- * enter: {
- * Kind(node) {
- * // enter the "Kind" node
- * }
- * },
- * leave: {
- * Kind(node) {
- * // leave the "Kind" node
- * }
- * }
- * })
- */
- exports.BREAK = BREAK;
- function visit(root, visitor) {
- var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys;
- /* eslint-disable no-undef-init */
- var stack = undefined;
- var inArray = Array.isArray(root);
- var keys = [root];
- var index = -1;
- var edits = [];
- var node = undefined;
- var key = undefined;
- var parent = undefined;
- var path = [];
- var ancestors = [];
- var newRoot = root;
- /* eslint-enable no-undef-init */
- do {
- index++;
- var isLeaving = index === keys.length;
- var isEdited = isLeaving && edits.length !== 0;
- if (isLeaving) {
- key = ancestors.length === 0 ? undefined : path[path.length - 1];
- node = parent;
- parent = ancestors.pop();
- if (isEdited) {
- if (inArray) {
- node = node.slice();
- } else {
- var clone = {};
- var _arr = Object.keys(node);
- for (var _i = 0; _i < _arr.length; _i++) {
- var k = _arr[_i];
- clone[k] = node[k];
- }
- node = clone;
- }
- var editOffset = 0;
- for (var ii = 0; ii < edits.length; ii++) {
- var editKey = edits[ii][0];
- var editValue = edits[ii][1];
- if (inArray) {
- editKey -= editOffset;
- }
- if (inArray && editValue === null) {
- node.splice(editKey, 1);
- editOffset++;
- } else {
- node[editKey] = editValue;
- }
- }
- }
- index = stack.index;
- keys = stack.keys;
- edits = stack.edits;
- inArray = stack.inArray;
- stack = stack.prev;
- } else {
- key = parent ? inArray ? index : keys[index] : undefined;
- node = parent ? parent[key] : newRoot;
- if (node === null || node === undefined) {
- continue;
- }
- if (parent) {
- path.push(key);
- }
- }
- var result = void 0;
- if (!Array.isArray(node)) {
- if (!isNode(node)) {
- throw new Error('Invalid AST Node: ' + (0, _inspect.default)(node));
- }
- var visitFn = getVisitFn(visitor, node.kind, isLeaving);
- if (visitFn) {
- result = visitFn.call(visitor, node, key, parent, path, ancestors);
- if (result === BREAK) {
- break;
- }
- if (result === false) {
- if (!isLeaving) {
- path.pop();
- continue;
- }
- } else if (result !== undefined) {
- edits.push([key, result]);
- if (!isLeaving) {
- if (isNode(result)) {
- node = result;
- } else {
- path.pop();
- continue;
- }
- }
- }
- }
- }
- if (result === undefined && isEdited) {
- edits.push([key, node]);
- }
- if (isLeaving) {
- path.pop();
- } else {
- stack = {
- inArray: inArray,
- index: index,
- keys: keys,
- edits: edits,
- prev: stack
- };
- inArray = Array.isArray(node);
- keys = inArray ? node : visitorKeys[node.kind] || [];
- index = -1;
- edits = [];
- if (parent) {
- ancestors.push(parent);
- }
- parent = node;
- }
- } while (stack !== undefined);
- if (edits.length !== 0) {
- newRoot = edits[edits.length - 1][1];
- }
- return newRoot;
- }
- function isNode(maybeNode) {
- return Boolean(maybeNode && typeof maybeNode.kind === 'string');
- }
- /**
- * Creates a new visitor instance which delegates to many visitors to run in
- * parallel. Each visitor will be visited for each node before moving on.
- *
- * If a prior visitor edits a node, no following visitors will see that node.
- */
- function visitInParallel(visitors) {
- var skipping = new Array(visitors.length);
- return {
- enter: function enter(node) {
- for (var i = 0; i < visitors.length; i++) {
- if (!skipping[i]) {
- var fn = getVisitFn(visitors[i], node.kind,
- /* isLeaving */
- false);
- if (fn) {
- var result = fn.apply(visitors[i], arguments);
- if (result === false) {
- skipping[i] = node;
- } else if (result === BREAK) {
- skipping[i] = BREAK;
- } else if (result !== undefined) {
- return result;
- }
- }
- }
- }
- },
- leave: function leave(node) {
- for (var i = 0; i < visitors.length; i++) {
- if (!skipping[i]) {
- var fn = getVisitFn(visitors[i], node.kind,
- /* isLeaving */
- true);
- if (fn) {
- var result = fn.apply(visitors[i], arguments);
- if (result === BREAK) {
- skipping[i] = BREAK;
- } else if (result !== undefined && result !== false) {
- return result;
- }
- }
- } else if (skipping[i] === node) {
- skipping[i] = null;
- }
- }
- }
- };
- }
- /**
- * Creates a new visitor instance which maintains a provided TypeInfo instance
- * along with visiting visitor.
- */
- function visitWithTypeInfo(typeInfo, visitor) {
- return {
- enter: function enter(node) {
- typeInfo.enter(node);
- var fn = getVisitFn(visitor, node.kind,
- /* isLeaving */
- false);
- if (fn) {
- var result = fn.apply(visitor, arguments);
- if (result !== undefined) {
- typeInfo.leave(node);
- if (isNode(result)) {
- typeInfo.enter(result);
- }
- }
- return result;
- }
- },
- leave: function leave(node) {
- var fn = getVisitFn(visitor, node.kind,
- /* isLeaving */
- true);
- var result;
- if (fn) {
- result = fn.apply(visitor, arguments);
- }
- typeInfo.leave(node);
- return result;
- }
- };
- }
- /**
- * Given a visitor instance, if it is leaving or not, and a node kind, return
- * the function the visitor runtime should call.
- */
- function getVisitFn(visitor, kind, isLeaving) {
- var kindVisitor = visitor[kind];
- if (kindVisitor) {
- if (!isLeaving && typeof kindVisitor === 'function') {
- // { Kind() {} }
- return kindVisitor;
- }
- var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
- if (typeof kindSpecificVisitor === 'function') {
- // { Kind: { enter() {}, leave() {} } }
- return kindSpecificVisitor;
- }
- } else {
- var specificVisitor = isLeaving ? visitor.leave : visitor.enter;
- if (specificVisitor) {
- if (typeof specificVisitor === 'function') {
- // { enter() {}, leave() {} }
- return specificVisitor;
- }
- var specificKindVisitor = specificVisitor[kind];
- if (typeof specificKindVisitor === 'function') {
- // { enter: { Kind() {} }, leave: { Kind() {} } }
- return specificKindVisitor;
- }
- }
- }
- }
- },{"../jsutils/inspect":288}],315:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe
- var find = Array.prototype.find ? function (list, predicate) {
- return Array.prototype.find.call(list, predicate);
- } : function (list, predicate) {
- for (var i = 0; i < list.length; i++) {
- var value = list[i];
- if (predicate(value)) {
- return value;
- }
- }
- };
- var _default = find;
- exports.default = _default;
- },{}],316:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
- var isFinite = Number.isFinite || function (value) {
- return typeof value === 'number' && isFinite(value);
- };
- var _default = isFinite;
- exports.default = _default;
- },{}],317:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441
- var isInteger = Number.isInteger || function (value) {
- return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
- };
- var _default = isInteger;
- exports.default = _default;
- },{}],318:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) 2019-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe workaround for: https://github.com/facebook/flow/issues/5838
- var objectEntries = Object.entries || function (obj) {
- return Object.keys(obj).map(function (key) {
- return [key, obj[key]];
- });
- };
- var _default = objectEntries;
- exports.default = _default;
- },{}],319:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /* eslint-disable no-redeclare */
- // $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221
- var objectValues = Object.values || function (obj) {
- return Object.keys(obj).map(function (key) {
- return obj[key];
- });
- };
- var _default = objectValues;
- exports.default = _default;
- },{}],320:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "subscribe", {
- enumerable: true,
- get: function get() {
- return _subscribe.subscribe;
- }
- });
- Object.defineProperty(exports, "createSourceEventStream", {
- enumerable: true,
- get: function get() {
- return _subscribe.createSourceEventStream;
- }
- });
- var _subscribe = require("./subscribe");
- },{"./subscribe":322}],321:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = mapAsyncIterator;
- var _iterall = require("iterall");
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * Given an AsyncIterable and a callback function, return an AsyncIterator
- * which produces values mapped via calling the callback function.
- */
- function mapAsyncIterator(iterable, callback, rejectCallback) {
- var iterator = (0, _iterall.getAsyncIterator)(iterable);
- var $return;
- var abruptClose; // $FlowFixMe(>=0.68.0)
- if (typeof iterator.return === 'function') {
- $return = iterator.return;
- abruptClose = function abruptClose(error) {
- var rethrow = function rethrow() {
- return Promise.reject(error);
- };
- return $return.call(iterator).then(rethrow, rethrow);
- };
- }
- function mapResult(result) {
- return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);
- }
- var mapReject;
- if (rejectCallback) {
- // Capture rejectCallback to ensure it cannot be null.
- var reject = rejectCallback;
- mapReject = function mapReject(error) {
- return asyncMapValue(error, reject).then(iteratorResult, abruptClose);
- };
- }
- /* TODO: Flow doesn't support symbols as keys:
- https://github.com/facebook/flow/issues/3258 */
- return _defineProperty({
- next: function next() {
- return iterator.next().then(mapResult, mapReject);
- },
- return: function _return() {
- return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({
- value: undefined,
- done: true
- });
- },
- throw: function _throw(error) {
- // $FlowFixMe(>=0.68.0)
- if (typeof iterator.throw === 'function') {
- return iterator.throw(error).then(mapResult, mapReject);
- }
- return Promise.reject(error).catch(abruptClose);
- }
- }, _iterall.$$asyncIterator, function () {
- return this;
- });
- }
- function asyncMapValue(value, callback) {
- return new Promise(function (resolve) {
- return resolve(callback(value));
- });
- }
- function iteratorResult(value) {
- return {
- value: value,
- done: false
- };
- }
- },{"iterall":137}],322:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.subscribe = subscribe;
- exports.createSourceEventStream = createSourceEventStream;
- var _iterall = require("iterall");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _GraphQLError = require("../error/GraphQLError");
- var _locatedError = require("../error/locatedError");
- var _execute = require("../execution/execute");
- var _mapAsyncIterator = _interopRequireDefault(require("./mapAsyncIterator"));
- var _getOperationRootType = require("../utilities/getOperationRootType");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2017-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) {
- /* eslint-enable no-redeclare */
- // Extract arguments from object args if provided.
- return arguments.length === 1 ? subscribeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, argsOrSchema.subscribeFieldResolver) : subscribeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver);
- }
- /**
- * This function checks if the error is a GraphQLError. If it is, report it as
- * an ExecutionResult, containing only errors and no data. Otherwise treat the
- * error as a system-class error and re-throw it.
- */
- function reportGraphQLError(error) {
- if (error instanceof _GraphQLError.GraphQLError) {
- return {
- errors: [error]
- };
- }
- throw error;
- }
- function subscribeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) {
- var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal
- // GraphQL `execute` function, with `payload` as the rootValue.
- // This implements the "MapSourceToResponseEvent" algorithm described in
- // the GraphQL specification. The `execute` function provides the
- // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
- // "ExecuteQuery" algorithm, for which `execute` is also used.
- var mapSourceToResponse = function mapSourceToResponse(payload) {
- return (0, _execute.execute)(schema, document, payload, contextValue, variableValues, operationName, fieldResolver);
- }; // Resolve the Source Stream, then map every source value to a
- // ExecutionResult value as described above.
- return sourcePromise.then(function (resultOrStream) {
- return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used.
- (0, _iterall.isAsyncIterable)(resultOrStream) ? (0, _mapAsyncIterator.default)(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream
- );
- }, reportGraphQLError);
- }
- /**
- * Implements the "CreateSourceEventStream" algorithm described in the
- * GraphQL specification, resolving the subscription source event stream.
- *
- * Returns a Promise<AsyncIterable>.
- *
- * If the client-provided invalid arguments, the source stream could not be
- * created, or the resolver did not return an AsyncIterable, this function will
- * will throw an error, which should be caught and handled by the caller.
- *
- * A Source Event Stream represents a sequence of events, each of which triggers
- * a GraphQL execution for that event.
- *
- * This may be useful when hosting the stateful subscription service in a
- * different process or machine than the stateless GraphQL execution engine,
- * or otherwise separating these two steps. For more on this, see the
- * "Supporting Subscriptions at Scale" information in the GraphQL specification.
- */
- function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {
- // If arguments are missing or incorrectly typed, this is an internal
- // developer mistake which should throw an early error.
- (0, _execute.assertValidExecutionArguments)(schema, document, variableValues);
- try {
- // If a valid context cannot be created due to incorrect arguments,
- // this will throw an error.
- var exeContext = (0, _execute.buildExecutionContext)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed.
- if (Array.isArray(exeContext)) {
- return Promise.resolve({
- errors: exeContext
- });
- }
- var type = (0, _getOperationRootType.getOperationRootType)(schema, exeContext.operation);
- var fields = (0, _execute.collectFields)(exeContext, type, exeContext.operation.selectionSet, Object.create(null), Object.create(null));
- var responseNames = Object.keys(fields);
- var responseName = responseNames[0];
- var fieldNodes = fields[responseName];
- var fieldNode = fieldNodes[0];
- var fieldName = fieldNode.name.value;
- var fieldDef = (0, _execute.getFieldDef)(schema, type, fieldName);
- if (!fieldDef) {
- throw new _GraphQLError.GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes);
- } // Call the `subscribe()` resolver or the default resolver to produce an
- // AsyncIterable yielding raw payloads.
- var resolveFn = fieldDef.subscribe || exeContext.fieldResolver;
- var path = (0, _execute.addPath)(undefined, responseName);
- var info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, type, path); // resolveFieldValueOrError implements the "ResolveFieldEventStream"
- // algorithm from GraphQL specification. It differs from
- // "ResolveFieldValue" due to providing a different `resolveFn`.
- var result = (0, _execute.resolveFieldValueOrError)(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); // Coerce to Promise for easier error handling and consistent return type.
- return Promise.resolve(result).then(function (eventStream) {
- // If eventStream is an Error, rethrow a located error.
- if (eventStream instanceof Error) {
- throw (0, _locatedError.locatedError)(eventStream, fieldNodes, (0, _execute.responsePathAsArray)(path));
- } // Assert field returned an event stream, otherwise yield an error.
- if ((0, _iterall.isAsyncIterable)(eventStream)) {
- // Note: isAsyncIterable above ensures this will be correct.
- return eventStream;
- }
- throw new Error('Subscription field must return Async Iterable. Received: ' + (0, _inspect.default)(eventStream));
- });
- } catch (error) {
- return Promise.reject(error);
- }
- }
- },{"../error/GraphQLError":275,"../error/locatedError":278,"../execution/execute":281,"../jsutils/inspect":288,"../utilities/getOperationRootType":341,"./mapAsyncIterator":321,"iterall":137}],323:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isType = isType;
- exports.assertType = assertType;
- exports.isScalarType = isScalarType;
- exports.assertScalarType = assertScalarType;
- exports.isObjectType = isObjectType;
- exports.assertObjectType = assertObjectType;
- exports.isInterfaceType = isInterfaceType;
- exports.assertInterfaceType = assertInterfaceType;
- exports.isUnionType = isUnionType;
- exports.assertUnionType = assertUnionType;
- exports.isEnumType = isEnumType;
- exports.assertEnumType = assertEnumType;
- exports.isInputObjectType = isInputObjectType;
- exports.assertInputObjectType = assertInputObjectType;
- exports.isListType = isListType;
- exports.assertListType = assertListType;
- exports.isNonNullType = isNonNullType;
- exports.assertNonNullType = assertNonNullType;
- exports.isInputType = isInputType;
- exports.assertInputType = assertInputType;
- exports.isOutputType = isOutputType;
- exports.assertOutputType = assertOutputType;
- exports.isLeafType = isLeafType;
- exports.assertLeafType = assertLeafType;
- exports.isCompositeType = isCompositeType;
- exports.assertCompositeType = assertCompositeType;
- exports.isAbstractType = isAbstractType;
- exports.assertAbstractType = assertAbstractType;
- exports.GraphQLList = GraphQLList;
- exports.GraphQLNonNull = GraphQLNonNull;
- exports.isWrappingType = isWrappingType;
- exports.assertWrappingType = assertWrappingType;
- exports.isNullableType = isNullableType;
- exports.assertNullableType = assertNullableType;
- exports.getNullableType = getNullableType;
- exports.isNamedType = isNamedType;
- exports.assertNamedType = assertNamedType;
- exports.getNamedType = getNamedType;
- exports.isRequiredArgument = isRequiredArgument;
- exports.isRequiredInputField = isRequiredInputField;
- exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = void 0;
- var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries"));
- var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON"));
- var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag"));
- var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- var _mapValue = _interopRequireDefault(require("../jsutils/mapValue"));
- var _kinds = require("../language/kinds");
- var _valueFromASTUntyped = require("../utilities/valueFromASTUntyped");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function isType(type) {
- return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type);
- }
- function assertType(type) {
- !isType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL type.")) : void 0;
- return type;
- }
- /**
- * There are predicates for each kind of GraphQL type.
- */
- // eslint-disable-next-line no-redeclare
- function isScalarType(type) {
- return (0, _instanceOf.default)(type, GraphQLScalarType);
- }
- function assertScalarType(type) {
- !isScalarType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Scalar type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isObjectType(type) {
- return (0, _instanceOf.default)(type, GraphQLObjectType);
- }
- function assertObjectType(type) {
- !isObjectType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Object type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isInterfaceType(type) {
- return (0, _instanceOf.default)(type, GraphQLInterfaceType);
- }
- function assertInterfaceType(type) {
- !isInterfaceType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Interface type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isUnionType(type) {
- return (0, _instanceOf.default)(type, GraphQLUnionType);
- }
- function assertUnionType(type) {
- !isUnionType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Union type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isEnumType(type) {
- return (0, _instanceOf.default)(type, GraphQLEnumType);
- }
- function assertEnumType(type) {
- !isEnumType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Enum type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isInputObjectType(type) {
- return (0, _instanceOf.default)(type, GraphQLInputObjectType);
- }
- function assertInputObjectType(type) {
- !isInputObjectType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Input Object type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isListType(type) {
- return (0, _instanceOf.default)(type, GraphQLList);
- }
- function assertListType(type) {
- !isListType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL List type.")) : void 0;
- return type;
- }
- // eslint-disable-next-line no-redeclare
- function isNonNullType(type) {
- return (0, _instanceOf.default)(type, GraphQLNonNull);
- }
- function assertNonNullType(type) {
- !isNonNullType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Non-Null type.")) : void 0;
- return type;
- }
- /**
- * These types may be used as input types for arguments and directives.
- */
- function isInputType(type) {
- return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType);
- }
- function assertInputType(type) {
- !isInputType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL input type.")) : void 0;
- return type;
- }
- /**
- * These types may be used as output types as the result of fields.
- */
- function isOutputType(type) {
- return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType);
- }
- function assertOutputType(type) {
- !isOutputType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL output type.")) : void 0;
- return type;
- }
- /**
- * These types may describe types which may be leaf values.
- */
- function isLeafType(type) {
- return isScalarType(type) || isEnumType(type);
- }
- function assertLeafType(type) {
- !isLeafType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL leaf type.")) : void 0;
- return type;
- }
- /**
- * These types may describe the parent context of a selection set.
- */
- function isCompositeType(type) {
- return isObjectType(type) || isInterfaceType(type) || isUnionType(type);
- }
- function assertCompositeType(type) {
- !isCompositeType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL composite type.")) : void 0;
- return type;
- }
- /**
- * These types may describe the parent context of a selection set.
- */
- function isAbstractType(type) {
- return isInterfaceType(type) || isUnionType(type);
- }
- function assertAbstractType(type) {
- !isAbstractType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL abstract type.")) : void 0;
- return type;
- }
- /**
- * List Type Wrapper
- *
- * A list is a wrapping type which points to another type.
- * Lists are often created within the context of defining the fields of
- * an object type.
- *
- * Example:
- *
- * const PersonType = new GraphQLObjectType({
- * name: 'Person',
- * fields: () => ({
- * parents: { type: GraphQLList(PersonType) },
- * children: { type: GraphQLList(PersonType) },
- * })
- * })
- *
- */
- // eslint-disable-next-line no-redeclare
- function GraphQLList(ofType) {
- if (this instanceof GraphQLList) {
- this.ofType = assertType(ofType);
- } else {
- return new GraphQLList(ofType);
- }
- } // Need to cast through any to alter the prototype.
- GraphQLList.prototype.toString = function toString() {
- return '[' + String(this.ofType) + ']';
- };
- (0, _defineToJSON.default)(GraphQLList);
- /**
- * Non-Null Type Wrapper
- *
- * A non-null is a wrapping type which points to another type.
- * Non-null types enforce that their values are never null and can ensure
- * an error is raised if this ever occurs during a request. It is useful for
- * fields which you can make a strong guarantee on non-nullability, for example
- * usually the id field of a database row will never be null.
- *
- * Example:
- *
- * const RowType = new GraphQLObjectType({
- * name: 'Row',
- * fields: () => ({
- * id: { type: GraphQLNonNull(GraphQLString) },
- * })
- * })
- *
- * Note: the enforcement of non-nullability occurs within the executor.
- */
- // eslint-disable-next-line no-redeclare
- function GraphQLNonNull(ofType) {
- if (this instanceof GraphQLNonNull) {
- this.ofType = assertNullableType(ofType);
- } else {
- return new GraphQLNonNull(ofType);
- }
- } // Need to cast through any to alter the prototype.
- GraphQLNonNull.prototype.toString = function toString() {
- return String(this.ofType) + '!';
- };
- (0, _defineToJSON.default)(GraphQLNonNull);
- /**
- * These types wrap and modify other types
- */
- function isWrappingType(type) {
- return isListType(type) || isNonNullType(type);
- }
- function assertWrappingType(type) {
- !isWrappingType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL wrapping type.")) : void 0;
- return type;
- }
- /**
- * These types can all accept null as a value.
- */
- function isNullableType(type) {
- return isType(type) && !isNonNullType(type);
- }
- function assertNullableType(type) {
- !isNullableType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL nullable type.")) : void 0;
- return type;
- }
- /* eslint-disable no-redeclare */
- function getNullableType(type) {
- /* eslint-enable no-redeclare */
- if (type) {
- return isNonNullType(type) ? type.ofType : type;
- }
- }
- /**
- * These named types do not include modifiers like List or NonNull.
- */
- function isNamedType(type) {
- return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type);
- }
- function assertNamedType(type) {
- !isNamedType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL named type.")) : void 0;
- return type;
- }
- /* eslint-disable no-redeclare */
- function getNamedType(type) {
- /* eslint-enable no-redeclare */
- if (type) {
- var unwrappedType = type;
- while (isWrappingType(unwrappedType)) {
- unwrappedType = unwrappedType.ofType;
- }
- return unwrappedType;
- }
- }
- /**
- * Used while defining GraphQL types to allow for circular references in
- * otherwise immutable type definitions.
- */
- function resolveThunk(thunk) {
- // $FlowFixMe(>=0.90.0)
- return typeof thunk === 'function' ? thunk() : thunk;
- }
- /**
- * Scalar Type Definition
- *
- * The leaf values of any request and input values to arguments are
- * Scalars (or Enums) and are defined with a name and a series of functions
- * used to parse input from ast or variables and to ensure validity.
- *
- * If a type's serialize function does not return a value (i.e. it returns
- * `undefined`) then an error will be raised and a `null` value will be returned
- * in the response. If the serialize function returns `null`, then no error will
- * be included in the response.
- *
- * Example:
- *
- * const OddType = new GraphQLScalarType({
- * name: 'Odd',
- * serialize(value) {
- * if (value % 2 === 1) {
- * return value;
- * }
- * }
- * });
- *
- */
- var GraphQLScalarType =
- /*#__PURE__*/
- function () {
- function GraphQLScalarType(config) {
- this.name = config.name;
- this.description = config.description;
- this.serialize = config.serialize;
- this.parseValue = config.parseValue || function (value) {
- return value;
- };
- this.parseLiteral = config.parseLiteral || _valueFromASTUntyped.valueFromASTUntyped;
- this.astNode = config.astNode;
- this.extensionASTNodes = config.extensionASTNodes;
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- !(typeof config.serialize === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"serialize\" function. If this custom Scalar ") + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.') : void 0;
- if (config.parseValue || config.parseLiteral) {
- !(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" ") + 'functions.') : void 0;
- }
- }
- var _proto = GraphQLScalarType.prototype;
- _proto.toString = function toString() {
- return this.name;
- };
- return GraphQLScalarType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLScalarType = GraphQLScalarType;
- (0, _defineToStringTag.default)(GraphQLScalarType);
- (0, _defineToJSON.default)(GraphQLScalarType);
- /**
- * Object Type Definition
- *
- * Almost all of the GraphQL types you define will be object types. Object types
- * have a name, but most importantly describe their fields.
- *
- * Example:
- *
- * const AddressType = new GraphQLObjectType({
- * name: 'Address',
- * fields: {
- * street: { type: GraphQLString },
- * number: { type: GraphQLInt },
- * formatted: {
- * type: GraphQLString,
- * resolve(obj) {
- * return obj.number + ' ' + obj.street
- * }
- * }
- * }
- * });
- *
- * When two types need to refer to each other, or a type needs to refer to
- * itself in a field, you can use a function expression (aka a closure or a
- * thunk) to supply the fields lazily.
- *
- * Example:
- *
- * const PersonType = new GraphQLObjectType({
- * name: 'Person',
- * fields: () => ({
- * name: { type: GraphQLString },
- * bestFriend: { type: PersonType },
- * })
- * });
- *
- */
- var GraphQLObjectType =
- /*#__PURE__*/
- function () {
- function GraphQLObjectType(config) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = config.extensionASTNodes;
- this.isTypeOf = config.isTypeOf;
- this._fields = defineFieldMap.bind(undefined, config);
- this._interfaces = defineInterfaces.bind(undefined, config);
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- !(config.isTypeOf == null || typeof config.isTypeOf === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.isTypeOf), ".")) : void 0;
- }
- var _proto2 = GraphQLObjectType.prototype;
- _proto2.getFields = function getFields() {
- if (typeof this._fields === 'function') {
- this._fields = this._fields();
- }
- return this._fields;
- };
- _proto2.getInterfaces = function getInterfaces() {
- if (typeof this._interfaces === 'function') {
- this._interfaces = this._interfaces();
- }
- return this._interfaces;
- };
- _proto2.toString = function toString() {
- return this.name;
- };
- return GraphQLObjectType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLObjectType = GraphQLObjectType;
- (0, _defineToStringTag.default)(GraphQLObjectType);
- (0, _defineToJSON.default)(GraphQLObjectType);
- function defineInterfaces(config) {
- var interfaces = resolveThunk(config.interfaces) || [];
- !Array.isArray(interfaces) ? (0, _invariant.default)(0, "".concat(config.name, " interfaces must be an Array or a function which returns ") + 'an Array.') : void 0;
- return interfaces;
- }
- function defineFieldMap(config) {
- var fieldMap = resolveThunk(config.fields) || {};
- !isPlainObj(fieldMap) ? (0, _invariant.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0;
- return (0, _mapValue.default)(fieldMap, function (fieldConfig, fieldName) {
- !isPlainObj(fieldConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object")) : void 0;
- !!fieldConfig.hasOwnProperty('isDeprecated') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" ") + 'instead of "isDeprecated".') : void 0;
- !(fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field resolver must be a function if ") + "provided, but got: ".concat((0, _inspect.default)(fieldConfig.resolve), ".")) : void 0;
- var argsConfig = fieldConfig.args || {};
- !isPlainObj(argsConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument ") + 'names as keys.') : void 0;
- var args = (0, _objectEntries.default)(argsConfig).map(function (_ref) {
- var argName = _ref[0],
- arg = _ref[1];
- return {
- name: argName,
- description: arg.description === undefined ? null : arg.description,
- type: arg.type,
- defaultValue: arg.defaultValue,
- astNode: arg.astNode
- };
- });
- return _objectSpread({}, fieldConfig, {
- isDeprecated: Boolean(fieldConfig.deprecationReason),
- name: fieldName,
- args: args
- });
- });
- }
- function isPlainObj(obj) {
- return obj && _typeof(obj) === 'object' && !Array.isArray(obj);
- }
- function isRequiredArgument(arg) {
- return isNonNullType(arg.type) && arg.defaultValue === undefined;
- }
- /**
- * Interface Type Definition
- *
- * When a field can return one of a heterogeneous set of types, a Interface type
- * is used to describe what types are possible, what fields are in common across
- * all types, as well as a function to determine which type is actually used
- * when the field is resolved.
- *
- * Example:
- *
- * const EntityType = new GraphQLInterfaceType({
- * name: 'Entity',
- * fields: {
- * name: { type: GraphQLString }
- * }
- * });
- *
- */
- var GraphQLInterfaceType =
- /*#__PURE__*/
- function () {
- function GraphQLInterfaceType(config) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = config.extensionASTNodes;
- this.resolveType = config.resolveType;
- this._fields = defineFieldMap.bind(undefined, config);
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- !(config.resolveType == null || typeof config.resolveType === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")) : void 0;
- }
- var _proto3 = GraphQLInterfaceType.prototype;
- _proto3.getFields = function getFields() {
- if (typeof this._fields === 'function') {
- this._fields = this._fields();
- }
- return this._fields;
- };
- _proto3.toString = function toString() {
- return this.name;
- };
- return GraphQLInterfaceType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLInterfaceType = GraphQLInterfaceType;
- (0, _defineToStringTag.default)(GraphQLInterfaceType);
- (0, _defineToJSON.default)(GraphQLInterfaceType);
- /**
- * Union Type Definition
- *
- * When a field can return one of a heterogeneous set of types, a Union type
- * is used to describe what types are possible as well as providing a function
- * to determine which type is actually used when the field is resolved.
- *
- * Example:
- *
- * const PetType = new GraphQLUnionType({
- * name: 'Pet',
- * types: [ DogType, CatType ],
- * resolveType(value) {
- * if (value instanceof Dog) {
- * return DogType;
- * }
- * if (value instanceof Cat) {
- * return CatType;
- * }
- * }
- * });
- *
- */
- var GraphQLUnionType =
- /*#__PURE__*/
- function () {
- function GraphQLUnionType(config) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = config.extensionASTNodes;
- this.resolveType = config.resolveType;
- this._types = defineTypes.bind(undefined, config);
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- !(config.resolveType == null || typeof config.resolveType === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")) : void 0;
- }
- var _proto4 = GraphQLUnionType.prototype;
- _proto4.getTypes = function getTypes() {
- if (typeof this._types === 'function') {
- this._types = this._types();
- }
- return this._types;
- };
- _proto4.toString = function toString() {
- return this.name;
- };
- return GraphQLUnionType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLUnionType = GraphQLUnionType;
- (0, _defineToStringTag.default)(GraphQLUnionType);
- (0, _defineToJSON.default)(GraphQLUnionType);
- function defineTypes(config) {
- var types = resolveThunk(config.types) || [];
- !Array.isArray(types) ? (0, _invariant.default)(0, 'Must provide Array of types or a function which returns ' + "such an array for Union ".concat(config.name, ".")) : void 0;
- return types;
- }
- /**
- * Enum Type Definition
- *
- * Some leaf values of requests and input values are Enums. GraphQL serializes
- * Enum values as strings, however internally Enums can be represented by any
- * kind of type, often integers.
- *
- * Example:
- *
- * const RGBType = new GraphQLEnumType({
- * name: 'RGB',
- * values: {
- * RED: { value: 0 },
- * GREEN: { value: 1 },
- * BLUE: { value: 2 }
- * }
- * });
- *
- * Note: If a value is not provided in a definition, the name of the enum value
- * will be used as its internal value.
- */
- var GraphQLEnumType
- /* <T> */
- =
- /*#__PURE__*/
- function () {
- function GraphQLEnumType(config
- /* <T> */
- ) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = config.extensionASTNodes;
- this._values = defineEnumValues(this, config.values);
- this._valueLookup = new Map(this._values.map(function (enumValue) {
- return [enumValue.value, enumValue];
- }));
- this._nameLookup = (0, _keyMap.default)(this._values, function (value) {
- return value.name;
- });
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- }
- var _proto5 = GraphQLEnumType.prototype;
- _proto5.getValues = function getValues() {
- return this._values;
- };
- _proto5.getValue = function getValue(name) {
- return this._nameLookup[name];
- };
- _proto5.serialize = function serialize(value
- /* T */
- ) {
- var enumValue = this._valueLookup.get(value);
- if (enumValue) {
- return enumValue.name;
- }
- };
- _proto5.parseValue = function parseValue(value)
- /* T */
- {
- if (typeof value === 'string') {
- var enumValue = this.getValue(value);
- if (enumValue) {
- return enumValue.value;
- }
- }
- };
- _proto5.parseLiteral = function parseLiteral(valueNode, _variables)
- /* T */
- {
- // Note: variables will be resolved to a value before calling this function.
- if (valueNode.kind === _kinds.Kind.ENUM) {
- var enumValue = this.getValue(valueNode.value);
- if (enumValue) {
- return enumValue.value;
- }
- }
- };
- _proto5.toString = function toString() {
- return this.name;
- };
- return GraphQLEnumType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLEnumType = GraphQLEnumType;
- (0, _defineToStringTag.default)(GraphQLEnumType);
- (0, _defineToJSON.default)(GraphQLEnumType);
- function defineEnumValues(type, valueMap
- /* <T> */
- ) {
- !isPlainObj(valueMap) ? (0, _invariant.default)(0, "".concat(type.name, " values must be an object with value names as keys.")) : void 0;
- return (0, _objectEntries.default)(valueMap).map(function (_ref2) {
- var valueName = _ref2[0],
- value = _ref2[1];
- !isPlainObj(value) ? (0, _invariant.default)(0, "".concat(type.name, ".").concat(valueName, " must refer to an object with a \"value\" key ") + "representing an internal value but got: ".concat((0, _inspect.default)(value), ".")) : void 0;
- !!value.hasOwnProperty('isDeprecated') ? (0, _invariant.default)(0, "".concat(type.name, ".").concat(valueName, " should provide \"deprecationReason\" instead ") + 'of "isDeprecated".') : void 0;
- return {
- name: valueName,
- description: value.description,
- isDeprecated: Boolean(value.deprecationReason),
- deprecationReason: value.deprecationReason,
- astNode: value.astNode,
- value: value.hasOwnProperty('value') ? value.value : valueName
- };
- });
- }
- /**
- * Input Object Type Definition
- *
- * An input object defines a structured collection of fields which may be
- * supplied to a field argument.
- *
- * Using `NonNull` will ensure that a value must be provided by the query
- *
- * Example:
- *
- * const GeoPoint = new GraphQLInputObjectType({
- * name: 'GeoPoint',
- * fields: {
- * lat: { type: GraphQLNonNull(GraphQLFloat) },
- * lon: { type: GraphQLNonNull(GraphQLFloat) },
- * alt: { type: GraphQLFloat, defaultValue: 0 },
- * }
- * });
- *
- */
- var GraphQLInputObjectType =
- /*#__PURE__*/
- function () {
- function GraphQLInputObjectType(config) {
- this.name = config.name;
- this.description = config.description;
- this.astNode = config.astNode;
- this.extensionASTNodes = config.extensionASTNodes;
- this._fields = defineInputFieldMap.bind(undefined, config);
- !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0;
- }
- var _proto6 = GraphQLInputObjectType.prototype;
- _proto6.getFields = function getFields() {
- if (typeof this._fields === 'function') {
- this._fields = this._fields();
- }
- return this._fields;
- };
- _proto6.toString = function toString() {
- return this.name;
- };
- return GraphQLInputObjectType;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLInputObjectType = GraphQLInputObjectType;
- (0, _defineToStringTag.default)(GraphQLInputObjectType);
- (0, _defineToJSON.default)(GraphQLInputObjectType);
- function defineInputFieldMap(config) {
- var fieldMap = resolveThunk(config.fields) || {};
- !isPlainObj(fieldMap) ? (0, _invariant.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0;
- return (0, _mapValue.default)(fieldMap, function (fieldConfig, fieldName) {
- !!fieldConfig.hasOwnProperty('resolve') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but ") + 'Input Types cannot define resolvers.') : void 0;
- return _objectSpread({}, fieldConfig, {
- name: fieldName
- });
- });
- }
- function isRequiredInputField(field) {
- return isNonNullType(field.type) && field.defaultValue === undefined;
- }
- },{"../jsutils/defineToJSON":286,"../jsutils/defineToStringTag":287,"../jsutils/inspect":288,"../jsutils/instanceOf":289,"../jsutils/invariant":290,"../jsutils/keyMap":294,"../jsutils/mapValue":296,"../language/kinds":307,"../polyfills/objectEntries":318,"../utilities/valueFromASTUntyped":353}],324:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isDirective = isDirective;
- exports.assertDirective = assertDirective;
- exports.isSpecifiedDirective = isSpecifiedDirective;
- exports.specifiedDirectives = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = void 0;
- var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries"));
- var _definition = require("./definition");
- var _scalars = require("./scalars");
- var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag"));
- var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON"));
- var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _directiveLocation = require("../language/directiveLocation");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- // eslint-disable-next-line no-redeclare
- function isDirective(directive) {
- return (0, _instanceOf.default)(directive, GraphQLDirective);
- }
- function assertDirective(directive) {
- !isDirective(directive) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(directive), " to be a GraphQL directive.")) : void 0;
- return directive;
- }
- /**
- * Directives are used by the GraphQL runtime as a way of modifying execution
- * behavior. Type system creators will usually not create these directly.
- */
- var GraphQLDirective =
- /*#__PURE__*/
- function () {
- function GraphQLDirective(config) {
- this.name = config.name;
- this.description = config.description;
- this.locations = config.locations;
- this.astNode = config.astNode;
- !config.name ? (0, _invariant.default)(0, 'Directive must be named.') : void 0;
- !Array.isArray(config.locations) ? (0, _invariant.default)(0, "@".concat(config.name, " locations must be an Array.")) : void 0;
- var args = config.args || {};
- !(_typeof(args) === 'object' && !Array.isArray(args)) ? (0, _invariant.default)(0, "@".concat(config.name, " args must be an object with argument names as keys.")) : void 0;
- this.args = (0, _objectEntries.default)(args).map(function (_ref) {
- var argName = _ref[0],
- arg = _ref[1];
- return {
- name: argName,
- description: arg.description === undefined ? null : arg.description,
- type: arg.type,
- defaultValue: arg.defaultValue,
- astNode: arg.astNode
- };
- });
- }
- var _proto = GraphQLDirective.prototype;
- _proto.toString = function toString() {
- return '@' + this.name;
- };
- return GraphQLDirective;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLDirective = GraphQLDirective;
- (0, _defineToStringTag.default)(GraphQLDirective);
- (0, _defineToJSON.default)(GraphQLDirective);
- /**
- * Used to conditionally include fields or fragments.
- */
- var GraphQLIncludeDirective = new GraphQLDirective({
- name: 'include',
- description: 'Directs the executor to include this field or fragment only when ' + 'the `if` argument is true.',
- locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT],
- args: {
- if: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean),
- description: 'Included when true.'
- }
- }
- });
- /**
- * Used to conditionally skip (exclude) fields or fragments.
- */
- exports.GraphQLIncludeDirective = GraphQLIncludeDirective;
- var GraphQLSkipDirective = new GraphQLDirective({
- name: 'skip',
- description: 'Directs the executor to skip this field or fragment when the `if` ' + 'argument is true.',
- locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT],
- args: {
- if: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean),
- description: 'Skipped when true.'
- }
- }
- });
- /**
- * Constant string used for default reason for a deprecation.
- */
- exports.GraphQLSkipDirective = GraphQLSkipDirective;
- var DEFAULT_DEPRECATION_REASON = 'No longer supported';
- /**
- * Used to declare element of a GraphQL schema as deprecated.
- */
- exports.DEFAULT_DEPRECATION_REASON = DEFAULT_DEPRECATION_REASON;
- var GraphQLDeprecatedDirective = new GraphQLDirective({
- name: 'deprecated',
- description: 'Marks an element of a GraphQL schema as no longer supported.',
- locations: [_directiveLocation.DirectiveLocation.FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ENUM_VALUE],
- args: {
- reason: {
- type: _scalars.GraphQLString,
- description: 'Explains why this element was deprecated, usually also including a ' + 'suggestion for how to access supported similar data. Formatted using ' + 'the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).',
- defaultValue: DEFAULT_DEPRECATION_REASON
- }
- }
- });
- /**
- * The full list of specified directives.
- */
- exports.GraphQLDeprecatedDirective = GraphQLDeprecatedDirective;
- var specifiedDirectives = [GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective];
- exports.specifiedDirectives = specifiedDirectives;
- function isSpecifiedDirective(directive) {
- return specifiedDirectives.some(function (specifiedDirective) {
- return specifiedDirective.name === directive.name;
- });
- }
- },{"../jsutils/defineToJSON":286,"../jsutils/defineToStringTag":287,"../jsutils/inspect":288,"../jsutils/instanceOf":289,"../jsutils/invariant":290,"../language/directiveLocation":305,"../polyfills/objectEntries":318,"./definition":323,"./scalars":327}],325:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "isSchema", {
- enumerable: true,
- get: function get() {
- return _schema.isSchema;
- }
- });
- Object.defineProperty(exports, "assertSchema", {
- enumerable: true,
- get: function get() {
- return _schema.assertSchema;
- }
- });
- Object.defineProperty(exports, "GraphQLSchema", {
- enumerable: true,
- get: function get() {
- return _schema.GraphQLSchema;
- }
- });
- Object.defineProperty(exports, "isType", {
- enumerable: true,
- get: function get() {
- return _definition.isType;
- }
- });
- Object.defineProperty(exports, "isScalarType", {
- enumerable: true,
- get: function get() {
- return _definition.isScalarType;
- }
- });
- Object.defineProperty(exports, "isObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.isObjectType;
- }
- });
- Object.defineProperty(exports, "isInterfaceType", {
- enumerable: true,
- get: function get() {
- return _definition.isInterfaceType;
- }
- });
- Object.defineProperty(exports, "isUnionType", {
- enumerable: true,
- get: function get() {
- return _definition.isUnionType;
- }
- });
- Object.defineProperty(exports, "isEnumType", {
- enumerable: true,
- get: function get() {
- return _definition.isEnumType;
- }
- });
- Object.defineProperty(exports, "isInputObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.isInputObjectType;
- }
- });
- Object.defineProperty(exports, "isListType", {
- enumerable: true,
- get: function get() {
- return _definition.isListType;
- }
- });
- Object.defineProperty(exports, "isNonNullType", {
- enumerable: true,
- get: function get() {
- return _definition.isNonNullType;
- }
- });
- Object.defineProperty(exports, "isInputType", {
- enumerable: true,
- get: function get() {
- return _definition.isInputType;
- }
- });
- Object.defineProperty(exports, "isOutputType", {
- enumerable: true,
- get: function get() {
- return _definition.isOutputType;
- }
- });
- Object.defineProperty(exports, "isLeafType", {
- enumerable: true,
- get: function get() {
- return _definition.isLeafType;
- }
- });
- Object.defineProperty(exports, "isCompositeType", {
- enumerable: true,
- get: function get() {
- return _definition.isCompositeType;
- }
- });
- Object.defineProperty(exports, "isAbstractType", {
- enumerable: true,
- get: function get() {
- return _definition.isAbstractType;
- }
- });
- Object.defineProperty(exports, "isWrappingType", {
- enumerable: true,
- get: function get() {
- return _definition.isWrappingType;
- }
- });
- Object.defineProperty(exports, "isNullableType", {
- enumerable: true,
- get: function get() {
- return _definition.isNullableType;
- }
- });
- Object.defineProperty(exports, "isNamedType", {
- enumerable: true,
- get: function get() {
- return _definition.isNamedType;
- }
- });
- Object.defineProperty(exports, "isRequiredArgument", {
- enumerable: true,
- get: function get() {
- return _definition.isRequiredArgument;
- }
- });
- Object.defineProperty(exports, "isRequiredInputField", {
- enumerable: true,
- get: function get() {
- return _definition.isRequiredInputField;
- }
- });
- Object.defineProperty(exports, "assertType", {
- enumerable: true,
- get: function get() {
- return _definition.assertType;
- }
- });
- Object.defineProperty(exports, "assertScalarType", {
- enumerable: true,
- get: function get() {
- return _definition.assertScalarType;
- }
- });
- Object.defineProperty(exports, "assertObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.assertObjectType;
- }
- });
- Object.defineProperty(exports, "assertInterfaceType", {
- enumerable: true,
- get: function get() {
- return _definition.assertInterfaceType;
- }
- });
- Object.defineProperty(exports, "assertUnionType", {
- enumerable: true,
- get: function get() {
- return _definition.assertUnionType;
- }
- });
- Object.defineProperty(exports, "assertEnumType", {
- enumerable: true,
- get: function get() {
- return _definition.assertEnumType;
- }
- });
- Object.defineProperty(exports, "assertInputObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.assertInputObjectType;
- }
- });
- Object.defineProperty(exports, "assertListType", {
- enumerable: true,
- get: function get() {
- return _definition.assertListType;
- }
- });
- Object.defineProperty(exports, "assertNonNullType", {
- enumerable: true,
- get: function get() {
- return _definition.assertNonNullType;
- }
- });
- Object.defineProperty(exports, "assertInputType", {
- enumerable: true,
- get: function get() {
- return _definition.assertInputType;
- }
- });
- Object.defineProperty(exports, "assertOutputType", {
- enumerable: true,
- get: function get() {
- return _definition.assertOutputType;
- }
- });
- Object.defineProperty(exports, "assertLeafType", {
- enumerable: true,
- get: function get() {
- return _definition.assertLeafType;
- }
- });
- Object.defineProperty(exports, "assertCompositeType", {
- enumerable: true,
- get: function get() {
- return _definition.assertCompositeType;
- }
- });
- Object.defineProperty(exports, "assertAbstractType", {
- enumerable: true,
- get: function get() {
- return _definition.assertAbstractType;
- }
- });
- Object.defineProperty(exports, "assertWrappingType", {
- enumerable: true,
- get: function get() {
- return _definition.assertWrappingType;
- }
- });
- Object.defineProperty(exports, "assertNullableType", {
- enumerable: true,
- get: function get() {
- return _definition.assertNullableType;
- }
- });
- Object.defineProperty(exports, "assertNamedType", {
- enumerable: true,
- get: function get() {
- return _definition.assertNamedType;
- }
- });
- Object.defineProperty(exports, "getNullableType", {
- enumerable: true,
- get: function get() {
- return _definition.getNullableType;
- }
- });
- Object.defineProperty(exports, "getNamedType", {
- enumerable: true,
- get: function get() {
- return _definition.getNamedType;
- }
- });
- Object.defineProperty(exports, "GraphQLScalarType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLScalarType;
- }
- });
- Object.defineProperty(exports, "GraphQLObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLObjectType;
- }
- });
- Object.defineProperty(exports, "GraphQLInterfaceType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLInterfaceType;
- }
- });
- Object.defineProperty(exports, "GraphQLUnionType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLUnionType;
- }
- });
- Object.defineProperty(exports, "GraphQLEnumType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLEnumType;
- }
- });
- Object.defineProperty(exports, "GraphQLInputObjectType", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLInputObjectType;
- }
- });
- Object.defineProperty(exports, "GraphQLList", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLList;
- }
- });
- Object.defineProperty(exports, "GraphQLNonNull", {
- enumerable: true,
- get: function get() {
- return _definition.GraphQLNonNull;
- }
- });
- Object.defineProperty(exports, "isDirective", {
- enumerable: true,
- get: function get() {
- return _directives.isDirective;
- }
- });
- Object.defineProperty(exports, "assertDirective", {
- enumerable: true,
- get: function get() {
- return _directives.assertDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLDirective", {
- enumerable: true,
- get: function get() {
- return _directives.GraphQLDirective;
- }
- });
- Object.defineProperty(exports, "isSpecifiedDirective", {
- enumerable: true,
- get: function get() {
- return _directives.isSpecifiedDirective;
- }
- });
- Object.defineProperty(exports, "specifiedDirectives", {
- enumerable: true,
- get: function get() {
- return _directives.specifiedDirectives;
- }
- });
- Object.defineProperty(exports, "GraphQLIncludeDirective", {
- enumerable: true,
- get: function get() {
- return _directives.GraphQLIncludeDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLSkipDirective", {
- enumerable: true,
- get: function get() {
- return _directives.GraphQLSkipDirective;
- }
- });
- Object.defineProperty(exports, "GraphQLDeprecatedDirective", {
- enumerable: true,
- get: function get() {
- return _directives.GraphQLDeprecatedDirective;
- }
- });
- Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", {
- enumerable: true,
- get: function get() {
- return _directives.DEFAULT_DEPRECATION_REASON;
- }
- });
- Object.defineProperty(exports, "isSpecifiedScalarType", {
- enumerable: true,
- get: function get() {
- return _scalars.isSpecifiedScalarType;
- }
- });
- Object.defineProperty(exports, "specifiedScalarTypes", {
- enumerable: true,
- get: function get() {
- return _scalars.specifiedScalarTypes;
- }
- });
- Object.defineProperty(exports, "GraphQLInt", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLInt;
- }
- });
- Object.defineProperty(exports, "GraphQLFloat", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLFloat;
- }
- });
- Object.defineProperty(exports, "GraphQLString", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLString;
- }
- });
- Object.defineProperty(exports, "GraphQLBoolean", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLBoolean;
- }
- });
- Object.defineProperty(exports, "GraphQLID", {
- enumerable: true,
- get: function get() {
- return _scalars.GraphQLID;
- }
- });
- Object.defineProperty(exports, "TypeKind", {
- enumerable: true,
- get: function get() {
- return _introspection.TypeKind;
- }
- });
- Object.defineProperty(exports, "isIntrospectionType", {
- enumerable: true,
- get: function get() {
- return _introspection.isIntrospectionType;
- }
- });
- Object.defineProperty(exports, "introspectionTypes", {
- enumerable: true,
- get: function get() {
- return _introspection.introspectionTypes;
- }
- });
- Object.defineProperty(exports, "__Schema", {
- enumerable: true,
- get: function get() {
- return _introspection.__Schema;
- }
- });
- Object.defineProperty(exports, "__Directive", {
- enumerable: true,
- get: function get() {
- return _introspection.__Directive;
- }
- });
- Object.defineProperty(exports, "__DirectiveLocation", {
- enumerable: true,
- get: function get() {
- return _introspection.__DirectiveLocation;
- }
- });
- Object.defineProperty(exports, "__Type", {
- enumerable: true,
- get: function get() {
- return _introspection.__Type;
- }
- });
- Object.defineProperty(exports, "__Field", {
- enumerable: true,
- get: function get() {
- return _introspection.__Field;
- }
- });
- Object.defineProperty(exports, "__InputValue", {
- enumerable: true,
- get: function get() {
- return _introspection.__InputValue;
- }
- });
- Object.defineProperty(exports, "__EnumValue", {
- enumerable: true,
- get: function get() {
- return _introspection.__EnumValue;
- }
- });
- Object.defineProperty(exports, "__TypeKind", {
- enumerable: true,
- get: function get() {
- return _introspection.__TypeKind;
- }
- });
- Object.defineProperty(exports, "SchemaMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _introspection.SchemaMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "TypeMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _introspection.TypeMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "TypeNameMetaFieldDef", {
- enumerable: true,
- get: function get() {
- return _introspection.TypeNameMetaFieldDef;
- }
- });
- Object.defineProperty(exports, "validateSchema", {
- enumerable: true,
- get: function get() {
- return _validate.validateSchema;
- }
- });
- Object.defineProperty(exports, "assertValidSchema", {
- enumerable: true,
- get: function get() {
- return _validate.assertValidSchema;
- }
- });
- var _schema = require("./schema");
- var _definition = require("./definition");
- var _directives = require("./directives");
- var _scalars = require("./scalars");
- var _introspection = require("./introspection");
- var _validate = require("./validate");
- },{"./definition":323,"./directives":324,"./introspection":326,"./scalars":327,"./schema":328,"./validate":329}],326:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isIntrospectionType = isIntrospectionType;
- exports.introspectionTypes = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.__TypeKind = exports.TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = void 0;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _astFromValue = require("../utilities/astFromValue");
- var _printer = require("../language/printer");
- var _definition = require("./definition");
- var _scalars = require("./scalars");
- var _directiveLocation = require("../language/directiveLocation");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var __Schema = new _definition.GraphQLObjectType({
- name: '__Schema',
- description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + 'exposes all available types and directives on the server, as well as ' + 'the entry points for query, mutation, and subscription operations.',
- fields: function fields() {
- return {
- types: {
- description: 'A list of all types supported by this server.',
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type))),
- resolve: function resolve(schema) {
- return (0, _objectValues.default)(schema.getTypeMap());
- }
- },
- queryType: {
- description: 'The type that query operations will be rooted at.',
- type: (0, _definition.GraphQLNonNull)(__Type),
- resolve: function resolve(schema) {
- return schema.getQueryType();
- }
- },
- mutationType: {
- description: 'If this server supports mutation, the type that ' + 'mutation operations will be rooted at.',
- type: __Type,
- resolve: function resolve(schema) {
- return schema.getMutationType();
- }
- },
- subscriptionType: {
- description: 'If this server support subscription, the type that ' + 'subscription operations will be rooted at.',
- type: __Type,
- resolve: function resolve(schema) {
- return schema.getSubscriptionType();
- }
- },
- directives: {
- description: 'A list of all directives supported by this server.',
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Directive))),
- resolve: function resolve(schema) {
- return schema.getDirectives();
- }
- }
- };
- }
- });
- exports.__Schema = __Schema;
- var __Directive = new _definition.GraphQLObjectType({
- name: '__Directive',
- description: 'A Directive provides a way to describe alternate runtime execution and ' + 'type validation behavior in a GraphQL document.' + "\n\nIn some cases, you need to provide options to alter GraphQL's " + 'execution behavior in ways field arguments will not suffice, such as ' + 'conditionally including or skipping a field. Directives provide this by ' + 'describing additional information to the executor.',
- fields: function fields() {
- return {
- name: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- locations: {
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__DirectiveLocation))),
- resolve: function resolve(obj) {
- return obj.locations;
- }
- },
- args: {
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue))),
- resolve: function resolve(directive) {
- return directive.args || [];
- }
- }
- };
- }
- });
- exports.__Directive = __Directive;
- var __DirectiveLocation = new _definition.GraphQLEnumType({
- name: '__DirectiveLocation',
- description: 'A Directive can be adjacent to many parts of the GraphQL language, a ' + '__DirectiveLocation describes one such possible adjacencies.',
- values: {
- QUERY: {
- value: _directiveLocation.DirectiveLocation.QUERY,
- description: 'Location adjacent to a query operation.'
- },
- MUTATION: {
- value: _directiveLocation.DirectiveLocation.MUTATION,
- description: 'Location adjacent to a mutation operation.'
- },
- SUBSCRIPTION: {
- value: _directiveLocation.DirectiveLocation.SUBSCRIPTION,
- description: 'Location adjacent to a subscription operation.'
- },
- FIELD: {
- value: _directiveLocation.DirectiveLocation.FIELD,
- description: 'Location adjacent to a field.'
- },
- FRAGMENT_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION,
- description: 'Location adjacent to a fragment definition.'
- },
- FRAGMENT_SPREAD: {
- value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD,
- description: 'Location adjacent to a fragment spread.'
- },
- INLINE_FRAGMENT: {
- value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT,
- description: 'Location adjacent to an inline fragment.'
- },
- VARIABLE_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION,
- description: 'Location adjacent to a variable definition.'
- },
- SCHEMA: {
- value: _directiveLocation.DirectiveLocation.SCHEMA,
- description: 'Location adjacent to a schema definition.'
- },
- SCALAR: {
- value: _directiveLocation.DirectiveLocation.SCALAR,
- description: 'Location adjacent to a scalar definition.'
- },
- OBJECT: {
- value: _directiveLocation.DirectiveLocation.OBJECT,
- description: 'Location adjacent to an object type definition.'
- },
- FIELD_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION,
- description: 'Location adjacent to a field definition.'
- },
- ARGUMENT_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION,
- description: 'Location adjacent to an argument definition.'
- },
- INTERFACE: {
- value: _directiveLocation.DirectiveLocation.INTERFACE,
- description: 'Location adjacent to an interface definition.'
- },
- UNION: {
- value: _directiveLocation.DirectiveLocation.UNION,
- description: 'Location adjacent to a union definition.'
- },
- ENUM: {
- value: _directiveLocation.DirectiveLocation.ENUM,
- description: 'Location adjacent to an enum definition.'
- },
- ENUM_VALUE: {
- value: _directiveLocation.DirectiveLocation.ENUM_VALUE,
- description: 'Location adjacent to an enum value definition.'
- },
- INPUT_OBJECT: {
- value: _directiveLocation.DirectiveLocation.INPUT_OBJECT,
- description: 'Location adjacent to an input object type definition.'
- },
- INPUT_FIELD_DEFINITION: {
- value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION,
- description: 'Location adjacent to an input object field definition.'
- }
- }
- });
- exports.__DirectiveLocation = __DirectiveLocation;
- var __Type = new _definition.GraphQLObjectType({
- name: '__Type',
- description: 'The fundamental unit of any GraphQL Schema is the type. There are ' + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + '\n\nDepending on the kind of a type, certain fields describe ' + 'information about that type. Scalar types provide no information ' + 'beyond a name and description, while Enum types provide their values. ' + 'Object and Interface types provide the fields they describe. Abstract ' + 'types, Union and Interface, provide the Object types possible ' + 'at runtime. List and NonNull types compose other types.',
- fields: function fields() {
- return {
- kind: {
- type: (0, _definition.GraphQLNonNull)(__TypeKind),
- resolve: function resolve(type) {
- if ((0, _definition.isScalarType)(type)) {
- return TypeKind.SCALAR;
- } else if ((0, _definition.isObjectType)(type)) {
- return TypeKind.OBJECT;
- } else if ((0, _definition.isInterfaceType)(type)) {
- return TypeKind.INTERFACE;
- } else if ((0, _definition.isUnionType)(type)) {
- return TypeKind.UNION;
- } else if ((0, _definition.isEnumType)(type)) {
- return TypeKind.ENUM;
- } else if ((0, _definition.isInputObjectType)(type)) {
- return TypeKind.INPUT_OBJECT;
- } else if ((0, _definition.isListType)(type)) {
- return TypeKind.LIST;
- } else if ((0, _definition.isNonNullType)(type)) {
- return TypeKind.NON_NULL;
- }
- throw new Error('Unknown kind of type: ' + type);
- }
- },
- name: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- fields: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Field)),
- args: {
- includeDeprecated: {
- type: _scalars.GraphQLBoolean,
- defaultValue: false
- }
- },
- resolve: function resolve(type, _ref) {
- var includeDeprecated = _ref.includeDeprecated;
- if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) {
- var fields = (0, _objectValues.default)(type.getFields());
- if (!includeDeprecated) {
- fields = fields.filter(function (field) {
- return !field.deprecationReason;
- });
- }
- return fields;
- }
- return null;
- }
- },
- interfaces: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type)),
- resolve: function resolve(type) {
- if ((0, _definition.isObjectType)(type)) {
- return type.getInterfaces();
- }
- }
- },
- possibleTypes: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type)),
- resolve: function resolve(type, args, context, _ref2) {
- var schema = _ref2.schema;
- if ((0, _definition.isAbstractType)(type)) {
- return schema.getPossibleTypes(type);
- }
- }
- },
- enumValues: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__EnumValue)),
- args: {
- includeDeprecated: {
- type: _scalars.GraphQLBoolean,
- defaultValue: false
- }
- },
- resolve: function resolve(type, _ref3) {
- var includeDeprecated = _ref3.includeDeprecated;
- if ((0, _definition.isEnumType)(type)) {
- var values = type.getValues();
- if (!includeDeprecated) {
- values = values.filter(function (value) {
- return !value.deprecationReason;
- });
- }
- return values;
- }
- }
- },
- inputFields: {
- type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue)),
- resolve: function resolve(type) {
- if ((0, _definition.isInputObjectType)(type)) {
- return (0, _objectValues.default)(type.getFields());
- }
- }
- },
- ofType: {
- type: __Type,
- resolve: function resolve(obj) {
- return obj.ofType;
- }
- }
- };
- }
- });
- exports.__Type = __Type;
- var __Field = new _definition.GraphQLObjectType({
- name: '__Field',
- description: 'Object and Interface types are described by a list of Fields, each of ' + 'which has a name, potentially a list of arguments, and a return type.',
- fields: function fields() {
- return {
- name: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- args: {
- type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue))),
- resolve: function resolve(field) {
- return field.args || [];
- }
- },
- type: {
- type: (0, _definition.GraphQLNonNull)(__Type),
- resolve: function resolve(obj) {
- return obj.type;
- }
- },
- isDeprecated: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean),
- resolve: function resolve(obj) {
- return obj.isDeprecated;
- }
- },
- deprecationReason: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.deprecationReason;
- }
- }
- };
- }
- });
- exports.__Field = __Field;
- var __InputValue = new _definition.GraphQLObjectType({
- name: '__InputValue',
- description: 'Arguments provided to Fields or Directives and the input fields of an ' + 'InputObject are represented as Input Values which describe their type ' + 'and optionally a default value.',
- fields: function fields() {
- return {
- name: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- type: {
- type: (0, _definition.GraphQLNonNull)(__Type),
- resolve: function resolve(obj) {
- return obj.type;
- }
- },
- defaultValue: {
- type: _scalars.GraphQLString,
- description: 'A GraphQL-formatted string representing the default value for this ' + 'input value.',
- resolve: function resolve(inputVal) {
- return (0, _isInvalid.default)(inputVal.defaultValue) ? null : (0, _printer.print)((0, _astFromValue.astFromValue)(inputVal.defaultValue, inputVal.type));
- }
- }
- };
- }
- });
- exports.__InputValue = __InputValue;
- var __EnumValue = new _definition.GraphQLObjectType({
- name: '__EnumValue',
- description: 'One possible value for a given Enum. Enum values are unique values, not ' + 'a placeholder for a string or numeric value. However an Enum value is ' + 'returned in a JSON response as a string.',
- fields: function fields() {
- return {
- name: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- resolve: function resolve(obj) {
- return obj.name;
- }
- },
- description: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.description;
- }
- },
- isDeprecated: {
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean),
- resolve: function resolve(obj) {
- return obj.isDeprecated;
- }
- },
- deprecationReason: {
- type: _scalars.GraphQLString,
- resolve: function resolve(obj) {
- return obj.deprecationReason;
- }
- }
- };
- }
- });
- exports.__EnumValue = __EnumValue;
- var TypeKind = {
- SCALAR: 'SCALAR',
- OBJECT: 'OBJECT',
- INTERFACE: 'INTERFACE',
- UNION: 'UNION',
- ENUM: 'ENUM',
- INPUT_OBJECT: 'INPUT_OBJECT',
- LIST: 'LIST',
- NON_NULL: 'NON_NULL'
- };
- exports.TypeKind = TypeKind;
- var __TypeKind = new _definition.GraphQLEnumType({
- name: '__TypeKind',
- description: 'An enum describing what kind of type a given `__Type` is.',
- values: {
- SCALAR: {
- value: TypeKind.SCALAR,
- description: 'Indicates this type is a scalar.'
- },
- OBJECT: {
- value: TypeKind.OBJECT,
- description: 'Indicates this type is an object. ' + '`fields` and `interfaces` are valid fields.'
- },
- INTERFACE: {
- value: TypeKind.INTERFACE,
- description: 'Indicates this type is an interface. ' + '`fields` and `possibleTypes` are valid fields.'
- },
- UNION: {
- value: TypeKind.UNION,
- description: 'Indicates this type is a union. `possibleTypes` is a valid field.'
- },
- ENUM: {
- value: TypeKind.ENUM,
- description: 'Indicates this type is an enum. `enumValues` is a valid field.'
- },
- INPUT_OBJECT: {
- value: TypeKind.INPUT_OBJECT,
- description: 'Indicates this type is an input object. ' + '`inputFields` is a valid field.'
- },
- LIST: {
- value: TypeKind.LIST,
- description: 'Indicates this type is a list. `ofType` is a valid field.'
- },
- NON_NULL: {
- value: TypeKind.NON_NULL,
- description: 'Indicates this type is a non-null. `ofType` is a valid field.'
- }
- }
- });
- /**
- * Note that these are GraphQLField and not GraphQLFieldConfig,
- * so the format for args is different.
- */
- exports.__TypeKind = __TypeKind;
- var SchemaMetaFieldDef = {
- name: '__schema',
- type: (0, _definition.GraphQLNonNull)(__Schema),
- description: 'Access the current type schema of this server.',
- args: [],
- resolve: function resolve(source, args, context, _ref4) {
- var schema = _ref4.schema;
- return schema;
- }
- };
- exports.SchemaMetaFieldDef = SchemaMetaFieldDef;
- var TypeMetaFieldDef = {
- name: '__type',
- type: __Type,
- description: 'Request the type information of a single type.',
- args: [{
- name: 'name',
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString)
- }],
- resolve: function resolve(source, _ref5, context, _ref6) {
- var name = _ref5.name;
- var schema = _ref6.schema;
- return schema.getType(name);
- }
- };
- exports.TypeMetaFieldDef = TypeMetaFieldDef;
- var TypeNameMetaFieldDef = {
- name: '__typename',
- type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString),
- description: 'The name of the current Object type at runtime.',
- args: [],
- resolve: function resolve(source, args, context, _ref7) {
- var parentType = _ref7.parentType;
- return parentType.name;
- }
- };
- exports.TypeNameMetaFieldDef = TypeNameMetaFieldDef;
- var introspectionTypes = [__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind];
- exports.introspectionTypes = introspectionTypes;
- function isIntrospectionType(type) {
- return (0, _definition.isNamedType)(type) && ( // Would prefer to use introspectionTypes.some(), however %checks needs
- // a simple expression.
- type.name === __Schema.name || type.name === __Directive.name || type.name === __DirectiveLocation.name || type.name === __Type.name || type.name === __Field.name || type.name === __InputValue.name || type.name === __EnumValue.name || type.name === __TypeKind.name);
- }
- },{"../jsutils/isInvalid":291,"../language/directiveLocation":305,"../language/printer":312,"../polyfills/objectValues":319,"../utilities/astFromValue":332,"./definition":323,"./scalars":327}],327:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isSpecifiedScalarType = isSpecifiedScalarType;
- exports.specifiedScalarTypes = exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = void 0;
- var _isFinite = _interopRequireDefault(require("../polyfills/isFinite"));
- var _isInteger = _interopRequireDefault(require("../polyfills/isInteger"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _definition = require("./definition");
- var _kinds = require("../language/kinds");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- // As per the GraphQL Spec, Integers are only treated as valid when a valid
- // 32-bit signed integer, providing the broadest support across platforms.
- //
- // n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because
- // they are internally represented as IEEE 754 doubles.
- var MAX_INT = 2147483647;
- var MIN_INT = -2147483648;
- function serializeInt(value) {
- if (typeof value === 'boolean') {
- return value ? 1 : 0;
- }
- var num = value;
- if (typeof value === 'string' && value !== '') {
- num = Number(value);
- }
- if (!(0, _isInteger.default)(num)) {
- throw new TypeError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(value)));
- }
- if (num > MAX_INT || num < MIN_INT) {
- throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat((0, _inspect.default)(value)));
- }
- return num;
- }
- function coerceInt(value) {
- if (!(0, _isInteger.default)(value)) {
- throw new TypeError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(value)));
- }
- if (value > MAX_INT || value < MIN_INT) {
- throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat((0, _inspect.default)(value)));
- }
- return value;
- }
- var GraphQLInt = new _definition.GraphQLScalarType({
- name: 'Int',
- description: 'The `Int` scalar type represents non-fractional signed whole numeric ' + 'values. Int can represent values between -(2^31) and 2^31 - 1. ',
- serialize: serializeInt,
- parseValue: coerceInt,
- parseLiteral: function parseLiteral(ast) {
- if (ast.kind === _kinds.Kind.INT) {
- var num = parseInt(ast.value, 10);
- if (num <= MAX_INT && num >= MIN_INT) {
- return num;
- }
- }
- return undefined;
- }
- });
- exports.GraphQLInt = GraphQLInt;
- function serializeFloat(value) {
- if (typeof value === 'boolean') {
- return value ? 1 : 0;
- }
- var num = value;
- if (typeof value === 'string' && value !== '') {
- num = Number(value);
- }
- if (!(0, _isFinite.default)(num)) {
- throw new TypeError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(value)));
- }
- return num;
- }
- function coerceFloat(value) {
- if (!(0, _isFinite.default)(value)) {
- throw new TypeError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(value)));
- }
- return value;
- }
- var GraphQLFloat = new _definition.GraphQLScalarType({
- name: 'Float',
- description: 'The `Float` scalar type represents signed double-precision fractional ' + 'values as specified by ' + '[IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point). ',
- serialize: serializeFloat,
- parseValue: coerceFloat,
- parseLiteral: function parseLiteral(ast) {
- return ast.kind === _kinds.Kind.FLOAT || ast.kind === _kinds.Kind.INT ? parseFloat(ast.value) : undefined;
- }
- }); // Support serializing objects with custom valueOf() or toJSON() functions -
- // a common way to represent a complex value which can be represented as
- // a string (ex: MongoDB id objects).
- exports.GraphQLFloat = GraphQLFloat;
- function serializeObject(value) {
- if (_typeof(value) === 'object' && value !== null) {
- if (typeof value.valueOf === 'function') {
- var valueOfResult = value.valueOf();
- if (_typeof(valueOfResult) !== 'object') {
- return valueOfResult;
- }
- }
- if (typeof value.toJSON === 'function') {
- // $FlowFixMe(>=0.90.0)
- return value.toJSON();
- }
- }
- return value;
- }
- function serializeString(rawValue) {
- var value = serializeObject(rawValue); // Serialize string, boolean and number values to a string, but do not
- // attempt to coerce object, function, symbol, or other types as strings.
- if (typeof value === 'string') {
- return value;
- }
- if (typeof value === 'boolean') {
- return value ? 'true' : 'false';
- }
- if ((0, _isFinite.default)(value)) {
- return value.toString();
- }
- throw new TypeError("String cannot represent value: ".concat((0, _inspect.default)(rawValue)));
- }
- function coerceString(value) {
- if (typeof value !== 'string') {
- throw new TypeError("String cannot represent a non string value: ".concat((0, _inspect.default)(value)));
- }
- return value;
- }
- var GraphQLString = new _definition.GraphQLScalarType({
- name: 'String',
- description: 'The `String` scalar type represents textual data, represented as UTF-8 ' + 'character sequences. The String type is most often used by GraphQL to ' + 'represent free-form human-readable text.',
- serialize: serializeString,
- parseValue: coerceString,
- parseLiteral: function parseLiteral(ast) {
- return ast.kind === _kinds.Kind.STRING ? ast.value : undefined;
- }
- });
- exports.GraphQLString = GraphQLString;
- function serializeBoolean(value) {
- if (typeof value === 'boolean') {
- return value;
- }
- if ((0, _isFinite.default)(value)) {
- return value !== 0;
- }
- throw new TypeError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(value)));
- }
- function coerceBoolean(value) {
- if (typeof value !== 'boolean') {
- throw new TypeError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(value)));
- }
- return value;
- }
- var GraphQLBoolean = new _definition.GraphQLScalarType({
- name: 'Boolean',
- description: 'The `Boolean` scalar type represents `true` or `false`.',
- serialize: serializeBoolean,
- parseValue: coerceBoolean,
- parseLiteral: function parseLiteral(ast) {
- return ast.kind === _kinds.Kind.BOOLEAN ? ast.value : undefined;
- }
- });
- exports.GraphQLBoolean = GraphQLBoolean;
- function serializeID(rawValue) {
- var value = serializeObject(rawValue);
- if (typeof value === 'string') {
- return value;
- }
- if ((0, _isInteger.default)(value)) {
- return String(value);
- }
- throw new TypeError("ID cannot represent value: ".concat((0, _inspect.default)(rawValue)));
- }
- function coerceID(value) {
- if (typeof value === 'string') {
- return value;
- }
- if ((0, _isInteger.default)(value)) {
- return value.toString();
- }
- throw new TypeError("ID cannot represent value: ".concat((0, _inspect.default)(value)));
- }
- var GraphQLID = new _definition.GraphQLScalarType({
- name: 'ID',
- description: 'The `ID` scalar type represents a unique identifier, often used to ' + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + 'response as a String; however, it is not intended to be human-readable. ' + 'When expected as an input type, any string (such as `"4"`) or integer ' + '(such as `4`) input value will be accepted as an ID.',
- serialize: serializeID,
- parseValue: coerceID,
- parseLiteral: function parseLiteral(ast) {
- return ast.kind === _kinds.Kind.STRING || ast.kind === _kinds.Kind.INT ? ast.value : undefined;
- }
- });
- exports.GraphQLID = GraphQLID;
- var specifiedScalarTypes = [GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID];
- exports.specifiedScalarTypes = specifiedScalarTypes;
- function isSpecifiedScalarType(type) {
- return (0, _definition.isNamedType)(type) && ( // Would prefer to use specifiedScalarTypes.some(), however %checks needs
- // a simple expression.
- type.name === GraphQLString.name || type.name === GraphQLInt.name || type.name === GraphQLFloat.name || type.name === GraphQLBoolean.name || type.name === GraphQLID.name);
- }
- },{"../jsutils/inspect":288,"../language/kinds":307,"../polyfills/isFinite":316,"../polyfills/isInteger":317,"./definition":323}],328:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isSchema = isSchema;
- exports.assertSchema = assertSchema;
- exports.GraphQLSchema = void 0;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _definition = require("./definition");
- var _directives = require("./directives");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _introspection = require("./introspection");
- var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag"));
- var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- // eslint-disable-next-line no-redeclare
- function isSchema(schema) {
- return (0, _instanceOf.default)(schema, GraphQLSchema);
- }
- function assertSchema(schema) {
- !isSchema(schema) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(schema), " to be a GraphQL schema.")) : void 0;
- return schema;
- }
- /**
- * Schema Definition
- *
- * A Schema is created by supplying the root types of each type of operation,
- * query and mutation (optional). A schema definition is then supplied to the
- * validator and executor.
- *
- * Example:
- *
- * const MyAppSchema = new GraphQLSchema({
- * query: MyAppQueryRootType,
- * mutation: MyAppMutationRootType,
- * })
- *
- * Note: If an array of `directives` are provided to GraphQLSchema, that will be
- * the exact list of directives represented and allowed. If `directives` is not
- * provided then a default set of the specified directives (e.g. @include and
- * @skip) will be used. If you wish to provide *additional* directives to these
- * specified directives, you must explicitly declare them. Example:
- *
- * const MyAppSchema = new GraphQLSchema({
- * ...
- * directives: specifiedDirectives.concat([ myCustomDirective ]),
- * })
- *
- */
- var GraphQLSchema =
- /*#__PURE__*/
- function () {
- // Used as a cache for validateSchema().
- // Referenced by validateSchema().
- function GraphQLSchema(config) {
- // If this schema was built from a source known to be valid, then it may be
- // marked with assumeValid to avoid an additional type system validation.
- if (config && config.assumeValid) {
- this.__validationErrors = [];
- } else {
- this.__validationErrors = undefined; // Otherwise check for common mistakes during construction to produce
- // clear and early error messages.
- !(_typeof(config) === 'object') ? (0, _invariant.default)(0, 'Must provide configuration object.') : void 0;
- !(!config.types || Array.isArray(config.types)) ? (0, _invariant.default)(0, "\"types\" must be Array if provided but got: ".concat((0, _inspect.default)(config.types), ".")) : void 0;
- !(!config.directives || Array.isArray(config.directives)) ? (0, _invariant.default)(0, '"directives" must be Array if provided but got: ' + "".concat((0, _inspect.default)(config.directives), ".")) : void 0;
- !(!config.allowedLegacyNames || Array.isArray(config.allowedLegacyNames)) ? (0, _invariant.default)(0, '"allowedLegacyNames" must be Array if provided but got: ' + "".concat((0, _inspect.default)(config.allowedLegacyNames), ".")) : void 0;
- }
- this.__allowedLegacyNames = config.allowedLegacyNames || [];
- this._queryType = config.query;
- this._mutationType = config.mutation;
- this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default.
- this._directives = config.directives || _directives.specifiedDirectives;
- this.astNode = config.astNode;
- this.extensionASTNodes = config.extensionASTNodes; // Build type map now to detect any errors within this schema.
- var initialTypes = [this.getQueryType(), this.getMutationType(), this.getSubscriptionType(), _introspection.__Schema];
- var types = config.types;
- if (types) {
- initialTypes = initialTypes.concat(types);
- } // Keep track of all types referenced within the schema.
- var typeMap = Object.create(null); // First by deeply visiting all initial types.
- typeMap = initialTypes.reduce(typeMapReducer, typeMap); // Then by deeply visiting all directive types.
- typeMap = this._directives.reduce(typeMapDirectiveReducer, typeMap); // Storing the resulting map for reference by the schema.
- this._typeMap = typeMap;
- this._possibleTypeMap = Object.create(null); // Keep track of all implementations by interface name.
- this._implementations = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectValues.default)(this._typeMap)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var type = _step.value;
- if ((0, _definition.isObjectType)(type)) {
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = type.getInterfaces()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var iface = _step2.value;
- if ((0, _definition.isInterfaceType)(iface)) {
- var impls = this._implementations[iface.name];
- if (impls) {
- impls.push(type);
- } else {
- this._implementations[iface.name] = [type];
- }
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- } else if ((0, _definition.isAbstractType)(type) && !this._implementations[type.name]) {
- this._implementations[type.name] = [];
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- var _proto = GraphQLSchema.prototype;
- _proto.getQueryType = function getQueryType() {
- return this._queryType;
- };
- _proto.getMutationType = function getMutationType() {
- return this._mutationType;
- };
- _proto.getSubscriptionType = function getSubscriptionType() {
- return this._subscriptionType;
- };
- _proto.getTypeMap = function getTypeMap() {
- return this._typeMap;
- };
- _proto.getType = function getType(name) {
- return this.getTypeMap()[name];
- };
- _proto.getPossibleTypes = function getPossibleTypes(abstractType) {
- if ((0, _definition.isUnionType)(abstractType)) {
- return abstractType.getTypes();
- }
- return this._implementations[abstractType.name];
- };
- _proto.isPossibleType = function isPossibleType(abstractType, possibleType) {
- var possibleTypeMap = this._possibleTypeMap;
- if (!possibleTypeMap[abstractType.name]) {
- var possibleTypes = this.getPossibleTypes(abstractType);
- possibleTypeMap[abstractType.name] = possibleTypes.reduce(function (map, type) {
- return map[type.name] = true, map;
- }, Object.create(null));
- }
- return Boolean(possibleTypeMap[abstractType.name][possibleType.name]);
- };
- _proto.getDirectives = function getDirectives() {
- return this._directives;
- };
- _proto.getDirective = function getDirective(name) {
- return (0, _find.default)(this.getDirectives(), function (directive) {
- return directive.name === name;
- });
- };
- return GraphQLSchema;
- }(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported
- exports.GraphQLSchema = GraphQLSchema;
- (0, _defineToStringTag.default)(GraphQLSchema);
- function typeMapReducer(map, type) {
- if (!type) {
- return map;
- }
- if ((0, _definition.isWrappingType)(type)) {
- return typeMapReducer(map, type.ofType);
- }
- if (map[type.name]) {
- !(map[type.name] === type) ? (0, _invariant.default)(0, 'Schema must contain unique named types but contains multiple ' + "types named \"".concat(type.name, "\".")) : void 0;
- return map;
- }
- map[type.name] = type;
- var reducedMap = map;
- if ((0, _definition.isUnionType)(type)) {
- reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap);
- }
- if ((0, _definition.isObjectType)(type)) {
- reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap);
- }
- if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) {
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var field = _step3.value;
- if (field.args) {
- var fieldArgTypes = field.args.map(function (arg) {
- return arg.type;
- });
- reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap);
- }
- reducedMap = typeMapReducer(reducedMap, field.type);
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- if ((0, _definition.isInputObjectType)(type)) {
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var _field = _step4.value;
- reducedMap = typeMapReducer(reducedMap, _field.type);
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- }
- return reducedMap;
- }
- function typeMapDirectiveReducer(map, directive) {
- // Directives are not validated until validateSchema() is called.
- if (!(0, _directives.isDirective)(directive)) {
- return map;
- }
- return directive.args.reduce(function (_map, arg) {
- return typeMapReducer(_map, arg.type);
- }, map);
- }
- },{"../jsutils/defineToStringTag":287,"../jsutils/inspect":288,"../jsutils/instanceOf":289,"../jsutils/invariant":290,"../polyfills/find":315,"../polyfills/objectValues":319,"./definition":323,"./directives":324,"./introspection":326}],329:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.validateSchema = validateSchema;
- exports.assertValidSchema = assertValidSchema;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _objectEntries = _interopRequireDefault(require("../polyfills/objectEntries"));
- var _definition = require("./definition");
- var _directives = require("./directives");
- var _introspection = require("./introspection");
- var _schema = require("./schema");
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _GraphQLError = require("../error/GraphQLError");
- var _assertValidName = require("../utilities/assertValidName");
- var _typeComparators = require("../utilities/typeComparators");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Implements the "Type Validation" sub-sections of the specification's
- * "Type System" section.
- *
- * Validation runs synchronously, returning an array of encountered errors, or
- * an empty array if no errors were encountered and the Schema is valid.
- */
- function validateSchema(schema) {
- // First check to ensure the provided value is in fact a GraphQLSchema.
- (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results.
- if (schema.__validationErrors) {
- return schema.__validationErrors;
- } // Validate the schema, producing a list of errors.
- var context = new SchemaValidationContext(schema);
- validateRootTypes(context);
- validateDirectives(context);
- validateTypes(context); // Persist the results of validation before returning to ensure validation
- // does not run multiple times for this schema.
- var errors = context.getErrors();
- schema.__validationErrors = errors;
- return errors;
- }
- /**
- * Utility function which asserts a schema is valid by throwing an error if
- * it is invalid.
- */
- function assertValidSchema(schema) {
- var errors = validateSchema(schema);
- if (errors.length !== 0) {
- throw new Error(errors.map(function (error) {
- return error.message;
- }).join('\n\n'));
- }
- }
- var SchemaValidationContext =
- /*#__PURE__*/
- function () {
- function SchemaValidationContext(schema) {
- this._errors = [];
- this.schema = schema;
- }
- var _proto = SchemaValidationContext.prototype;
- _proto.reportError = function reportError(message, nodes) {
- var _nodes = (Array.isArray(nodes) ? nodes : [nodes]).filter(Boolean);
- this.addError(new _GraphQLError.GraphQLError(message, _nodes));
- };
- _proto.addError = function addError(error) {
- this._errors.push(error);
- };
- _proto.getErrors = function getErrors() {
- return this._errors;
- };
- return SchemaValidationContext;
- }();
- function validateRootTypes(context) {
- var schema = context.schema;
- var queryType = schema.getQueryType();
- if (!queryType) {
- context.reportError("Query root type must be provided.", schema.astNode);
- } else if (!(0, _definition.isObjectType)(queryType)) {
- context.reportError("Query root type must be Object type, it cannot be ".concat((0, _inspect.default)(queryType), "."), getOperationTypeNode(schema, queryType, 'query'));
- }
- var mutationType = schema.getMutationType();
- if (mutationType && !(0, _definition.isObjectType)(mutationType)) {
- context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(mutationType), "."), getOperationTypeNode(schema, mutationType, 'mutation'));
- }
- var subscriptionType = schema.getSubscriptionType();
- if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) {
- context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(subscriptionType), "."), getOperationTypeNode(schema, subscriptionType, 'subscription'));
- }
- }
- function getOperationTypeNode(schema, type, operation) {
- var operationNodes = getAllSubNodes(schema, function (node) {
- return node.operationTypes;
- });
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = operationNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var node = _step.value;
- if (node.operation === operation) {
- return node.type;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return type.astNode;
- }
- function validateDirectives(context) {
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = context.schema.getDirectives()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var directive = _step2.value;
- // Ensure all directives are in fact GraphQL directives.
- if (!(0, _directives.isDirective)(directive)) {
- context.reportError("Expected directive but got: ".concat((0, _inspect.default)(directive), "."), directive && directive.astNode);
- continue;
- } // Ensure they are named correctly.
- validateName(context, directive); // TODO: Ensure proper locations.
- // Ensure the arguments are valid.
- var argNames = Object.create(null);
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = directive.args[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var arg = _step3.value;
- var argName = arg.name; // Ensure they are named correctly.
- validateName(context, arg); // Ensure they are unique per directive.
- if (argNames[argName]) {
- context.reportError("Argument @".concat(directive.name, "(").concat(argName, ":) can only be defined once."), getAllDirectiveArgNodes(directive, argName));
- continue;
- }
- argNames[argName] = true; // Ensure the type is an input type.
- if (!(0, _definition.isInputType)(arg.type)) {
- context.reportError("The type of @".concat(directive.name, "(").concat(argName, ":) must be Input Type ") + "but got: ".concat((0, _inspect.default)(arg.type), "."), getDirectiveArgTypeNode(directive, argName));
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- }
- function validateName(context, node) {
- // If a schema explicitly allows some legacy name which is no longer valid,
- // allow it to be assumed valid.
- if (context.schema.__allowedLegacyNames.indexOf(node.name) !== -1) {
- return;
- } // Ensure names are valid, however introspection types opt out.
- var error = (0, _assertValidName.isValidNameError)(node.name, node.astNode || undefined);
- if (error) {
- context.addError(error);
- }
- }
- function validateTypes(context) {
- var typeMap = context.schema.getTypeMap();
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = (0, _objectValues.default)(typeMap)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var type = _step4.value;
- // Ensure all provided types are in fact GraphQL type.
- if (!(0, _definition.isNamedType)(type)) {
- context.reportError("Expected GraphQL named type but got: ".concat((0, _inspect.default)(type), "."), type && type.astNode);
- continue;
- } // Ensure it is named correctly (excluding introspection types).
- if (!(0, _introspection.isIntrospectionType)(type)) {
- validateName(context, type);
- }
- if ((0, _definition.isObjectType)(type)) {
- // Ensure fields are valid
- validateFields(context, type); // Ensure objects implement the interfaces they claim to.
- validateObjectInterfaces(context, type);
- } else if ((0, _definition.isInterfaceType)(type)) {
- // Ensure fields are valid.
- validateFields(context, type);
- } else if ((0, _definition.isUnionType)(type)) {
- // Ensure Unions include valid member types.
- validateUnionMembers(context, type);
- } else if ((0, _definition.isEnumType)(type)) {
- // Ensure Enums have valid values.
- validateEnumValues(context, type);
- } else if ((0, _definition.isInputObjectType)(type)) {
- // Ensure Input Object fields are valid.
- validateInputFields(context, type);
- }
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- }
- function validateFields(context, type) {
- var fields = (0, _objectValues.default)(type.getFields()); // Objects and Interfaces both must define one or more fields.
- if (fields.length === 0) {
- context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type));
- }
- var _iteratorNormalCompletion5 = true;
- var _didIteratorError5 = false;
- var _iteratorError5 = undefined;
- try {
- for (var _iterator5 = fields[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
- var field = _step5.value;
- // Ensure they are named correctly.
- validateName(context, field); // Ensure the type is an output type
- if (!(0, _definition.isOutputType)(field.type)) {
- context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), getFieldTypeNode(type, field.name));
- } // Ensure the arguments are valid
- var argNames = Object.create(null);
- var _iteratorNormalCompletion6 = true;
- var _didIteratorError6 = false;
- var _iteratorError6 = undefined;
- try {
- for (var _iterator6 = field.args[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
- var arg = _step6.value;
- var argName = arg.name; // Ensure they are named correctly.
- validateName(context, arg); // Ensure they are unique per field.
- if (argNames[argName]) {
- context.reportError("Field argument ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) can only ") + 'be defined once.', getAllFieldArgNodes(type, field.name, argName));
- }
- argNames[argName] = true; // Ensure the type is an input type
- if (!(0, _definition.isInputType)(arg.type)) {
- context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat((0, _inspect.default)(arg.type), "."), getFieldArgTypeNode(type, field.name, argName));
- }
- }
- } catch (err) {
- _didIteratorError6 = true;
- _iteratorError6 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
- _iterator6.return();
- }
- } finally {
- if (_didIteratorError6) {
- throw _iteratorError6;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError5 = true;
- _iteratorError5 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
- _iterator5.return();
- }
- } finally {
- if (_didIteratorError5) {
- throw _iteratorError5;
- }
- }
- }
- }
- function validateObjectInterfaces(context, object) {
- var implementedTypeNames = Object.create(null);
- var _iteratorNormalCompletion7 = true;
- var _didIteratorError7 = false;
- var _iteratorError7 = undefined;
- try {
- for (var _iterator7 = object.getInterfaces()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
- var iface = _step7.value;
- if (!(0, _definition.isInterfaceType)(iface)) {
- context.reportError("Type ".concat((0, _inspect.default)(object), " must only implement Interface types, ") + "it cannot implement ".concat((0, _inspect.default)(iface), "."), getImplementsInterfaceNode(object, iface));
- continue;
- }
- if (implementedTypeNames[iface.name]) {
- context.reportError("Type ".concat(object.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(object, iface));
- continue;
- }
- implementedTypeNames[iface.name] = true;
- validateObjectImplementsInterface(context, object, iface);
- }
- } catch (err) {
- _didIteratorError7 = true;
- _iteratorError7 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
- _iterator7.return();
- }
- } finally {
- if (_didIteratorError7) {
- throw _iteratorError7;
- }
- }
- }
- }
- function validateObjectImplementsInterface(context, object, iface) {
- var objectFieldMap = object.getFields();
- var ifaceFieldMap = iface.getFields(); // Assert each interface field is implemented.
- var _iteratorNormalCompletion8 = true;
- var _didIteratorError8 = false;
- var _iteratorError8 = undefined;
- try {
- for (var _iterator8 = (0, _objectEntries.default)(ifaceFieldMap)[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
- var _ref2 = _step8.value;
- var fieldName = _ref2[0];
- var ifaceField = _ref2[1];
- var objectField = objectFieldMap[fieldName]; // Assert interface field exists on object.
- if (!objectField) {
- context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ") + "".concat(object.name, " does not provide it."), [getFieldNode(iface, fieldName)].concat(getAllNodes(object)));
- continue;
- } // Assert interface field type is satisfied by object field type, by being
- // a valid subtype. (covariant)
- if (!(0, _typeComparators.isTypeSubTypeOf)(context.schema, objectField.type, ifaceField.type)) {
- context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat((0, _inspect.default)(ifaceField.type), " but ").concat(object.name, ".").concat(fieldName, " ") + "is type ".concat((0, _inspect.default)(objectField.type), "."), [getFieldTypeNode(iface, fieldName), getFieldTypeNode(object, fieldName)]);
- } // Assert each interface field arg is implemented.
- var _iteratorNormalCompletion9 = true;
- var _didIteratorError9 = false;
- var _iteratorError9 = undefined;
- try {
- var _loop = function _loop() {
- var ifaceArg = _step9.value;
- var argName = ifaceArg.name;
- var objectArg = (0, _find.default)(objectField.args, function (arg) {
- return arg.name === argName;
- }); // Assert interface field arg exists on object field.
- if (!objectArg) {
- context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expected but ".concat(object.name, ".").concat(fieldName, " does not provide it."), [getFieldArgNode(iface, fieldName, argName), getFieldNode(object, fieldName)]);
- return "continue";
- } // Assert interface field arg type matches object field arg type.
- // (invariant)
- // TODO: change to contravariant?
- if (!(0, _typeComparators.isEqualType)(ifaceArg.type, objectArg.type)) {
- context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat((0, _inspect.default)(ifaceArg.type), " but ") + "".concat(object.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat((0, _inspect.default)(objectArg.type), "."), [getFieldArgTypeNode(iface, fieldName, argName), getFieldArgTypeNode(object, fieldName, argName)]);
- } // TODO: validate default values?
- };
- for (var _iterator9 = ifaceField.args[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
- var _ret = _loop();
- if (_ret === "continue") continue;
- } // Assert additional arguments must not be required.
- } catch (err) {
- _didIteratorError9 = true;
- _iteratorError9 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
- _iterator9.return();
- }
- } finally {
- if (_didIteratorError9) {
- throw _iteratorError9;
- }
- }
- }
- var _iteratorNormalCompletion10 = true;
- var _didIteratorError10 = false;
- var _iteratorError10 = undefined;
- try {
- var _loop2 = function _loop2() {
- var objectArg = _step10.value;
- var argName = objectArg.name;
- var ifaceArg = (0, _find.default)(ifaceField.args, function (arg) {
- return arg.name === argName;
- });
- if (!ifaceArg && (0, _definition.isRequiredArgument)(objectArg)) {
- context.reportError("Object field ".concat(object.name, ".").concat(fieldName, " includes required ") + "argument ".concat(argName, " that is missing from the Interface field ") + "".concat(iface.name, ".").concat(fieldName, "."), [getFieldArgNode(object, fieldName, argName), getFieldNode(iface, fieldName)]);
- }
- };
- for (var _iterator10 = objectField.args[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
- _loop2();
- }
- } catch (err) {
- _didIteratorError10 = true;
- _iteratorError10 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
- _iterator10.return();
- }
- } finally {
- if (_didIteratorError10) {
- throw _iteratorError10;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError8 = true;
- _iteratorError8 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
- _iterator8.return();
- }
- } finally {
- if (_didIteratorError8) {
- throw _iteratorError8;
- }
- }
- }
- }
- function validateUnionMembers(context, union) {
- var memberTypes = union.getTypes();
- if (memberTypes.length === 0) {
- context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union));
- }
- var includedTypeNames = Object.create(null);
- var _iteratorNormalCompletion11 = true;
- var _didIteratorError11 = false;
- var _iteratorError11 = undefined;
- try {
- for (var _iterator11 = memberTypes[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
- var memberType = _step11.value;
- if (includedTypeNames[memberType.name]) {
- context.reportError("Union type ".concat(union.name, " can only include type ") + "".concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name));
- continue;
- }
- includedTypeNames[memberType.name] = true;
- if (!(0, _definition.isObjectType)(memberType)) {
- context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat((0, _inspect.default)(memberType), "."), getUnionMemberTypeNodes(union, String(memberType)));
- }
- }
- } catch (err) {
- _didIteratorError11 = true;
- _iteratorError11 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion11 && _iterator11.return != null) {
- _iterator11.return();
- }
- } finally {
- if (_didIteratorError11) {
- throw _iteratorError11;
- }
- }
- }
- }
- function validateEnumValues(context, enumType) {
- var enumValues = enumType.getValues();
- if (enumValues.length === 0) {
- context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType));
- }
- var _iteratorNormalCompletion12 = true;
- var _didIteratorError12 = false;
- var _iteratorError12 = undefined;
- try {
- for (var _iterator12 = enumValues[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
- var enumValue = _step12.value;
- var valueName = enumValue.name; // Ensure valid name.
- validateName(context, enumValue);
- if (valueName === 'true' || valueName === 'false' || valueName === 'null') {
- context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode);
- }
- }
- } catch (err) {
- _didIteratorError12 = true;
- _iteratorError12 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion12 && _iterator12.return != null) {
- _iterator12.return();
- }
- } finally {
- if (_didIteratorError12) {
- throw _iteratorError12;
- }
- }
- }
- }
- function validateInputFields(context, inputObj) {
- var fields = (0, _objectValues.default)(inputObj.getFields());
- if (fields.length === 0) {
- context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj));
- } // Ensure the arguments are valid
- var _iteratorNormalCompletion13 = true;
- var _didIteratorError13 = false;
- var _iteratorError13 = undefined;
- try {
- for (var _iterator13 = fields[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
- var field = _step13.value;
- // Ensure they are named correctly.
- validateName(context, field); // Ensure the type is an input type
- if (!(0, _definition.isInputType)(field.type)) {
- context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), field.astNode && field.astNode.type);
- }
- }
- } catch (err) {
- _didIteratorError13 = true;
- _iteratorError13 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion13 && _iterator13.return != null) {
- _iterator13.return();
- }
- } finally {
- if (_didIteratorError13) {
- throw _iteratorError13;
- }
- }
- }
- }
- function getAllNodes(object) {
- var astNode = object.astNode,
- extensionASTNodes = object.extensionASTNodes;
- return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes || [];
- }
- function getAllSubNodes(object, getter) {
- var result = [];
- var _iteratorNormalCompletion14 = true;
- var _didIteratorError14 = false;
- var _iteratorError14 = undefined;
- try {
- for (var _iterator14 = getAllNodes(object)[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {
- var astNode = _step14.value;
- if (astNode) {
- var subNodes = getter(astNode);
- if (subNodes) {
- result = result.concat(subNodes);
- }
- }
- }
- } catch (err) {
- _didIteratorError14 = true;
- _iteratorError14 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion14 && _iterator14.return != null) {
- _iterator14.return();
- }
- } finally {
- if (_didIteratorError14) {
- throw _iteratorError14;
- }
- }
- }
- return result;
- }
- function getImplementsInterfaceNode(type, iface) {
- return getAllImplementsInterfaceNodes(type, iface)[0];
- }
- function getAllImplementsInterfaceNodes(type, iface) {
- return getAllSubNodes(type, function (typeNode) {
- return typeNode.interfaces;
- }).filter(function (ifaceNode) {
- return ifaceNode.name.value === iface.name;
- });
- }
- function getFieldNode(type, fieldName) {
- return (0, _find.default)(getAllSubNodes(type, function (typeNode) {
- return typeNode.fields;
- }), function (fieldNode) {
- return fieldNode.name.value === fieldName;
- });
- }
- function getFieldTypeNode(type, fieldName) {
- var fieldNode = getFieldNode(type, fieldName);
- return fieldNode && fieldNode.type;
- }
- function getFieldArgNode(type, fieldName, argName) {
- return getAllFieldArgNodes(type, fieldName, argName)[0];
- }
- function getAllFieldArgNodes(type, fieldName, argName) {
- var argNodes = [];
- var fieldNode = getFieldNode(type, fieldName);
- if (fieldNode && fieldNode.arguments) {
- var _iteratorNormalCompletion15 = true;
- var _didIteratorError15 = false;
- var _iteratorError15 = undefined;
- try {
- for (var _iterator15 = fieldNode.arguments[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) {
- var node = _step15.value;
- if (node.name.value === argName) {
- argNodes.push(node);
- }
- }
- } catch (err) {
- _didIteratorError15 = true;
- _iteratorError15 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion15 && _iterator15.return != null) {
- _iterator15.return();
- }
- } finally {
- if (_didIteratorError15) {
- throw _iteratorError15;
- }
- }
- }
- }
- return argNodes;
- }
- function getFieldArgTypeNode(type, fieldName, argName) {
- var fieldArgNode = getFieldArgNode(type, fieldName, argName);
- return fieldArgNode && fieldArgNode.type;
- }
- function getAllDirectiveArgNodes(directive, argName) {
- return getAllSubNodes(directive, function (directiveNode) {
- return directiveNode.arguments;
- }).filter(function (argNode) {
- return argNode.name.value === argName;
- });
- }
- function getDirectiveArgTypeNode(directive, argName) {
- var argNode = getAllDirectiveArgNodes(directive, argName)[0];
- return argNode && argNode.type;
- }
- function getUnionMemberTypeNodes(union, typeName) {
- return getAllSubNodes(union, function (unionNode) {
- return unionNode.types;
- }).filter(function (typeNode) {
- return typeNode.name.value === typeName;
- });
- }
- },{"../error/GraphQLError":275,"../jsutils/inspect":288,"../polyfills/find":315,"../polyfills/objectEntries":318,"../polyfills/objectValues":319,"../utilities/assertValidName":331,"../utilities/typeComparators":350,"./definition":323,"./directives":324,"./introspection":326,"./schema":328}],330:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.TypeInfo = void 0;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _kinds = require("../language/kinds");
- var _definition = require("../type/definition");
- var _introspection = require("../type/introspection");
- var _typeFromAST = require("./typeFromAST");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * TypeInfo is a utility class which, given a GraphQL schema, can keep track
- * of the current field and type definitions at any point in a GraphQL document
- * AST during a recursive descent by calling `enter(node)` and `leave(node)`.
- */
- var TypeInfo =
- /*#__PURE__*/
- function () {
- function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order
- // to support non-spec-compliant codebases. You should never need to use it.
- getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals
- initialType) {
- this._schema = schema;
- this._typeStack = [];
- this._parentTypeStack = [];
- this._inputTypeStack = [];
- this._fieldDefStack = [];
- this._defaultValueStack = [];
- this._directive = null;
- this._argument = null;
- this._enumValue = null;
- this._getFieldDef = getFieldDefFn || getFieldDef;
- if (initialType) {
- if ((0, _definition.isInputType)(initialType)) {
- this._inputTypeStack.push(initialType);
- }
- if ((0, _definition.isCompositeType)(initialType)) {
- this._parentTypeStack.push(initialType);
- }
- if ((0, _definition.isOutputType)(initialType)) {
- this._typeStack.push(initialType);
- }
- }
- }
- var _proto = TypeInfo.prototype;
- _proto.getType = function getType() {
- if (this._typeStack.length > 0) {
- return this._typeStack[this._typeStack.length - 1];
- }
- };
- _proto.getParentType = function getParentType() {
- if (this._parentTypeStack.length > 0) {
- return this._parentTypeStack[this._parentTypeStack.length - 1];
- }
- };
- _proto.getInputType = function getInputType() {
- if (this._inputTypeStack.length > 0) {
- return this._inputTypeStack[this._inputTypeStack.length - 1];
- }
- };
- _proto.getParentInputType = function getParentInputType() {
- if (this._inputTypeStack.length > 1) {
- return this._inputTypeStack[this._inputTypeStack.length - 2];
- }
- };
- _proto.getFieldDef = function getFieldDef() {
- if (this._fieldDefStack.length > 0) {
- return this._fieldDefStack[this._fieldDefStack.length - 1];
- }
- };
- _proto.getDefaultValue = function getDefaultValue() {
- if (this._defaultValueStack.length > 0) {
- return this._defaultValueStack[this._defaultValueStack.length - 1];
- }
- };
- _proto.getDirective = function getDirective() {
- return this._directive;
- };
- _proto.getArgument = function getArgument() {
- return this._argument;
- };
- _proto.getEnumValue = function getEnumValue() {
- return this._enumValue;
- };
- _proto.enter = function enter(node) {
- var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop
- // any assumptions of a valid schema to ensure runtime types are properly
- // checked before continuing since TypeInfo is used as part of validation
- // which occurs before guarantees of schema and document validity.
- switch (node.kind) {
- case _kinds.Kind.SELECTION_SET:
- var namedType = (0, _definition.getNamedType)(this.getType());
- this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined);
- break;
- case _kinds.Kind.FIELD:
- var parentType = this.getParentType();
- var fieldDef;
- var fieldType;
- if (parentType) {
- fieldDef = this._getFieldDef(schema, parentType, node);
- if (fieldDef) {
- fieldType = fieldDef.type;
- }
- }
- this._fieldDefStack.push(fieldDef);
- this._typeStack.push((0, _definition.isOutputType)(fieldType) ? fieldType : undefined);
- break;
- case _kinds.Kind.DIRECTIVE:
- this._directive = schema.getDirective(node.name.value);
- break;
- case _kinds.Kind.OPERATION_DEFINITION:
- var type;
- if (node.operation === 'query') {
- type = schema.getQueryType();
- } else if (node.operation === 'mutation') {
- type = schema.getMutationType();
- } else if (node.operation === 'subscription') {
- type = schema.getSubscriptionType();
- }
- this._typeStack.push((0, _definition.isObjectType)(type) ? type : undefined);
- break;
- case _kinds.Kind.INLINE_FRAGMENT:
- case _kinds.Kind.FRAGMENT_DEFINITION:
- var typeConditionAST = node.typeCondition;
- var outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : (0, _definition.getNamedType)(this.getType());
- this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined);
- break;
- case _kinds.Kind.VARIABLE_DEFINITION:
- var inputType = (0, _typeFromAST.typeFromAST)(schema, node.type);
- this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined);
- break;
- case _kinds.Kind.ARGUMENT:
- var argDef;
- var argType;
- var fieldOrDirective = this.getDirective() || this.getFieldDef();
- if (fieldOrDirective) {
- argDef = (0, _find.default)(fieldOrDirective.args, function (arg) {
- return arg.name === node.name.value;
- });
- if (argDef) {
- argType = argDef.type;
- }
- }
- this._argument = argDef;
- this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);
- this._inputTypeStack.push((0, _definition.isInputType)(argType) ? argType : undefined);
- break;
- case _kinds.Kind.LIST:
- var listType = (0, _definition.getNullableType)(this.getInputType());
- var itemType = (0, _definition.isListType)(listType) ? listType.ofType : listType; // List positions never have a default value.
- this._defaultValueStack.push(undefined);
- this._inputTypeStack.push((0, _definition.isInputType)(itemType) ? itemType : undefined);
- break;
- case _kinds.Kind.OBJECT_FIELD:
- var objectType = (0, _definition.getNamedType)(this.getInputType());
- var inputFieldType;
- var inputField;
- if ((0, _definition.isInputObjectType)(objectType)) {
- inputField = objectType.getFields()[node.name.value];
- if (inputField) {
- inputFieldType = inputField.type;
- }
- }
- this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined);
- this._inputTypeStack.push((0, _definition.isInputType)(inputFieldType) ? inputFieldType : undefined);
- break;
- case _kinds.Kind.ENUM:
- var enumType = (0, _definition.getNamedType)(this.getInputType());
- var enumValue;
- if ((0, _definition.isEnumType)(enumType)) {
- enumValue = enumType.getValue(node.value);
- }
- this._enumValue = enumValue;
- break;
- }
- };
- _proto.leave = function leave(node) {
- switch (node.kind) {
- case _kinds.Kind.SELECTION_SET:
- this._parentTypeStack.pop();
- break;
- case _kinds.Kind.FIELD:
- this._fieldDefStack.pop();
- this._typeStack.pop();
- break;
- case _kinds.Kind.DIRECTIVE:
- this._directive = null;
- break;
- case _kinds.Kind.OPERATION_DEFINITION:
- case _kinds.Kind.INLINE_FRAGMENT:
- case _kinds.Kind.FRAGMENT_DEFINITION:
- this._typeStack.pop();
- break;
- case _kinds.Kind.VARIABLE_DEFINITION:
- this._inputTypeStack.pop();
- break;
- case _kinds.Kind.ARGUMENT:
- this._argument = null;
- this._defaultValueStack.pop();
- this._inputTypeStack.pop();
- break;
- case _kinds.Kind.LIST:
- case _kinds.Kind.OBJECT_FIELD:
- this._defaultValueStack.pop();
- this._inputTypeStack.pop();
- break;
- case _kinds.Kind.ENUM:
- this._enumValue = null;
- break;
- }
- };
- return TypeInfo;
- }();
- /**
- * Not exactly the same as the executor's definition of getFieldDef, in this
- * statically evaluated environment we do not always have an Object type,
- * and need to handle Interface and Union types.
- */
- exports.TypeInfo = TypeInfo;
- function getFieldDef(schema, parentType, fieldNode) {
- var name = fieldNode.name.value;
- if (name === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
- return _introspection.SchemaMetaFieldDef;
- }
- if (name === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
- return _introspection.TypeMetaFieldDef;
- }
- if (name === _introspection.TypeNameMetaFieldDef.name && (0, _definition.isCompositeType)(parentType)) {
- return _introspection.TypeNameMetaFieldDef;
- }
- if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) {
- return parentType.getFields()[name];
- }
- }
- },{"../language/kinds":307,"../polyfills/find":315,"../type/definition":323,"../type/introspection":326,"./typeFromAST":351}],331:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.assertValidName = assertValidName;
- exports.isValidNameError = isValidNameError;
- var _GraphQLError = require("../error/GraphQLError");
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
- /**
- * Upholds the spec rules about naming.
- */
- function assertValidName(name) {
- var error = isValidNameError(name);
- if (error) {
- throw error;
- }
- return name;
- }
- /**
- * Returns an Error if a name is invalid.
- */
- function isValidNameError(name, node) {
- !(typeof name === 'string') ? (0, _invariant.default)(0, 'Expected string') : void 0;
- if (name.length > 1 && name[0] === '_' && name[1] === '_') {
- return new _GraphQLError.GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by ") + 'GraphQL introspection.', node);
- }
- if (!NAME_RX.test(name)) {
- return new _GraphQLError.GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."), node);
- }
- }
- },{"../error/GraphQLError":275,"../jsutils/invariant":290}],332:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.astFromValue = astFromValue;
- var _iterall = require("iterall");
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _isNullish = _interopRequireDefault(require("../jsutils/isNullish"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _kinds = require("../language/kinds");
- var _definition = require("../type/definition");
- var _scalars = require("../type/scalars");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- /**
- * Produces a GraphQL Value AST given a JavaScript value.
- *
- * A GraphQL type must be provided, which will be used to interpret different
- * JavaScript values.
- *
- * | JSON Value | GraphQL Value |
- * | ------------- | -------------------- |
- * | Object | Input Object |
- * | Array | List |
- * | Boolean | Boolean |
- * | String | String / Enum Value |
- * | Number | Int / Float |
- * | Mixed | Enum Value |
- * | null | NullValue |
- *
- */
- function astFromValue(value, type) {
- if ((0, _definition.isNonNullType)(type)) {
- var astValue = astFromValue(value, type.ofType);
- if (astValue && astValue.kind === _kinds.Kind.NULL) {
- return null;
- }
- return astValue;
- } // only explicit null, not undefined, NaN
- if (value === null) {
- return {
- kind: _kinds.Kind.NULL
- };
- } // undefined, NaN
- if ((0, _isInvalid.default)(value)) {
- return null;
- } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
- // the value is not an array, convert the value using the list's item type.
- if ((0, _definition.isListType)(type)) {
- var itemType = type.ofType;
- if ((0, _iterall.isCollection)(value)) {
- var valuesNodes = [];
- (0, _iterall.forEach)(value, function (item) {
- var itemNode = astFromValue(item, itemType);
- if (itemNode) {
- valuesNodes.push(itemNode);
- }
- });
- return {
- kind: _kinds.Kind.LIST,
- values: valuesNodes
- };
- }
- return astFromValue(value, itemType);
- } // Populate the fields of the input object by creating ASTs from each value
- // in the JavaScript object according to the fields in the input type.
- if ((0, _definition.isInputObjectType)(type)) {
- if (value === null || _typeof(value) !== 'object') {
- return null;
- }
- var fields = (0, _objectValues.default)(type.getFields());
- var fieldNodes = [];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var field = _step.value;
- var fieldValue = astFromValue(value[field.name], field.type);
- if (fieldValue) {
- fieldNodes.push({
- kind: _kinds.Kind.OBJECT_FIELD,
- name: {
- kind: _kinds.Kind.NAME,
- value: field.name
- },
- value: fieldValue
- });
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return {
- kind: _kinds.Kind.OBJECT,
- fields: fieldNodes
- };
- }
- if ((0, _definition.isScalarType)(type) || (0, _definition.isEnumType)(type)) {
- // Since value is an internally represented value, it must be serialized
- // to an externally represented value before converting into an AST.
- var serialized = type.serialize(value);
- if ((0, _isNullish.default)(serialized)) {
- return null;
- } // Others serialize based on their corresponding JavaScript scalar types.
- if (typeof serialized === 'boolean') {
- return {
- kind: _kinds.Kind.BOOLEAN,
- value: serialized
- };
- } // JavaScript numbers can be Int or Float values.
- if (typeof serialized === 'number') {
- var stringNum = String(serialized);
- return integerStringRegExp.test(stringNum) ? {
- kind: _kinds.Kind.INT,
- value: stringNum
- } : {
- kind: _kinds.Kind.FLOAT,
- value: stringNum
- };
- }
- if (typeof serialized === 'string') {
- // Enum types use Enum literals.
- if ((0, _definition.isEnumType)(type)) {
- return {
- kind: _kinds.Kind.ENUM,
- value: serialized
- };
- } // ID types can use Int literals.
- if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) {
- return {
- kind: _kinds.Kind.INT,
- value: serialized
- };
- }
- return {
- kind: _kinds.Kind.STRING,
- value: serialized
- };
- }
- throw new TypeError("Cannot convert value to AST: ".concat((0, _inspect.default)(serialized)));
- }
- /* istanbul ignore next */
- throw new Error("Unknown type: ".concat(type, "."));
- }
- /**
- * IntValue:
- * - NegativeSign? 0
- * - NegativeSign? NonZeroDigit ( Digit+ )?
- */
- var integerStringRegExp = /^-?(0|[1-9][0-9]*)$/;
- },{"../jsutils/inspect":288,"../jsutils/isInvalid":291,"../jsutils/isNullish":292,"../language/kinds":307,"../polyfills/objectValues":319,"../type/definition":323,"../type/scalars":327,"iterall":137}],333:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.buildASTSchema = buildASTSchema;
- exports.getDescription = getDescription;
- exports.buildSchema = buildSchema;
- exports.ASTDefinitionBuilder = void 0;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _valueFromAST = require("./valueFromAST");
- var _validate = require("../validation/validate");
- var _blockStringValue = _interopRequireDefault(require("../language/blockStringValue"));
- var _lexer = require("../language/lexer");
- var _parser = require("../language/parser");
- var _values = require("../execution/values");
- var _kinds = require("../language/kinds");
- var _predicates = require("../language/predicates");
- var _definition = require("../type/definition");
- var _directives = require("../type/directives");
- var _introspection = require("../type/introspection");
- var _scalars = require("../type/scalars");
- var _schema = require("../type/schema");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * This takes the ast of a schema document produced by the parse function in
- * src/language/parser.js.
- *
- * If no schema definition is provided, then it will look for types named Query
- * and Mutation.
- *
- * Given that AST it constructs a GraphQLSchema. The resulting schema
- * has no resolve methods, so execution will use default resolvers.
- *
- * Accepts options as a second argument:
- *
- * - commentDescriptions:
- * Provide true to use preceding comments as the description.
- *
- */
- function buildASTSchema(documentAST, options) {
- !(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0;
- if (!options || !(options.assumeValid || options.assumeValidSDL)) {
- (0, _validate.assertValidSDL)(documentAST);
- }
- var schemaDef;
- var nodeMap = Object.create(null);
- var directiveDefs = [];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = documentAST.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var def = _step.value;
- if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) {
- schemaDef = def;
- } else if ((0, _predicates.isTypeDefinitionNode)(def)) {
- nodeMap[def.name.value] = def;
- } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- directiveDefs.push(def);
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var operationTypes = schemaDef ? getOperationTypes(schemaDef) : {
- query: nodeMap.Query,
- mutation: nodeMap.Mutation,
- subscription: nodeMap.Subscription
- };
- var definitionBuilder = new ASTDefinitionBuilder(nodeMap, options, function (typeName) {
- throw new Error("Type \"".concat(typeName, "\" not found in document."));
- });
- var directives = directiveDefs.map(function (def) {
- return definitionBuilder.buildDirective(def);
- }); // If specified directives were not explicitly declared, add them.
- if (!directives.some(function (directive) {
- return directive.name === 'skip';
- })) {
- directives.push(_directives.GraphQLSkipDirective);
- }
- if (!directives.some(function (directive) {
- return directive.name === 'include';
- })) {
- directives.push(_directives.GraphQLIncludeDirective);
- }
- if (!directives.some(function (directive) {
- return directive.name === 'deprecated';
- })) {
- directives.push(_directives.GraphQLDeprecatedDirective);
- } // Note: While this could make early assertions to get the correctly
- // typed values below, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- return new _schema.GraphQLSchema({
- query: operationTypes.query ? definitionBuilder.buildType(operationTypes.query) : null,
- mutation: operationTypes.mutation ? definitionBuilder.buildType(operationTypes.mutation) : null,
- subscription: operationTypes.subscription ? definitionBuilder.buildType(operationTypes.subscription) : null,
- types: (0, _objectValues.default)(nodeMap).map(function (node) {
- return definitionBuilder.buildType(node);
- }),
- directives: directives,
- astNode: schemaDef,
- assumeValid: options && options.assumeValid,
- allowedLegacyNames: options && options.allowedLegacyNames
- });
- function getOperationTypes(schema) {
- var opTypes = {};
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = schema.operationTypes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var operationType = _step2.value;
- opTypes[operationType.operation] = operationType.type;
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return opTypes;
- }
- }
- var ASTDefinitionBuilder =
- /*#__PURE__*/
- function () {
- function ASTDefinitionBuilder(typeDefinitionsMap, options, resolveType) {
- this._typeDefinitionsMap = typeDefinitionsMap;
- this._options = options;
- this._resolveType = resolveType; // Initialize to the GraphQL built in scalars and introspection types.
- this._cache = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) {
- return type.name;
- });
- }
- var _proto = ASTDefinitionBuilder.prototype;
- _proto.buildType = function buildType(node) {
- var typeName = node.name.value;
- if (!this._cache[typeName]) {
- if (node.kind === _kinds.Kind.NAMED_TYPE) {
- var defNode = this._typeDefinitionsMap[typeName];
- this._cache[typeName] = defNode ? this._makeSchemaDef(defNode) : this._resolveType(node.name.value);
- } else {
- this._cache[typeName] = this._makeSchemaDef(node);
- }
- }
- return this._cache[typeName];
- };
- _proto._buildWrappedType = function _buildWrappedType(typeNode) {
- if (typeNode.kind === _kinds.Kind.LIST_TYPE) {
- return (0, _definition.GraphQLList)(this._buildWrappedType(typeNode.type));
- }
- if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) {
- return (0, _definition.GraphQLNonNull)( // Note: GraphQLNonNull constructor validates this type
- this._buildWrappedType(typeNode.type));
- }
- return this.buildType(typeNode);
- };
- _proto.buildDirective = function buildDirective(directive) {
- var _this = this;
- var locations = directive.locations.map(function (_ref) {
- var value = _ref.value;
- return value;
- });
- return new _directives.GraphQLDirective({
- name: directive.name.value,
- description: getDescription(directive, this._options),
- locations: locations,
- args: keyByNameNode(directive.arguments || [], function (arg) {
- return _this.buildArg(arg);
- }),
- astNode: directive
- });
- };
- _proto.buildField = function buildField(field) {
- var _this2 = this;
- return {
- // Note: While this could make assertions to get the correctly typed
- // value, that would throw immediately while type system validation
- // with validateSchema() will produce more actionable results.
- type: this._buildWrappedType(field.type),
- description: getDescription(field, this._options),
- args: keyByNameNode(field.arguments || [], function (arg) {
- return _this2.buildArg(arg);
- }),
- deprecationReason: getDeprecationReason(field),
- astNode: field
- };
- };
- _proto.buildArg = function buildArg(value) {
- // Note: While this could make assertions to get the correctly typed
- // value, that would throw immediately while type system validation
- var type = this._buildWrappedType(value.type);
- return {
- type: type,
- description: getDescription(value, this._options),
- defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type),
- astNode: value
- };
- };
- _proto.buildInputField = function buildInputField(value) {
- // Note: While this could make assertions to get the correctly typed
- // value, that would throw immediately while type system validation
- var type = this._buildWrappedType(value.type);
- return {
- type: type,
- description: getDescription(value, this._options),
- defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type),
- astNode: value
- };
- };
- _proto.buildEnumValue = function buildEnumValue(value) {
- return {
- description: getDescription(value, this._options),
- deprecationReason: getDeprecationReason(value),
- astNode: value
- };
- };
- _proto._makeSchemaDef = function _makeSchemaDef(astNode) {
- switch (astNode.kind) {
- case _kinds.Kind.OBJECT_TYPE_DEFINITION:
- return this._makeTypeDef(astNode);
- case _kinds.Kind.INTERFACE_TYPE_DEFINITION:
- return this._makeInterfaceDef(astNode);
- case _kinds.Kind.ENUM_TYPE_DEFINITION:
- return this._makeEnumDef(astNode);
- case _kinds.Kind.UNION_TYPE_DEFINITION:
- return this._makeUnionDef(astNode);
- case _kinds.Kind.SCALAR_TYPE_DEFINITION:
- return this._makeScalarDef(astNode);
- case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION:
- return this._makeInputObjectDef(astNode);
- default:
- throw new Error("Type kind \"".concat(astNode.kind, "\" not supported."));
- }
- };
- _proto._makeTypeDef = function _makeTypeDef(astNode) {
- var _this3 = this;
- var interfaceNodes = astNode.interfaces;
- var fieldNodes = astNode.fields; // Note: While this could make assertions to get the correctly typed
- // values below, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- var interfaces = interfaceNodes && interfaceNodes.length > 0 ? function () {
- return interfaceNodes.map(function (ref) {
- return _this3.buildType(ref);
- });
- } : [];
- var fields = fieldNodes && fieldNodes.length > 0 ? function () {
- return keyByNameNode(fieldNodes, function (field) {
- return _this3.buildField(field);
- });
- } : Object.create(null);
- return new _definition.GraphQLObjectType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- interfaces: interfaces,
- fields: fields,
- astNode: astNode
- });
- };
- _proto._makeInterfaceDef = function _makeInterfaceDef(astNode) {
- var _this4 = this;
- var fieldNodes = astNode.fields;
- var fields = fieldNodes && fieldNodes.length > 0 ? function () {
- return keyByNameNode(fieldNodes, function (field) {
- return _this4.buildField(field);
- });
- } : Object.create(null);
- return new _definition.GraphQLInterfaceType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- fields: fields,
- astNode: astNode
- });
- };
- _proto._makeEnumDef = function _makeEnumDef(astNode) {
- var _this5 = this;
- var valueNodes = astNode.values || [];
- return new _definition.GraphQLEnumType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- values: keyByNameNode(valueNodes, function (value) {
- return _this5.buildEnumValue(value);
- }),
- astNode: astNode
- });
- };
- _proto._makeUnionDef = function _makeUnionDef(astNode) {
- var _this6 = this;
- var typeNodes = astNode.types; // Note: While this could make assertions to get the correctly typed
- // values below, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- var types = typeNodes && typeNodes.length > 0 ? function () {
- return typeNodes.map(function (ref) {
- return _this6.buildType(ref);
- });
- } : [];
- return new _definition.GraphQLUnionType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- types: types,
- astNode: astNode
- });
- };
- _proto._makeScalarDef = function _makeScalarDef(astNode) {
- return new _definition.GraphQLScalarType({
- name: astNode.name.value,
- description: getDescription(astNode, this._options),
- astNode: astNode,
- serialize: function serialize(value) {
- return value;
- }
- });
- };
- _proto._makeInputObjectDef = function _makeInputObjectDef(def) {
- var _this7 = this;
- var fields = def.fields;
- return new _definition.GraphQLInputObjectType({
- name: def.name.value,
- description: getDescription(def, this._options),
- fields: fields ? function () {
- return keyByNameNode(fields, function (field) {
- return _this7.buildInputField(field);
- });
- } : Object.create(null),
- astNode: def
- });
- };
- return ASTDefinitionBuilder;
- }();
- exports.ASTDefinitionBuilder = ASTDefinitionBuilder;
- function keyByNameNode(list, valFn) {
- return (0, _keyValMap.default)(list, function (_ref2) {
- var name = _ref2.name;
- return name.value;
- }, valFn);
- }
- /**
- * Given a field or enum value node, returns the string value for the
- * deprecation reason.
- */
- function getDeprecationReason(node) {
- var deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node);
- return deprecated && deprecated.reason;
- }
- /**
- * Given an ast node, returns its string description.
- * @deprecated: provided to ease adoption and will be removed in v16.
- *
- * Accepts options as a second argument:
- *
- * - commentDescriptions:
- * Provide true to use preceding comments as the description.
- *
- */
- function getDescription(node, options) {
- if (node.description) {
- return node.description.value;
- }
- if (options && options.commentDescriptions) {
- var rawValue = getLeadingCommentBlock(node);
- if (rawValue !== undefined) {
- return (0, _blockStringValue.default)('\n' + rawValue);
- }
- }
- }
- function getLeadingCommentBlock(node) {
- var loc = node.loc;
- if (!loc) {
- return;
- }
- var comments = [];
- var token = loc.startToken.prev;
- while (token && token.kind === _lexer.TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) {
- var value = String(token.value);
- comments.push(value);
- token = token.prev;
- }
- return comments.reverse().join('\n');
- }
- /**
- * A helper function to build a GraphQLSchema directly from a source
- * document.
- */
- function buildSchema(source, options) {
- return buildASTSchema((0, _parser.parse)(source, options), options);
- }
- },{"../execution/values":283,"../jsutils/invariant":290,"../jsutils/keyMap":294,"../jsutils/keyValMap":295,"../language/blockStringValue":304,"../language/kinds":307,"../language/lexer":308,"../language/parser":310,"../language/predicates":311,"../polyfills/objectValues":319,"../type/definition":323,"../type/directives":324,"../type/introspection":326,"../type/scalars":327,"../type/schema":328,"../validation/validate":390,"./valueFromAST":352}],334:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.buildClientSchema = buildClientSchema;
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _valueFromAST = require("./valueFromAST");
- var _parser = require("../language/parser");
- var _schema = require("../type/schema");
- var _definition = require("../type/definition");
- var _directives = require("../type/directives");
- var _introspection = require("../type/introspection");
- var _scalars = require("../type/scalars");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Build a GraphQLSchema for use by client tools.
- *
- * Given the result of a client running the introspection query, creates and
- * returns a GraphQLSchema instance which can be then used with all graphql-js
- * tools, but cannot be used to execute a query, as introspection does not
- * represent the "resolver", "parse" or "serialize" functions or any other
- * server-internal mechanisms.
- *
- * This function expects a complete introspection result. Don't forget to check
- * the "errors" field of a server response before calling this function.
- */
- function buildClientSchema(introspection, options) {
- // Get the schema from the introspection result.
- var schemaIntrospection = introspection.__schema; // Converts the list of types into a keyMap based on the type names.
- var typeIntrospectionMap = (0, _keyMap.default)(schemaIntrospection.types, function (type) {
- return type.name;
- }); // A cache to use to store the actual GraphQLType definition objects by name.
- // Initialize to the GraphQL built in scalars. All functions below are inline
- // so that this type def cache is within the scope of the closure.
- var typeDefCache = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) {
- return type.name;
- }); // Given a type reference in introspection, return the GraphQLType instance.
- // preferring cached instances before building new instances.
- function getType(typeRef) {
- if (typeRef.kind === _introspection.TypeKind.LIST) {
- var itemRef = typeRef.ofType;
- if (!itemRef) {
- throw new Error('Decorated type deeper than introspection query.');
- }
- return (0, _definition.GraphQLList)(getType(itemRef));
- }
- if (typeRef.kind === _introspection.TypeKind.NON_NULL) {
- var nullableRef = typeRef.ofType;
- if (!nullableRef) {
- throw new Error('Decorated type deeper than introspection query.');
- }
- var nullableType = getType(nullableRef);
- return (0, _definition.GraphQLNonNull)((0, _definition.assertNullableType)(nullableType));
- }
- if (!typeRef.name) {
- throw new Error('Unknown type reference: ' + (0, _inspect.default)(typeRef));
- }
- return getNamedType(typeRef.name);
- }
- function getNamedType(typeName) {
- if (typeDefCache[typeName]) {
- return typeDefCache[typeName];
- }
- var typeIntrospection = typeIntrospectionMap[typeName];
- if (!typeIntrospection) {
- throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure ") + 'that a full introspection query is used in order to build a ' + 'client schema.');
- }
- var typeDef = buildType(typeIntrospection);
- typeDefCache[typeName] = typeDef;
- return typeDef;
- }
- function getInputType(typeRef) {
- var type = getType(typeRef);
- !(0, _definition.isInputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide input type for arguments, but received: ' + (0, _inspect.default)(type) + '.') : void 0;
- return type;
- }
- function getOutputType(typeRef) {
- var type = getType(typeRef);
- !(0, _definition.isOutputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide output type for fields, but received: ' + (0, _inspect.default)(type) + '.') : void 0;
- return type;
- }
- function getObjectType(typeRef) {
- var type = getType(typeRef);
- return (0, _definition.assertObjectType)(type);
- }
- function getInterfaceType(typeRef) {
- var type = getType(typeRef);
- return (0, _definition.assertInterfaceType)(type);
- } // Given a type's introspection result, construct the correct
- // GraphQLType instance.
- function buildType(type) {
- if (type && type.name && type.kind) {
- switch (type.kind) {
- case _introspection.TypeKind.SCALAR:
- return buildScalarDef(type);
- case _introspection.TypeKind.OBJECT:
- return buildObjectDef(type);
- case _introspection.TypeKind.INTERFACE:
- return buildInterfaceDef(type);
- case _introspection.TypeKind.UNION:
- return buildUnionDef(type);
- case _introspection.TypeKind.ENUM:
- return buildEnumDef(type);
- case _introspection.TypeKind.INPUT_OBJECT:
- return buildInputObjectDef(type);
- }
- }
- throw new Error('Invalid or incomplete introspection result. Ensure that a full ' + 'introspection query is used in order to build a client schema:' + (0, _inspect.default)(type));
- }
- function buildScalarDef(scalarIntrospection) {
- return new _definition.GraphQLScalarType({
- name: scalarIntrospection.name,
- description: scalarIntrospection.description,
- serialize: function serialize(value) {
- return value;
- }
- });
- }
- function buildObjectDef(objectIntrospection) {
- if (!objectIntrospection.interfaces) {
- throw new Error('Introspection result missing interfaces: ' + (0, _inspect.default)(objectIntrospection));
- }
- return new _definition.GraphQLObjectType({
- name: objectIntrospection.name,
- description: objectIntrospection.description,
- interfaces: function interfaces() {
- return objectIntrospection.interfaces.map(getInterfaceType);
- },
- fields: function fields() {
- return buildFieldDefMap(objectIntrospection);
- }
- });
- }
- function buildInterfaceDef(interfaceIntrospection) {
- return new _definition.GraphQLInterfaceType({
- name: interfaceIntrospection.name,
- description: interfaceIntrospection.description,
- fields: function fields() {
- return buildFieldDefMap(interfaceIntrospection);
- }
- });
- }
- function buildUnionDef(unionIntrospection) {
- if (!unionIntrospection.possibleTypes) {
- throw new Error('Introspection result missing possibleTypes: ' + (0, _inspect.default)(unionIntrospection));
- }
- return new _definition.GraphQLUnionType({
- name: unionIntrospection.name,
- description: unionIntrospection.description,
- types: function types() {
- return unionIntrospection.possibleTypes.map(getObjectType);
- }
- });
- }
- function buildEnumDef(enumIntrospection) {
- if (!enumIntrospection.enumValues) {
- throw new Error('Introspection result missing enumValues: ' + (0, _inspect.default)(enumIntrospection));
- }
- return new _definition.GraphQLEnumType({
- name: enumIntrospection.name,
- description: enumIntrospection.description,
- values: (0, _keyValMap.default)(enumIntrospection.enumValues, function (valueIntrospection) {
- return valueIntrospection.name;
- }, function (valueIntrospection) {
- return {
- description: valueIntrospection.description,
- deprecationReason: valueIntrospection.deprecationReason
- };
- })
- });
- }
- function buildInputObjectDef(inputObjectIntrospection) {
- if (!inputObjectIntrospection.inputFields) {
- throw new Error('Introspection result missing inputFields: ' + (0, _inspect.default)(inputObjectIntrospection));
- }
- return new _definition.GraphQLInputObjectType({
- name: inputObjectIntrospection.name,
- description: inputObjectIntrospection.description,
- fields: function fields() {
- return buildInputValueDefMap(inputObjectIntrospection.inputFields);
- }
- });
- }
- function buildFieldDefMap(typeIntrospection) {
- if (!typeIntrospection.fields) {
- throw new Error('Introspection result missing fields: ' + (0, _inspect.default)(typeIntrospection));
- }
- return (0, _keyValMap.default)(typeIntrospection.fields, function (fieldIntrospection) {
- return fieldIntrospection.name;
- }, function (fieldIntrospection) {
- if (!fieldIntrospection.args) {
- throw new Error('Introspection result missing field args: ' + (0, _inspect.default)(fieldIntrospection));
- }
- return {
- description: fieldIntrospection.description,
- deprecationReason: fieldIntrospection.deprecationReason,
- type: getOutputType(fieldIntrospection.type),
- args: buildInputValueDefMap(fieldIntrospection.args)
- };
- });
- }
- function buildInputValueDefMap(inputValueIntrospections) {
- return (0, _keyValMap.default)(inputValueIntrospections, function (inputValue) {
- return inputValue.name;
- }, buildInputValue);
- }
- function buildInputValue(inputValueIntrospection) {
- var type = getInputType(inputValueIntrospection.type);
- var defaultValue = inputValueIntrospection.defaultValue ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined;
- return {
- description: inputValueIntrospection.description,
- type: type,
- defaultValue: defaultValue
- };
- }
- function buildDirective(directiveIntrospection) {
- if (!directiveIntrospection.args) {
- throw new Error('Introspection result missing directive args: ' + (0, _inspect.default)(directiveIntrospection));
- }
- if (!directiveIntrospection.locations) {
- throw new Error('Introspection result missing directive locations: ' + (0, _inspect.default)(directiveIntrospection));
- }
- return new _directives.GraphQLDirective({
- name: directiveIntrospection.name,
- description: directiveIntrospection.description,
- locations: directiveIntrospection.locations.slice(),
- args: buildInputValueDefMap(directiveIntrospection.args)
- });
- } // Iterate through all types, getting the type definition for each, ensuring
- // that any type not directly referenced by a field will get created.
- var types = schemaIntrospection.types.map(function (typeIntrospection) {
- return getNamedType(typeIntrospection.name);
- }); // Get the root Query, Mutation, and Subscription types.
- var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null;
- var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null;
- var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if
- // directives were not queried for.
- var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types.
- return new _schema.GraphQLSchema({
- query: queryType,
- mutation: mutationType,
- subscription: subscriptionType,
- types: types,
- directives: directives,
- assumeValid: options && options.assumeValid,
- allowedLegacyNames: options && options.allowedLegacyNames
- });
- }
- },{"../jsutils/inspect":288,"../jsutils/invariant":290,"../jsutils/keyMap":294,"../jsutils/keyValMap":295,"../language/parser":310,"../type/definition":323,"../type/directives":324,"../type/introspection":326,"../type/scalars":327,"../type/schema":328,"./valueFromAST":352}],335:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.coerceValue = coerceValue;
- var _iterall = require("iterall");
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _orList = _interopRequireDefault(require("../jsutils/orList"));
- var _suggestionList = _interopRequireDefault(require("../jsutils/suggestionList"));
- var _GraphQLError = require("../error/GraphQLError");
- var _definition = require("../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
- /**
- * Coerces a JavaScript value given a GraphQL Type.
- *
- * Returns either a value which is valid for the provided type or a list of
- * encountered coercion errors.
- *
- */
- function coerceValue(value, type, blameNode, path) {
- // A value must be provided if the type is non-null.
- if ((0, _definition.isNonNullType)(type)) {
- if (value == null) {
- return ofErrors([coercionError("Expected non-nullable type ".concat((0, _inspect.default)(type), " not to be null"), blameNode, path)]);
- }
- return coerceValue(value, type.ofType, blameNode, path);
- }
- if (value == null) {
- // Explicitly return the value null.
- return ofValue(null);
- }
- if ((0, _definition.isScalarType)(type)) {
- // Scalars determine if a value is valid via parseValue(), which can
- // throw to indicate failure. If it throws, maintain a reference to
- // the original error.
- try {
- var parseResult = type.parseValue(value);
- if ((0, _isInvalid.default)(parseResult)) {
- return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path)]);
- }
- return ofValue(parseResult);
- } catch (error) {
- return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, error.message, error)]);
- }
- }
- if ((0, _definition.isEnumType)(type)) {
- if (typeof value === 'string') {
- var enumValue = type.getValue(value);
- if (enumValue) {
- return ofValue(enumValue.value);
- }
- }
- var suggestions = (0, _suggestionList.default)(String(value), type.getValues().map(function (enumValue) {
- return enumValue.name;
- }));
- var didYouMean = suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(suggestions), "?") : undefined;
- return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, didYouMean)]);
- }
- if ((0, _definition.isListType)(type)) {
- var itemType = type.ofType;
- if ((0, _iterall.isCollection)(value)) {
- var errors;
- var coercedValue = [];
- (0, _iterall.forEach)(value, function (itemValue, index) {
- var coercedItem = coerceValue(itemValue, itemType, blameNode, atPath(path, index));
- if (coercedItem.errors) {
- errors = add(errors, coercedItem.errors);
- } else if (!errors) {
- coercedValue.push(coercedItem.value);
- }
- });
- return errors ? ofErrors(errors) : ofValue(coercedValue);
- } // Lists accept a non-list value as a list of one.
- var coercedItem = coerceValue(value, itemType, blameNode);
- return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]);
- }
- if ((0, _definition.isInputObjectType)(type)) {
- if (_typeof(value) !== 'object') {
- return ofErrors([coercionError("Expected type ".concat(type.name, " to be an object"), blameNode, path)]);
- }
- var _errors;
- var _coercedValue = {};
- var fields = type.getFields(); // Ensure every defined field is valid.
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectValues.default)(fields)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var field = _step.value;
- var fieldValue = value[field.name];
- if ((0, _isInvalid.default)(fieldValue)) {
- if (!(0, _isInvalid.default)(field.defaultValue)) {
- _coercedValue[field.name] = field.defaultValue;
- } else if ((0, _definition.isNonNullType)(field.type)) {
- _errors = add(_errors, coercionError("Field ".concat(printPath(atPath(path, field.name)), " of required ") + "type ".concat((0, _inspect.default)(field.type), " was not provided"), blameNode));
- }
- } else {
- var coercedField = coerceValue(fieldValue, field.type, blameNode, atPath(path, field.name));
- if (coercedField.errors) {
- _errors = add(_errors, coercedField.errors);
- } else if (!_errors) {
- _coercedValue[field.name] = coercedField.value;
- }
- }
- } // Ensure every provided field is defined.
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var _arr = Object.keys(value);
- for (var _i = 0; _i < _arr.length; _i++) {
- var fieldName = _arr[_i];
- if (!fields[fieldName]) {
- var _suggestions = (0, _suggestionList.default)(fieldName, Object.keys(fields));
- var _didYouMean = _suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(_suggestions), "?") : undefined;
- _errors = add(_errors, coercionError("Field \"".concat(fieldName, "\" is not defined by type ").concat(type.name), blameNode, path, _didYouMean));
- }
- }
- return _errors ? ofErrors(_errors) : ofValue(_coercedValue);
- }
- /* istanbul ignore next */
- throw new Error("Unexpected type: ".concat(type, "."));
- }
- function ofValue(value) {
- return {
- errors: undefined,
- value: value
- };
- }
- function ofErrors(errors) {
- return {
- errors: errors,
- value: undefined
- };
- }
- function add(errors, moreErrors) {
- return (errors || []).concat(moreErrors);
- }
- function atPath(prev, key) {
- return {
- prev: prev,
- key: key
- };
- }
- function coercionError(message, blameNode, path, subMessage, originalError) {
- var pathStr = printPath(path); // Return a GraphQLError instance
- return new _GraphQLError.GraphQLError(message + (pathStr ? ' at ' + pathStr : '') + (subMessage ? '; ' + subMessage : '.'), blameNode, undefined, undefined, undefined, originalError);
- } // Build a string describing the path into the value where the error was found
- function printPath(path) {
- var pathStr = '';
- var currentPath = path;
- while (currentPath) {
- pathStr = (typeof currentPath.key === 'string' ? '.' + currentPath.key : '[' + String(currentPath.key) + ']') + pathStr;
- currentPath = currentPath.prev;
- }
- return pathStr ? 'value' + pathStr : '';
- }
- },{"../error/GraphQLError":275,"../jsutils/inspect":288,"../jsutils/isInvalid":291,"../jsutils/orList":299,"../jsutils/suggestionList":303,"../polyfills/objectValues":319,"../type/definition":323,"iterall":137}],336:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.concatAST = concatAST;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Provided a collection of ASTs, presumably each from different files,
- * concatenate the ASTs together into batched AST, useful for validating many
- * GraphQL source files which together represent one conceptual application.
- */
- function concatAST(asts) {
- var batchDefinitions = [];
- for (var i = 0; i < asts.length; i++) {
- var definitions = asts[i].definitions;
- for (var j = 0; j < definitions.length; j++) {
- batchDefinitions.push(definitions[j]);
- }
- }
- return {
- kind: 'Document',
- definitions: batchDefinitions
- };
- }
- },{}],337:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.extendSchema = extendSchema;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _mapValue = _interopRequireDefault(require("../jsutils/mapValue"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _buildASTSchema = require("./buildASTSchema");
- var _validate = require("../validation/validate");
- var _schema = require("../type/schema");
- var _introspection = require("../type/introspection");
- var _scalars = require("../type/scalars");
- var _definition = require("../type/definition");
- var _directives = require("../type/directives");
- var _kinds = require("../language/kinds");
- var _predicates = require("../language/predicates");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * Produces a new schema given an existing schema and a document which may
- * contain GraphQL type extensions and definitions. The original schema will
- * remain unaltered.
- *
- * Because a schema represents a graph of references, a schema cannot be
- * extended without effectively making an entire copy. We do not know until it's
- * too late if subgraphs remain unchanged.
- *
- * This algorithm copies the provided schema, applying extensions while
- * producing the copy. The original schema remains unaltered.
- *
- * Accepts options as a third argument:
- *
- * - commentDescriptions:
- * Provide true to use preceding comments as the description.
- *
- */
- function extendSchema(schema, documentAST, options) {
- (0, _schema.assertSchema)(schema);
- !(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0;
- if (!options || !(options.assumeValid || options.assumeValidSDL)) {
- (0, _validate.assertValidSDLExtension)(documentAST, schema);
- } // Collect the type definitions and extensions found in the document.
- var typeDefinitionMap = Object.create(null);
- var typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can
- // have the same name. For example, a type named "skip".
- var directiveDefinitions = [];
- var schemaDef; // Schema extensions are collected which may add additional operation types.
- var schemaExtensions = [];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = documentAST.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var def = _step.value;
- if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) {
- schemaDef = def;
- } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) {
- schemaExtensions.push(def);
- } else if ((0, _predicates.isTypeDefinitionNode)(def)) {
- var typeName = def.name.value;
- typeDefinitionMap[typeName] = def;
- } else if ((0, _predicates.isTypeExtensionNode)(def)) {
- var extendedTypeName = def.name.value;
- var existingTypeExtensions = typeExtensionsMap[extendedTypeName];
- typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def];
- } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- directiveDefinitions.push(def);
- }
- } // If this document contains no new types, extensions, or directives then
- // return the same unmodified GraphQLSchema instance.
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- if (Object.keys(typeExtensionsMap).length === 0 && Object.keys(typeDefinitionMap).length === 0 && directiveDefinitions.length === 0 && schemaExtensions.length === 0 && !schemaDef) {
- return schema;
- }
- var astBuilder = new _buildASTSchema.ASTDefinitionBuilder(typeDefinitionMap, options, function (typeName) {
- var existingType = schema.getType(typeName);
- !existingType ? (0, _invariant.default)(0, "Unknown type: \"".concat(typeName, "\".")) : void 0;
- return extendNamedType(existingType);
- });
- var extendTypeCache = Object.create(null); // Get the extended root operation types.
- var operationTypes = {
- query: extendMaybeNamedType(schema.getQueryType()),
- mutation: extendMaybeNamedType(schema.getMutationType()),
- subscription: extendMaybeNamedType(schema.getSubscriptionType())
- };
- if (schemaDef) {
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = schemaDef.operationTypes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var _ref2 = _step2.value;
- var operation = _ref2.operation;
- var type = _ref2.type;
- // Note: While this could make early assertions to get the correctly
- // typed values, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- operationTypes[operation] = astBuilder.buildType(type);
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- } // Then, incorporate schema definition and all schema extensions.
- for (var _i = 0; _i < schemaExtensions.length; _i++) {
- var schemaExtension = schemaExtensions[_i];
- if (schemaExtension.operationTypes) {
- var _iteratorNormalCompletion14 = true;
- var _didIteratorError14 = false;
- var _iteratorError14 = undefined;
- try {
- for (var _iterator14 = schemaExtension.operationTypes[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {
- var _ref4 = _step14.value;
- var _operation = _ref4.operation;
- var _type = _ref4.type;
- // Note: While this could make early assertions to get the correctly
- // typed values, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- operationTypes[_operation] = astBuilder.buildType(_type);
- }
- } catch (err) {
- _didIteratorError14 = true;
- _iteratorError14 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion14 && _iterator14.return != null) {
- _iterator14.return();
- }
- } finally {
- if (_didIteratorError14) {
- throw _iteratorError14;
- }
- }
- }
- }
- }
- var schemaExtensionASTNodes = schemaExtensions ? schema.extensionASTNodes ? schema.extensionASTNodes.concat(schemaExtensions) : schemaExtensions : schema.extensionASTNodes;
- var types = [].concat((0, _objectValues.default)(schema.getTypeMap()).map(function (type) {
- return extendNamedType(type);
- }), (0, _objectValues.default)(typeDefinitionMap).map(function (type) {
- return astBuilder.buildType(type);
- })); // Support both original legacy names and extended legacy names.
- var allowedLegacyNames = schema.__allowedLegacyNames.concat(options && options.allowedLegacyNames || []); // Then produce and return a Schema with these types.
- return new _schema.GraphQLSchema(_objectSpread({}, operationTypes, {
- types: types,
- directives: getMergedDirectives(),
- astNode: schema.astNode,
- extensionASTNodes: schemaExtensionASTNodes,
- allowedLegacyNames: allowedLegacyNames
- })); // Below are functions used for producing this schema that have closed over
- // this scope and have access to the schema, cache, and newly defined types.
- function getMergedDirectives() {
- var existingDirectives = schema.getDirectives().map(extendDirective);
- !existingDirectives ? (0, _invariant.default)(0, 'schema must have default directives') : void 0;
- return existingDirectives.concat(directiveDefinitions.map(function (node) {
- return astBuilder.buildDirective(node);
- }));
- }
- function extendMaybeNamedType(type) {
- return type ? extendNamedType(type) : null;
- }
- function extendNamedType(type) {
- if ((0, _introspection.isIntrospectionType)(type) || (0, _scalars.isSpecifiedScalarType)(type)) {
- // Builtin types are not extended.
- return type;
- }
- var name = type.name;
- if (!extendTypeCache[name]) {
- if ((0, _definition.isScalarType)(type)) {
- extendTypeCache[name] = extendScalarType(type);
- } else if ((0, _definition.isObjectType)(type)) {
- extendTypeCache[name] = extendObjectType(type);
- } else if ((0, _definition.isInterfaceType)(type)) {
- extendTypeCache[name] = extendInterfaceType(type);
- } else if ((0, _definition.isUnionType)(type)) {
- extendTypeCache[name] = extendUnionType(type);
- } else if ((0, _definition.isEnumType)(type)) {
- extendTypeCache[name] = extendEnumType(type);
- } else if ((0, _definition.isInputObjectType)(type)) {
- extendTypeCache[name] = extendInputObjectType(type);
- }
- }
- return extendTypeCache[name];
- }
- function extendDirective(directive) {
- return new _directives.GraphQLDirective({
- name: directive.name,
- description: directive.description,
- locations: directive.locations,
- args: extendArgs(directive.args),
- astNode: directive.astNode
- });
- }
- function extendInputObjectType(type) {
- var name = type.name;
- var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
- return new _definition.GraphQLInputObjectType({
- name: name,
- description: type.description,
- fields: function fields() {
- return extendInputFieldMap(type);
- },
- astNode: type.astNode,
- extensionASTNodes: extensionASTNodes
- });
- }
- function extendInputFieldMap(type) {
- var newFieldMap = (0, _mapValue.default)(type.getFields(), function (field) {
- return {
- description: field.description,
- type: extendType(field.type),
- defaultValue: field.defaultValue,
- astNode: field.astNode
- };
- }); // If there are any extensions to the fields, apply those here.
- var extensions = typeExtensionsMap[type.name];
- if (extensions) {
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = extensions[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var extension = _step3.value;
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = extension.fields[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var field = _step4.value;
- newFieldMap[field.name.value] = astBuilder.buildInputField(field);
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- return newFieldMap;
- }
- function extendEnumType(type) {
- var name = type.name;
- var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
- return new _definition.GraphQLEnumType({
- name: name,
- description: type.description,
- values: extendValueMap(type),
- astNode: type.astNode,
- extensionASTNodes: extensionASTNodes
- });
- }
- function extendValueMap(type) {
- var newValueMap = Object.create(null);
- var _iteratorNormalCompletion5 = true;
- var _didIteratorError5 = false;
- var _iteratorError5 = undefined;
- try {
- for (var _iterator5 = type.getValues()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
- var _value = _step5.value;
- newValueMap[_value.name] = {
- description: _value.description,
- value: _value.value,
- deprecationReason: _value.deprecationReason,
- astNode: _value.astNode
- };
- } // If there are any extensions to the values, apply those here.
- } catch (err) {
- _didIteratorError5 = true;
- _iteratorError5 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
- _iterator5.return();
- }
- } finally {
- if (_didIteratorError5) {
- throw _iteratorError5;
- }
- }
- }
- var extensions = typeExtensionsMap[type.name];
- if (extensions) {
- var _iteratorNormalCompletion6 = true;
- var _didIteratorError6 = false;
- var _iteratorError6 = undefined;
- try {
- for (var _iterator6 = extensions[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
- var extension = _step6.value;
- var _iteratorNormalCompletion7 = true;
- var _didIteratorError7 = false;
- var _iteratorError7 = undefined;
- try {
- for (var _iterator7 = extension.values[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
- var value = _step7.value;
- newValueMap[value.name.value] = astBuilder.buildEnumValue(value);
- }
- } catch (err) {
- _didIteratorError7 = true;
- _iteratorError7 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
- _iterator7.return();
- }
- } finally {
- if (_didIteratorError7) {
- throw _iteratorError7;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError6 = true;
- _iteratorError6 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
- _iterator6.return();
- }
- } finally {
- if (_didIteratorError6) {
- throw _iteratorError6;
- }
- }
- }
- }
- return newValueMap;
- }
- function extendScalarType(type) {
- var name = type.name;
- var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
- return new _definition.GraphQLScalarType({
- name: name,
- description: type.description,
- astNode: type.astNode,
- extensionASTNodes: extensionASTNodes,
- serialize: type.serialize,
- parseValue: type.parseValue,
- parseLiteral: type.parseLiteral
- });
- }
- function extendObjectType(type) {
- var name = type.name;
- var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
- return new _definition.GraphQLObjectType({
- name: name,
- description: type.description,
- interfaces: function interfaces() {
- return extendImplementedInterfaces(type);
- },
- fields: function fields() {
- return extendFieldMap(type);
- },
- astNode: type.astNode,
- extensionASTNodes: extensionASTNodes,
- isTypeOf: type.isTypeOf
- });
- }
- function extendArgs(args) {
- return (0, _keyValMap.default)(args, function (arg) {
- return arg.name;
- }, function (arg) {
- return {
- type: extendType(arg.type),
- defaultValue: arg.defaultValue,
- description: arg.description,
- astNode: arg.astNode
- };
- });
- }
- function extendInterfaceType(type) {
- var name = type.name;
- var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
- return new _definition.GraphQLInterfaceType({
- name: type.name,
- description: type.description,
- fields: function fields() {
- return extendFieldMap(type);
- },
- astNode: type.astNode,
- extensionASTNodes: extensionASTNodes,
- resolveType: type.resolveType
- });
- }
- function extendUnionType(type) {
- var name = type.name;
- var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
- return new _definition.GraphQLUnionType({
- name: name,
- description: type.description,
- types: function types() {
- return extendPossibleTypes(type);
- },
- astNode: type.astNode,
- resolveType: type.resolveType,
- extensionASTNodes: extensionASTNodes
- });
- }
- function extendPossibleTypes(type) {
- var possibleTypes = type.getTypes().map(extendNamedType); // If there are any extensions to the union, apply those here.
- var extensions = typeExtensionsMap[type.name];
- if (extensions) {
- var _iteratorNormalCompletion8 = true;
- var _didIteratorError8 = false;
- var _iteratorError8 = undefined;
- try {
- for (var _iterator8 = extensions[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
- var extension = _step8.value;
- var _iteratorNormalCompletion9 = true;
- var _didIteratorError9 = false;
- var _iteratorError9 = undefined;
- try {
- for (var _iterator9 = extension.types[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
- var namedType = _step9.value;
- // Note: While this could make early assertions to get the correctly
- // typed values, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- possibleTypes.push(astBuilder.buildType(namedType));
- }
- } catch (err) {
- _didIteratorError9 = true;
- _iteratorError9 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
- _iterator9.return();
- }
- } finally {
- if (_didIteratorError9) {
- throw _iteratorError9;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError8 = true;
- _iteratorError8 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
- _iterator8.return();
- }
- } finally {
- if (_didIteratorError8) {
- throw _iteratorError8;
- }
- }
- }
- }
- return possibleTypes;
- }
- function extendImplementedInterfaces(type) {
- var interfaces = type.getInterfaces().map(extendNamedType); // If there are any extensions to the interfaces, apply those here.
- var extensions = typeExtensionsMap[type.name];
- if (extensions) {
- var _iteratorNormalCompletion10 = true;
- var _didIteratorError10 = false;
- var _iteratorError10 = undefined;
- try {
- for (var _iterator10 = extensions[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
- var extension = _step10.value;
- var _iteratorNormalCompletion11 = true;
- var _didIteratorError11 = false;
- var _iteratorError11 = undefined;
- try {
- for (var _iterator11 = extension.interfaces[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
- var namedType = _step11.value;
- // Note: While this could make early assertions to get the correctly
- // typed values, that would throw immediately while type system
- // validation with validateSchema() will produce more actionable results.
- interfaces.push(astBuilder.buildType(namedType));
- }
- } catch (err) {
- _didIteratorError11 = true;
- _iteratorError11 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion11 && _iterator11.return != null) {
- _iterator11.return();
- }
- } finally {
- if (_didIteratorError11) {
- throw _iteratorError11;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError10 = true;
- _iteratorError10 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
- _iterator10.return();
- }
- } finally {
- if (_didIteratorError10) {
- throw _iteratorError10;
- }
- }
- }
- }
- return interfaces;
- }
- function extendFieldMap(type) {
- var newFieldMap = (0, _mapValue.default)(type.getFields(), function (field) {
- return {
- description: field.description,
- deprecationReason: field.deprecationReason,
- type: extendType(field.type),
- args: extendArgs(field.args),
- astNode: field.astNode,
- resolve: field.resolve
- };
- }); // If there are any extensions to the fields, apply those here.
- var extensions = typeExtensionsMap[type.name];
- if (extensions) {
- var _iteratorNormalCompletion12 = true;
- var _didIteratorError12 = false;
- var _iteratorError12 = undefined;
- try {
- for (var _iterator12 = extensions[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
- var extension = _step12.value;
- var _iteratorNormalCompletion13 = true;
- var _didIteratorError13 = false;
- var _iteratorError13 = undefined;
- try {
- for (var _iterator13 = extension.fields[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
- var field = _step13.value;
- newFieldMap[field.name.value] = astBuilder.buildField(field);
- }
- } catch (err) {
- _didIteratorError13 = true;
- _iteratorError13 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion13 && _iterator13.return != null) {
- _iterator13.return();
- }
- } finally {
- if (_didIteratorError13) {
- throw _iteratorError13;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError12 = true;
- _iteratorError12 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion12 && _iterator12.return != null) {
- _iterator12.return();
- }
- } finally {
- if (_didIteratorError12) {
- throw _iteratorError12;
- }
- }
- }
- }
- return newFieldMap;
- }
- function extendType(typeDef) {
- if ((0, _definition.isListType)(typeDef)) {
- return (0, _definition.GraphQLList)(extendType(typeDef.ofType));
- }
- if ((0, _definition.isNonNullType)(typeDef)) {
- return (0, _definition.GraphQLNonNull)(extendType(typeDef.ofType));
- }
- return extendNamedType(typeDef);
- }
- }
- },{"../jsutils/invariant":290,"../jsutils/keyValMap":295,"../jsutils/mapValue":296,"../language/kinds":307,"../language/predicates":311,"../polyfills/objectValues":319,"../type/definition":323,"../type/directives":324,"../type/introspection":326,"../type/scalars":327,"../type/schema":328,"../validation/validate":390,"./buildASTSchema":333}],338:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.findBreakingChanges = findBreakingChanges;
- exports.findDangerousChanges = findDangerousChanges;
- exports.findRemovedTypes = findRemovedTypes;
- exports.findTypesThatChangedKind = findTypesThatChangedKind;
- exports.findArgChanges = findArgChanges;
- exports.findFieldsThatChangedTypeOnObjectOrInterfaceTypes = findFieldsThatChangedTypeOnObjectOrInterfaceTypes;
- exports.findFieldsThatChangedTypeOnInputObjectTypes = findFieldsThatChangedTypeOnInputObjectTypes;
- exports.findTypesRemovedFromUnions = findTypesRemovedFromUnions;
- exports.findTypesAddedToUnions = findTypesAddedToUnions;
- exports.findValuesRemovedFromEnums = findValuesRemovedFromEnums;
- exports.findValuesAddedToEnums = findValuesAddedToEnums;
- exports.findInterfacesRemovedFromObjectTypes = findInterfacesRemovedFromObjectTypes;
- exports.findInterfacesAddedToObjectTypes = findInterfacesAddedToObjectTypes;
- exports.findRemovedDirectives = findRemovedDirectives;
- exports.findRemovedDirectiveArgs = findRemovedDirectiveArgs;
- exports.findAddedNonNullDirectiveArgs = findAddedNonNullDirectiveArgs;
- exports.findRemovedLocationsForDirective = findRemovedLocationsForDirective;
- exports.findRemovedDirectiveLocations = findRemovedDirectiveLocations;
- exports.DangerousChangeType = exports.BreakingChangeType = void 0;
- var _find = _interopRequireDefault(require("../polyfills/find"));
- var _definition = require("../type/definition");
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2016-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var BreakingChangeType = {
- FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND',
- FIELD_REMOVED: 'FIELD_REMOVED',
- TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND',
- TYPE_REMOVED: 'TYPE_REMOVED',
- TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION',
- VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM',
- ARG_REMOVED: 'ARG_REMOVED',
- ARG_CHANGED_KIND: 'ARG_CHANGED_KIND',
- REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED',
- REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED',
- INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT',
- DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED',
- DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED',
- DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED',
- REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED'
- };
- exports.BreakingChangeType = BreakingChangeType;
- var DangerousChangeType = {
- ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE',
- VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM',
- INTERFACE_ADDED_TO_OBJECT: 'INTERFACE_ADDED_TO_OBJECT',
- TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION',
- OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED',
- OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED'
- };
- exports.DangerousChangeType = DangerousChangeType;
- /**
- * Given two schemas, returns an Array containing descriptions of all the types
- * of breaking changes covered by the other functions down below.
- */
- function findBreakingChanges(oldSchema, newSchema) {
- return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema));
- }
- /**
- * Given two schemas, returns an Array containing descriptions of all the types
- * of potentially dangerous changes covered by the other functions down below.
- */
- function findDangerousChanges(oldSchema, newSchema) {
- return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges);
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any breaking
- * changes in the newSchema related to removing an entire type.
- */
- function findRemovedTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- var _arr = Object.keys(oldTypeMap);
- for (var _i = 0; _i < _arr.length; _i++) {
- var typeName = _arr[_i];
- if (!newTypeMap[typeName]) {
- breakingChanges.push({
- type: BreakingChangeType.TYPE_REMOVED,
- description: "".concat(typeName, " was removed.")
- });
- }
- }
- return breakingChanges;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any breaking
- * changes in the newSchema related to changing the type of a type.
- */
- function findTypesThatChangedKind(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- var _arr2 = Object.keys(oldTypeMap);
- for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
- var typeName = _arr2[_i2];
- if (!newTypeMap[typeName]) {
- continue;
- }
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (oldType.constructor !== newType.constructor) {
- breakingChanges.push({
- type: BreakingChangeType.TYPE_CHANGED_KIND,
- description: "".concat(typeName, " changed from ") + "".concat(typeKindName(oldType), " to ").concat(typeKindName(newType), ".")
- });
- }
- }
- return breakingChanges;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any
- * breaking or dangerous changes in the newSchema related to arguments
- * (such as removal or change of type of an argument, or a change in an
- * argument's default value).
- */
- function findArgChanges(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- var dangerousChanges = [];
- var _arr3 = Object.keys(oldTypeMap);
- for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
- var typeName = _arr3[_i3];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!((0, _definition.isObjectType)(oldType) || (0, _definition.isInterfaceType)(oldType)) || !((0, _definition.isObjectType)(newType) || (0, _definition.isInterfaceType)(newType)) || newType.constructor !== oldType.constructor) {
- continue;
- }
- var oldTypeFields = oldType.getFields();
- var newTypeFields = newType.getFields();
- var _arr4 = Object.keys(oldTypeFields);
- for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
- var fieldName = _arr4[_i4];
- if (!newTypeFields[fieldName]) {
- continue;
- }
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- var _loop = function _loop() {
- var oldArgDef = _step.value;
- var newArgs = newTypeFields[fieldName].args;
- var newArgDef = (0, _find.default)(newArgs, function (arg) {
- return arg.name === oldArgDef.name;
- }); // Arg not present
- if (!newArgDef) {
- breakingChanges.push({
- type: BreakingChangeType.ARG_REMOVED,
- description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " was removed")
- });
- } else {
- var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);
- if (!isSafe) {
- breakingChanges.push({
- type: BreakingChangeType.ARG_CHANGED_KIND,
- description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed type from ") + "".concat(oldArgDef.type.toString(), " to ").concat(newArgDef.type.toString())
- });
- } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {
- dangerousChanges.push({
- type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,
- description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed defaultValue")
- });
- }
- }
- };
- for (var _iterator = oldTypeFields[fieldName].args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- _loop();
- } // Check if arg was added to the field
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- var _loop2 = function _loop2() {
- var newArgDef = _step2.value;
- var oldArgs = oldTypeFields[fieldName].args;
- var oldArgDef = (0, _find.default)(oldArgs, function (arg) {
- return arg.name === newArgDef.name;
- });
- if (!oldArgDef) {
- var argName = newArgDef.name;
- if ((0, _definition.isRequiredArgument)(newArgDef)) {
- breakingChanges.push({
- type: BreakingChangeType.REQUIRED_ARG_ADDED,
- description: "A required arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added")
- });
- } else {
- dangerousChanges.push({
- type: DangerousChangeType.OPTIONAL_ARG_ADDED,
- description: "An optional arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added")
- });
- }
- }
- };
- for (var _iterator2 = newTypeFields[fieldName].args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- _loop2();
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- }
- }
- return {
- breakingChanges: breakingChanges,
- dangerousChanges: dangerousChanges
- };
- }
- function typeKindName(type) {
- if ((0, _definition.isScalarType)(type)) {
- return 'a Scalar type';
- }
- if ((0, _definition.isObjectType)(type)) {
- return 'an Object type';
- }
- if ((0, _definition.isInterfaceType)(type)) {
- return 'an Interface type';
- }
- if ((0, _definition.isUnionType)(type)) {
- return 'a Union type';
- }
- if ((0, _definition.isEnumType)(type)) {
- return 'an Enum type';
- }
- if ((0, _definition.isInputObjectType)(type)) {
- return 'an Input type';
- }
- throw new TypeError('Unknown type ' + type.constructor.name);
- }
- function findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- var _arr5 = Object.keys(oldTypeMap);
- for (var _i5 = 0; _i5 < _arr5.length; _i5++) {
- var typeName = _arr5[_i5];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!((0, _definition.isObjectType)(oldType) || (0, _definition.isInterfaceType)(oldType)) || !((0, _definition.isObjectType)(newType) || (0, _definition.isInterfaceType)(newType)) || newType.constructor !== oldType.constructor) {
- continue;
- }
- var oldTypeFieldsDef = oldType.getFields();
- var newTypeFieldsDef = newType.getFields();
- var _arr6 = Object.keys(oldTypeFieldsDef);
- for (var _i6 = 0; _i6 < _arr6.length; _i6++) {
- var fieldName = _arr6[_i6];
- // Check if the field is missing on the type in the new schema.
- if (!(fieldName in newTypeFieldsDef)) {
- breakingChanges.push({
- type: BreakingChangeType.FIELD_REMOVED,
- description: "".concat(typeName, ".").concat(fieldName, " was removed.")
- });
- } else {
- var oldFieldType = oldTypeFieldsDef[fieldName].type;
- var newFieldType = newTypeFieldsDef[fieldName].type;
- var isSafe = isChangeSafeForObjectOrInterfaceField(oldFieldType, newFieldType);
- if (!isSafe) {
- var oldFieldTypeString = (0, _definition.isNamedType)(oldFieldType) ? oldFieldType.name : oldFieldType.toString();
- var newFieldTypeString = (0, _definition.isNamedType)(newFieldType) ? newFieldType.name : newFieldType.toString();
- breakingChanges.push({
- type: BreakingChangeType.FIELD_CHANGED_KIND,
- description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".")
- });
- }
- }
- }
- }
- return breakingChanges;
- }
- function findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- var dangerousChanges = [];
- var _arr7 = Object.keys(oldTypeMap);
- for (var _i7 = 0; _i7 < _arr7.length; _i7++) {
- var typeName = _arr7[_i7];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isInputObjectType)(oldType) || !(0, _definition.isInputObjectType)(newType)) {
- continue;
- }
- var oldTypeFieldsDef = oldType.getFields();
- var newTypeFieldsDef = newType.getFields();
- var _arr8 = Object.keys(oldTypeFieldsDef);
- for (var _i8 = 0; _i8 < _arr8.length; _i8++) {
- var fieldName = _arr8[_i8];
- // Check if the field is missing on the type in the new schema.
- if (!(fieldName in newTypeFieldsDef)) {
- breakingChanges.push({
- type: BreakingChangeType.FIELD_REMOVED,
- description: "".concat(typeName, ".").concat(fieldName, " was removed.")
- });
- } else {
- var oldFieldType = oldTypeFieldsDef[fieldName].type;
- var newFieldType = newTypeFieldsDef[fieldName].type;
- var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldFieldType, newFieldType);
- if (!isSafe) {
- var oldFieldTypeString = (0, _definition.isNamedType)(oldFieldType) ? oldFieldType.name : oldFieldType.toString();
- var newFieldTypeString = (0, _definition.isNamedType)(newFieldType) ? newFieldType.name : newFieldType.toString();
- breakingChanges.push({
- type: BreakingChangeType.FIELD_CHANGED_KIND,
- description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".")
- });
- }
- }
- } // Check if a field was added to the input object type
- var _arr9 = Object.keys(newTypeFieldsDef);
- for (var _i9 = 0; _i9 < _arr9.length; _i9++) {
- var _fieldName = _arr9[_i9];
- if (!(_fieldName in oldTypeFieldsDef)) {
- if ((0, _definition.isRequiredInputField)(newTypeFieldsDef[_fieldName])) {
- breakingChanges.push({
- type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED,
- description: "A required field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.")
- });
- } else {
- dangerousChanges.push({
- type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED,
- description: "An optional field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.")
- });
- }
- }
- }
- }
- return {
- breakingChanges: breakingChanges,
- dangerousChanges: dangerousChanges
- };
- }
- function isChangeSafeForObjectOrInterfaceField(oldType, newType) {
- if ((0, _definition.isNamedType)(oldType)) {
- return (// if they're both named types, see if their names are equivalent
- (0, _definition.isNamedType)(newType) && oldType.name === newType.name || // moving from nullable to non-null of the same underlying type is safe
- (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)
- );
- } else if ((0, _definition.isListType)(oldType)) {
- return (// if they're both lists, make sure the underlying types are compatible
- (0, _definition.isListType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || // moving from nullable to non-null of the same underlying type is safe
- (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)
- );
- } else if ((0, _definition.isNonNullType)(oldType)) {
- // if they're both non-null, make sure the underlying types are compatible
- return (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType);
- }
- return false;
- }
- function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) {
- if ((0, _definition.isNamedType)(oldType)) {
- // if they're both named types, see if their names are equivalent
- return (0, _definition.isNamedType)(newType) && oldType.name === newType.name;
- } else if ((0, _definition.isListType)(oldType)) {
- // if they're both lists, make sure the underlying types are compatible
- return (0, _definition.isListType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType);
- } else if ((0, _definition.isNonNullType)(oldType)) {
- return (// if they're both non-null, make sure the underlying types are
- // compatible
- (0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || // moving from non-null to nullable of the same underlying type is safe
- !(0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)
- );
- }
- return false;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any breaking
- * changes in the newSchema related to removing types from a union type.
- */
- function findTypesRemovedFromUnions(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var typesRemovedFromUnion = [];
- var _arr10 = Object.keys(oldTypeMap);
- for (var _i10 = 0; _i10 < _arr10.length; _i10++) {
- var typeName = _arr10[_i10];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isUnionType)(oldType) || !(0, _definition.isUnionType)(newType)) {
- continue;
- }
- var typeNamesInNewUnion = Object.create(null);
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var type = _step3.value;
- typeNamesInNewUnion[type.name] = true;
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var _type = _step4.value;
- if (!typeNamesInNewUnion[_type.name]) {
- typesRemovedFromUnion.push({
- type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,
- description: "".concat(_type.name, " was removed from union type ").concat(typeName, ".")
- });
- }
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- }
- return typesRemovedFromUnion;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any dangerous
- * changes in the newSchema related to adding types to a union type.
- */
- function findTypesAddedToUnions(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var typesAddedToUnion = [];
- var _arr11 = Object.keys(newTypeMap);
- for (var _i11 = 0; _i11 < _arr11.length; _i11++) {
- var typeName = _arr11[_i11];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isUnionType)(oldType) || !(0, _definition.isUnionType)(newType)) {
- continue;
- }
- var typeNamesInOldUnion = Object.create(null);
- var _iteratorNormalCompletion5 = true;
- var _didIteratorError5 = false;
- var _iteratorError5 = undefined;
- try {
- for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
- var type = _step5.value;
- typeNamesInOldUnion[type.name] = true;
- }
- } catch (err) {
- _didIteratorError5 = true;
- _iteratorError5 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
- _iterator5.return();
- }
- } finally {
- if (_didIteratorError5) {
- throw _iteratorError5;
- }
- }
- }
- var _iteratorNormalCompletion6 = true;
- var _didIteratorError6 = false;
- var _iteratorError6 = undefined;
- try {
- for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
- var _type2 = _step6.value;
- if (!typeNamesInOldUnion[_type2.name]) {
- typesAddedToUnion.push({
- type: DangerousChangeType.TYPE_ADDED_TO_UNION,
- description: "".concat(_type2.name, " was added to union type ").concat(typeName, ".")
- });
- }
- }
- } catch (err) {
- _didIteratorError6 = true;
- _iteratorError6 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
- _iterator6.return();
- }
- } finally {
- if (_didIteratorError6) {
- throw _iteratorError6;
- }
- }
- }
- }
- return typesAddedToUnion;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any breaking
- * changes in the newSchema related to removing values from an enum type.
- */
- function findValuesRemovedFromEnums(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var valuesRemovedFromEnums = [];
- var _arr12 = Object.keys(oldTypeMap);
- for (var _i12 = 0; _i12 < _arr12.length; _i12++) {
- var typeName = _arr12[_i12];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isEnumType)(oldType) || !(0, _definition.isEnumType)(newType)) {
- continue;
- }
- var valuesInNewEnum = Object.create(null);
- var _iteratorNormalCompletion7 = true;
- var _didIteratorError7 = false;
- var _iteratorError7 = undefined;
- try {
- for (var _iterator7 = newType.getValues()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
- var value = _step7.value;
- valuesInNewEnum[value.name] = true;
- }
- } catch (err) {
- _didIteratorError7 = true;
- _iteratorError7 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
- _iterator7.return();
- }
- } finally {
- if (_didIteratorError7) {
- throw _iteratorError7;
- }
- }
- }
- var _iteratorNormalCompletion8 = true;
- var _didIteratorError8 = false;
- var _iteratorError8 = undefined;
- try {
- for (var _iterator8 = oldType.getValues()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
- var _value = _step8.value;
- if (!valuesInNewEnum[_value.name]) {
- valuesRemovedFromEnums.push({
- type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,
- description: "".concat(_value.name, " was removed from enum type ").concat(typeName, ".")
- });
- }
- }
- } catch (err) {
- _didIteratorError8 = true;
- _iteratorError8 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
- _iterator8.return();
- }
- } finally {
- if (_didIteratorError8) {
- throw _iteratorError8;
- }
- }
- }
- }
- return valuesRemovedFromEnums;
- }
- /**
- * Given two schemas, returns an Array containing descriptions of any dangerous
- * changes in the newSchema related to adding values to an enum type.
- */
- function findValuesAddedToEnums(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var valuesAddedToEnums = [];
- var _arr13 = Object.keys(oldTypeMap);
- for (var _i13 = 0; _i13 < _arr13.length; _i13++) {
- var typeName = _arr13[_i13];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isEnumType)(oldType) || !(0, _definition.isEnumType)(newType)) {
- continue;
- }
- var valuesInOldEnum = Object.create(null);
- var _iteratorNormalCompletion9 = true;
- var _didIteratorError9 = false;
- var _iteratorError9 = undefined;
- try {
- for (var _iterator9 = oldType.getValues()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
- var value = _step9.value;
- valuesInOldEnum[value.name] = true;
- }
- } catch (err) {
- _didIteratorError9 = true;
- _iteratorError9 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
- _iterator9.return();
- }
- } finally {
- if (_didIteratorError9) {
- throw _iteratorError9;
- }
- }
- }
- var _iteratorNormalCompletion10 = true;
- var _didIteratorError10 = false;
- var _iteratorError10 = undefined;
- try {
- for (var _iterator10 = newType.getValues()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
- var _value2 = _step10.value;
- if (!valuesInOldEnum[_value2.name]) {
- valuesAddedToEnums.push({
- type: DangerousChangeType.VALUE_ADDED_TO_ENUM,
- description: "".concat(_value2.name, " was added to enum type ").concat(typeName, ".")
- });
- }
- }
- } catch (err) {
- _didIteratorError10 = true;
- _iteratorError10 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
- _iterator10.return();
- }
- } finally {
- if (_didIteratorError10) {
- throw _iteratorError10;
- }
- }
- }
- }
- return valuesAddedToEnums;
- }
- function findInterfacesRemovedFromObjectTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var breakingChanges = [];
- var _arr14 = Object.keys(oldTypeMap);
- for (var _i14 = 0; _i14 < _arr14.length; _i14++) {
- var typeName = _arr14[_i14];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isObjectType)(oldType) || !(0, _definition.isObjectType)(newType)) {
- continue;
- }
- var oldInterfaces = oldType.getInterfaces();
- var newInterfaces = newType.getInterfaces();
- var _iteratorNormalCompletion11 = true;
- var _didIteratorError11 = false;
- var _iteratorError11 = undefined;
- try {
- var _loop3 = function _loop3() {
- var oldInterface = _step11.value;
- if (!newInterfaces.some(function (int) {
- return int.name === oldInterface.name;
- })) {
- breakingChanges.push({
- type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT,
- description: "".concat(typeName, " no longer implements interface ") + "".concat(oldInterface.name, ".")
- });
- }
- };
- for (var _iterator11 = oldInterfaces[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
- _loop3();
- }
- } catch (err) {
- _didIteratorError11 = true;
- _iteratorError11 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion11 && _iterator11.return != null) {
- _iterator11.return();
- }
- } finally {
- if (_didIteratorError11) {
- throw _iteratorError11;
- }
- }
- }
- }
- return breakingChanges;
- }
- function findInterfacesAddedToObjectTypes(oldSchema, newSchema) {
- var oldTypeMap = oldSchema.getTypeMap();
- var newTypeMap = newSchema.getTypeMap();
- var interfacesAddedToObjectTypes = [];
- var _arr15 = Object.keys(newTypeMap);
- for (var _i15 = 0; _i15 < _arr15.length; _i15++) {
- var typeName = _arr15[_i15];
- var oldType = oldTypeMap[typeName];
- var newType = newTypeMap[typeName];
- if (!(0, _definition.isObjectType)(oldType) || !(0, _definition.isObjectType)(newType)) {
- continue;
- }
- var oldInterfaces = oldType.getInterfaces();
- var newInterfaces = newType.getInterfaces();
- var _iteratorNormalCompletion12 = true;
- var _didIteratorError12 = false;
- var _iteratorError12 = undefined;
- try {
- var _loop4 = function _loop4() {
- var newInterface = _step12.value;
- if (!oldInterfaces.some(function (int) {
- return int.name === newInterface.name;
- })) {
- interfacesAddedToObjectTypes.push({
- type: DangerousChangeType.INTERFACE_ADDED_TO_OBJECT,
- description: "".concat(newInterface.name, " added to interfaces implemented ") + "by ".concat(typeName, ".")
- });
- }
- };
- for (var _iterator12 = newInterfaces[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
- _loop4();
- }
- } catch (err) {
- _didIteratorError12 = true;
- _iteratorError12 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion12 && _iterator12.return != null) {
- _iterator12.return();
- }
- } finally {
- if (_didIteratorError12) {
- throw _iteratorError12;
- }
- }
- }
- }
- return interfacesAddedToObjectTypes;
- }
- function findRemovedDirectives(oldSchema, newSchema) {
- var removedDirectives = [];
- var newSchemaDirectiveMap = getDirectiveMapForSchema(newSchema);
- var _iteratorNormalCompletion13 = true;
- var _didIteratorError13 = false;
- var _iteratorError13 = undefined;
- try {
- for (var _iterator13 = oldSchema.getDirectives()[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
- var directive = _step13.value;
- if (!newSchemaDirectiveMap[directive.name]) {
- removedDirectives.push({
- type: BreakingChangeType.DIRECTIVE_REMOVED,
- description: "".concat(directive.name, " was removed")
- });
- }
- }
- } catch (err) {
- _didIteratorError13 = true;
- _iteratorError13 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion13 && _iterator13.return != null) {
- _iterator13.return();
- }
- } finally {
- if (_didIteratorError13) {
- throw _iteratorError13;
- }
- }
- }
- return removedDirectives;
- }
- function findRemovedArgsForDirective(oldDirective, newDirective) {
- var removedArgs = [];
- var newArgMap = getArgumentMapForDirective(newDirective);
- var _iteratorNormalCompletion14 = true;
- var _didIteratorError14 = false;
- var _iteratorError14 = undefined;
- try {
- for (var _iterator14 = oldDirective.args[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {
- var arg = _step14.value;
- if (!newArgMap[arg.name]) {
- removedArgs.push(arg);
- }
- }
- } catch (err) {
- _didIteratorError14 = true;
- _iteratorError14 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion14 && _iterator14.return != null) {
- _iterator14.return();
- }
- } finally {
- if (_didIteratorError14) {
- throw _iteratorError14;
- }
- }
- }
- return removedArgs;
- }
- function findRemovedDirectiveArgs(oldSchema, newSchema) {
- var removedDirectiveArgs = [];
- var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema);
- var _iteratorNormalCompletion15 = true;
- var _didIteratorError15 = false;
- var _iteratorError15 = undefined;
- try {
- for (var _iterator15 = newSchema.getDirectives()[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) {
- var newDirective = _step15.value;
- var oldDirective = oldSchemaDirectiveMap[newDirective.name];
- if (!oldDirective) {
- continue;
- }
- var _iteratorNormalCompletion16 = true;
- var _didIteratorError16 = false;
- var _iteratorError16 = undefined;
- try {
- for (var _iterator16 = findRemovedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) {
- var arg = _step16.value;
- removedDirectiveArgs.push({
- type: BreakingChangeType.DIRECTIVE_ARG_REMOVED,
- description: "".concat(arg.name, " was removed from ").concat(newDirective.name)
- });
- }
- } catch (err) {
- _didIteratorError16 = true;
- _iteratorError16 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion16 && _iterator16.return != null) {
- _iterator16.return();
- }
- } finally {
- if (_didIteratorError16) {
- throw _iteratorError16;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError15 = true;
- _iteratorError15 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion15 && _iterator15.return != null) {
- _iterator15.return();
- }
- } finally {
- if (_didIteratorError15) {
- throw _iteratorError15;
- }
- }
- }
- return removedDirectiveArgs;
- }
- function findAddedArgsForDirective(oldDirective, newDirective) {
- var addedArgs = [];
- var oldArgMap = getArgumentMapForDirective(oldDirective);
- var _iteratorNormalCompletion17 = true;
- var _didIteratorError17 = false;
- var _iteratorError17 = undefined;
- try {
- for (var _iterator17 = newDirective.args[Symbol.iterator](), _step17; !(_iteratorNormalCompletion17 = (_step17 = _iterator17.next()).done); _iteratorNormalCompletion17 = true) {
- var arg = _step17.value;
- if (!oldArgMap[arg.name]) {
- addedArgs.push(arg);
- }
- }
- } catch (err) {
- _didIteratorError17 = true;
- _iteratorError17 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion17 && _iterator17.return != null) {
- _iterator17.return();
- }
- } finally {
- if (_didIteratorError17) {
- throw _iteratorError17;
- }
- }
- }
- return addedArgs;
- }
- function findAddedNonNullDirectiveArgs(oldSchema, newSchema) {
- var addedNonNullableArgs = [];
- var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema);
- var _iteratorNormalCompletion18 = true;
- var _didIteratorError18 = false;
- var _iteratorError18 = undefined;
- try {
- for (var _iterator18 = newSchema.getDirectives()[Symbol.iterator](), _step18; !(_iteratorNormalCompletion18 = (_step18 = _iterator18.next()).done); _iteratorNormalCompletion18 = true) {
- var newDirective = _step18.value;
- var oldDirective = oldSchemaDirectiveMap[newDirective.name];
- if (!oldDirective) {
- continue;
- }
- var _iteratorNormalCompletion19 = true;
- var _didIteratorError19 = false;
- var _iteratorError19 = undefined;
- try {
- for (var _iterator19 = findAddedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step19; !(_iteratorNormalCompletion19 = (_step19 = _iterator19.next()).done); _iteratorNormalCompletion19 = true) {
- var arg = _step19.value;
- if ((0, _definition.isRequiredArgument)(arg)) {
- addedNonNullableArgs.push({
- type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED,
- description: "A required arg ".concat(arg.name, " on directive ") + "".concat(newDirective.name, " was added")
- });
- }
- }
- } catch (err) {
- _didIteratorError19 = true;
- _iteratorError19 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion19 && _iterator19.return != null) {
- _iterator19.return();
- }
- } finally {
- if (_didIteratorError19) {
- throw _iteratorError19;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError18 = true;
- _iteratorError18 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion18 && _iterator18.return != null) {
- _iterator18.return();
- }
- } finally {
- if (_didIteratorError18) {
- throw _iteratorError18;
- }
- }
- }
- return addedNonNullableArgs;
- }
- function findRemovedLocationsForDirective(oldDirective, newDirective) {
- var removedLocations = [];
- var newLocationSet = new Set(newDirective.locations);
- var _iteratorNormalCompletion20 = true;
- var _didIteratorError20 = false;
- var _iteratorError20 = undefined;
- try {
- for (var _iterator20 = oldDirective.locations[Symbol.iterator](), _step20; !(_iteratorNormalCompletion20 = (_step20 = _iterator20.next()).done); _iteratorNormalCompletion20 = true) {
- var oldLocation = _step20.value;
- if (!newLocationSet.has(oldLocation)) {
- removedLocations.push(oldLocation);
- }
- }
- } catch (err) {
- _didIteratorError20 = true;
- _iteratorError20 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion20 && _iterator20.return != null) {
- _iterator20.return();
- }
- } finally {
- if (_didIteratorError20) {
- throw _iteratorError20;
- }
- }
- }
- return removedLocations;
- }
- function findRemovedDirectiveLocations(oldSchema, newSchema) {
- var removedLocations = [];
- var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema);
- var _iteratorNormalCompletion21 = true;
- var _didIteratorError21 = false;
- var _iteratorError21 = undefined;
- try {
- for (var _iterator21 = newSchema.getDirectives()[Symbol.iterator](), _step21; !(_iteratorNormalCompletion21 = (_step21 = _iterator21.next()).done); _iteratorNormalCompletion21 = true) {
- var newDirective = _step21.value;
- var oldDirective = oldSchemaDirectiveMap[newDirective.name];
- if (!oldDirective) {
- continue;
- }
- var _iteratorNormalCompletion22 = true;
- var _didIteratorError22 = false;
- var _iteratorError22 = undefined;
- try {
- for (var _iterator22 = findRemovedLocationsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step22; !(_iteratorNormalCompletion22 = (_step22 = _iterator22.next()).done); _iteratorNormalCompletion22 = true) {
- var location = _step22.value;
- removedLocations.push({
- type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED,
- description: "".concat(location, " was removed from ").concat(newDirective.name)
- });
- }
- } catch (err) {
- _didIteratorError22 = true;
- _iteratorError22 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion22 && _iterator22.return != null) {
- _iterator22.return();
- }
- } finally {
- if (_didIteratorError22) {
- throw _iteratorError22;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError21 = true;
- _iteratorError21 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion21 && _iterator21.return != null) {
- _iterator21.return();
- }
- } finally {
- if (_didIteratorError21) {
- throw _iteratorError21;
- }
- }
- }
- return removedLocations;
- }
- function getDirectiveMapForSchema(schema) {
- return (0, _keyMap.default)(schema.getDirectives(), function (dir) {
- return dir.name;
- });
- }
- function getArgumentMapForDirective(directive) {
- return (0, _keyMap.default)(directive.args, function (arg) {
- return arg.name;
- });
- }
- },{"../jsutils/keyMap":294,"../polyfills/find":315,"../type/definition":323}],339:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.findDeprecatedUsages = findDeprecatedUsages;
- var _GraphQLError = require("../error/GraphQLError");
- var _visitor = require("../language/visitor");
- var _definition = require("../type/definition");
- var _TypeInfo = require("./TypeInfo");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * A validation rule which reports deprecated usages.
- *
- * Returns a list of GraphQLError instances describing each deprecated use.
- */
- function findDeprecatedUsages(schema, ast) {
- var errors = [];
- var typeInfo = new _TypeInfo.TypeInfo(schema);
- (0, _visitor.visit)(ast, (0, _visitor.visitWithTypeInfo)(typeInfo, {
- Field: function Field(node) {
- var fieldDef = typeInfo.getFieldDef();
- if (fieldDef && fieldDef.isDeprecated) {
- var parentType = typeInfo.getParentType();
- if (parentType) {
- var reason = fieldDef.deprecationReason;
- errors.push(new _GraphQLError.GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node]));
- }
- }
- },
- EnumValue: function EnumValue(node) {
- var enumVal = typeInfo.getEnumValue();
- if (enumVal && enumVal.isDeprecated) {
- var type = (0, _definition.getNamedType)(typeInfo.getInputType());
- if (type) {
- var reason = enumVal.deprecationReason;
- errors.push(new _GraphQLError.GraphQLError("The enum value ".concat(type.name, ".").concat(enumVal.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node]));
- }
- }
- }
- }));
- return errors;
- }
- },{"../error/GraphQLError":275,"../language/visitor":314,"../type/definition":323,"./TypeInfo":330}],340:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getOperationAST = getOperationAST;
- var _kinds = require("../language/kinds");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Returns an operation AST given a document AST and optionally an operation
- * name. If a name is not provided, an operation is only returned if only one is
- * provided in the document.
- */
- function getOperationAST(documentAST, operationName) {
- var operation = null;
- for (var i = 0; i < documentAST.definitions.length; i++) {
- var definition = documentAST.definitions[i];
- if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) {
- if (!operationName) {
- // If no operation name was provided, only return an Operation if there
- // is one defined in the document. Upon encountering the second, return
- // null.
- if (operation) {
- return null;
- }
- operation = definition;
- } else if (definition.name && definition.name.value === operationName) {
- return definition;
- }
- }
- }
- return operation;
- }
- },{"../language/kinds":307}],341:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getOperationRootType = getOperationRootType;
- var _GraphQLError = require("../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Extracts the root type of the operation from the schema.
- */
- function getOperationRootType(schema, operation) {
- switch (operation.operation) {
- case 'query':
- var queryType = schema.getQueryType();
- if (!queryType) {
- throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', [operation]);
- }
- return queryType;
- case 'mutation':
- var mutationType = schema.getMutationType();
- if (!mutationType) {
- throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', [operation]);
- }
- return mutationType;
- case 'subscription':
- var subscriptionType = schema.getSubscriptionType();
- if (!subscriptionType) {
- throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', [operation]);
- }
- return subscriptionType;
- default:
- throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', [operation]);
- }
- }
- },{"../error/GraphQLError":275}],342:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "getIntrospectionQuery", {
- enumerable: true,
- get: function get() {
- return _introspectionQuery.getIntrospectionQuery;
- }
- });
- Object.defineProperty(exports, "introspectionQuery", {
- enumerable: true,
- get: function get() {
- return _introspectionQuery.introspectionQuery;
- }
- });
- Object.defineProperty(exports, "getOperationAST", {
- enumerable: true,
- get: function get() {
- return _getOperationAST.getOperationAST;
- }
- });
- Object.defineProperty(exports, "getOperationRootType", {
- enumerable: true,
- get: function get() {
- return _getOperationRootType.getOperationRootType;
- }
- });
- Object.defineProperty(exports, "introspectionFromSchema", {
- enumerable: true,
- get: function get() {
- return _introspectionFromSchema.introspectionFromSchema;
- }
- });
- Object.defineProperty(exports, "buildClientSchema", {
- enumerable: true,
- get: function get() {
- return _buildClientSchema.buildClientSchema;
- }
- });
- Object.defineProperty(exports, "buildASTSchema", {
- enumerable: true,
- get: function get() {
- return _buildASTSchema.buildASTSchema;
- }
- });
- Object.defineProperty(exports, "buildSchema", {
- enumerable: true,
- get: function get() {
- return _buildASTSchema.buildSchema;
- }
- });
- Object.defineProperty(exports, "getDescription", {
- enumerable: true,
- get: function get() {
- return _buildASTSchema.getDescription;
- }
- });
- Object.defineProperty(exports, "extendSchema", {
- enumerable: true,
- get: function get() {
- return _extendSchema.extendSchema;
- }
- });
- Object.defineProperty(exports, "lexicographicSortSchema", {
- enumerable: true,
- get: function get() {
- return _lexicographicSortSchema.lexicographicSortSchema;
- }
- });
- Object.defineProperty(exports, "printSchema", {
- enumerable: true,
- get: function get() {
- return _schemaPrinter.printSchema;
- }
- });
- Object.defineProperty(exports, "printType", {
- enumerable: true,
- get: function get() {
- return _schemaPrinter.printType;
- }
- });
- Object.defineProperty(exports, "printIntrospectionSchema", {
- enumerable: true,
- get: function get() {
- return _schemaPrinter.printIntrospectionSchema;
- }
- });
- Object.defineProperty(exports, "typeFromAST", {
- enumerable: true,
- get: function get() {
- return _typeFromAST.typeFromAST;
- }
- });
- Object.defineProperty(exports, "valueFromAST", {
- enumerable: true,
- get: function get() {
- return _valueFromAST.valueFromAST;
- }
- });
- Object.defineProperty(exports, "valueFromASTUntyped", {
- enumerable: true,
- get: function get() {
- return _valueFromASTUntyped.valueFromASTUntyped;
- }
- });
- Object.defineProperty(exports, "astFromValue", {
- enumerable: true,
- get: function get() {
- return _astFromValue.astFromValue;
- }
- });
- Object.defineProperty(exports, "TypeInfo", {
- enumerable: true,
- get: function get() {
- return _TypeInfo.TypeInfo;
- }
- });
- Object.defineProperty(exports, "coerceValue", {
- enumerable: true,
- get: function get() {
- return _coerceValue.coerceValue;
- }
- });
- Object.defineProperty(exports, "isValidJSValue", {
- enumerable: true,
- get: function get() {
- return _isValidJSValue.isValidJSValue;
- }
- });
- Object.defineProperty(exports, "isValidLiteralValue", {
- enumerable: true,
- get: function get() {
- return _isValidLiteralValue.isValidLiteralValue;
- }
- });
- Object.defineProperty(exports, "concatAST", {
- enumerable: true,
- get: function get() {
- return _concatAST.concatAST;
- }
- });
- Object.defineProperty(exports, "separateOperations", {
- enumerable: true,
- get: function get() {
- return _separateOperations.separateOperations;
- }
- });
- Object.defineProperty(exports, "isEqualType", {
- enumerable: true,
- get: function get() {
- return _typeComparators.isEqualType;
- }
- });
- Object.defineProperty(exports, "isTypeSubTypeOf", {
- enumerable: true,
- get: function get() {
- return _typeComparators.isTypeSubTypeOf;
- }
- });
- Object.defineProperty(exports, "doTypesOverlap", {
- enumerable: true,
- get: function get() {
- return _typeComparators.doTypesOverlap;
- }
- });
- Object.defineProperty(exports, "assertValidName", {
- enumerable: true,
- get: function get() {
- return _assertValidName.assertValidName;
- }
- });
- Object.defineProperty(exports, "isValidNameError", {
- enumerable: true,
- get: function get() {
- return _assertValidName.isValidNameError;
- }
- });
- Object.defineProperty(exports, "BreakingChangeType", {
- enumerable: true,
- get: function get() {
- return _findBreakingChanges.BreakingChangeType;
- }
- });
- Object.defineProperty(exports, "DangerousChangeType", {
- enumerable: true,
- get: function get() {
- return _findBreakingChanges.DangerousChangeType;
- }
- });
- Object.defineProperty(exports, "findBreakingChanges", {
- enumerable: true,
- get: function get() {
- return _findBreakingChanges.findBreakingChanges;
- }
- });
- Object.defineProperty(exports, "findDangerousChanges", {
- enumerable: true,
- get: function get() {
- return _findBreakingChanges.findDangerousChanges;
- }
- });
- Object.defineProperty(exports, "findDeprecatedUsages", {
- enumerable: true,
- get: function get() {
- return _findDeprecatedUsages.findDeprecatedUsages;
- }
- });
- var _introspectionQuery = require("./introspectionQuery");
- var _getOperationAST = require("./getOperationAST");
- var _getOperationRootType = require("./getOperationRootType");
- var _introspectionFromSchema = require("./introspectionFromSchema");
- var _buildClientSchema = require("./buildClientSchema");
- var _buildASTSchema = require("./buildASTSchema");
- var _extendSchema = require("./extendSchema");
- var _lexicographicSortSchema = require("./lexicographicSortSchema");
- var _schemaPrinter = require("./schemaPrinter");
- var _typeFromAST = require("./typeFromAST");
- var _valueFromAST = require("./valueFromAST");
- var _valueFromASTUntyped = require("./valueFromASTUntyped");
- var _astFromValue = require("./astFromValue");
- var _TypeInfo = require("./TypeInfo");
- var _coerceValue = require("./coerceValue");
- var _isValidJSValue = require("./isValidJSValue");
- var _isValidLiteralValue = require("./isValidLiteralValue");
- var _concatAST = require("./concatAST");
- var _separateOperations = require("./separateOperations");
- var _typeComparators = require("./typeComparators");
- var _assertValidName = require("./assertValidName");
- var _findBreakingChanges = require("./findBreakingChanges");
- var _findDeprecatedUsages = require("./findDeprecatedUsages");
- },{"./TypeInfo":330,"./assertValidName":331,"./astFromValue":332,"./buildASTSchema":333,"./buildClientSchema":334,"./coerceValue":335,"./concatAST":336,"./extendSchema":337,"./findBreakingChanges":338,"./findDeprecatedUsages":339,"./getOperationAST":340,"./getOperationRootType":341,"./introspectionFromSchema":343,"./introspectionQuery":344,"./isValidJSValue":345,"./isValidLiteralValue":346,"./lexicographicSortSchema":347,"./schemaPrinter":348,"./separateOperations":349,"./typeComparators":350,"./typeFromAST":351,"./valueFromAST":352,"./valueFromASTUntyped":353}],343:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.introspectionFromSchema = introspectionFromSchema;
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _introspectionQuery = require("./introspectionQuery");
- var _execute = require("../execution/execute");
- var _parser = require("../language/parser");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Build an IntrospectionQuery from a GraphQLSchema
- *
- * IntrospectionQuery is useful for utilities that care about type and field
- * relationships, but do not need to traverse through those relationships.
- *
- * This is the inverse of buildClientSchema. The primary use case is outside
- * of the server context, for instance when doing schema comparisons.
- */
- function introspectionFromSchema(schema, options) {
- var queryAST = (0, _parser.parse)((0, _introspectionQuery.getIntrospectionQuery)(options));
- var result = (0, _execute.execute)(schema, queryAST);
- !(!result.then && !result.errors && result.data) ? (0, _invariant.default)(0) : void 0;
- return result.data;
- }
- },{"../execution/execute":281,"../jsutils/invariant":290,"../language/parser":310,"./introspectionQuery":344}],344:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getIntrospectionQuery = getIntrospectionQuery;
- exports.introspectionQuery = void 0;
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function getIntrospectionQuery(options) {
- var descriptions = !(options && options.descriptions === false);
- return "\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ".concat(descriptions ? 'description' : '', "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions ? 'description' : '', "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions ? 'description' : '', "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n ");
- }
- /**
- * Deprecated, call getIntrospectionQuery directly.
- *
- * This function will be removed in v15
- */
- var introspectionQuery = getIntrospectionQuery();
- exports.introspectionQuery = introspectionQuery;
- },{}],345:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isValidJSValue = isValidJSValue;
- var _coerceValue = require("./coerceValue");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Deprecated. Use coerceValue() directly for richer information.
- *
- * This function will be removed in v15
- */
- function isValidJSValue(value, type) {
- var errors = (0, _coerceValue.coerceValue)(value, type).errors;
- return errors ? errors.map(function (error) {
- return error.message;
- }) : [];
- }
- },{"./coerceValue":335}],346:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isValidLiteralValue = isValidLiteralValue;
- var _TypeInfo = require("./TypeInfo");
- var _kinds = require("../language/kinds");
- var _visitor = require("../language/visitor");
- var _schema = require("../type/schema");
- var _ValuesOfCorrectType = require("../validation/rules/ValuesOfCorrectType");
- var _ValidationContext = require("../validation/ValidationContext");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Utility which determines if a value literal node is valid for an input type.
- *
- * Deprecated. Rely on validation for documents containing literal values.
- *
- * This function will be removed in v15
- */
- function isValidLiteralValue(type, valueNode) {
- var emptySchema = new _schema.GraphQLSchema({});
- var emptyDoc = {
- kind: _kinds.Kind.DOCUMENT,
- definitions: []
- };
- var typeInfo = new _TypeInfo.TypeInfo(emptySchema, undefined, type);
- var context = new _ValidationContext.ValidationContext(emptySchema, emptyDoc, typeInfo);
- var visitor = (0, _ValuesOfCorrectType.ValuesOfCorrectType)(context);
- (0, _visitor.visit)(valueNode, (0, _visitor.visitWithTypeInfo)(typeInfo, visitor));
- return context.getErrors();
- }
- },{"../language/kinds":307,"../language/visitor":314,"../type/schema":328,"../validation/ValidationContext":354,"../validation/rules/ValuesOfCorrectType":386,"./TypeInfo":330}],347:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.lexicographicSortSchema = lexicographicSortSchema;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _schema = require("../type/schema");
- var _directives = require("../type/directives");
- var _definition = require("../type/definition");
- var _scalars = require("../type/scalars");
- var _introspection = require("../type/introspection");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- /**
- * Sort GraphQLSchema.
- */
- function lexicographicSortSchema(schema) {
- var cache = Object.create(null);
- var sortMaybeType = function sortMaybeType(maybeType) {
- return maybeType && sortNamedType(maybeType);
- };
- return new _schema.GraphQLSchema({
- types: sortTypes((0, _objectValues.default)(schema.getTypeMap())),
- directives: sortByName(schema.getDirectives()).map(sortDirective),
- query: sortMaybeType(schema.getQueryType()),
- mutation: sortMaybeType(schema.getMutationType()),
- subscription: sortMaybeType(schema.getSubscriptionType()),
- astNode: schema.astNode
- });
- function sortDirective(directive) {
- return new _directives.GraphQLDirective({
- name: directive.name,
- description: directive.description,
- locations: sortBy(directive.locations, function (x) {
- return x;
- }),
- args: sortArgs(directive.args),
- astNode: directive.astNode
- });
- }
- function sortArgs(args) {
- return (0, _keyValMap.default)(sortByName(args), function (arg) {
- return arg.name;
- }, function (arg) {
- return _objectSpread({}, arg, {
- type: sortType(arg.type)
- });
- });
- }
- function sortFields(fieldsMap) {
- return sortObjMap(fieldsMap, function (field) {
- return {
- type: sortType(field.type),
- args: sortArgs(field.args),
- resolve: field.resolve,
- subscribe: field.subscribe,
- deprecationReason: field.deprecationReason,
- description: field.description,
- astNode: field.astNode
- };
- });
- }
- function sortInputFields(fieldsMap) {
- return sortObjMap(fieldsMap, function (field) {
- return {
- type: sortType(field.type),
- defaultValue: field.defaultValue,
- description: field.description,
- astNode: field.astNode
- };
- });
- }
- function sortType(type) {
- if ((0, _definition.isListType)(type)) {
- return new _definition.GraphQLList(sortType(type.ofType));
- } else if ((0, _definition.isNonNullType)(type)) {
- return new _definition.GraphQLNonNull(sortType(type.ofType));
- }
- return sortNamedType(type);
- }
- function sortTypes(arr) {
- return sortByName(arr).map(sortNamedType);
- }
- function sortNamedType(type) {
- if ((0, _scalars.isSpecifiedScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) {
- return type;
- }
- var sortedType = cache[type.name];
- if (!sortedType) {
- sortedType = sortNamedTypeImpl(type);
- cache[type.name] = sortedType;
- }
- return sortedType;
- }
- function sortNamedTypeImpl(type) {
- if ((0, _definition.isScalarType)(type)) {
- return type;
- } else if ((0, _definition.isObjectType)(type)) {
- return new _definition.GraphQLObjectType({
- name: type.name,
- interfaces: function interfaces() {
- return sortTypes(type.getInterfaces());
- },
- fields: function fields() {
- return sortFields(type.getFields());
- },
- isTypeOf: type.isTypeOf,
- description: type.description,
- astNode: type.astNode,
- extensionASTNodes: type.extensionASTNodes
- });
- } else if ((0, _definition.isInterfaceType)(type)) {
- return new _definition.GraphQLInterfaceType({
- name: type.name,
- fields: function fields() {
- return sortFields(type.getFields());
- },
- resolveType: type.resolveType,
- description: type.description,
- astNode: type.astNode,
- extensionASTNodes: type.extensionASTNodes
- });
- } else if ((0, _definition.isUnionType)(type)) {
- return new _definition.GraphQLUnionType({
- name: type.name,
- types: function types() {
- return sortTypes(type.getTypes());
- },
- resolveType: type.resolveType,
- description: type.description,
- astNode: type.astNode
- });
- } else if ((0, _definition.isEnumType)(type)) {
- return new _definition.GraphQLEnumType({
- name: type.name,
- values: (0, _keyValMap.default)(sortByName(type.getValues()), function (val) {
- return val.name;
- }, function (val) {
- return {
- value: val.value,
- deprecationReason: val.deprecationReason,
- description: val.description,
- astNode: val.astNode
- };
- }),
- description: type.description,
- astNode: type.astNode
- });
- } else if ((0, _definition.isInputObjectType)(type)) {
- return new _definition.GraphQLInputObjectType({
- name: type.name,
- fields: function fields() {
- return sortInputFields(type.getFields());
- },
- description: type.description,
- astNode: type.astNode
- });
- }
- throw new Error("Unknown type: \"".concat(type, "\""));
- }
- }
- function sortObjMap(map, sortValueFn) {
- var sortedMap = Object.create(null);
- var sortedKeys = sortBy(Object.keys(map), function (x) {
- return x;
- });
- for (var _i = 0; _i < sortedKeys.length; _i++) {
- var key = sortedKeys[_i];
- var value = map[key];
- sortedMap[key] = sortValueFn ? sortValueFn(value) : value;
- }
- return sortedMap;
- }
- function sortByName(array) {
- return sortBy(array, function (obj) {
- return obj.name;
- });
- }
- function sortBy(array, mapToKey) {
- return array.slice().sort(function (obj1, obj2) {
- var key1 = mapToKey(obj1);
- var key2 = mapToKey(obj2);
- return key1.localeCompare(key2);
- });
- }
- },{"../jsutils/keyValMap":295,"../polyfills/objectValues":319,"../type/definition":323,"../type/directives":324,"../type/introspection":326,"../type/scalars":327,"../type/schema":328}],348:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.printSchema = printSchema;
- exports.printIntrospectionSchema = printIntrospectionSchema;
- exports.printType = printType;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _isNullish = _interopRequireDefault(require("../jsutils/isNullish"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _astFromValue = require("../utilities/astFromValue");
- var _printer = require("../language/printer");
- var _definition = require("../type/definition");
- var _scalars = require("../type/scalars");
- var _directives = require("../type/directives");
- var _introspection = require("../type/introspection");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Accepts options as a second argument:
- *
- * - commentDescriptions:
- * Provide true to use preceding comments as the description.
- *
- */
- function printSchema(schema, options) {
- return printFilteredSchema(schema, function (n) {
- return !(0, _directives.isSpecifiedDirective)(n);
- }, isDefinedType, options);
- }
- function printIntrospectionSchema(schema, options) {
- return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType, options);
- }
- function isDefinedType(type) {
- return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type);
- }
- function printFilteredSchema(schema, directiveFilter, typeFilter, options) {
- var directives = schema.getDirectives().filter(directiveFilter);
- var typeMap = schema.getTypeMap();
- var types = (0, _objectValues.default)(typeMap).sort(function (type1, type2) {
- return type1.name.localeCompare(type2.name);
- }).filter(typeFilter);
- return [printSchemaDefinition(schema)].concat(directives.map(function (directive) {
- return printDirective(directive, options);
- }), types.map(function (type) {
- return printType(type, options);
- })).filter(Boolean).join('\n\n') + '\n';
- }
- function printSchemaDefinition(schema) {
- if (isSchemaOfCommonNames(schema)) {
- return;
- }
- var operationTypes = [];
- var queryType = schema.getQueryType();
- if (queryType) {
- operationTypes.push(" query: ".concat(queryType.name));
- }
- var mutationType = schema.getMutationType();
- if (mutationType) {
- operationTypes.push(" mutation: ".concat(mutationType.name));
- }
- var subscriptionType = schema.getSubscriptionType();
- if (subscriptionType) {
- operationTypes.push(" subscription: ".concat(subscriptionType.name));
- }
- return "schema {\n".concat(operationTypes.join('\n'), "\n}");
- }
- /**
- * GraphQL schema define root types for each type of operation. These types are
- * the same as any other type and can be named in any manner, however there is
- * a common naming convention:
- *
- * schema {
- * query: Query
- * mutation: Mutation
- * }
- *
- * When using this naming convention, the schema description can be omitted.
- */
- function isSchemaOfCommonNames(schema) {
- var queryType = schema.getQueryType();
- if (queryType && queryType.name !== 'Query') {
- return false;
- }
- var mutationType = schema.getMutationType();
- if (mutationType && mutationType.name !== 'Mutation') {
- return false;
- }
- var subscriptionType = schema.getSubscriptionType();
- if (subscriptionType && subscriptionType.name !== 'Subscription') {
- return false;
- }
- return true;
- }
- function printType(type, options) {
- if ((0, _definition.isScalarType)(type)) {
- return printScalar(type, options);
- } else if ((0, _definition.isObjectType)(type)) {
- return printObject(type, options);
- } else if ((0, _definition.isInterfaceType)(type)) {
- return printInterface(type, options);
- } else if ((0, _definition.isUnionType)(type)) {
- return printUnion(type, options);
- } else if ((0, _definition.isEnumType)(type)) {
- return printEnum(type, options);
- } else if ((0, _definition.isInputObjectType)(type)) {
- return printInputObject(type, options);
- }
- /* istanbul ignore next */
- throw new Error("Unknown type: ".concat(type, "."));
- }
- function printScalar(type, options) {
- return printDescription(options, type) + "scalar ".concat(type.name);
- }
- function printObject(type, options) {
- var interfaces = type.getInterfaces();
- var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) {
- return i.name;
- }).join(' & ') : '';
- return printDescription(options, type) + "type ".concat(type.name).concat(implementedInterfaces, " {\n") + printFields(options, type) + '\n' + '}';
- }
- function printInterface(type, options) {
- return printDescription(options, type) + "interface ".concat(type.name, " {\n") + printFields(options, type) + '\n' + '}';
- }
- function printUnion(type, options) {
- return printDescription(options, type) + "union ".concat(type.name, " = ").concat(type.getTypes().join(' | '));
- }
- function printEnum(type, options) {
- return printDescription(options, type) + "enum ".concat(type.name, " {\n") + printEnumValues(type.getValues(), options) + '\n' + '}';
- }
- function printEnumValues(values, options) {
- return values.map(function (value, i) {
- return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value);
- }).join('\n');
- }
- function printInputObject(type, options) {
- var fields = (0, _objectValues.default)(type.getFields());
- return printDescription(options, type) + "input ".concat(type.name, " {\n") + fields.map(function (f, i) {
- return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f);
- }).join('\n') + '\n' + '}';
- }
- function printFields(options, type) {
- var fields = (0, _objectValues.default)(type.getFields());
- return fields.map(function (f, i) {
- return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f);
- }).join('\n');
- }
- function printArgs(options, args) {
- var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
- if (args.length === 0) {
- return '';
- } // If every arg does not have a description, print them on one line.
- if (args.every(function (arg) {
- return !arg.description;
- })) {
- return '(' + args.map(printInputValue).join(', ') + ')';
- }
- return '(\n' + args.map(function (arg, i) {
- return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg);
- }).join('\n') + '\n' + indentation + ')';
- }
- function printInputValue(arg) {
- var argDecl = arg.name + ': ' + String(arg.type);
- if (!(0, _isInvalid.default)(arg.defaultValue)) {
- argDecl += " = ".concat((0, _printer.print)((0, _astFromValue.astFromValue)(arg.defaultValue, arg.type)));
- }
- return argDecl;
- }
- function printDirective(directive, options) {
- return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + ' on ' + directive.locations.join(' | ');
- }
- function printDeprecated(fieldOrEnumVal) {
- if (!fieldOrEnumVal.isDeprecated) {
- return '';
- }
- var reason = fieldOrEnumVal.deprecationReason;
- if ((0, _isNullish.default)(reason) || reason === '' || reason === _directives.DEFAULT_DEPRECATION_REASON) {
- return ' @deprecated';
- }
- return ' @deprecated(reason: ' + (0, _printer.print)((0, _astFromValue.astFromValue)(reason, _scalars.GraphQLString)) + ')';
- }
- function printDescription(options, def) {
- var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
- var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
- if (!def.description) {
- return '';
- }
- var lines = descriptionLines(def.description, 120 - indentation.length);
- if (options && options.commentDescriptions) {
- return printDescriptionWithComments(lines, indentation, firstInBlock);
- }
- var description = indentation && !firstInBlock ? '\n' + indentation + '"""' : indentation + '"""'; // In some circumstances, a single line can be used for the description.
- if (lines.length === 1 && lines[0].length < 70 && lines[0][lines[0].length - 1] !== '"') {
- return description + escapeQuote(lines[0]) + '"""\n';
- } // Format a multi-line block quote to account for leading space.
- var hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t';
- if (!hasLeadingSpace) {
- description += '\n';
- }
- for (var i = 0; i < lines.length; i++) {
- if (i !== 0 || !hasLeadingSpace) {
- description += indentation;
- }
- description += escapeQuote(lines[i]) + '\n';
- }
- description += indentation + '"""\n';
- return description;
- }
- function escapeQuote(line) {
- return line.replace(/"""/g, '\\"""');
- }
- function printDescriptionWithComments(lines, indentation, firstInBlock) {
- var description = indentation && !firstInBlock ? '\n' : '';
- for (var i = 0; i < lines.length; i++) {
- if (lines[i] === '') {
- description += indentation + '#\n';
- } else {
- description += indentation + '# ' + lines[i] + '\n';
- }
- }
- return description;
- }
- function descriptionLines(description, maxLen) {
- var lines = [];
- var rawLines = description.split('\n');
- for (var i = 0; i < rawLines.length; i++) {
- if (rawLines[i] === '') {
- lines.push(rawLines[i]);
- } else {
- // For > 120 character long lines, cut at space boundaries into sublines
- // of ~80 chars.
- var sublines = breakLine(rawLines[i], maxLen);
- for (var j = 0; j < sublines.length; j++) {
- lines.push(sublines[j]);
- }
- }
- }
- return lines;
- }
- function breakLine(line, maxLen) {
- if (line.length < maxLen + 5) {
- return [line];
- }
- var parts = line.split(new RegExp("((?: |^).{15,".concat(maxLen - 40, "}(?= |$))")));
- if (parts.length < 4) {
- return [line];
- }
- var sublines = [parts[0] + parts[1] + parts[2]];
- for (var i = 3; i < parts.length; i += 2) {
- sublines.push(parts[i].slice(1) + parts[i + 1]);
- }
- return sublines;
- }
- },{"../jsutils/isInvalid":291,"../jsutils/isNullish":292,"../language/printer":312,"../polyfills/objectValues":319,"../type/definition":323,"../type/directives":324,"../type/introspection":326,"../type/scalars":327,"../utilities/astFromValue":332}],349:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.separateOperations = separateOperations;
- var _visitor = require("../language/visitor");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * separateOperations accepts a single AST document which may contain many
- * operations and fragments and returns a collection of AST documents each of
- * which contains a single operation as well the fragment definitions it
- * refers to.
- */
- function separateOperations(documentAST) {
- var operations = [];
- var fragments = Object.create(null);
- var positions = new Map();
- var depGraph = Object.create(null);
- var fromName;
- var idx = 0; // Populate metadata and build a dependency graph.
- (0, _visitor.visit)(documentAST, {
- OperationDefinition: function OperationDefinition(node) {
- fromName = opName(node);
- operations.push(node);
- positions.set(node, idx++);
- },
- FragmentDefinition: function FragmentDefinition(node) {
- fromName = node.name.value;
- fragments[fromName] = node;
- positions.set(node, idx++);
- },
- FragmentSpread: function FragmentSpread(node) {
- var toName = node.name.value;
- (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true;
- }
- }); // For each operation, produce a new synthesized AST which includes only what
- // is necessary for completing that operation.
- var separatedDocumentASTs = Object.create(null);
- for (var _i = 0; _i < operations.length; _i++) {
- var operation = operations[_i];
- var operationName = opName(operation);
- var dependencies = Object.create(null);
- collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted
- // to retain the same order as the original document.
- var definitions = [operation];
- var _arr = Object.keys(dependencies);
- for (var _i2 = 0; _i2 < _arr.length; _i2++) {
- var name = _arr[_i2];
- definitions.push(fragments[name]);
- }
- definitions.sort(function (n1, n2) {
- return (positions.get(n1) || 0) - (positions.get(n2) || 0);
- });
- separatedDocumentASTs[operationName] = {
- kind: 'Document',
- definitions: definitions
- };
- }
- return separatedDocumentASTs;
- }
- // Provides the empty string for anonymous operations.
- function opName(operation) {
- return operation.name ? operation.name.value : '';
- } // From a dependency graph, collects a list of transitive dependencies by
- // recursing through a dependency graph.
- function collectTransitiveDependencies(collected, depGraph, fromName) {
- var immediateDeps = depGraph[fromName];
- if (immediateDeps) {
- var _arr2 = Object.keys(immediateDeps);
- for (var _i3 = 0; _i3 < _arr2.length; _i3++) {
- var toName = _arr2[_i3];
- if (!collected[toName]) {
- collected[toName] = true;
- collectTransitiveDependencies(collected, depGraph, toName);
- }
- }
- }
- }
- },{"../language/visitor":314}],350:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.isEqualType = isEqualType;
- exports.isTypeSubTypeOf = isTypeSubTypeOf;
- exports.doTypesOverlap = doTypesOverlap;
- var _definition = require("../type/definition");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Provided two types, return true if the types are equal (invariant).
- */
- function isEqualType(typeA, typeB) {
- // Equivalent types are equal.
- if (typeA === typeB) {
- return true;
- } // If either type is non-null, the other must also be non-null.
- if ((0, _definition.isNonNullType)(typeA) && (0, _definition.isNonNullType)(typeB)) {
- return isEqualType(typeA.ofType, typeB.ofType);
- } // If either type is a list, the other must also be a list.
- if ((0, _definition.isListType)(typeA) && (0, _definition.isListType)(typeB)) {
- return isEqualType(typeA.ofType, typeB.ofType);
- } // Otherwise the types are not equal.
- return false;
- }
- /**
- * Provided a type and a super type, return true if the first type is either
- * equal or a subset of the second super type (covariant).
- */
- function isTypeSubTypeOf(schema, maybeSubType, superType) {
- // Equivalent type is a valid subtype
- if (maybeSubType === superType) {
- return true;
- } // If superType is non-null, maybeSubType must also be non-null.
- if ((0, _definition.isNonNullType)(superType)) {
- if ((0, _definition.isNonNullType)(maybeSubType)) {
- return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
- }
- return false;
- }
- if ((0, _definition.isNonNullType)(maybeSubType)) {
- // If superType is nullable, maybeSubType may be non-null or nullable.
- return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);
- } // If superType type is a list, maybeSubType type must also be a list.
- if ((0, _definition.isListType)(superType)) {
- if ((0, _definition.isListType)(maybeSubType)) {
- return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
- }
- return false;
- }
- if ((0, _definition.isListType)(maybeSubType)) {
- // If superType is not a list, maybeSubType must also be not a list.
- return false;
- } // If superType type is an abstract type, maybeSubType type may be a currently
- // possible object type.
- if ((0, _definition.isAbstractType)(superType) && (0, _definition.isObjectType)(maybeSubType) && schema.isPossibleType(superType, maybeSubType)) {
- return true;
- } // Otherwise, the child type is not a valid subtype of the parent type.
- return false;
- }
- /**
- * Provided two composite types, determine if they "overlap". Two composite
- * types overlap when the Sets of possible concrete types for each intersect.
- *
- * This is often used to determine if a fragment of a given type could possibly
- * be visited in a context of another type.
- *
- * This function is commutative.
- */
- function doTypesOverlap(schema, typeA, typeB) {
- // Equivalent types overlap
- if (typeA === typeB) {
- return true;
- }
- if ((0, _definition.isAbstractType)(typeA)) {
- if ((0, _definition.isAbstractType)(typeB)) {
- // If both types are abstract, then determine if there is any intersection
- // between possible concrete types of each.
- return schema.getPossibleTypes(typeA).some(function (type) {
- return schema.isPossibleType(typeB, type);
- });
- } // Determine if the latter type is a possible concrete type of the former.
- return schema.isPossibleType(typeA, typeB);
- }
- if ((0, _definition.isAbstractType)(typeB)) {
- // Determine if the former type is a possible concrete type of the latter.
- return schema.isPossibleType(typeB, typeA);
- } // Otherwise the types do not overlap.
- return false;
- }
- },{"../type/definition":323}],351:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.typeFromAST = typeFromAST;
- var _kinds = require("../language/kinds");
- var _definition = require("../type/definition");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function typeFromAST(schema, typeNode) {
- /* eslint-enable no-redeclare */
- var innerType;
- if (typeNode.kind === _kinds.Kind.LIST_TYPE) {
- innerType = typeFromAST(schema, typeNode.type);
- return innerType && (0, _definition.GraphQLList)(innerType);
- }
- if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) {
- innerType = typeFromAST(schema, typeNode.type);
- return innerType && (0, _definition.GraphQLNonNull)(innerType);
- }
- if (typeNode.kind === _kinds.Kind.NAMED_TYPE) {
- return schema.getType(typeNode.name.value);
- }
- /* istanbul ignore next */
- throw new Error("Unexpected type kind: ".concat(typeNode.kind, "."));
- }
- },{"../language/kinds":307,"../type/definition":323}],352:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.valueFromAST = valueFromAST;
- var _objectValues = _interopRequireDefault(require("../polyfills/objectValues"));
- var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _kinds = require("../language/kinds");
- var _definition = require("../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Produces a JavaScript value given a GraphQL Value AST.
- *
- * A GraphQL type must be provided, which will be used to interpret different
- * GraphQL Value literals.
- *
- * Returns `undefined` when the value could not be validly coerced according to
- * the provided type.
- *
- * | GraphQL Value | JSON Value |
- * | -------------------- | ------------- |
- * | Input Object | Object |
- * | List | Array |
- * | Boolean | Boolean |
- * | String | String |
- * | Int / Float | Number |
- * | Enum Value | Mixed |
- * | NullValue | null |
- *
- */
- function valueFromAST(valueNode, type, variables) {
- if (!valueNode) {
- // When there is no node, then there is also no value.
- // Importantly, this is different from returning the value null.
- return;
- }
- if ((0, _definition.isNonNullType)(type)) {
- if (valueNode.kind === _kinds.Kind.NULL) {
- return; // Invalid: intentionally return no value.
- }
- return valueFromAST(valueNode, type.ofType, variables);
- }
- if (valueNode.kind === _kinds.Kind.NULL) {
- // This is explicitly returning the value null.
- return null;
- }
- if (valueNode.kind === _kinds.Kind.VARIABLE) {
- var variableName = valueNode.name.value;
- if (!variables || (0, _isInvalid.default)(variables[variableName])) {
- // No valid return value.
- return;
- }
- var variableValue = variables[variableName];
- if (variableValue === null && (0, _definition.isNonNullType)(type)) {
- return; // Invalid: intentionally return no value.
- } // Note: This does no further checking that this variable is correct.
- // This assumes that this query has been validated and the variable
- // usage here is of the correct type.
- return variableValue;
- }
- if ((0, _definition.isListType)(type)) {
- var itemType = type.ofType;
- if (valueNode.kind === _kinds.Kind.LIST) {
- var coercedValues = [];
- var itemNodes = valueNode.values;
- for (var i = 0; i < itemNodes.length; i++) {
- if (isMissingVariable(itemNodes[i], variables)) {
- // If an array contains a missing variable, it is either coerced to
- // null or if the item type is non-null, it considered invalid.
- if ((0, _definition.isNonNullType)(itemType)) {
- return; // Invalid: intentionally return no value.
- }
- coercedValues.push(null);
- } else {
- var itemValue = valueFromAST(itemNodes[i], itemType, variables);
- if ((0, _isInvalid.default)(itemValue)) {
- return; // Invalid: intentionally return no value.
- }
- coercedValues.push(itemValue);
- }
- }
- return coercedValues;
- }
- var coercedValue = valueFromAST(valueNode, itemType, variables);
- if ((0, _isInvalid.default)(coercedValue)) {
- return; // Invalid: intentionally return no value.
- }
- return [coercedValue];
- }
- if ((0, _definition.isInputObjectType)(type)) {
- if (valueNode.kind !== _kinds.Kind.OBJECT) {
- return; // Invalid: intentionally return no value.
- }
- var coercedObj = Object.create(null);
- var fieldNodes = (0, _keyMap.default)(valueNode.fields, function (field) {
- return field.name.value;
- });
- var fields = (0, _objectValues.default)(type.getFields());
- for (var _i = 0; _i < fields.length; _i++) {
- var field = fields[_i];
- var fieldNode = fieldNodes[field.name];
- if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
- if (field.defaultValue !== undefined) {
- coercedObj[field.name] = field.defaultValue;
- } else if ((0, _definition.isNonNullType)(field.type)) {
- return; // Invalid: intentionally return no value.
- }
- continue;
- }
- var fieldValue = valueFromAST(fieldNode.value, field.type, variables);
- if ((0, _isInvalid.default)(fieldValue)) {
- return; // Invalid: intentionally return no value.
- }
- coercedObj[field.name] = fieldValue;
- }
- return coercedObj;
- }
- if ((0, _definition.isEnumType)(type)) {
- if (valueNode.kind !== _kinds.Kind.ENUM) {
- return; // Invalid: intentionally return no value.
- }
- var enumValue = type.getValue(valueNode.value);
- if (!enumValue) {
- return; // Invalid: intentionally return no value.
- }
- return enumValue.value;
- }
- if ((0, _definition.isScalarType)(type)) {
- // Scalars fulfill parsing a literal value via parseLiteral().
- // Invalid values represent a failure to parse correctly, in which case
- // no value is returned.
- var result;
- try {
- result = type.parseLiteral(valueNode, variables);
- } catch (_error) {
- return; // Invalid: intentionally return no value.
- }
- if ((0, _isInvalid.default)(result)) {
- return; // Invalid: intentionally return no value.
- }
- return result;
- }
- /* istanbul ignore next */
- throw new Error("Unknown type: ".concat(type, "."));
- } // Returns true if the provided valueNode is a variable which is not defined
- // in the set of variables.
- function isMissingVariable(valueNode, variables) {
- return valueNode.kind === _kinds.Kind.VARIABLE && (!variables || (0, _isInvalid.default)(variables[valueNode.name.value]));
- }
- },{"../jsutils/isInvalid":291,"../jsutils/keyMap":294,"../language/kinds":307,"../polyfills/objectValues":319,"../type/definition":323}],353:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.valueFromASTUntyped = valueFromASTUntyped;
- var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
- var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
- var _kinds = require("../language/kinds");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Produces a JavaScript value given a GraphQL Value AST.
- *
- * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value
- * will reflect the provided GraphQL value AST.
- *
- * | GraphQL Value | JavaScript Value |
- * | -------------------- | ---------------- |
- * | Input Object | Object |
- * | List | Array |
- * | Boolean | Boolean |
- * | String / Enum | String |
- * | Int / Float | Number |
- * | Null | null |
- *
- */
- function valueFromASTUntyped(valueNode, variables) {
- switch (valueNode.kind) {
- case _kinds.Kind.NULL:
- return null;
- case _kinds.Kind.INT:
- return parseInt(valueNode.value, 10);
- case _kinds.Kind.FLOAT:
- return parseFloat(valueNode.value);
- case _kinds.Kind.STRING:
- case _kinds.Kind.ENUM:
- case _kinds.Kind.BOOLEAN:
- return valueNode.value;
- case _kinds.Kind.LIST:
- return valueNode.values.map(function (node) {
- return valueFromASTUntyped(node, variables);
- });
- case _kinds.Kind.OBJECT:
- return (0, _keyValMap.default)(valueNode.fields, function (field) {
- return field.name.value;
- }, function (field) {
- return valueFromASTUntyped(field.value, variables);
- });
- case _kinds.Kind.VARIABLE:
- var variableName = valueNode.name.value;
- return variables && !(0, _isInvalid.default)(variables[variableName]) ? variables[variableName] : undefined;
- }
- /* istanbul ignore next */
- throw new Error('Unexpected value kind: ' + valueNode.kind);
- }
- },{"../jsutils/isInvalid":291,"../jsutils/keyValMap":295,"../language/kinds":307}],354:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = void 0;
- var _visitor = require("../language/visitor");
- var _kinds = require("../language/kinds");
- var _TypeInfo = require("../utilities/TypeInfo");
- function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
- /**
- * An instance of this class is passed as the "this" context to all validators,
- * allowing access to commonly useful contextual information from within a
- * validation rule.
- */
- var ASTValidationContext =
- /*#__PURE__*/
- function () {
- function ASTValidationContext(ast) {
- this._ast = ast;
- this._errors = [];
- this._fragments = undefined;
- this._fragmentSpreads = new Map();
- this._recursivelyReferencedFragments = new Map();
- }
- var _proto = ASTValidationContext.prototype;
- _proto.reportError = function reportError(error) {
- this._errors.push(error);
- };
- _proto.getErrors = function getErrors() {
- return this._errors;
- };
- _proto.getDocument = function getDocument() {
- return this._ast;
- };
- _proto.getFragment = function getFragment(name) {
- var fragments = this._fragments;
- if (!fragments) {
- this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) {
- if (statement.kind === _kinds.Kind.FRAGMENT_DEFINITION) {
- frags[statement.name.value] = statement;
- }
- return frags;
- }, Object.create(null));
- }
- return fragments[name];
- };
- _proto.getFragmentSpreads = function getFragmentSpreads(node) {
- var spreads = this._fragmentSpreads.get(node);
- if (!spreads) {
- spreads = [];
- var setsToVisit = [node];
- while (setsToVisit.length !== 0) {
- var set = setsToVisit.pop();
- for (var i = 0; i < set.selections.length; i++) {
- var selection = set.selections[i];
- if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) {
- spreads.push(selection);
- } else if (selection.selectionSet) {
- setsToVisit.push(selection.selectionSet);
- }
- }
- }
- this._fragmentSpreads.set(node, spreads);
- }
- return spreads;
- };
- _proto.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) {
- var fragments = this._recursivelyReferencedFragments.get(operation);
- if (!fragments) {
- fragments = [];
- var collectedNames = Object.create(null);
- var nodesToVisit = [operation.selectionSet];
- while (nodesToVisit.length !== 0) {
- var node = nodesToVisit.pop();
- var spreads = this.getFragmentSpreads(node);
- for (var i = 0; i < spreads.length; i++) {
- var fragName = spreads[i].name.value;
- if (collectedNames[fragName] !== true) {
- collectedNames[fragName] = true;
- var fragment = this.getFragment(fragName);
- if (fragment) {
- fragments.push(fragment);
- nodesToVisit.push(fragment.selectionSet);
- }
- }
- }
- }
- this._recursivelyReferencedFragments.set(operation, fragments);
- }
- return fragments;
- };
- return ASTValidationContext;
- }();
- exports.ASTValidationContext = ASTValidationContext;
- var SDLValidationContext =
- /*#__PURE__*/
- function (_ASTValidationContext) {
- _inheritsLoose(SDLValidationContext, _ASTValidationContext);
- function SDLValidationContext(ast, schema) {
- var _this;
- _this = _ASTValidationContext.call(this, ast) || this;
- _this._schema = schema;
- return _this;
- }
- var _proto2 = SDLValidationContext.prototype;
- _proto2.getSchema = function getSchema() {
- return this._schema;
- };
- return SDLValidationContext;
- }(ASTValidationContext);
- exports.SDLValidationContext = SDLValidationContext;
- var ValidationContext =
- /*#__PURE__*/
- function (_ASTValidationContext2) {
- _inheritsLoose(ValidationContext, _ASTValidationContext2);
- function ValidationContext(schema, ast, typeInfo) {
- var _this2;
- _this2 = _ASTValidationContext2.call(this, ast) || this;
- _this2._schema = schema;
- _this2._typeInfo = typeInfo;
- _this2._variableUsages = new Map();
- _this2._recursiveVariableUsages = new Map();
- return _this2;
- }
- var _proto3 = ValidationContext.prototype;
- _proto3.getSchema = function getSchema() {
- return this._schema;
- };
- _proto3.getVariableUsages = function getVariableUsages(node) {
- var usages = this._variableUsages.get(node);
- if (!usages) {
- var newUsages = [];
- var typeInfo = new _TypeInfo.TypeInfo(this._schema);
- (0, _visitor.visit)(node, (0, _visitor.visitWithTypeInfo)(typeInfo, {
- VariableDefinition: function VariableDefinition() {
- return false;
- },
- Variable: function Variable(variable) {
- newUsages.push({
- node: variable,
- type: typeInfo.getInputType(),
- defaultValue: typeInfo.getDefaultValue()
- });
- }
- }));
- usages = newUsages;
- this._variableUsages.set(node, usages);
- }
- return usages;
- };
- _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) {
- var usages = this._recursiveVariableUsages.get(operation);
- if (!usages) {
- usages = this.getVariableUsages(operation);
- var fragments = this.getRecursivelyReferencedFragments(operation);
- for (var i = 0; i < fragments.length; i++) {
- Array.prototype.push.apply(usages, this.getVariableUsages(fragments[i]));
- }
- this._recursiveVariableUsages.set(operation, usages);
- }
- return usages;
- };
- _proto3.getType = function getType() {
- return this._typeInfo.getType();
- };
- _proto3.getParentType = function getParentType() {
- return this._typeInfo.getParentType();
- };
- _proto3.getInputType = function getInputType() {
- return this._typeInfo.getInputType();
- };
- _proto3.getParentInputType = function getParentInputType() {
- return this._typeInfo.getParentInputType();
- };
- _proto3.getFieldDef = function getFieldDef() {
- return this._typeInfo.getFieldDef();
- };
- _proto3.getDirective = function getDirective() {
- return this._typeInfo.getDirective();
- };
- _proto3.getArgument = function getArgument() {
- return this._typeInfo.getArgument();
- };
- return ValidationContext;
- }(ASTValidationContext);
- exports.ValidationContext = ValidationContext;
- },{"../language/kinds":307,"../language/visitor":314,"../utilities/TypeInfo":330}],355:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- Object.defineProperty(exports, "validate", {
- enumerable: true,
- get: function get() {
- return _validate.validate;
- }
- });
- Object.defineProperty(exports, "ValidationContext", {
- enumerable: true,
- get: function get() {
- return _ValidationContext.ValidationContext;
- }
- });
- Object.defineProperty(exports, "specifiedRules", {
- enumerable: true,
- get: function get() {
- return _specifiedRules.specifiedRules;
- }
- });
- Object.defineProperty(exports, "FieldsOnCorrectTypeRule", {
- enumerable: true,
- get: function get() {
- return _FieldsOnCorrectType.FieldsOnCorrectType;
- }
- });
- Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", {
- enumerable: true,
- get: function get() {
- return _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes;
- }
- });
- Object.defineProperty(exports, "KnownArgumentNamesRule", {
- enumerable: true,
- get: function get() {
- return _KnownArgumentNames.KnownArgumentNames;
- }
- });
- Object.defineProperty(exports, "KnownDirectivesRule", {
- enumerable: true,
- get: function get() {
- return _KnownDirectives.KnownDirectives;
- }
- });
- Object.defineProperty(exports, "KnownFragmentNamesRule", {
- enumerable: true,
- get: function get() {
- return _KnownFragmentNames.KnownFragmentNames;
- }
- });
- Object.defineProperty(exports, "KnownTypeNamesRule", {
- enumerable: true,
- get: function get() {
- return _KnownTypeNames.KnownTypeNames;
- }
- });
- Object.defineProperty(exports, "LoneAnonymousOperationRule", {
- enumerable: true,
- get: function get() {
- return _LoneAnonymousOperation.LoneAnonymousOperation;
- }
- });
- Object.defineProperty(exports, "NoFragmentCyclesRule", {
- enumerable: true,
- get: function get() {
- return _NoFragmentCycles.NoFragmentCycles;
- }
- });
- Object.defineProperty(exports, "NoUndefinedVariablesRule", {
- enumerable: true,
- get: function get() {
- return _NoUndefinedVariables.NoUndefinedVariables;
- }
- });
- Object.defineProperty(exports, "NoUnusedFragmentsRule", {
- enumerable: true,
- get: function get() {
- return _NoUnusedFragments.NoUnusedFragments;
- }
- });
- Object.defineProperty(exports, "NoUnusedVariablesRule", {
- enumerable: true,
- get: function get() {
- return _NoUnusedVariables.NoUnusedVariables;
- }
- });
- Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", {
- enumerable: true,
- get: function get() {
- return _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged;
- }
- });
- Object.defineProperty(exports, "PossibleFragmentSpreadsRule", {
- enumerable: true,
- get: function get() {
- return _PossibleFragmentSpreads.PossibleFragmentSpreads;
- }
- });
- Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", {
- enumerable: true,
- get: function get() {
- return _ProvidedRequiredArguments.ProvidedRequiredArguments;
- }
- });
- Object.defineProperty(exports, "ScalarLeafsRule", {
- enumerable: true,
- get: function get() {
- return _ScalarLeafs.ScalarLeafs;
- }
- });
- Object.defineProperty(exports, "SingleFieldSubscriptionsRule", {
- enumerable: true,
- get: function get() {
- return _SingleFieldSubscriptions.SingleFieldSubscriptions;
- }
- });
- Object.defineProperty(exports, "UniqueArgumentNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueArgumentNames.UniqueArgumentNames;
- }
- });
- Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", {
- enumerable: true,
- get: function get() {
- return _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation;
- }
- });
- Object.defineProperty(exports, "UniqueFragmentNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueFragmentNames.UniqueFragmentNames;
- }
- });
- Object.defineProperty(exports, "UniqueInputFieldNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueInputFieldNames.UniqueInputFieldNames;
- }
- });
- Object.defineProperty(exports, "UniqueOperationNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueOperationNames.UniqueOperationNames;
- }
- });
- Object.defineProperty(exports, "UniqueVariableNamesRule", {
- enumerable: true,
- get: function get() {
- return _UniqueVariableNames.UniqueVariableNames;
- }
- });
- Object.defineProperty(exports, "ValuesOfCorrectTypeRule", {
- enumerable: true,
- get: function get() {
- return _ValuesOfCorrectType.ValuesOfCorrectType;
- }
- });
- Object.defineProperty(exports, "VariablesAreInputTypesRule", {
- enumerable: true,
- get: function get() {
- return _VariablesAreInputTypes.VariablesAreInputTypes;
- }
- });
- Object.defineProperty(exports, "VariablesInAllowedPositionRule", {
- enumerable: true,
- get: function get() {
- return _VariablesInAllowedPosition.VariablesInAllowedPosition;
- }
- });
- var _validate = require("./validate");
- var _ValidationContext = require("./ValidationContext");
- var _specifiedRules = require("./specifiedRules");
- var _FieldsOnCorrectType = require("./rules/FieldsOnCorrectType");
- var _FragmentsOnCompositeTypes = require("./rules/FragmentsOnCompositeTypes");
- var _KnownArgumentNames = require("./rules/KnownArgumentNames");
- var _KnownDirectives = require("./rules/KnownDirectives");
- var _KnownFragmentNames = require("./rules/KnownFragmentNames");
- var _KnownTypeNames = require("./rules/KnownTypeNames");
- var _LoneAnonymousOperation = require("./rules/LoneAnonymousOperation");
- var _NoFragmentCycles = require("./rules/NoFragmentCycles");
- var _NoUndefinedVariables = require("./rules/NoUndefinedVariables");
- var _NoUnusedFragments = require("./rules/NoUnusedFragments");
- var _NoUnusedVariables = require("./rules/NoUnusedVariables");
- var _OverlappingFieldsCanBeMerged = require("./rules/OverlappingFieldsCanBeMerged");
- var _PossibleFragmentSpreads = require("./rules/PossibleFragmentSpreads");
- var _ProvidedRequiredArguments = require("./rules/ProvidedRequiredArguments");
- var _ScalarLeafs = require("./rules/ScalarLeafs");
- var _SingleFieldSubscriptions = require("./rules/SingleFieldSubscriptions");
- var _UniqueArgumentNames = require("./rules/UniqueArgumentNames");
- var _UniqueDirectivesPerLocation = require("./rules/UniqueDirectivesPerLocation");
- var _UniqueFragmentNames = require("./rules/UniqueFragmentNames");
- var _UniqueInputFieldNames = require("./rules/UniqueInputFieldNames");
- var _UniqueOperationNames = require("./rules/UniqueOperationNames");
- var _UniqueVariableNames = require("./rules/UniqueVariableNames");
- var _ValuesOfCorrectType = require("./rules/ValuesOfCorrectType");
- var _VariablesAreInputTypes = require("./rules/VariablesAreInputTypes");
- var _VariablesInAllowedPosition = require("./rules/VariablesInAllowedPosition");
- },{"./ValidationContext":354,"./rules/FieldsOnCorrectType":357,"./rules/FragmentsOnCompositeTypes":358,"./rules/KnownArgumentNames":359,"./rules/KnownDirectives":360,"./rules/KnownFragmentNames":361,"./rules/KnownTypeNames":362,"./rules/LoneAnonymousOperation":363,"./rules/NoFragmentCycles":365,"./rules/NoUndefinedVariables":366,"./rules/NoUnusedFragments":367,"./rules/NoUnusedVariables":368,"./rules/OverlappingFieldsCanBeMerged":369,"./rules/PossibleFragmentSpreads":370,"./rules/ProvidedRequiredArguments":372,"./rules/ScalarLeafs":373,"./rules/SingleFieldSubscriptions":374,"./rules/UniqueArgumentNames":375,"./rules/UniqueDirectivesPerLocation":377,"./rules/UniqueFragmentNames":380,"./rules/UniqueInputFieldNames":381,"./rules/UniqueOperationNames":382,"./rules/UniqueVariableNames":385,"./rules/ValuesOfCorrectType":386,"./rules/VariablesAreInputTypes":387,"./rules/VariablesInAllowedPosition":388,"./specifiedRules":389,"./validate":390}],356:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.nonExecutableDefinitionMessage = nonExecutableDefinitionMessage;
- exports.ExecutableDefinitions = ExecutableDefinitions;
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _predicates = require("../../language/predicates");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function nonExecutableDefinitionMessage(defName) {
- return "The ".concat(defName, " definition is not executable.");
- }
- /**
- * Executable definitions
- *
- * A GraphQL document is only valid for execution if all definitions are either
- * operation or fragment definitions.
- */
- function ExecutableDefinitions(context) {
- return {
- Document: function Document(node) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = node.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var definition = _step.value;
- if (!(0, _predicates.isExecutableDefinitionNode)(definition)) {
- context.reportError(new _GraphQLError.GraphQLError(nonExecutableDefinitionMessage(definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : definition.name.value), [definition]));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":275,"../../language/kinds":307,"../../language/predicates":311}],357:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.undefinedFieldMessage = undefinedFieldMessage;
- exports.FieldsOnCorrectType = FieldsOnCorrectType;
- var _GraphQLError = require("../../error/GraphQLError");
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList"));
- var _definition = require("../../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function undefinedFieldMessage(fieldName, type, suggestedTypeNames, suggestedFieldNames) {
- var message = "Cannot query field \"".concat(fieldName, "\" on type \"").concat(type, "\".");
- if (suggestedTypeNames.length !== 0) {
- var suggestions = (0, _quotedOrList.default)(suggestedTypeNames);
- message += " Did you mean to use an inline fragment on ".concat(suggestions, "?");
- } else if (suggestedFieldNames.length !== 0) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedFieldNames), "?");
- }
- return message;
- }
- /**
- * Fields on correct type
- *
- * A GraphQL document is only valid if all fields selected are defined by the
- * parent type, or are an allowed meta field such as __typename.
- */
- function FieldsOnCorrectType(context) {
- return {
- Field: function Field(node) {
- var type = context.getParentType();
- if (type) {
- var fieldDef = context.getFieldDef();
- if (!fieldDef) {
- // This field doesn't exist, lets look for suggestions.
- var schema = context.getSchema();
- var fieldName = node.name.value; // First determine if there are any suggested types to condition on.
- var suggestedTypeNames = getSuggestedTypeNames(schema, type, fieldName); // If there are no suggested types, then perhaps this was a typo?
- var suggestedFieldNames = suggestedTypeNames.length !== 0 ? [] : getSuggestedFieldNames(schema, type, fieldName); // Report an error, including helpful suggestions.
- context.reportError(new _GraphQLError.GraphQLError(undefinedFieldMessage(fieldName, type.name, suggestedTypeNames, suggestedFieldNames), [node]));
- }
- }
- }
- };
- }
- /**
- * Go through all of the implementations of type, as well as the interfaces that
- * they implement. If any of those types include the provided field, suggest
- * them, sorted by how often the type is referenced, starting with Interfaces.
- */
- function getSuggestedTypeNames(schema, type, fieldName) {
- if ((0, _definition.isAbstractType)(type)) {
- var suggestedObjectTypes = [];
- var interfaceUsageCount = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = schema.getPossibleTypes(type)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var possibleType = _step.value;
- if (!possibleType.getFields()[fieldName]) {
- continue;
- } // This object type defines this field.
- suggestedObjectTypes.push(possibleType.name);
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = possibleType.getInterfaces()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var possibleInterface = _step2.value;
- if (!possibleInterface.getFields()[fieldName]) {
- continue;
- } // This interface type defines this field.
- interfaceUsageCount[possibleInterface.name] = (interfaceUsageCount[possibleInterface.name] || 0) + 1;
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- } // Suggest interface types based on how common they are.
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort(function (a, b) {
- return interfaceUsageCount[b] - interfaceUsageCount[a];
- }); // Suggest both interface and object types.
- return suggestedInterfaceTypes.concat(suggestedObjectTypes);
- } // Otherwise, must be an Object type, which does not have possible fields.
- return [];
- }
- /**
- * For the field name provided, determine if there are any similar field names
- * that may be the result of a typo.
- */
- function getSuggestedFieldNames(schema, type, fieldName) {
- if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) {
- var possibleFieldNames = Object.keys(type.getFields());
- return (0, _suggestionList.default)(fieldName, possibleFieldNames);
- } // Otherwise, must be a Union type, which does not define fields.
- return [];
- }
- },{"../../error/GraphQLError":275,"../../jsutils/quotedOrList":302,"../../jsutils/suggestionList":303,"../../type/definition":323}],358:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.inlineFragmentOnNonCompositeErrorMessage = inlineFragmentOnNonCompositeErrorMessage;
- exports.fragmentOnNonCompositeErrorMessage = fragmentOnNonCompositeErrorMessage;
- exports.FragmentsOnCompositeTypes = FragmentsOnCompositeTypes;
- var _GraphQLError = require("../../error/GraphQLError");
- var _printer = require("../../language/printer");
- var _definition = require("../../type/definition");
- var _typeFromAST = require("../../utilities/typeFromAST");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function inlineFragmentOnNonCompositeErrorMessage(type) {
- return "Fragment cannot condition on non composite type \"".concat(type, "\".");
- }
- function fragmentOnNonCompositeErrorMessage(fragName, type) {
- return "Fragment \"".concat(fragName, "\" cannot condition on non composite ") + "type \"".concat(type, "\".");
- }
- /**
- * Fragments on composite type
- *
- * Fragments use a type condition to determine if they apply, since fragments
- * can only be spread into a composite type (object, interface, or union), the
- * type condition must also be a composite type.
- */
- function FragmentsOnCompositeTypes(context) {
- return {
- InlineFragment: function InlineFragment(node) {
- var typeCondition = node.typeCondition;
- if (typeCondition) {
- var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition);
- if (type && !(0, _definition.isCompositeType)(type)) {
- context.reportError(new _GraphQLError.GraphQLError(inlineFragmentOnNonCompositeErrorMessage((0, _printer.print)(typeCondition)), [typeCondition]));
- }
- }
- },
- FragmentDefinition: function FragmentDefinition(node) {
- var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition);
- if (type && !(0, _definition.isCompositeType)(type)) {
- context.reportError(new _GraphQLError.GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, (0, _printer.print)(node.typeCondition)), [node.typeCondition]));
- }
- }
- };
- }
- },{"../../error/GraphQLError":275,"../../language/printer":312,"../../type/definition":323,"../../utilities/typeFromAST":351}],359:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unknownArgMessage = unknownArgMessage;
- exports.unknownDirectiveArgMessage = unknownDirectiveArgMessage;
- exports.KnownArgumentNames = KnownArgumentNames;
- exports.KnownArgumentNamesOnDirectives = KnownArgumentNamesOnDirectives;
- var _GraphQLError = require("../../error/GraphQLError");
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList"));
- var _kinds = require("../../language/kinds");
- var _directives = require("../../type/directives");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function unknownArgMessage(argName, fieldName, typeName, suggestedArgs) {
- var message = "Unknown argument \"".concat(argName, "\" on field \"").concat(fieldName, "\" of ") + "type \"".concat(typeName, "\".");
- if (suggestedArgs.length) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedArgs), "?");
- }
- return message;
- }
- function unknownDirectiveArgMessage(argName, directiveName, suggestedArgs) {
- var message = "Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\".");
- if (suggestedArgs.length) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedArgs), "?");
- }
- return message;
- }
- /**
- * Known argument names
- *
- * A GraphQL field is only valid if all supplied arguments are defined by
- * that field.
- */
- function KnownArgumentNames(context) {
- return _objectSpread({}, KnownArgumentNamesOnDirectives(context), {
- Argument: function Argument(argNode) {
- var argDef = context.getArgument();
- var fieldDef = context.getFieldDef();
- var parentType = context.getParentType();
- if (!argDef && fieldDef && parentType) {
- var argName = argNode.name.value;
- var knownArgsNames = fieldDef.args.map(function (arg) {
- return arg.name;
- });
- context.reportError(new _GraphQLError.GraphQLError(unknownArgMessage(argName, fieldDef.name, parentType.name, (0, _suggestionList.default)(argName, knownArgsNames)), argNode));
- }
- }
- });
- } // @internal
- function KnownArgumentNamesOnDirectives(context) {
- var directiveArgs = Object.create(null);
- var schema = context.getSchema();
- var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var directive = _step.value;
- directiveArgs[directive.name] = directive.args.map(function (arg) {
- return arg.name;
- });
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var astDefinitions = context.getDocument().definitions;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var def = _step2.value;
- if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- directiveArgs[def.name.value] = def.arguments ? def.arguments.map(function (arg) {
- return arg.name.value;
- }) : [];
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return {
- Directive: function Directive(directiveNode) {
- var directiveName = directiveNode.name.value;
- var knownArgs = directiveArgs[directiveName];
- if (directiveNode.arguments && knownArgs) {
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = directiveNode.arguments[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var argNode = _step3.value;
- var argName = argNode.name.value;
- if (knownArgs.indexOf(argName) === -1) {
- var suggestions = (0, _suggestionList.default)(argName, knownArgs);
- context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveArgMessage(argName, directiveName, suggestions), argNode));
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":275,"../../jsutils/quotedOrList":302,"../../jsutils/suggestionList":303,"../../language/kinds":307,"../../type/directives":324}],360:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unknownDirectiveMessage = unknownDirectiveMessage;
- exports.misplacedDirectiveMessage = misplacedDirectiveMessage;
- exports.KnownDirectives = KnownDirectives;
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _directiveLocation = require("../../language/directiveLocation");
- var _directives = require("../../type/directives");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unknownDirectiveMessage(directiveName) {
- return "Unknown directive \"".concat(directiveName, "\".");
- }
- function misplacedDirectiveMessage(directiveName, location) {
- return "Directive \"".concat(directiveName, "\" may not be used on ").concat(location, ".");
- }
- /**
- * Known directives
- *
- * A GraphQL document is only valid if all `@directives` are known by the
- * schema and legally positioned.
- */
- function KnownDirectives(context) {
- var locationsMap = Object.create(null);
- var schema = context.getSchema();
- var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var directive = _step.value;
- locationsMap[directive.name] = directive.locations;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var astDefinitions = context.getDocument().definitions;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var def = _step2.value;
- if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- locationsMap[def.name.value] = def.locations.map(function (name) {
- return name.value;
- });
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return {
- Directive: function Directive(node, key, parent, path, ancestors) {
- var name = node.name.value;
- var locations = locationsMap[name];
- if (!locations) {
- context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveMessage(name), [node]));
- return;
- }
- var candidateLocation = getDirectiveLocationForASTPath(ancestors);
- if (candidateLocation && locations.indexOf(candidateLocation) === -1) {
- context.reportError(new _GraphQLError.GraphQLError(misplacedDirectiveMessage(name, candidateLocation), [node]));
- }
- }
- };
- }
- function getDirectiveLocationForASTPath(ancestors) {
- var appliedTo = ancestors[ancestors.length - 1];
- if (!Array.isArray(appliedTo)) {
- switch (appliedTo.kind) {
- case _kinds.Kind.OPERATION_DEFINITION:
- switch (appliedTo.operation) {
- case 'query':
- return _directiveLocation.DirectiveLocation.QUERY;
- case 'mutation':
- return _directiveLocation.DirectiveLocation.MUTATION;
- case 'subscription':
- return _directiveLocation.DirectiveLocation.SUBSCRIPTION;
- }
- break;
- case _kinds.Kind.FIELD:
- return _directiveLocation.DirectiveLocation.FIELD;
- case _kinds.Kind.FRAGMENT_SPREAD:
- return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD;
- case _kinds.Kind.INLINE_FRAGMENT:
- return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT;
- case _kinds.Kind.FRAGMENT_DEFINITION:
- return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION;
- case _kinds.Kind.VARIABLE_DEFINITION:
- return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION;
- case _kinds.Kind.SCHEMA_DEFINITION:
- case _kinds.Kind.SCHEMA_EXTENSION:
- return _directiveLocation.DirectiveLocation.SCHEMA;
- case _kinds.Kind.SCALAR_TYPE_DEFINITION:
- case _kinds.Kind.SCALAR_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.SCALAR;
- case _kinds.Kind.OBJECT_TYPE_DEFINITION:
- case _kinds.Kind.OBJECT_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.OBJECT;
- case _kinds.Kind.FIELD_DEFINITION:
- return _directiveLocation.DirectiveLocation.FIELD_DEFINITION;
- case _kinds.Kind.INTERFACE_TYPE_DEFINITION:
- case _kinds.Kind.INTERFACE_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.INTERFACE;
- case _kinds.Kind.UNION_TYPE_DEFINITION:
- case _kinds.Kind.UNION_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.UNION;
- case _kinds.Kind.ENUM_TYPE_DEFINITION:
- case _kinds.Kind.ENUM_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.ENUM;
- case _kinds.Kind.ENUM_VALUE_DEFINITION:
- return _directiveLocation.DirectiveLocation.ENUM_VALUE;
- case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION:
- case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION:
- return _directiveLocation.DirectiveLocation.INPUT_OBJECT;
- case _kinds.Kind.INPUT_VALUE_DEFINITION:
- var parentNode = ancestors[ancestors.length - 3];
- return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION;
- }
- }
- }
- },{"../../error/GraphQLError":275,"../../language/directiveLocation":305,"../../language/kinds":307,"../../type/directives":324}],361:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unknownFragmentMessage = unknownFragmentMessage;
- exports.KnownFragmentNames = KnownFragmentNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unknownFragmentMessage(fragName) {
- return "Unknown fragment \"".concat(fragName, "\".");
- }
- /**
- * Known fragment names
- *
- * A GraphQL document is only valid if all `...Fragment` fragment spreads refer
- * to fragments defined in the same document.
- */
- function KnownFragmentNames(context) {
- return {
- FragmentSpread: function FragmentSpread(node) {
- var fragmentName = node.name.value;
- var fragment = context.getFragment(fragmentName);
- if (!fragment) {
- context.reportError(new _GraphQLError.GraphQLError(unknownFragmentMessage(fragmentName), [node.name]));
- }
- }
- };
- }
- },{"../../error/GraphQLError":275}],362:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unknownTypeMessage = unknownTypeMessage;
- exports.KnownTypeNames = KnownTypeNames;
- var _GraphQLError = require("../../error/GraphQLError");
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList"));
- var _predicates = require("../../language/predicates");
- var _scalars = require("../../type/scalars");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unknownTypeMessage(typeName, suggestedTypes) {
- var message = "Unknown type \"".concat(typeName, "\".");
- if (suggestedTypes.length) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedTypes), "?");
- }
- return message;
- }
- /**
- * Known type names
- *
- * A GraphQL document is only valid if referenced types (specifically
- * variable definitions and fragment conditions) are defined by the type schema.
- */
- function KnownTypeNames(context) {
- var schema = context.getSchema();
- var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);
- var definedTypes = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = context.getDocument().definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var def = _step.value;
- if ((0, _predicates.isTypeDefinitionNode)(def)) {
- definedTypes[def.name.value] = true;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes));
- return {
- NamedType: function NamedType(node, _1, parent, _2, ancestors) {
- var typeName = node.name.value;
- if (!existingTypesMap[typeName] && !definedTypes[typeName]) {
- var definitionNode = ancestors[2] || parent;
- var isSDL = isSDLNode(definitionNode);
- if (isSDL && isSpecifiedScalarName(typeName)) {
- return;
- }
- var suggestedTypes = (0, _suggestionList.default)(typeName, isSDL ? specifiedScalarsNames.concat(typeNames) : typeNames);
- context.reportError(new _GraphQLError.GraphQLError(unknownTypeMessage(typeName, suggestedTypes), node));
- }
- }
- };
- }
- var specifiedScalarsNames = _scalars.specifiedScalarTypes.map(function (type) {
- return type.name;
- });
- function isSpecifiedScalarName(typeName) {
- return specifiedScalarsNames.indexOf(typeName) !== -1;
- }
- function isSDLNode(value) {
- return Boolean(value && !Array.isArray(value) && ((0, _predicates.isTypeSystemDefinitionNode)(value) || (0, _predicates.isTypeSystemExtensionNode)(value)));
- }
- },{"../../error/GraphQLError":275,"../../jsutils/quotedOrList":302,"../../jsutils/suggestionList":303,"../../language/predicates":311,"../../type/scalars":327}],363:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.anonOperationNotAloneMessage = anonOperationNotAloneMessage;
- exports.LoneAnonymousOperation = LoneAnonymousOperation;
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function anonOperationNotAloneMessage() {
- return 'This anonymous operation must be the only defined operation.';
- }
- /**
- * Lone anonymous operation
- *
- * A GraphQL document is only valid if when it contains an anonymous operation
- * (the query short-hand) that it contains only that one operation definition.
- */
- function LoneAnonymousOperation(context) {
- var operationCount = 0;
- return {
- Document: function Document(node) {
- operationCount = node.definitions.filter(function (definition) {
- return definition.kind === _kinds.Kind.OPERATION_DEFINITION;
- }).length;
- },
- OperationDefinition: function OperationDefinition(node) {
- if (!node.name && operationCount > 1) {
- context.reportError(new _GraphQLError.GraphQLError(anonOperationNotAloneMessage(), [node]));
- }
- }
- };
- }
- },{"../../error/GraphQLError":275,"../../language/kinds":307}],364:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.schemaDefinitionNotAloneMessage = schemaDefinitionNotAloneMessage;
- exports.canNotDefineSchemaWithinExtensionMessage = canNotDefineSchemaWithinExtensionMessage;
- exports.LoneSchemaDefinition = LoneSchemaDefinition;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function schemaDefinitionNotAloneMessage() {
- return 'Must provide only one schema definition.';
- }
- function canNotDefineSchemaWithinExtensionMessage() {
- return 'Cannot define a new schema within a schema extension.';
- }
- /**
- * Lone Schema definition
- *
- * A GraphQL document is only valid if it contains only one schema definition.
- */
- function LoneSchemaDefinition(context) {
- var oldSchema = context.getSchema();
- var alreadyDefined = oldSchema && (oldSchema.astNode || oldSchema.getQueryType() || oldSchema.getMutationType() || oldSchema.getSubscriptionType());
- var schemaDefinitionsCount = 0;
- return {
- SchemaDefinition: function SchemaDefinition(node) {
- if (alreadyDefined) {
- context.reportError(new _GraphQLError.GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node));
- return;
- }
- if (schemaDefinitionsCount > 0) {
- context.reportError(new _GraphQLError.GraphQLError(schemaDefinitionNotAloneMessage(), node));
- }
- ++schemaDefinitionsCount;
- }
- };
- }
- },{"../../error/GraphQLError":275}],365:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.cycleErrorMessage = cycleErrorMessage;
- exports.NoFragmentCycles = NoFragmentCycles;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function cycleErrorMessage(fragName, spreadNames) {
- var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : '';
- return "Cannot spread fragment \"".concat(fragName, "\" within itself").concat(via, ".");
- }
- function NoFragmentCycles(context) {
- // Tracks already visited fragments to maintain O(N) and to ensure that cycles
- // are not redundantly reported.
- var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors
- var spreadPath = []; // Position in the spread path
- var spreadPathIndexByName = Object.create(null);
- return {
- OperationDefinition: function OperationDefinition() {
- return false;
- },
- FragmentDefinition: function FragmentDefinition(node) {
- detectCycleRecursive(node);
- return false;
- }
- }; // This does a straight-forward DFS to find cycles.
- // It does not terminate when a cycle was found but continues to explore
- // the graph to find all possible cycles.
- function detectCycleRecursive(fragment) {
- if (visitedFrags[fragment.name.value]) {
- return;
- }
- var fragmentName = fragment.name.value;
- visitedFrags[fragmentName] = true;
- var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
- if (spreadNodes.length === 0) {
- return;
- }
- spreadPathIndexByName[fragmentName] = spreadPath.length;
- for (var i = 0; i < spreadNodes.length; i++) {
- var spreadNode = spreadNodes[i];
- var spreadName = spreadNode.name.value;
- var cycleIndex = spreadPathIndexByName[spreadName];
- spreadPath.push(spreadNode);
- if (cycleIndex === undefined) {
- var spreadFragment = context.getFragment(spreadName);
- if (spreadFragment) {
- detectCycleRecursive(spreadFragment);
- }
- } else {
- var cyclePath = spreadPath.slice(cycleIndex);
- var fragmentNames = cyclePath.slice(0, -1).map(function (s) {
- return s.name.value;
- });
- context.reportError(new _GraphQLError.GraphQLError(cycleErrorMessage(spreadName, fragmentNames), cyclePath));
- }
- spreadPath.pop();
- }
- spreadPathIndexByName[fragmentName] = undefined;
- }
- }
- },{"../../error/GraphQLError":275}],366:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.undefinedVarMessage = undefinedVarMessage;
- exports.NoUndefinedVariables = NoUndefinedVariables;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function undefinedVarMessage(varName, opName) {
- return opName ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is not defined.");
- }
- /**
- * No undefined variables
- *
- * A GraphQL operation is only valid if all variables encountered, both directly
- * and via fragment spreads, are defined by that operation.
- */
- function NoUndefinedVariables(context) {
- var variableNameDefined = Object.create(null);
- return {
- OperationDefinition: {
- enter: function enter() {
- variableNameDefined = Object.create(null);
- },
- leave: function leave(operation) {
- var usages = context.getRecursiveVariableUsages(operation);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref2 = _step.value;
- var node = _ref2.node;
- var varName = node.name.value;
- if (variableNameDefined[varName] !== true) {
- context.reportError(new _GraphQLError.GraphQLError(undefinedVarMessage(varName, operation.name && operation.name.value), [node, operation]));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- },
- VariableDefinition: function VariableDefinition(node) {
- variableNameDefined[node.variable.name.value] = true;
- }
- };
- }
- },{"../../error/GraphQLError":275}],367:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unusedFragMessage = unusedFragMessage;
- exports.NoUnusedFragments = NoUnusedFragments;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unusedFragMessage(fragName) {
- return "Fragment \"".concat(fragName, "\" is never used.");
- }
- /**
- * No unused fragments
- *
- * A GraphQL document is only valid if all fragment definitions are spread
- * within operations, or spread within other fragments spread within operations.
- */
- function NoUnusedFragments(context) {
- var operationDefs = [];
- var fragmentDefs = [];
- return {
- OperationDefinition: function OperationDefinition(node) {
- operationDefs.push(node);
- return false;
- },
- FragmentDefinition: function FragmentDefinition(node) {
- fragmentDefs.push(node);
- return false;
- },
- Document: {
- leave: function leave() {
- var fragmentNameUsed = Object.create(null);
- for (var _i = 0; _i < operationDefs.length; _i++) {
- var operation = operationDefs[_i];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = context.getRecursivelyReferencedFragments(operation)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var fragment = _step.value;
- fragmentNameUsed[fragment.name.value] = true;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- for (var _i2 = 0; _i2 < fragmentDefs.length; _i2++) {
- var fragmentDef = fragmentDefs[_i2];
- var fragName = fragmentDef.name.value;
- if (fragmentNameUsed[fragName] !== true) {
- context.reportError(new _GraphQLError.GraphQLError(unusedFragMessage(fragName), [fragmentDef]));
- }
- }
- }
- }
- };
- }
- },{"../../error/GraphQLError":275}],368:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.unusedVariableMessage = unusedVariableMessage;
- exports.NoUnusedVariables = NoUnusedVariables;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function unusedVariableMessage(varName, opName) {
- return opName ? "Variable \"$".concat(varName, "\" is never used in operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is never used.");
- }
- /**
- * No unused variables
- *
- * A GraphQL operation is only valid if all variables defined by an operation
- * are used, either directly or within a spread fragment.
- */
- function NoUnusedVariables(context) {
- var variableDefs = [];
- return {
- OperationDefinition: {
- enter: function enter() {
- variableDefs = [];
- },
- leave: function leave(operation) {
- var variableNameUsed = Object.create(null);
- var usages = context.getRecursiveVariableUsages(operation);
- var opName = operation.name ? operation.name.value : null;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref2 = _step.value;
- var node = _ref2.node;
- variableNameUsed[node.name.value] = true;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- for (var _i = 0; _i < variableDefs.length; _i++) {
- var variableDef = variableDefs[_i];
- var variableName = variableDef.variable.name.value;
- if (variableNameUsed[variableName] !== true) {
- context.reportError(new _GraphQLError.GraphQLError(unusedVariableMessage(variableName, opName), [variableDef]));
- }
- }
- }
- },
- VariableDefinition: function VariableDefinition(def) {
- variableDefs.push(def);
- }
- };
- }
- },{"../../error/GraphQLError":275}],369:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.fieldsConflictMessage = fieldsConflictMessage;
- exports.OverlappingFieldsCanBeMerged = OverlappingFieldsCanBeMerged;
- var _find = _interopRequireDefault(require("../../polyfills/find"));
- var _objectEntries = _interopRequireDefault(require("../../polyfills/objectEntries"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _kinds = require("../../language/kinds");
- var _printer = require("../../language/printer");
- var _definition = require("../../type/definition");
- var _typeFromAST = require("../../utilities/typeFromAST");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function fieldsConflictMessage(responseName, reason) {
- return "Fields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(reason), ". ") + 'Use different aliases on the fields to fetch both if this was intentional.';
- }
- function reasonMessage(reason) {
- if (Array.isArray(reason)) {
- return reason.map(function (_ref) {
- var responseName = _ref[0],
- subreason = _ref[1];
- return "subfields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(subreason));
- }).join(' and ');
- }
- return reason;
- }
- /**
- * Overlapping fields can be merged
- *
- * A selection set is only valid if all fields (including spreading any
- * fragments) either correspond to distinct response names or can be merged
- * without ambiguity.
- */
- function OverlappingFieldsCanBeMerged(context) {
- // A memoization for when two fragments are compared "between" each other for
- // conflicts. Two fragments may be compared many times, so memoizing this can
- // dramatically improve the performance of this validator.
- var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given
- // selection set. Selection sets may be asked for this information multiple
- // times, so this improves the performance of this validator.
- var cachedFieldsAndFragmentNames = new Map();
- return {
- SelectionSet: function SelectionSet(selectionSet) {
- var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet);
- for (var _i = 0; _i < conflicts.length; _i++) {
- var _ref3 = conflicts[_i];
- var _ref2$ = _ref3[0];
- var responseName = _ref2$[0];
- var reason = _ref2$[1];
- var fields1 = _ref3[1];
- var fields2 = _ref3[2];
- context.reportError(new _GraphQLError.GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2)));
- }
- }
- };
- }
- /**
- * Algorithm:
- *
- * Conflicts occur when two fields exist in a query which will produce the same
- * response name, but represent differing values, thus creating a conflict.
- * The algorithm below finds all conflicts via making a series of comparisons
- * between fields. In order to compare as few fields as possible, this makes
- * a series of comparisons "within" sets of fields and "between" sets of fields.
- *
- * Given any selection set, a collection produces both a set of fields by
- * also including all inline fragments, as well as a list of fragments
- * referenced by fragment spreads.
- *
- * A) Each selection set represented in the document first compares "within" its
- * collected set of fields, finding any conflicts between every pair of
- * overlapping fields.
- * Note: This is the *only time* that a the fields "within" a set are compared
- * to each other. After this only fields "between" sets are compared.
- *
- * B) Also, if any fragment is referenced in a selection set, then a
- * comparison is made "between" the original set of fields and the
- * referenced fragment.
- *
- * C) Also, if multiple fragments are referenced, then comparisons
- * are made "between" each referenced fragment.
- *
- * D) When comparing "between" a set of fields and a referenced fragment, first
- * a comparison is made between each field in the original set of fields and
- * each field in the the referenced set of fields.
- *
- * E) Also, if any fragment is referenced in the referenced selection set,
- * then a comparison is made "between" the original set of fields and the
- * referenced fragment (recursively referring to step D).
- *
- * F) When comparing "between" two fragments, first a comparison is made between
- * each field in the first referenced set of fields and each field in the the
- * second referenced set of fields.
- *
- * G) Also, any fragments referenced by the first must be compared to the
- * second, and any fragments referenced by the second must be compared to the
- * first (recursively referring to step F).
- *
- * H) When comparing two fields, if both have selection sets, then a comparison
- * is made "between" both selection sets, first comparing the set of fields in
- * the first selection set with the set of fields in the second.
- *
- * I) Also, if any fragment is referenced in either selection set, then a
- * comparison is made "between" the other set of fields and the
- * referenced fragment.
- *
- * J) Also, if two fragments are referenced in both selection sets, then a
- * comparison is made "between" the two fragments.
- *
- */
- // Find all conflicts found "within" a selection set, including those found
- // via spreading in fragments. Called when visiting each SelectionSet in the
- // GraphQL Document.
- function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) {
- var conflicts = [];
- var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet),
- fieldMap = _getFieldsAndFragment[0],
- fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set.
- // Note: this is the *only place* `collectConflictsWithin` is called.
- collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap);
- if (fragmentNames.length !== 0) {
- // (B) Then collect conflicts between these fields and those represented by
- // each spread fragment name found.
- var comparedFragments = Object.create(null);
- for (var i = 0; i < fragmentNames.length; i++) {
- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this
- // selection set to collect conflicts between fragments spread together.
- // This compares each item in the list of fragment names to every other
- // item in that same list (except for itself).
- for (var j = i + 1; j < fragmentNames.length; j++) {
- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]);
- }
- }
- }
- return conflicts;
- } // Collect all conflicts found between a set of fields and a fragment reference
- // including via spreading in any nested fragments.
- function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) {
- // Memoize so a fragment is not compared for conflicts more than once.
- if (comparedFragments[fragmentName]) {
- return;
- }
- comparedFragments[fragmentName] = true;
- var fragment = context.getFragment(fragmentName);
- if (!fragment) {
- return;
- }
- var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment),
- fieldMap2 = _getReferencedFieldsA[0],
- fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself.
- if (fieldMap === fieldMap2) {
- return;
- } // (D) First collect any conflicts between the provided collection of fields
- // and the collection of fields represented by the given fragment.
- collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields
- // and any fragment names found in the given fragment.
- for (var i = 0; i < fragmentNames2.length; i++) {
- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]);
- }
- } // Collect all conflicts found between two fragments, including via spreading in
- // any nested fragments.
- function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) {
- // No need to compare a fragment to itself.
- if (fragmentName1 === fragmentName2) {
- return;
- } // Memoize so two fragments are not compared for conflicts more than once.
- if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) {
- return;
- }
- comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);
- var fragment1 = context.getFragment(fragmentName1);
- var fragment2 = context.getFragment(fragmentName2);
- if (!fragment1 || !fragment2) {
- return;
- }
- var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1),
- fieldMap1 = _getReferencedFieldsA2[0],
- fragmentNames1 = _getReferencedFieldsA2[1];
- var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2),
- fieldMap2 = _getReferencedFieldsA3[0],
- fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields
- // (not including any nested fragments).
- collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested
- // fragments spread in the second fragment.
- for (var j = 0; j < fragmentNames2.length; j++) {
- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]);
- } // (G) Then collect conflicts between the second fragment and any nested
- // fragments spread in the first fragment.
- for (var i = 0; i < fragmentNames1.length; i++) {
- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2);
- }
- } // Find all conflicts found between two selection sets, including those found
- // via spreading in fragments. Called when determining if conflicts exist
- // between the sub-fields of two overlapping fields.
- function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) {
- var conflicts = [];
- var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1),
- fieldMap1 = _getFieldsAndFragment2[0],
- fragmentNames1 = _getFieldsAndFragment2[1];
- var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2),
- fieldMap2 = _getFieldsAndFragment3[0],
- fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field.
- collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and
- // those referenced by each fragment name associated with the second.
- if (fragmentNames2.length !== 0) {
- var comparedFragments = Object.create(null);
- for (var j = 0; j < fragmentNames2.length; j++) {
- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]);
- }
- } // (I) Then collect conflicts between the second collection of fields and
- // those referenced by each fragment name associated with the first.
- if (fragmentNames1.length !== 0) {
- var _comparedFragments = Object.create(null);
- for (var i = 0; i < fragmentNames1.length; i++) {
- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, _comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]);
- }
- } // (J) Also collect conflicts between any fragment names by the first and
- // fragment names by the second. This compares each item in the first set of
- // names to each item in the second set of names.
- for (var _i2 = 0; _i2 < fragmentNames1.length; _i2++) {
- for (var _j = 0; _j < fragmentNames2.length; _j++) {
- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i2], fragmentNames2[_j]);
- }
- }
- return conflicts;
- } // Collect all Conflicts "within" one collection of fields.
- function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) {
- // A field map is a keyed collection, where each key represents a response
- // name and the value at that key is a list of all fields which provide that
- // response name. For every response name, if there are multiple fields, they
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectEntries.default)(fieldMap)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref5 = _step.value;
- var responseName = _ref5[0];
- var fields = _ref5[1];
- // This compares every field in the list to every other field in this list
- // (except to itself). If the list only has one item, nothing needs to
- // be compared.
- if (fields.length > 1) {
- for (var i = 0; i < fields.length; i++) {
- for (var j = i + 1; j < fields.length; j++) {
- var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive
- responseName, fields[i], fields[j]);
- if (conflict) {
- conflicts.push(conflict);
- }
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- } // Collect all Conflicts between two collections of fields. This is similar to,
- // but different from the `collectConflictsWithin` function above. This check
- // assumes that `collectConflictsWithin` has already been called on each
- // provided collection of fields. This is true because this validator traverses
- // each individual selection set.
- function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) {
- // A field map is a keyed collection, where each key represents a response
- // name and the value at that key is a list of all fields which provide that
- // response name. For any response name which appears in both provided field
- // maps, each field from the first field map must be compared to every field
- // in the second field map to find potential conflicts.
- var _arr = Object.keys(fieldMap1);
- for (var _i3 = 0; _i3 < _arr.length; _i3++) {
- var responseName = _arr[_i3];
- var fields2 = fieldMap2[responseName];
- if (fields2) {
- var fields1 = fieldMap1[responseName];
- for (var i = 0; i < fields1.length; i++) {
- for (var j = 0; j < fields2.length; j++) {
- var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]);
- if (conflict) {
- conflicts.push(conflict);
- }
- }
- }
- }
- }
- } // Determines if there is a conflict between two particular fields, including
- // comparing their sub-fields.
- function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) {
- var parentType1 = field1[0],
- node1 = field1[1],
- def1 = field1[2];
- var parentType2 = field2[0],
- node2 = field2[1],
- def2 = field2[2]; // If it is known that two fields could not possibly apply at the same
- // time, due to the parent types, then it is safe to permit them to diverge
- // in aliased field or arguments used as they will not present any ambiguity
- // by differing.
- // It is known that two parent types could never overlap if they are
- // different Object types. Interface or Union types might overlap - if not
- // in the current state of the schema, then perhaps in some future version,
- // thus may not safely diverge.
- var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); // The return type for each field.
- var type1 = def1 && def1.type;
- var type2 = def2 && def2.type;
- if (!areMutuallyExclusive) {
- // Two aliases must refer to the same field.
- var name1 = node1.name.value;
- var name2 = node2.name.value;
- if (name1 !== name2) {
- return [[responseName, "".concat(name1, " and ").concat(name2, " are different fields")], [node1], [node2]];
- } // Two field calls must have the same arguments.
- if (!sameArguments(node1.arguments || [], node2.arguments || [])) {
- return [[responseName, 'they have differing arguments'], [node1], [node2]];
- }
- }
- if (type1 && type2 && doTypesConflict(type1, type2)) {
- return [[responseName, "they return conflicting types ".concat((0, _inspect.default)(type1), " and ").concat((0, _inspect.default)(type2))], [node1], [node2]];
- } // Collect and compare sub-fields. Use the same "visited fragment names" list
- // for both collections so fields in a fragment reference are never
- // compared to themselves.
- var selectionSet1 = node1.selectionSet;
- var selectionSet2 = node2.selectionSet;
- if (selectionSet1 && selectionSet2) {
- var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2);
- return subfieldConflicts(conflicts, responseName, node1, node2);
- }
- }
- function sameArguments(arguments1, arguments2) {
- if (arguments1.length !== arguments2.length) {
- return false;
- }
- return arguments1.every(function (argument1) {
- var argument2 = (0, _find.default)(arguments2, function (argument) {
- return argument.name.value === argument1.name.value;
- });
- if (!argument2) {
- return false;
- }
- return sameValue(argument1.value, argument2.value);
- });
- }
- function sameValue(value1, value2) {
- return !value1 && !value2 || (0, _printer.print)(value1) === (0, _printer.print)(value2);
- } // Two types conflict if both types could not apply to a value simultaneously.
- // Composite types are ignored as their individual field types will be compared
- // later recursively. However List and Non-Null types must match.
- function doTypesConflict(type1, type2) {
- if ((0, _definition.isListType)(type1)) {
- return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
- }
- if ((0, _definition.isListType)(type2)) {
- return true;
- }
- if ((0, _definition.isNonNullType)(type1)) {
- return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
- }
- if ((0, _definition.isNonNullType)(type2)) {
- return true;
- }
- if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) {
- return type1 !== type2;
- }
- return false;
- } // Given a selection set, return the collection of fields (a mapping of response
- // name to field nodes and definitions) as well as a list of fragment names
- // referenced via fragment spreads.
- function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) {
- var cached = cachedFieldsAndFragmentNames.get(selectionSet);
- if (!cached) {
- var nodeAndDefs = Object.create(null);
- var fragmentNames = Object.create(null);
- _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames);
- cached = [nodeAndDefs, Object.keys(fragmentNames)];
- cachedFieldsAndFragmentNames.set(selectionSet, cached);
- }
- return cached;
- } // Given a reference to a fragment, return the represented collection of fields
- // as well as a list of nested fragment names referenced via fragment spreads.
- function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) {
- // Short-circuit building a type from the node if possible.
- var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);
- if (cached) {
- return cached;
- }
- var fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition);
- return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet);
- }
- function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) {
- for (var i = 0; i < selectionSet.selections.length; i++) {
- var selection = selectionSet.selections[i];
- switch (selection.kind) {
- case _kinds.Kind.FIELD:
- var fieldName = selection.name.value;
- var fieldDef = void 0;
- if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) {
- fieldDef = parentType.getFields()[fieldName];
- }
- var responseName = selection.alias ? selection.alias.value : fieldName;
- if (!nodeAndDefs[responseName]) {
- nodeAndDefs[responseName] = [];
- }
- nodeAndDefs[responseName].push([parentType, selection, fieldDef]);
- break;
- case _kinds.Kind.FRAGMENT_SPREAD:
- fragmentNames[selection.name.value] = true;
- break;
- case _kinds.Kind.INLINE_FRAGMENT:
- var typeCondition = selection.typeCondition;
- var inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType;
- _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames);
- break;
- }
- }
- } // Given a series of Conflicts which occurred between two sub-fields, generate
- // a single Conflict.
- function subfieldConflicts(conflicts, responseName, node1, node2) {
- if (conflicts.length > 0) {
- return [[responseName, conflicts.map(function (_ref6) {
- var reason = _ref6[0];
- return reason;
- })], conflicts.reduce(function (allFields, _ref7) {
- var fields1 = _ref7[1];
- return allFields.concat(fields1);
- }, [node1]), conflicts.reduce(function (allFields, _ref8) {
- var fields2 = _ref8[2];
- return allFields.concat(fields2);
- }, [node2])];
- }
- }
- /**
- * A way to keep track of pairs of things when the ordering of the pair does
- * not matter. We do this by maintaining a sort of double adjacency sets.
- */
- var PairSet =
- /*#__PURE__*/
- function () {
- function PairSet() {
- this._data = Object.create(null);
- }
- var _proto = PairSet.prototype;
- _proto.has = function has(a, b, areMutuallyExclusive) {
- var first = this._data[a];
- var result = first && first[b];
- if (result === undefined) {
- return false;
- } // areMutuallyExclusive being false is a superset of being true,
- // hence if we want to know if this PairSet "has" these two with no
- // exclusivity, we have to ensure it was added as such.
- if (areMutuallyExclusive === false) {
- return result === false;
- }
- return true;
- };
- _proto.add = function add(a, b, areMutuallyExclusive) {
- _pairSetAdd(this._data, a, b, areMutuallyExclusive);
- _pairSetAdd(this._data, b, a, areMutuallyExclusive);
- };
- return PairSet;
- }();
- function _pairSetAdd(data, a, b, areMutuallyExclusive) {
- var map = data[a];
- if (!map) {
- map = Object.create(null);
- data[a] = map;
- }
- map[b] = areMutuallyExclusive;
- }
- },{"../../error/GraphQLError":275,"../../jsutils/inspect":288,"../../language/kinds":307,"../../language/printer":312,"../../polyfills/find":315,"../../polyfills/objectEntries":318,"../../type/definition":323,"../../utilities/typeFromAST":351}],370:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.typeIncompatibleSpreadMessage = typeIncompatibleSpreadMessage;
- exports.typeIncompatibleAnonSpreadMessage = typeIncompatibleAnonSpreadMessage;
- exports.PossibleFragmentSpreads = PossibleFragmentSpreads;
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _typeComparators = require("../../utilities/typeComparators");
- var _typeFromAST = require("../../utilities/typeFromAST");
- var _definition = require("../../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function typeIncompatibleSpreadMessage(fragName, parentType, fragType) {
- return "Fragment \"".concat(fragName, "\" cannot be spread here as objects of ") + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\".");
- }
- function typeIncompatibleAnonSpreadMessage(parentType, fragType) {
- return 'Fragment cannot be spread here as objects of ' + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\".");
- }
- /**
- * Possible fragment spread
- *
- * A fragment spread is only valid if the type condition could ever possibly
- * be true: if there is a non-empty intersection of the possible parent types,
- * and possible types which pass the type condition.
- */
- function PossibleFragmentSpreads(context) {
- return {
- InlineFragment: function InlineFragment(node) {
- var fragType = context.getType();
- var parentType = context.getParentType();
- if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) {
- context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleAnonSpreadMessage((0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), [node]));
- }
- },
- FragmentSpread: function FragmentSpread(node) {
- var fragName = node.name.value;
- var fragType = getFragmentType(context, fragName);
- var parentType = context.getParentType();
- if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) {
- context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleSpreadMessage(fragName, (0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), [node]));
- }
- }
- };
- }
- function getFragmentType(context, name) {
- var frag = context.getFragment(name);
- if (frag) {
- var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition);
- if ((0, _definition.isCompositeType)(type)) {
- return type;
- }
- }
- }
- },{"../../error/GraphQLError":275,"../../jsutils/inspect":288,"../../type/definition":323,"../../utilities/typeComparators":350,"../../utilities/typeFromAST":351}],371:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.extendingUnknownTypeMessage = extendingUnknownTypeMessage;
- exports.extendingDifferentTypeKindMessage = extendingDifferentTypeKindMessage;
- exports.PossibleTypeExtensions = PossibleTypeExtensions;
- var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList"));
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _predicates = require("../../language/predicates");
- var _definition = require("../../type/definition");
- var _defKindToExtKind;
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function extendingUnknownTypeMessage(typeName, suggestedTypes) {
- var message = "Cannot extend type \"".concat(typeName, "\" because it does not defined.");
- if (suggestedTypes.length) {
- message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedTypes), "?");
- }
- return message;
- }
- function extendingDifferentTypeKindMessage(typeName, kind) {
- return "Cannot extend non-".concat(kind, " type \"").concat(typeName, "\".");
- }
- /**
- * Possible type extension
- *
- * A type extension is only valid if the type defined and have the same kind.
- */
- function PossibleTypeExtensions(context) {
- var schema = context.getSchema();
- var definedTypes = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = context.getDocument().definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var def = _step.value;
- if ((0, _predicates.isTypeDefinitionNode)(def)) {
- definedTypes[def.name.value] = def;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return {
- ScalarTypeExtension: checkExtension,
- ObjectTypeExtension: checkExtension,
- InterfaceTypeExtension: checkExtension,
- UnionTypeExtension: checkExtension,
- EnumTypeExtension: checkExtension,
- InputObjectTypeExtension: checkExtension
- };
- function checkExtension(node) {
- var typeName = node.name.value;
- var defNode = definedTypes[typeName];
- var existingType = schema && schema.getType(typeName);
- if (defNode) {
- var expectedKind = defKindToExtKind[defNode.kind];
- if (expectedKind !== node.kind) {
- context.reportError(new _GraphQLError.GraphQLError(extendingDifferentTypeKindMessage(typeName, extensionKindToTypeName(expectedKind)), [defNode, node]));
- }
- } else if (existingType) {
- var _expectedKind = typeToExtKind(existingType);
- if (_expectedKind !== node.kind) {
- context.reportError(new _GraphQLError.GraphQLError(extendingDifferentTypeKindMessage(typeName, extensionKindToTypeName(_expectedKind)), node));
- }
- } else {
- var allTypeNames = Object.keys(definedTypes);
- if (schema) {
- allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap()));
- }
- var suggestedTypes = (0, _suggestionList.default)(typeName, allTypeNames);
- context.reportError(new _GraphQLError.GraphQLError(extendingUnknownTypeMessage(typeName, suggestedTypes), node.name));
- }
- }
- }
- var defKindToExtKind = (_defKindToExtKind = {}, _defineProperty(_defKindToExtKind, _kinds.Kind.SCALAR_TYPE_DEFINITION, _kinds.Kind.SCALAR_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.OBJECT_TYPE_DEFINITION, _kinds.Kind.OBJECT_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.INTERFACE_TYPE_DEFINITION, _kinds.Kind.INTERFACE_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.UNION_TYPE_DEFINITION, _kinds.Kind.UNION_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.ENUM_TYPE_DEFINITION, _kinds.Kind.ENUM_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION), _defKindToExtKind);
- function typeToExtKind(type) {
- if ((0, _definition.isScalarType)(type)) {
- return _kinds.Kind.SCALAR_TYPE_EXTENSION;
- } else if ((0, _definition.isObjectType)(type)) {
- return _kinds.Kind.OBJECT_TYPE_EXTENSION;
- } else if ((0, _definition.isInterfaceType)(type)) {
- return _kinds.Kind.INTERFACE_TYPE_EXTENSION;
- } else if ((0, _definition.isUnionType)(type)) {
- return _kinds.Kind.UNION_TYPE_EXTENSION;
- } else if ((0, _definition.isEnumType)(type)) {
- return _kinds.Kind.ENUM_TYPE_EXTENSION;
- } else if ((0, _definition.isInputObjectType)(type)) {
- return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION;
- }
- }
- function extensionKindToTypeName(kind) {
- switch (kind) {
- case _kinds.Kind.SCALAR_TYPE_EXTENSION:
- return 'scalar';
- case _kinds.Kind.OBJECT_TYPE_EXTENSION:
- return 'object';
- case _kinds.Kind.INTERFACE_TYPE_EXTENSION:
- return 'interface';
- case _kinds.Kind.UNION_TYPE_EXTENSION:
- return 'union';
- case _kinds.Kind.ENUM_TYPE_EXTENSION:
- return 'enum';
- case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION:
- return 'input object';
- default:
- return 'unknown type';
- }
- }
- },{"../../error/GraphQLError":275,"../../jsutils/quotedOrList":302,"../../jsutils/suggestionList":303,"../../language/kinds":307,"../../language/predicates":311,"../../type/definition":323}],372:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.missingFieldArgMessage = missingFieldArgMessage;
- exports.missingDirectiveArgMessage = missingDirectiveArgMessage;
- exports.ProvidedRequiredArguments = ProvidedRequiredArguments;
- exports.ProvidedRequiredArgumentsOnDirectives = ProvidedRequiredArgumentsOnDirectives;
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap"));
- var _definition = require("../../type/definition");
- var _printer = require("../../language/printer");
- var _directives = require("../../type/directives");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
- function missingFieldArgMessage(fieldName, argName, type) {
- return "Field \"".concat(fieldName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided.");
- }
- function missingDirectiveArgMessage(directiveName, argName, type) {
- return "Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided.");
- }
- /**
- * Provided required arguments
- *
- * A field or directive is only valid if all required (non-null without a
- * default value) field arguments have been provided.
- */
- function ProvidedRequiredArguments(context) {
- return _objectSpread({}, ProvidedRequiredArgumentsOnDirectives(context), {
- Field: {
- // Validate on leave to allow for deeper errors to appear first.
- leave: function leave(fieldNode) {
- var fieldDef = context.getFieldDef();
- if (!fieldDef) {
- return false;
- }
- var argNodes = fieldNode.arguments || [];
- var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) {
- return arg.name.value;
- });
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = fieldDef.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var argDef = _step.value;
- var argNode = argNodeMap[argDef.name];
- if (!argNode && (0, _definition.isRequiredArgument)(argDef)) {
- context.reportError(new _GraphQLError.GraphQLError(missingFieldArgMessage(fieldDef.name, argDef.name, (0, _inspect.default)(argDef.type)), [fieldNode]));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- }
- });
- } // @internal
- function ProvidedRequiredArgumentsOnDirectives(context) {
- var requiredArgsMap = Object.create(null);
- var schema = context.getSchema();
- var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = definedDirectives[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var directive = _step2.value;
- requiredArgsMap[directive.name] = (0, _keyMap.default)(directive.args.filter(_definition.isRequiredArgument), function (arg) {
- return arg.name;
- });
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- var astDefinitions = context.getDocument().definitions;
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = astDefinitions[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var def = _step3.value;
- if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
- requiredArgsMap[def.name.value] = (0, _keyMap.default)(def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], function (arg) {
- return arg.name.value;
- });
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- return {
- Directive: {
- // Validate on leave to allow for deeper errors to appear first.
- leave: function leave(directiveNode) {
- var directiveName = directiveNode.name.value;
- var requiredArgs = requiredArgsMap[directiveName];
- if (requiredArgs) {
- var argNodes = directiveNode.arguments || [];
- var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) {
- return arg.name.value;
- });
- var _arr = Object.keys(requiredArgs);
- for (var _i = 0; _i < _arr.length; _i++) {
- var argName = _arr[_i];
- if (!argNodeMap[argName]) {
- var argType = requiredArgs[argName].type;
- context.reportError(new _GraphQLError.GraphQLError(missingDirectiveArgMessage(directiveName, argName, (0, _definition.isType)(argType) ? (0, _inspect.default)(argType) : (0, _printer.print)(argType)), directiveNode));
- }
- }
- }
- }
- }
- };
- }
- function isRequiredArgumentNode(arg) {
- return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null;
- }
- },{"../../error/GraphQLError":275,"../../jsutils/inspect":288,"../../jsutils/keyMap":294,"../../language/kinds":307,"../../language/printer":312,"../../type/definition":323,"../../type/directives":324}],373:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.noSubselectionAllowedMessage = noSubselectionAllowedMessage;
- exports.requiredSubselectionMessage = requiredSubselectionMessage;
- exports.ScalarLeafs = ScalarLeafs;
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _definition = require("../../type/definition");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function noSubselectionAllowedMessage(fieldName, type) {
- return "Field \"".concat(fieldName, "\" must not have a selection since ") + "type \"".concat(type, "\" has no subfields.");
- }
- function requiredSubselectionMessage(fieldName, type) {
- return "Field \"".concat(fieldName, "\" of type \"").concat(type, "\" must have a ") + "selection of subfields. Did you mean \"".concat(fieldName, " { ... }\"?");
- }
- /**
- * Scalar leafs
- *
- * A GraphQL document is valid only if all leaf fields (fields without
- * sub selections) are of scalar or enum types.
- */
- function ScalarLeafs(context) {
- return {
- Field: function Field(node) {
- var type = context.getType();
- var selectionSet = node.selectionSet;
- if (type) {
- if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) {
- if (selectionSet) {
- context.reportError(new _GraphQLError.GraphQLError(noSubselectionAllowedMessage(node.name.value, (0, _inspect.default)(type)), [selectionSet]));
- }
- } else if (!selectionSet) {
- context.reportError(new _GraphQLError.GraphQLError(requiredSubselectionMessage(node.name.value, (0, _inspect.default)(type)), [node]));
- }
- }
- }
- };
- }
- },{"../../error/GraphQLError":275,"../../jsutils/inspect":288,"../../type/definition":323}],374:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.singleFieldOnlyMessage = singleFieldOnlyMessage;
- exports.SingleFieldSubscriptions = SingleFieldSubscriptions;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function singleFieldOnlyMessage(name) {
- return (name ? "Subscription \"".concat(name, "\" ") : 'Anonymous Subscription ') + 'must select only one top level field.';
- }
- /**
- * Subscriptions must only include one field.
- *
- * A GraphQL subscription is valid only if it contains a single root field.
- */
- function SingleFieldSubscriptions(context) {
- return {
- OperationDefinition: function OperationDefinition(node) {
- if (node.operation === 'subscription') {
- if (node.selectionSet.selections.length !== 1) {
- context.reportError(new _GraphQLError.GraphQLError(singleFieldOnlyMessage(node.name && node.name.value), node.selectionSet.selections.slice(1)));
- }
- }
- }
- };
- }
- },{"../../error/GraphQLError":275}],375:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateArgMessage = duplicateArgMessage;
- exports.UniqueArgumentNames = UniqueArgumentNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateArgMessage(argName) {
- return "There can be only one argument named \"".concat(argName, "\".");
- }
- /**
- * Unique argument names
- *
- * A GraphQL field or directive is only valid if all supplied arguments are
- * uniquely named.
- */
- function UniqueArgumentNames(context) {
- var knownArgNames = Object.create(null);
- return {
- Field: function Field() {
- knownArgNames = Object.create(null);
- },
- Directive: function Directive() {
- knownArgNames = Object.create(null);
- },
- Argument: function Argument(node) {
- var argName = node.name.value;
- if (knownArgNames[argName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name]));
- } else {
- knownArgNames[argName] = node.name;
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":275}],376:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateDirectiveNameMessage = duplicateDirectiveNameMessage;
- exports.existedDirectiveNameMessage = existedDirectiveNameMessage;
- exports.UniqueDirectiveNames = UniqueDirectiveNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateDirectiveNameMessage(directiveName) {
- return "There can be only one directive named \"".concat(directiveName, "\".");
- }
- function existedDirectiveNameMessage(directiveName) {
- return "Directive \"".concat(directiveName, "\" already exists in the schema. ") + 'It cannot be redefined.';
- }
- /**
- * Unique directive names
- *
- * A GraphQL document is only valid if all defined directives have unique names.
- */
- function UniqueDirectiveNames(context) {
- var knownDirectiveNames = Object.create(null);
- var schema = context.getSchema();
- return {
- DirectiveDefinition: function DirectiveDefinition(node) {
- var directiveName = node.name.value;
- if (schema && schema.getDirective(directiveName)) {
- context.reportError(new _GraphQLError.GraphQLError(existedDirectiveNameMessage(directiveName), node.name));
- return;
- }
- if (knownDirectiveNames[directiveName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateDirectiveNameMessage(directiveName), [knownDirectiveNames[directiveName], node.name]));
- } else {
- knownDirectiveNames[directiveName] = node.name;
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":275}],377:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateDirectiveMessage = duplicateDirectiveMessage;
- exports.UniqueDirectivesPerLocation = UniqueDirectivesPerLocation;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateDirectiveMessage(directiveName) {
- return "The directive \"".concat(directiveName, "\" can only be used once at ") + 'this location.';
- }
- /**
- * Unique directive names per location
- *
- * A GraphQL document is only valid if all directives at a given location
- * are uniquely named.
- */
- function UniqueDirectivesPerLocation(context) {
- return {
- // Many different AST nodes may contain directives. Rather than listing
- // them all, just listen for entering any node, and check to see if it
- // defines any directives.
- enter: function enter(node) {
- // Flow can't refine that node.directives will only contain directives,
- var directives = node.directives;
- if (directives) {
- var knownDirectives = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = directives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var directive = _step.value;
- var directiveName = directive.name.value;
- if (knownDirectives[directiveName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], directive]));
- } else {
- knownDirectives[directiveName] = directive;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- }
- };
- }
- },{"../../error/GraphQLError":275}],378:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateEnumValueNameMessage = duplicateEnumValueNameMessage;
- exports.existedEnumValueNameMessage = existedEnumValueNameMessage;
- exports.UniqueEnumValueNames = UniqueEnumValueNames;
- var _GraphQLError = require("../../error/GraphQLError");
- var _definition = require("../../type/definition");
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateEnumValueNameMessage(typeName, valueName) {
- return "Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once.");
- }
- function existedEnumValueNameMessage(typeName, valueName) {
- return "Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. ") + 'It cannot also be defined in this type extension.';
- }
- /**
- * Unique enum value names
- *
- * A GraphQL enum type is only valid if all its values are uniquely named.
- */
- function UniqueEnumValueNames(context) {
- var schema = context.getSchema();
- var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
- var knownValueNames = Object.create(null);
- return {
- EnumTypeDefinition: checkValueUniqueness,
- EnumTypeExtension: checkValueUniqueness
- };
- function checkValueUniqueness(node) {
- var typeName = node.name.value;
- if (!knownValueNames[typeName]) {
- knownValueNames[typeName] = Object.create(null);
- }
- var valueNames = knownValueNames[typeName];
- if (node.values) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = node.values[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var valueDef = _step.value;
- var valueName = valueDef.name.value;
- var existingType = existingTypeMap[typeName];
- if ((0, _definition.isEnumType)(existingType) && existingType.getValue(valueName)) {
- context.reportError(new _GraphQLError.GraphQLError(existedEnumValueNameMessage(typeName, valueName), valueDef.name));
- continue;
- }
- if (valueNames[valueName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateEnumValueNameMessage(typeName, valueName), [valueNames[valueName], valueDef.name]));
- } else {
- valueNames[valueName] = valueDef.name;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- return false;
- }
- }
- },{"../../error/GraphQLError":275,"../../type/definition":323}],379:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateFieldDefinitionNameMessage = duplicateFieldDefinitionNameMessage;
- exports.existedFieldDefinitionNameMessage = existedFieldDefinitionNameMessage;
- exports.UniqueFieldDefinitionNames = UniqueFieldDefinitionNames;
- var _GraphQLError = require("../../error/GraphQLError");
- var _definition = require("../../type/definition");
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateFieldDefinitionNameMessage(typeName, fieldName) {
- return "Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once.");
- }
- function existedFieldDefinitionNameMessage(typeName, fieldName) {
- return "Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. ") + 'It cannot also be defined in this type extension.';
- }
- /**
- * Unique field definition names
- *
- * A GraphQL complex type is only valid if all its fields are uniquely named.
- */
- function UniqueFieldDefinitionNames(context) {
- var schema = context.getSchema();
- var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
- var knownFieldNames = Object.create(null);
- return {
- InputObjectTypeDefinition: checkFieldUniqueness,
- InputObjectTypeExtension: checkFieldUniqueness,
- InterfaceTypeDefinition: checkFieldUniqueness,
- InterfaceTypeExtension: checkFieldUniqueness,
- ObjectTypeDefinition: checkFieldUniqueness,
- ObjectTypeExtension: checkFieldUniqueness
- };
- function checkFieldUniqueness(node) {
- var typeName = node.name.value;
- if (!knownFieldNames[typeName]) {
- knownFieldNames[typeName] = Object.create(null);
- }
- var fieldNames = knownFieldNames[typeName];
- if (node.fields) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = node.fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var fieldDef = _step.value;
- var fieldName = fieldDef.name.value;
- if (hasField(existingTypeMap[typeName], fieldName)) {
- context.reportError(new _GraphQLError.GraphQLError(existedFieldDefinitionNameMessage(typeName, fieldName), fieldDef.name));
- continue;
- }
- if (fieldNames[fieldName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateFieldDefinitionNameMessage(typeName, fieldName), [fieldNames[fieldName], fieldDef.name]));
- } else {
- fieldNames[fieldName] = fieldDef.name;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- return false;
- }
- }
- function hasField(type, fieldName) {
- if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type) || (0, _definition.isInputObjectType)(type)) {
- return type.getFields()[fieldName];
- }
- return false;
- }
- },{"../../error/GraphQLError":275,"../../type/definition":323}],380:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateFragmentNameMessage = duplicateFragmentNameMessage;
- exports.UniqueFragmentNames = UniqueFragmentNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateFragmentNameMessage(fragName) {
- return "There can be only one fragment named \"".concat(fragName, "\".");
- }
- /**
- * Unique fragment names
- *
- * A GraphQL document is only valid if all defined fragments have unique names.
- */
- function UniqueFragmentNames(context) {
- var knownFragmentNames = Object.create(null);
- return {
- OperationDefinition: function OperationDefinition() {
- return false;
- },
- FragmentDefinition: function FragmentDefinition(node) {
- var fragmentName = node.name.value;
- if (knownFragmentNames[fragmentName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name]));
- } else {
- knownFragmentNames[fragmentName] = node.name;
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":275}],381:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateInputFieldMessage = duplicateInputFieldMessage;
- exports.UniqueInputFieldNames = UniqueInputFieldNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateInputFieldMessage(fieldName) {
- return "There can be only one input field named \"".concat(fieldName, "\".");
- }
- /**
- * Unique input field names
- *
- * A GraphQL input object value is only valid if all supplied fields are
- * uniquely named.
- */
- function UniqueInputFieldNames(context) {
- var knownNameStack = [];
- var knownNames = Object.create(null);
- return {
- ObjectValue: {
- enter: function enter() {
- knownNameStack.push(knownNames);
- knownNames = Object.create(null);
- },
- leave: function leave() {
- knownNames = knownNameStack.pop();
- }
- },
- ObjectField: function ObjectField(node) {
- var fieldName = node.name.value;
- if (knownNames[fieldName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateInputFieldMessage(fieldName), [knownNames[fieldName], node.name]));
- } else {
- knownNames[fieldName] = node.name;
- }
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":275}],382:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateOperationNameMessage = duplicateOperationNameMessage;
- exports.UniqueOperationNames = UniqueOperationNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateOperationNameMessage(operationName) {
- return "There can be only one operation named \"".concat(operationName, "\".");
- }
- /**
- * Unique operation names
- *
- * A GraphQL document is only valid if all defined operations have unique names.
- */
- function UniqueOperationNames(context) {
- var knownOperationNames = Object.create(null);
- return {
- OperationDefinition: function OperationDefinition(node) {
- var operationName = node.name;
- if (operationName) {
- if (knownOperationNames[operationName.value]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateOperationNameMessage(operationName.value), [knownOperationNames[operationName.value], operationName]));
- } else {
- knownOperationNames[operationName.value] = operationName;
- }
- }
- return false;
- },
- FragmentDefinition: function FragmentDefinition() {
- return false;
- }
- };
- }
- },{"../../error/GraphQLError":275}],383:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateOperationTypeMessage = duplicateOperationTypeMessage;
- exports.existedOperationTypeMessage = existedOperationTypeMessage;
- exports.UniqueOperationTypes = UniqueOperationTypes;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateOperationTypeMessage(operation) {
- return "There can be only one ".concat(operation, " type in schema.");
- }
- function existedOperationTypeMessage(operation) {
- return "Type for ".concat(operation, " already defined in the schema. ") + 'It cannot be redefined.';
- }
- /**
- * Unique operation types
- *
- * A GraphQL document is only valid if it has only one type per operation.
- */
- function UniqueOperationTypes(context) {
- var schema = context.getSchema();
- var definedOperationTypes = Object.create(null);
- var existingOperationTypes = schema ? {
- query: schema.getQueryType(),
- mutation: schema.getMutationType(),
- subscription: schema.getSubscriptionType()
- } : {};
- return {
- SchemaDefinition: checkOperationTypes,
- SchemaExtension: checkOperationTypes
- };
- function checkOperationTypes(node) {
- if (node.operationTypes) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (node.operationTypes || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var operationType = _step.value;
- var operation = operationType.operation;
- var alreadyDefinedOperationType = definedOperationTypes[operation];
- if (existingOperationTypes[operation]) {
- context.reportError(new _GraphQLError.GraphQLError(existedOperationTypeMessage(operation), operationType));
- } else if (alreadyDefinedOperationType) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateOperationTypeMessage(operation), [alreadyDefinedOperationType, operationType]));
- } else {
- definedOperationTypes[operation] = operationType;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- return false;
- }
- }
- },{"../../error/GraphQLError":275}],384:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateTypeNameMessage = duplicateTypeNameMessage;
- exports.existedTypeNameMessage = existedTypeNameMessage;
- exports.UniqueTypeNames = UniqueTypeNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2018-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateTypeNameMessage(typeName) {
- return "There can be only one type named \"".concat(typeName, "\".");
- }
- function existedTypeNameMessage(typeName) {
- return "Type \"".concat(typeName, "\" already exists in the schema. ") + 'It cannot also be defined in this type definition.';
- }
- /**
- * Unique type names
- *
- * A GraphQL document is only valid if all defined types have unique names.
- */
- function UniqueTypeNames(context) {
- var knownTypeNames = Object.create(null);
- var schema = context.getSchema();
- return {
- ScalarTypeDefinition: checkTypeName,
- ObjectTypeDefinition: checkTypeName,
- InterfaceTypeDefinition: checkTypeName,
- UnionTypeDefinition: checkTypeName,
- EnumTypeDefinition: checkTypeName,
- InputObjectTypeDefinition: checkTypeName
- };
- function checkTypeName(node) {
- var typeName = node.name.value;
- if (schema && schema.getType(typeName)) {
- context.reportError(new _GraphQLError.GraphQLError(existedTypeNameMessage(typeName), node.name));
- return;
- }
- if (knownTypeNames[typeName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateTypeNameMessage(typeName), [knownTypeNames[typeName], node.name]));
- } else {
- knownTypeNames[typeName] = node.name;
- }
- return false;
- }
- }
- },{"../../error/GraphQLError":275}],385:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.duplicateVariableMessage = duplicateVariableMessage;
- exports.UniqueVariableNames = UniqueVariableNames;
- var _GraphQLError = require("../../error/GraphQLError");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function duplicateVariableMessage(variableName) {
- return "There can be only one variable named \"".concat(variableName, "\".");
- }
- /**
- * Unique variable names
- *
- * A GraphQL operation is only valid if all its variables are uniquely named.
- */
- function UniqueVariableNames(context) {
- var knownVariableNames = Object.create(null);
- return {
- OperationDefinition: function OperationDefinition() {
- knownVariableNames = Object.create(null);
- },
- VariableDefinition: function VariableDefinition(node) {
- var variableName = node.variable.name.value;
- if (knownVariableNames[variableName]) {
- context.reportError(new _GraphQLError.GraphQLError(duplicateVariableMessage(variableName), [knownVariableNames[variableName], node.variable.name]));
- } else {
- knownVariableNames[variableName] = node.variable.name;
- }
- }
- };
- }
- },{"../../error/GraphQLError":275}],386:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.badValueMessage = badValueMessage;
- exports.requiredFieldMessage = requiredFieldMessage;
- exports.unknownFieldMessage = unknownFieldMessage;
- exports.ValuesOfCorrectType = ValuesOfCorrectType;
- var _objectValues = _interopRequireDefault(require("../../polyfills/objectValues"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _printer = require("../../language/printer");
- var _definition = require("../../type/definition");
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _isInvalid = _interopRequireDefault(require("../../jsutils/isInvalid"));
- var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap"));
- var _orList = _interopRequireDefault(require("../../jsutils/orList"));
- var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function badValueMessage(typeName, valueName, message) {
- return "Expected type ".concat(typeName, ", found ").concat(valueName) + (message ? "; ".concat(message) : '.');
- }
- function requiredFieldMessage(typeName, fieldName, fieldTypeName) {
- return "Field ".concat(typeName, ".").concat(fieldName, " of required type ") + "".concat(fieldTypeName, " was not provided.");
- }
- function unknownFieldMessage(typeName, fieldName, message) {
- return "Field \"".concat(fieldName, "\" is not defined by type ").concat(typeName) + (message ? "; ".concat(message) : '.');
- }
- /**
- * Value literals of correct type
- *
- * A GraphQL document is only valid if all value literals are of the type
- * expected at their position.
- */
- function ValuesOfCorrectType(context) {
- return {
- NullValue: function NullValue(node) {
- var type = context.getInputType();
- if ((0, _definition.isNonNullType)(type)) {
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(type), (0, _printer.print)(node)), node));
- }
- },
- ListValue: function ListValue(node) {
- // Note: TypeInfo will traverse into a list's item type, so look to the
- // parent input type to check if it is a list.
- var type = (0, _definition.getNullableType)(context.getParentInputType());
- if (!(0, _definition.isListType)(type)) {
- isValidScalar(context, node);
- return false; // Don't traverse further.
- }
- },
- ObjectValue: function ObjectValue(node) {
- var type = (0, _definition.getNamedType)(context.getInputType());
- if (!(0, _definition.isInputObjectType)(type)) {
- isValidScalar(context, node);
- return false; // Don't traverse further.
- } // Ensure every required field exists.
- var fieldNodeMap = (0, _keyMap.default)(node.fields, function (field) {
- return field.name.value;
- });
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var fieldDef = _step.value;
- var fieldNode = fieldNodeMap[fieldDef.name];
- if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) {
- var typeStr = (0, _inspect.default)(fieldDef.type);
- context.reportError(new _GraphQLError.GraphQLError(requiredFieldMessage(type.name, fieldDef.name, typeStr), node));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- },
- ObjectField: function ObjectField(node) {
- var parentType = (0, _definition.getNamedType)(context.getParentInputType());
- var fieldType = context.getInputType();
- if (!fieldType && (0, _definition.isInputObjectType)(parentType)) {
- var suggestions = (0, _suggestionList.default)(node.name.value, Object.keys(parentType.getFields()));
- var didYouMean = suggestions.length !== 0 ? "Did you mean ".concat((0, _orList.default)(suggestions), "?") : undefined;
- context.reportError(new _GraphQLError.GraphQLError(unknownFieldMessage(parentType.name, node.name.value, didYouMean), node));
- }
- },
- EnumValue: function EnumValue(node) {
- var type = (0, _definition.getNamedType)(context.getInputType());
- if (!(0, _definition.isEnumType)(type)) {
- isValidScalar(context, node);
- } else if (!type.getValue(node.value)) {
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage(type.name, (0, _printer.print)(node), enumTypeSuggestion(type, node)), node));
- }
- },
- IntValue: function IntValue(node) {
- return isValidScalar(context, node);
- },
- FloatValue: function FloatValue(node) {
- return isValidScalar(context, node);
- },
- StringValue: function StringValue(node) {
- return isValidScalar(context, node);
- },
- BooleanValue: function BooleanValue(node) {
- return isValidScalar(context, node);
- }
- };
- }
- /**
- * Any value literal may be a valid representation of a Scalar, depending on
- * that scalar type.
- */
- function isValidScalar(context, node) {
- // Report any error at the full type expected by the location.
- var locationType = context.getInputType();
- if (!locationType) {
- return;
- }
- var type = (0, _definition.getNamedType)(locationType);
- if (!(0, _definition.isScalarType)(type)) {
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node), enumTypeSuggestion(type, node)), node));
- return;
- } // Scalars determine if a literal value is valid via parseLiteral() which
- // may throw or return an invalid value to indicate failure.
- try {
- var parseResult = type.parseLiteral(node, undefined
- /* variables */
- );
- if ((0, _isInvalid.default)(parseResult)) {
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node)), node));
- }
- } catch (error) {
- // Ensure a reference to the original error is maintained.
- context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node), error.message), node, undefined, undefined, undefined, error));
- }
- }
- function enumTypeSuggestion(type, node) {
- if ((0, _definition.isEnumType)(type)) {
- var suggestions = (0, _suggestionList.default)((0, _printer.print)(node), type.getValues().map(function (value) {
- return value.name;
- }));
- if (suggestions.length !== 0) {
- return "Did you mean the enum value ".concat((0, _orList.default)(suggestions), "?");
- }
- }
- }
- },{"../../error/GraphQLError":275,"../../jsutils/inspect":288,"../../jsutils/isInvalid":291,"../../jsutils/keyMap":294,"../../jsutils/orList":299,"../../jsutils/suggestionList":303,"../../language/printer":312,"../../polyfills/objectValues":319,"../../type/definition":323}],387:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.nonInputTypeOnVarMessage = nonInputTypeOnVarMessage;
- exports.VariablesAreInputTypes = VariablesAreInputTypes;
- var _GraphQLError = require("../../error/GraphQLError");
- var _printer = require("../../language/printer");
- var _definition = require("../../type/definition");
- var _typeFromAST = require("../../utilities/typeFromAST");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function nonInputTypeOnVarMessage(variableName, typeName) {
- return "Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\".");
- }
- /**
- * Variables are input types
- *
- * A GraphQL operation is only valid if all the variables it defines are of
- * input types (scalar, enum, or input object).
- */
- function VariablesAreInputTypes(context) {
- return {
- VariableDefinition: function VariableDefinition(node) {
- var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.type); // If the variable type is not an input type, return an error.
- if (type && !(0, _definition.isInputType)(type)) {
- var variableName = node.variable.name.value;
- context.reportError(new _GraphQLError.GraphQLError(nonInputTypeOnVarMessage(variableName, (0, _printer.print)(node.type)), [node.type]));
- }
- }
- };
- }
- },{"../../error/GraphQLError":275,"../../language/printer":312,"../../type/definition":323,"../../utilities/typeFromAST":351}],388:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.badVarPosMessage = badVarPosMessage;
- exports.VariablesInAllowedPosition = VariablesInAllowedPosition;
- var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
- var _GraphQLError = require("../../error/GraphQLError");
- var _kinds = require("../../language/kinds");
- var _definition = require("../../type/definition");
- var _typeComparators = require("../../utilities/typeComparators");
- var _typeFromAST = require("../../utilities/typeFromAST");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- function badVarPosMessage(varName, varType, expectedType) {
- return "Variable \"$".concat(varName, "\" of type \"").concat(varType, "\" used in ") + "position expecting type \"".concat(expectedType, "\".");
- }
- /**
- * Variables passed to field arguments conform to type
- */
- function VariablesInAllowedPosition(context) {
- var varDefMap = Object.create(null);
- return {
- OperationDefinition: {
- enter: function enter() {
- varDefMap = Object.create(null);
- },
- leave: function leave(operation) {
- var usages = context.getRecursiveVariableUsages(operation);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ref2 = _step.value;
- var node = _ref2.node;
- var type = _ref2.type;
- var defaultValue = _ref2.defaultValue;
- var varName = node.name.value;
- var varDef = varDefMap[varName];
- if (varDef && type) {
- // A var type is allowed if it is the same or more strict (e.g. is
- // a subtype of) than the expected type. It can be more strict if
- // the variable type is non-null when the expected type is nullable.
- // If both are list types, the variable item type can be more strict
- // than the expected item type (contravariant).
- var schema = context.getSchema();
- var varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type);
- if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) {
- context.reportError(new _GraphQLError.GraphQLError(badVarPosMessage(varName, (0, _inspect.default)(varType), (0, _inspect.default)(type)), [varDef, node]));
- }
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- },
- VariableDefinition: function VariableDefinition(node) {
- varDefMap[node.variable.name.value] = node;
- }
- };
- }
- /**
- * Returns true if the variable is allowed in the location it was found,
- * which includes considering if default values exist for either the variable
- * or the location at which it is located.
- */
- function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) {
- if ((0, _definition.isNonNullType)(locationType) && !(0, _definition.isNonNullType)(varType)) {
- var hasNonNullVariableDefaultValue = varDefaultValue && varDefaultValue.kind !== _kinds.Kind.NULL;
- var hasLocationDefaultValue = locationDefaultValue !== undefined;
- if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) {
- return false;
- }
- var nullableLocationType = locationType.ofType;
- return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, nullableLocationType);
- }
- return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType);
- }
- },{"../../error/GraphQLError":275,"../../jsutils/inspect":288,"../../language/kinds":307,"../../type/definition":323,"../../utilities/typeComparators":350,"../../utilities/typeFromAST":351}],389:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.specifiedSDLRules = exports.specifiedRules = void 0;
- var _ExecutableDefinitions = require("./rules/ExecutableDefinitions");
- var _UniqueOperationNames = require("./rules/UniqueOperationNames");
- var _LoneAnonymousOperation = require("./rules/LoneAnonymousOperation");
- var _SingleFieldSubscriptions = require("./rules/SingleFieldSubscriptions");
- var _KnownTypeNames = require("./rules/KnownTypeNames");
- var _FragmentsOnCompositeTypes = require("./rules/FragmentsOnCompositeTypes");
- var _VariablesAreInputTypes = require("./rules/VariablesAreInputTypes");
- var _ScalarLeafs = require("./rules/ScalarLeafs");
- var _FieldsOnCorrectType = require("./rules/FieldsOnCorrectType");
- var _UniqueFragmentNames = require("./rules/UniqueFragmentNames");
- var _KnownFragmentNames = require("./rules/KnownFragmentNames");
- var _NoUnusedFragments = require("./rules/NoUnusedFragments");
- var _PossibleFragmentSpreads = require("./rules/PossibleFragmentSpreads");
- var _NoFragmentCycles = require("./rules/NoFragmentCycles");
- var _UniqueVariableNames = require("./rules/UniqueVariableNames");
- var _NoUndefinedVariables = require("./rules/NoUndefinedVariables");
- var _NoUnusedVariables = require("./rules/NoUnusedVariables");
- var _KnownDirectives = require("./rules/KnownDirectives");
- var _UniqueDirectivesPerLocation = require("./rules/UniqueDirectivesPerLocation");
- var _KnownArgumentNames = require("./rules/KnownArgumentNames");
- var _UniqueArgumentNames = require("./rules/UniqueArgumentNames");
- var _ValuesOfCorrectType = require("./rules/ValuesOfCorrectType");
- var _ProvidedRequiredArguments = require("./rules/ProvidedRequiredArguments");
- var _VariablesInAllowedPosition = require("./rules/VariablesInAllowedPosition");
- var _OverlappingFieldsCanBeMerged = require("./rules/OverlappingFieldsCanBeMerged");
- var _UniqueInputFieldNames = require("./rules/UniqueInputFieldNames");
- var _LoneSchemaDefinition = require("./rules/LoneSchemaDefinition");
- var _UniqueOperationTypes = require("./rules/UniqueOperationTypes");
- var _UniqueTypeNames = require("./rules/UniqueTypeNames");
- var _UniqueEnumValueNames = require("./rules/UniqueEnumValueNames");
- var _UniqueFieldDefinitionNames = require("./rules/UniqueFieldDefinitionNames");
- var _UniqueDirectiveNames = require("./rules/UniqueDirectiveNames");
- var _PossibleTypeExtensions = require("./rules/PossibleTypeExtensions");
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- // Spec Section: "Executable Definitions"
- // Spec Section: "Operation Name Uniqueness"
- // Spec Section: "Lone Anonymous Operation"
- // Spec Section: "Subscriptions with Single Root Field"
- // Spec Section: "Fragment Spread Type Existence"
- // Spec Section: "Fragments on Composite Types"
- // Spec Section: "Variables are Input Types"
- // Spec Section: "Leaf Field Selections"
- // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types"
- // Spec Section: "Fragment Name Uniqueness"
- // Spec Section: "Fragment spread target defined"
- // Spec Section: "Fragments must be used"
- // Spec Section: "Fragment spread is possible"
- // Spec Section: "Fragments must not form cycles"
- // Spec Section: "Variable Uniqueness"
- // Spec Section: "All Variable Used Defined"
- // Spec Section: "All Variables Used"
- // Spec Section: "Directives Are Defined"
- // Spec Section: "Directives Are Unique Per Location"
- // Spec Section: "Argument Names"
- // Spec Section: "Argument Uniqueness"
- // Spec Section: "Value Type Correctness"
- // Spec Section: "Argument Optionality"
- // Spec Section: "All Variable Usages Are Allowed"
- // Spec Section: "Field Selection Merging"
- // Spec Section: "Input Object Field Uniqueness"
- /**
- * This set includes all validation rules defined by the GraphQL spec.
- *
- * The order of the rules in this list has been adjusted to lead to the
- * most clear output when encountering multiple validation errors.
- */
- var specifiedRules = [_ExecutableDefinitions.ExecutableDefinitions, _UniqueOperationNames.UniqueOperationNames, _LoneAnonymousOperation.LoneAnonymousOperation, _SingleFieldSubscriptions.SingleFieldSubscriptions, _KnownTypeNames.KnownTypeNames, _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes, _VariablesAreInputTypes.VariablesAreInputTypes, _ScalarLeafs.ScalarLeafs, _FieldsOnCorrectType.FieldsOnCorrectType, _UniqueFragmentNames.UniqueFragmentNames, _KnownFragmentNames.KnownFragmentNames, _NoUnusedFragments.NoUnusedFragments, _PossibleFragmentSpreads.PossibleFragmentSpreads, _NoFragmentCycles.NoFragmentCycles, _UniqueVariableNames.UniqueVariableNames, _NoUndefinedVariables.NoUndefinedVariables, _NoUnusedVariables.NoUnusedVariables, _KnownDirectives.KnownDirectives, _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation, _KnownArgumentNames.KnownArgumentNames, _UniqueArgumentNames.UniqueArgumentNames, _ValuesOfCorrectType.ValuesOfCorrectType, _ProvidedRequiredArguments.ProvidedRequiredArguments, _VariablesInAllowedPosition.VariablesInAllowedPosition, _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged, _UniqueInputFieldNames.UniqueInputFieldNames];
- exports.specifiedRules = specifiedRules;
- // @internal
- var specifiedSDLRules = [_LoneSchemaDefinition.LoneSchemaDefinition, _UniqueOperationTypes.UniqueOperationTypes, _UniqueTypeNames.UniqueTypeNames, _UniqueEnumValueNames.UniqueEnumValueNames, _UniqueFieldDefinitionNames.UniqueFieldDefinitionNames, _UniqueDirectiveNames.UniqueDirectiveNames, _KnownTypeNames.KnownTypeNames, _KnownDirectives.KnownDirectives, _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation, _PossibleTypeExtensions.PossibleTypeExtensions, _KnownArgumentNames.KnownArgumentNamesOnDirectives, _UniqueArgumentNames.UniqueArgumentNames, _UniqueInputFieldNames.UniqueInputFieldNames, _ProvidedRequiredArguments.ProvidedRequiredArgumentsOnDirectives];
- exports.specifiedSDLRules = specifiedSDLRules;
- },{"./rules/ExecutableDefinitions":356,"./rules/FieldsOnCorrectType":357,"./rules/FragmentsOnCompositeTypes":358,"./rules/KnownArgumentNames":359,"./rules/KnownDirectives":360,"./rules/KnownFragmentNames":361,"./rules/KnownTypeNames":362,"./rules/LoneAnonymousOperation":363,"./rules/LoneSchemaDefinition":364,"./rules/NoFragmentCycles":365,"./rules/NoUndefinedVariables":366,"./rules/NoUnusedFragments":367,"./rules/NoUnusedVariables":368,"./rules/OverlappingFieldsCanBeMerged":369,"./rules/PossibleFragmentSpreads":370,"./rules/PossibleTypeExtensions":371,"./rules/ProvidedRequiredArguments":372,"./rules/ScalarLeafs":373,"./rules/SingleFieldSubscriptions":374,"./rules/UniqueArgumentNames":375,"./rules/UniqueDirectiveNames":376,"./rules/UniqueDirectivesPerLocation":377,"./rules/UniqueEnumValueNames":378,"./rules/UniqueFieldDefinitionNames":379,"./rules/UniqueFragmentNames":380,"./rules/UniqueInputFieldNames":381,"./rules/UniqueOperationNames":382,"./rules/UniqueOperationTypes":383,"./rules/UniqueTypeNames":384,"./rules/UniqueVariableNames":385,"./rules/ValuesOfCorrectType":386,"./rules/VariablesAreInputTypes":387,"./rules/VariablesInAllowedPosition":388}],390:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.validate = validate;
- exports.validateSDL = validateSDL;
- exports.assertValidSDL = assertValidSDL;
- exports.assertValidSDLExtension = assertValidSDLExtension;
- var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
- var _visitor = require("../language/visitor");
- var _validate = require("../type/validate");
- var _TypeInfo = require("../utilities/TypeInfo");
- var _specifiedRules = require("./specifiedRules");
- var _ValidationContext = require("./ValidationContext");
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- /**
- * Implements the "Validation" section of the spec.
- *
- * Validation runs synchronously, returning an array of encountered errors, or
- * an empty array if no errors were encountered and the document is valid.
- *
- * A list of specific validation rules may be provided. If not provided, the
- * default list of rules defined by the GraphQL specification will be used.
- *
- * Each validation rules is a function which returns a visitor
- * (see the language/visitor API). Visitor methods are expected to return
- * GraphQLErrors, or Arrays of GraphQLErrors when invalid.
- *
- * Optionally a custom TypeInfo instance may be provided. If not provided, one
- * will be created from the provided schema.
- */
- function validate(schema, documentAST) {
- var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedRules;
- var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new _TypeInfo.TypeInfo(schema);
- !documentAST ? (0, _invariant.default)(0, 'Must provide document') : void 0; // If the schema used for validation is invalid, throw an error.
- (0, _validate.assertValidSchema)(schema);
- var context = new _ValidationContext.ValidationContext(schema, documentAST, typeInfo); // This uses a specialized visitor which runs multiple visitors in parallel,
- // while maintaining the visitor skip and break API.
- var visitor = (0, _visitor.visitInParallel)(rules.map(function (rule) {
- return rule(context);
- })); // Visit the whole document with each instance of all provided rules.
- (0, _visitor.visit)(documentAST, (0, _visitor.visitWithTypeInfo)(typeInfo, visitor));
- return context.getErrors();
- } // @internal
- function validateSDL(documentAST, schemaToExtend) {
- var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedSDLRules;
- var context = new _ValidationContext.SDLValidationContext(documentAST, schemaToExtend);
- var visitors = rules.map(function (rule) {
- return rule(context);
- });
- (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors));
- return context.getErrors();
- }
- /**
- * Utility function which asserts a SDL document is valid by throwing an error
- * if it is invalid.
- *
- * @internal
- */
- function assertValidSDL(documentAST) {
- var errors = validateSDL(documentAST);
- if (errors.length !== 0) {
- throw new Error(errors.map(function (error) {
- return error.message;
- }).join('\n\n'));
- }
- }
- /**
- * Utility function which asserts a SDL document is valid by throwing an error
- * if it is invalid.
- *
- * @internal
- */
- function assertValidSDLExtension(documentAST, schema) {
- var errors = validateSDL(documentAST, schema);
- if (errors.length !== 0) {
- throw new Error(errors.map(function (error) {
- return error.message;
- }).join('\n\n'));
- }
- }
- },{"../jsutils/invariant":290,"../language/visitor":314,"../type/validate":329,"../utilities/TypeInfo":330,"./ValidationContext":354,"./specifiedRules":389}],391:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- var _graphqlLanguageServiceParser = require('graphql-language-service-parser');
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * This mode defines JSON, but provides a data-laden parser state to enable
- * better code intelligence.
- */
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- _codemirror2.default.defineMode('graphql-results', function (config) {
- var parser = (0, _graphqlLanguageServiceParser.onlineParser)({
- eatWhitespace: function eatWhitespace(stream) {
- return stream.eatSpace();
- },
- lexRules: LexRules,
- parseRules: ParseRules,
- editorConfig: { tabSize: config.tabSize }
- });
- return {
- config: config,
- startState: parser.startState,
- token: parser.token,
- indent: indent,
- electricInput: /^\s*[}\]]/,
- fold: 'brace',
- closeBrackets: {
- pairs: '[]{}""',
- explode: '[]{}'
- }
- };
- });
- function indent(state, textAfter) {
- var levels = state.levels;
- // If there is no stack of levels, use the current level.
- // Otherwise, use the top level, pre-emptively dedenting for close braces.
- var level = !levels || levels.length === 0 ? state.indentLevel : levels[levels.length - 1] - (this.electricInput.test(textAfter) ? 1 : 0);
- return level * this.config.indentUnit;
- }
- /**
- * The lexer rules. These are exactly as described by the spec.
- */
- var LexRules = {
- // All Punctuation used in JSON.
- Punctuation: /^\[|]|\{|\}|:|,/,
- // JSON Number.
- Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,
- // JSON String.
- String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/,
- // JSON literal keywords.
- Keyword: /^true|false|null/
- };
- /**
- * The parser rules for JSON.
- */
- var ParseRules = {
- Document: [(0, _graphqlLanguageServiceParser.p)('{'), (0, _graphqlLanguageServiceParser.list)('Entry', (0, _graphqlLanguageServiceParser.p)(',')), (0, _graphqlLanguageServiceParser.p)('}')],
- Entry: [(0, _graphqlLanguageServiceParser.t)('String', 'def'), (0, _graphqlLanguageServiceParser.p)(':'), 'Value'],
- Value: function Value(token) {
- switch (token.kind) {
- case 'Number':
- return 'NumberValue';
- case 'String':
- return 'StringValue';
- case 'Punctuation':
- switch (token.value) {
- case '[':
- return 'ListValue';
- case '{':
- return 'ObjectValue';
- }
- return null;
- case 'Keyword':
- switch (token.value) {
- case 'true':
- case 'false':
- return 'BooleanValue';
- case 'null':
- return 'NullValue';
- }
- return null;
- }
- },
- NumberValue: [(0, _graphqlLanguageServiceParser.t)('Number', 'number')],
- StringValue: [(0, _graphqlLanguageServiceParser.t)('String', 'string')],
- BooleanValue: [(0, _graphqlLanguageServiceParser.t)('Keyword', 'builtin')],
- NullValue: [(0, _graphqlLanguageServiceParser.t)('Keyword', 'keyword')],
- ListValue: [(0, _graphqlLanguageServiceParser.p)('['), (0, _graphqlLanguageServiceParser.list)('Value', (0, _graphqlLanguageServiceParser.p)(',')), (0, _graphqlLanguageServiceParser.p)(']')],
- ObjectValue: [(0, _graphqlLanguageServiceParser.p)('{'), (0, _graphqlLanguageServiceParser.list)('ObjectField', (0, _graphqlLanguageServiceParser.p)(',')), (0, _graphqlLanguageServiceParser.p)('}')],
- ObjectField: [(0, _graphqlLanguageServiceParser.t)('String', 'property'), (0, _graphqlLanguageServiceParser.p)(':'), 'Value']
- };
- },{"codemirror":16,"graphql-language-service-parser":269}],392:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.getFieldReference = getFieldReference;
- exports.getDirectiveReference = getDirectiveReference;
- exports.getArgumentReference = getArgumentReference;
- exports.getEnumValueReference = getEnumValueReference;
- exports.getTypeReference = getTypeReference;
- var _graphql = require('graphql');
- function getFieldReference(typeInfo) {
- return {
- kind: 'Field',
- schema: typeInfo.schema,
- field: typeInfo.fieldDef,
- type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType
- };
- }
- /**
- * Copyright (c), Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- function getDirectiveReference(typeInfo) {
- return {
- kind: 'Directive',
- schema: typeInfo.schema,
- directive: typeInfo.directiveDef
- };
- }
- function getArgumentReference(typeInfo) {
- return typeInfo.directiveDef ? {
- kind: 'Argument',
- schema: typeInfo.schema,
- argument: typeInfo.argDef,
- directive: typeInfo.directiveDef
- } : {
- kind: 'Argument',
- schema: typeInfo.schema,
- argument: typeInfo.argDef,
- field: typeInfo.fieldDef,
- type: isMetaField(typeInfo.fieldDef) ? null : typeInfo.parentType
- };
- }
- function getEnumValueReference(typeInfo) {
- return {
- kind: 'EnumValue',
- value: typeInfo.enumValue,
- type: (0, _graphql.getNamedType)(typeInfo.inputType)
- };
- }
- // Note: for reusability, getTypeReference can produce a reference to any type,
- // though it defaults to the current type.
- function getTypeReference(typeInfo, type) {
- return {
- kind: 'Type',
- schema: typeInfo.schema,
- type: type || typeInfo.type
- };
- }
- function isMetaField(fieldDef) {
- return fieldDef.name.slice(0, 2) === '__';
- }
- },{"graphql":285}],393:[function(require,module,exports){
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = forEachState;
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- // Utility for iterating through a CodeMirror parse state stack bottom-up.
- function forEachState(stack, fn) {
- var reverseStateStack = [];
- var state = stack;
- while (state && state.kind) {
- reverseStateStack.push(state);
- state = state.prevState;
- }
- for (var i = reverseStateStack.length - 1; i >= 0; i--) {
- fn(reverseStateStack[i]);
- }
- }
- },{}],394:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = getTypeInfo;
- var _graphql = require('graphql');
- var _introspection = require('graphql/type/introspection');
- var _forEachState = require('./forEachState');
- var _forEachState2 = _interopRequireDefault(_forEachState);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Utility for collecting rich type information given any token's state
- * from the graphql-mode parser.
- */
- function getTypeInfo(schema, tokenState) {
- var info = {
- schema: schema,
- type: null,
- parentType: null,
- inputType: null,
- directiveDef: null,
- fieldDef: null,
- argDef: null,
- argDefs: null,
- objectFieldDefs: null
- };
- (0, _forEachState2.default)(tokenState, function (state) {
- switch (state.kind) {
- case 'Query':
- case 'ShortQuery':
- info.type = schema.getQueryType();
- break;
- case 'Mutation':
- info.type = schema.getMutationType();
- break;
- case 'Subscription':
- info.type = schema.getSubscriptionType();
- break;
- case 'InlineFragment':
- case 'FragmentDefinition':
- if (state.type) {
- info.type = schema.getType(state.type);
- }
- break;
- case 'Field':
- case 'AliasedField':
- info.fieldDef = info.type && state.name ? getFieldDef(schema, info.parentType, state.name) : null;
- info.type = info.fieldDef && info.fieldDef.type;
- break;
- case 'SelectionSet':
- info.parentType = (0, _graphql.getNamedType)(info.type);
- break;
- case 'Directive':
- info.directiveDef = state.name && schema.getDirective(state.name);
- break;
- case 'Arguments':
- var parentDef = state.prevState.kind === 'Field' ? info.fieldDef : state.prevState.kind === 'Directive' ? info.directiveDef : state.prevState.kind === 'AliasedField' ? state.prevState.name && getFieldDef(schema, info.parentType, state.prevState.name) : null;
- info.argDefs = parentDef && parentDef.args;
- break;
- case 'Argument':
- info.argDef = null;
- if (info.argDefs) {
- for (var i = 0; i < info.argDefs.length; i++) {
- if (info.argDefs[i].name === state.name) {
- info.argDef = info.argDefs[i];
- break;
- }
- }
- }
- info.inputType = info.argDef && info.argDef.type;
- break;
- case 'EnumValue':
- var enumType = (0, _graphql.getNamedType)(info.inputType);
- info.enumValue = enumType instanceof _graphql.GraphQLEnumType ? find(enumType.getValues(), function (val) {
- return val.value === state.name;
- }) : null;
- break;
- case 'ListValue':
- var nullableType = (0, _graphql.getNullableType)(info.inputType);
- info.inputType = nullableType instanceof _graphql.GraphQLList ? nullableType.ofType : null;
- break;
- case 'ObjectValue':
- var objectType = (0, _graphql.getNamedType)(info.inputType);
- info.objectFieldDefs = objectType instanceof _graphql.GraphQLInputObjectType ? objectType.getFields() : null;
- break;
- case 'ObjectField':
- var objectField = state.name && info.objectFieldDefs ? info.objectFieldDefs[state.name] : null;
- info.inputType = objectField && objectField.type;
- break;
- case 'NamedType':
- info.type = schema.getType(state.name);
- break;
- }
- });
- return info;
- }
- // Gets the field definition given a type and field name
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- function getFieldDef(schema, type, fieldName) {
- if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === type) {
- return _introspection.SchemaMetaFieldDef;
- }
- if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === type) {
- return _introspection.TypeMetaFieldDef;
- }
- if (fieldName === _introspection.TypeNameMetaFieldDef.name && (0, _graphql.isCompositeType)(type)) {
- return _introspection.TypeNameMetaFieldDef;
- }
- if (type.getFields) {
- return type.getFields()[fieldName];
- }
- }
- // Returns the first item in the array which causes predicate to return truthy.
- function find(array, predicate) {
- for (var i = 0; i < array.length; i++) {
- if (predicate(array[i])) {
- return array[i];
- }
- }
- }
- },{"./forEachState":393,"graphql":285,"graphql/type/introspection":326}],395:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = hintList;
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- // Create the expected hint response given a possible list and a token
- function hintList(cursor, token, list) {
- var hints = filterAndSortList(list, normalizeText(token.string));
- if (!hints) {
- return;
- }
- var tokenStart = token.type !== null && /"|\w/.test(token.string[0]) ? token.start : token.end;
- return {
- list: hints,
- from: { line: cursor.line, column: tokenStart },
- to: { line: cursor.line, column: token.end }
- };
- }
- // Given a list of hint entries and currently typed text, sort and filter to
- // provide a concise list.
- function filterAndSortList(list, text) {
- if (!text) {
- return filterNonEmpty(list, function (entry) {
- return !entry.isDeprecated;
- });
- }
- var byProximity = list.map(function (entry) {
- return {
- proximity: getProximity(normalizeText(entry.text), text),
- entry: entry
- };
- });
- var conciseMatches = filterNonEmpty(filterNonEmpty(byProximity, function (pair) {
- return pair.proximity <= 2;
- }), function (pair) {
- return !pair.entry.isDeprecated;
- });
- var sortedMatches = conciseMatches.sort(function (a, b) {
- return (a.entry.isDeprecated ? 1 : 0) - (b.entry.isDeprecated ? 1 : 0) || a.proximity - b.proximity || a.entry.text.length - b.entry.text.length;
- });
- return sortedMatches.map(function (pair) {
- return pair.entry;
- });
- }
- // Filters the array by the predicate, unless it results in an empty array,
- // in which case return the original array.
- function filterNonEmpty(array, predicate) {
- var filtered = array.filter(predicate);
- return filtered.length === 0 ? array : filtered;
- }
- function normalizeText(text) {
- return text.toLowerCase().replace(/\W/g, '');
- }
- // Determine a numeric proximity for a suggestion based on current text.
- function getProximity(suggestion, text) {
- // start with lexical distance
- var proximity = lexicalDistance(text, suggestion);
- if (suggestion.length > text.length) {
- // do not penalize long suggestions.
- proximity -= suggestion.length - text.length - 1;
- // penalize suggestions not starting with this phrase
- proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5;
- }
- return proximity;
- }
- /**
- * Computes the lexical distance between strings A and B.
- *
- * The "distance" between two strings is given by counting the minimum number
- * of edits needed to transform string A into string B. An edit can be an
- * insertion, deletion, or substitution of a single character, or a swap of two
- * adjacent characters.
- *
- * This distance can be useful for detecting typos in input or sorting
- *
- * @param {string} a
- * @param {string} b
- * @return {int} distance in number of edits
- */
- function lexicalDistance(a, b) {
- var i = void 0;
- var j = void 0;
- var d = [];
- var aLength = a.length;
- var bLength = b.length;
- for (i = 0; i <= aLength; i++) {
- d[i] = [i];
- }
- for (j = 1; j <= bLength; j++) {
- d[0][j] = j;
- }
- for (i = 1; i <= aLength; i++) {
- for (j = 1; j <= bLength; j++) {
- var cost = a[i - 1] === b[j - 1] ? 0 : 1;
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
- }
- }
- }
- return d[aLength][bLength];
- }
- },{}],396:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- _codemirror2.default.defineOption('info', false, function (cm, options, old) {
- if (old && old !== _codemirror2.default.Init) {
- var oldOnMouseOver = cm.state.info.onMouseOver;
- _codemirror2.default.off(cm.getWrapperElement(), 'mouseover', oldOnMouseOver);
- clearTimeout(cm.state.info.hoverTimeout);
- delete cm.state.info;
- }
- if (options) {
- var state = cm.state.info = createState(options);
- state.onMouseOver = onMouseOver.bind(null, cm);
- _codemirror2.default.on(cm.getWrapperElement(), 'mouseover', state.onMouseOver);
- }
- }); /**
- * Copyright (c) 2017, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- function createState(options) {
- return {
- options: options instanceof Function ? { render: options } : options === true ? {} : options
- };
- }
- function getHoverTime(cm) {
- var options = cm.state.info.options;
- return options && options.hoverTime || 500;
- }
- function onMouseOver(cm, e) {
- var state = cm.state.info;
- var target = e.target || e.srcElement;
- if (target.nodeName !== 'SPAN' || state.hoverTimeout !== undefined) {
- return;
- }
- var box = target.getBoundingClientRect();
- var hoverTime = getHoverTime(cm);
- state.hoverTimeout = setTimeout(onHover, hoverTime);
- var onMouseMove = function onMouseMove() {
- clearTimeout(state.hoverTimeout);
- state.hoverTimeout = setTimeout(onHover, hoverTime);
- };
- var onMouseOut = function onMouseOut() {
- _codemirror2.default.off(document, 'mousemove', onMouseMove);
- _codemirror2.default.off(cm.getWrapperElement(), 'mouseout', onMouseOut);
- clearTimeout(state.hoverTimeout);
- state.hoverTimeout = undefined;
- };
- var onHover = function onHover() {
- _codemirror2.default.off(document, 'mousemove', onMouseMove);
- _codemirror2.default.off(cm.getWrapperElement(), 'mouseout', onMouseOut);
- state.hoverTimeout = undefined;
- onMouseHover(cm, box);
- };
- _codemirror2.default.on(document, 'mousemove', onMouseMove);
- _codemirror2.default.on(cm.getWrapperElement(), 'mouseout', onMouseOut);
- }
- function onMouseHover(cm, box) {
- var pos = cm.coordsChar({
- left: (box.left + box.right) / 2,
- top: (box.top + box.bottom) / 2
- });
- var state = cm.state.info;
- var options = state.options;
- var render = options.render || cm.getHelper(pos, 'info');
- if (render) {
- var token = cm.getTokenAt(pos, true);
- if (token) {
- var info = render(token, options, cm, pos);
- if (info) {
- showPopup(cm, box, info);
- }
- }
- }
- }
- function showPopup(cm, box, info) {
- var popup = document.createElement('div');
- popup.className = 'CodeMirror-info';
- popup.appendChild(info);
- document.body.appendChild(popup);
- var popupBox = popup.getBoundingClientRect();
- var popupStyle = popup.currentStyle || window.getComputedStyle(popup);
- var popupWidth = popupBox.right - popupBox.left + parseFloat(popupStyle.marginLeft) + parseFloat(popupStyle.marginRight);
- var popupHeight = popupBox.bottom - popupBox.top + parseFloat(popupStyle.marginTop) + parseFloat(popupStyle.marginBottom);
- var topPos = box.bottom;
- if (popupHeight > window.innerHeight - box.bottom - 15 && box.top > window.innerHeight - box.bottom) {
- topPos = box.top - popupHeight;
- }
- if (topPos < 0) {
- topPos = box.bottom;
- }
- var leftPos = Math.max(0, window.innerWidth - popupWidth - 15);
- if (leftPos > box.left) {
- leftPos = box.left;
- }
- popup.style.opacity = 1;
- popup.style.top = topPos + 'px';
- popup.style.left = leftPos + 'px';
- var popupTimeout = void 0;
- var onMouseOverPopup = function onMouseOverPopup() {
- clearTimeout(popupTimeout);
- };
- var onMouseOut = function onMouseOut() {
- clearTimeout(popupTimeout);
- popupTimeout = setTimeout(hidePopup, 200);
- };
- var hidePopup = function hidePopup() {
- _codemirror2.default.off(popup, 'mouseover', onMouseOverPopup);
- _codemirror2.default.off(popup, 'mouseout', onMouseOut);
- _codemirror2.default.off(cm.getWrapperElement(), 'mouseout', onMouseOut);
- if (popup.style.opacity) {
- popup.style.opacity = 0;
- setTimeout(function () {
- if (popup.parentNode) {
- popup.parentNode.removeChild(popup);
- }
- }, 600);
- } else if (popup.parentNode) {
- popup.parentNode.removeChild(popup);
- }
- };
- _codemirror2.default.on(popup, 'mouseover', onMouseOverPopup);
- _codemirror2.default.on(popup, 'mouseout', onMouseOut);
- _codemirror2.default.on(cm.getWrapperElement(), 'mouseout', onMouseOut);
- }
- },{"codemirror":16}],397:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = jsonParse;
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- /**
- * This JSON parser simply walks the input, generating an AST. Use this in lieu
- * of JSON.parse if you need character offset parse errors and an AST parse tree
- * with location information.
- *
- * If an error is encountered, a SyntaxError will be thrown, with properties:
- *
- * - message: string
- * - start: int - the start inclusive offset of the syntax error
- * - end: int - the end exclusive offset of the syntax error
- *
- */
- function jsonParse(str) {
- string = str;
- strLen = str.length;
- start = end = lastEnd = -1;
- ch();
- lex();
- var ast = parseObj();
- expect('EOF');
- return ast;
- }
- var string = void 0;
- var strLen = void 0;
- var start = void 0;
- var end = void 0;
- var lastEnd = void 0;
- var code = void 0;
- var kind = void 0;
- function parseObj() {
- var nodeStart = start;
- var members = [];
- expect('{');
- if (!skip('}')) {
- do {
- members.push(parseMember());
- } while (skip(','));
- expect('}');
- }
- return {
- kind: 'Object',
- start: nodeStart,
- end: lastEnd,
- members: members
- };
- }
- function parseMember() {
- var nodeStart = start;
- var key = kind === 'String' ? curToken() : null;
- expect('String');
- expect(':');
- var value = parseVal();
- return {
- kind: 'Member',
- start: nodeStart,
- end: lastEnd,
- key: key,
- value: value
- };
- }
- function parseArr() {
- var nodeStart = start;
- var values = [];
- expect('[');
- if (!skip(']')) {
- do {
- values.push(parseVal());
- } while (skip(','));
- expect(']');
- }
- return {
- kind: 'Array',
- start: nodeStart,
- end: lastEnd,
- values: values
- };
- }
- function parseVal() {
- switch (kind) {
- case '[':
- return parseArr();
- case '{':
- return parseObj();
- case 'String':
- case 'Number':
- case 'Boolean':
- case 'Null':
- var token = curToken();
- lex();
- return token;
- }
- return expect('Value');
- }
- function curToken() {
- return { kind: kind, start: start, end: end, value: JSON.parse(string.slice(start, end)) };
- }
- function expect(str) {
- if (kind === str) {
- lex();
- return;
- }
- var found = void 0;
- if (kind === 'EOF') {
- found = '[end of file]';
- } else if (end - start > 1) {
- found = '`' + string.slice(start, end) + '`';
- } else {
- var match = string.slice(start).match(/^.+?\b/);
- found = '`' + (match ? match[0] : string[start]) + '`';
- }
- throw syntaxError('Expected ' + str + ' but found ' + found + '.');
- }
- function syntaxError(message) {
- return { message: message, start: start, end: end };
- }
- function skip(k) {
- if (kind === k) {
- lex();
- return true;
- }
- }
- function ch() {
- if (end < strLen) {
- end++;
- code = end === strLen ? 0 : string.charCodeAt(end);
- }
- }
- function lex() {
- lastEnd = end;
- while (code === 9 || code === 10 || code === 13 || code === 32) {
- ch();
- }
- if (code === 0) {
- kind = 'EOF';
- return;
- }
- start = end;
- switch (code) {
- // "
- case 34:
- kind = 'String';
- return readString();
- // -, 0-9
- case 45:
- case 48:
- case 49:
- case 50:
- case 51:
- case 52:
- case 53:
- case 54:
- case 55:
- case 56:
- case 57:
- kind = 'Number';
- return readNumber();
- // f
- case 102:
- if (string.slice(start, start + 5) !== 'false') {
- break;
- }
- end += 4;
- ch();
- kind = 'Boolean';
- return;
- // n
- case 110:
- if (string.slice(start, start + 4) !== 'null') {
- break;
- }
- end += 3;
- ch();
- kind = 'Null';
- return;
- // t
- case 116:
- if (string.slice(start, start + 4) !== 'true') {
- break;
- }
- end += 3;
- ch();
- kind = 'Boolean';
- return;
- }
- kind = string[start];
- ch();
- }
- function readString() {
- ch();
- while (code !== 34 && code > 31) {
- if (code === 92) {
- // \
- ch();
- switch (code) {
- case 34: // "
- case 47: // /
- case 92: // \
- case 98: // b
- case 102: // f
- case 110: // n
- case 114: // r
- case 116:
- // t
- ch();
- break;
- case 117:
- // u
- ch();
- readHex();
- readHex();
- readHex();
- readHex();
- break;
- default:
- throw syntaxError('Bad character escape sequence.');
- }
- } else if (end === strLen) {
- throw syntaxError('Unterminated string.');
- } else {
- ch();
- }
- }
- if (code === 34) {
- ch();
- return;
- }
- throw syntaxError('Unterminated string.');
- }
- function readHex() {
- if (code >= 48 && code <= 57 || // 0-9
- code >= 65 && code <= 70 || // A-F
- code >= 97 && code <= 102 // a-f
- ) {
- return ch();
- }
- throw syntaxError('Expected hexadecimal digit.');
- }
- function readNumber() {
- if (code === 45) {
- // -
- ch();
- }
- if (code === 48) {
- // 0
- ch();
- } else {
- readDigits();
- }
- if (code === 46) {
- // .
- ch();
- readDigits();
- }
- if (code === 69 || code === 101) {
- // E e
- ch();
- if (code === 43 || code === 45) {
- // + -
- ch();
- }
- readDigits();
- }
- }
- function readDigits() {
- if (code < 48 || code > 57) {
- // 0 - 9
- throw syntaxError('Expected decimal digit.');
- }
- do {
- ch();
- } while (code >= 48 && code <= 57); // 0 - 9
- }
- },{}],398:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- _codemirror2.default.defineOption('jump', false, function (cm, options, old) {
- if (old && old !== _codemirror2.default.Init) {
- var oldOnMouseOver = cm.state.jump.onMouseOver;
- _codemirror2.default.off(cm.getWrapperElement(), 'mouseover', oldOnMouseOver);
- var oldOnMouseOut = cm.state.jump.onMouseOut;
- _codemirror2.default.off(cm.getWrapperElement(), 'mouseout', oldOnMouseOut);
- _codemirror2.default.off(document, 'keydown', cm.state.jump.onKeyDown);
- delete cm.state.jump;
- }
- if (options) {
- var state = cm.state.jump = {
- options: options,
- onMouseOver: onMouseOver.bind(null, cm),
- onMouseOut: onMouseOut.bind(null, cm),
- onKeyDown: onKeyDown.bind(null, cm)
- };
- _codemirror2.default.on(cm.getWrapperElement(), 'mouseover', state.onMouseOver);
- _codemirror2.default.on(cm.getWrapperElement(), 'mouseout', state.onMouseOut);
- _codemirror2.default.on(document, 'keydown', state.onKeyDown);
- }
- }); /**
- * Copyright (c) 2017, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- function onMouseOver(cm, event) {
- var target = event.target || event.srcElement;
- if (target.nodeName !== 'SPAN') {
- return;
- }
- var box = target.getBoundingClientRect();
- var cursor = {
- left: (box.left + box.right) / 2,
- top: (box.top + box.bottom) / 2
- };
- cm.state.jump.cursor = cursor;
- if (cm.state.jump.isHoldingModifier) {
- enableJumpMode(cm);
- }
- }
- function onMouseOut(cm) {
- if (!cm.state.jump.isHoldingModifier && cm.state.jump.cursor) {
- cm.state.jump.cursor = null;
- return;
- }
- if (cm.state.jump.isHoldingModifier && cm.state.jump.marker) {
- disableJumpMode(cm);
- }
- }
- function onKeyDown(cm, event) {
- if (cm.state.jump.isHoldingModifier || !isJumpModifier(event.key)) {
- return;
- }
- cm.state.jump.isHoldingModifier = true;
- if (cm.state.jump.cursor) {
- enableJumpMode(cm);
- }
- var onKeyUp = function onKeyUp(upEvent) {
- if (upEvent.code !== event.code) {
- return;
- }
- cm.state.jump.isHoldingModifier = false;
- if (cm.state.jump.marker) {
- disableJumpMode(cm);
- }
- _codemirror2.default.off(document, 'keyup', onKeyUp);
- _codemirror2.default.off(document, 'click', onClick);
- cm.off('mousedown', onMouseDown);
- };
- var onClick = function onClick(clickEvent) {
- var destination = cm.state.jump.destination;
- if (destination) {
- cm.state.jump.options.onClick(destination, clickEvent);
- }
- };
- var onMouseDown = function onMouseDown(_, downEvent) {
- if (cm.state.jump.destination) {
- downEvent.codemirrorIgnore = true;
- }
- };
- _codemirror2.default.on(document, 'keyup', onKeyUp);
- _codemirror2.default.on(document, 'click', onClick);
- cm.on('mousedown', onMouseDown);
- }
- var isMac = navigator && navigator.appVersion.indexOf('Mac') !== -1;
- function isJumpModifier(key) {
- return key === (isMac ? 'Meta' : 'Control');
- }
- function enableJumpMode(cm) {
- if (cm.state.jump.marker) {
- return;
- }
- var cursor = cm.state.jump.cursor;
- var pos = cm.coordsChar(cursor);
- var token = cm.getTokenAt(pos, true);
- var options = cm.state.jump.options;
- var getDestination = options.getDestination || cm.getHelper(pos, 'jump');
- if (getDestination) {
- var destination = getDestination(token, options, cm);
- if (destination) {
- var marker = cm.markText({ line: pos.line, ch: token.start }, { line: pos.line, ch: token.end }, { className: 'CodeMirror-jump-token' });
- cm.state.jump.marker = marker;
- cm.state.jump.destination = destination;
- }
- }
- }
- function disableJumpMode(cm) {
- var marker = cm.state.jump.marker;
- cm.state.jump.marker = null;
- cm.state.jump.destination = null;
- marker.clear();
- }
- },{"codemirror":16}],399:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- var _graphql = require('graphql');
- var _forEachState = require('../utils/forEachState');
- var _forEachState2 = _interopRequireDefault(_forEachState);
- var _hintList = require('../utils/hintList');
- var _hintList2 = _interopRequireDefault(_hintList);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Registers a "hint" helper for CodeMirror.
- *
- * Using CodeMirror's "hint" addon: https://codemirror.net/demo/complete.html
- * Given an editor, this helper will take the token at the cursor and return a
- * list of suggested tokens.
- *
- * Options:
- *
- * - variableToType: { [variable: string]: GraphQLInputType }
- *
- * Additional Events:
- *
- * - hasCompletion (codemirror, data, token) - signaled when the hinter has a
- * new list of completion suggestions.
- *
- */
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- _codemirror2.default.registerHelper('hint', 'graphql-variables', function (editor, options) {
- var cur = editor.getCursor();
- var token = editor.getTokenAt(cur);
- var results = getVariablesHint(cur, token, options);
- if (results && results.list && results.list.length > 0) {
- results.from = _codemirror2.default.Pos(results.from.line, results.from.column);
- results.to = _codemirror2.default.Pos(results.to.line, results.to.column);
- _codemirror2.default.signal(editor, 'hasCompletion', editor, results, token);
- }
- return results;
- });
- function getVariablesHint(cur, token, options) {
- // If currently parsing an invalid state, attempt to hint to the prior state.
- var state = token.state.kind === 'Invalid' ? token.state.prevState : token.state;
- var kind = state.kind;
- var step = state.step;
- // Variables can only be an object literal.
- if (kind === 'Document' && step === 0) {
- return (0, _hintList2.default)(cur, token, [{ text: '{' }]);
- }
- var variableToType = options.variableToType;
- if (!variableToType) {
- return;
- }
- var typeInfo = getTypeInfo(variableToType, token.state);
- // Top level should typeahead possible variables.
- if (kind === 'Document' || kind === 'Variable' && step === 0) {
- var variableNames = Object.keys(variableToType);
- return (0, _hintList2.default)(cur, token, variableNames.map(function (name) {
- return {
- text: '"' + name + '": ',
- type: variableToType[name]
- };
- }));
- }
- // Input Object fields
- if (kind === 'ObjectValue' || kind === 'ObjectField' && step === 0) {
- if (typeInfo.fields) {
- var inputFields = Object.keys(typeInfo.fields).map(function (fieldName) {
- return typeInfo.fields[fieldName];
- });
- return (0, _hintList2.default)(cur, token, inputFields.map(function (field) {
- return {
- text: '"' + field.name + '": ',
- type: field.type,
- description: field.description
- };
- }));
- }
- }
- // Input values.
- if (kind === 'StringValue' || kind === 'NumberValue' || kind === 'BooleanValue' || kind === 'NullValue' || kind === 'ListValue' && step === 1 || kind === 'ObjectField' && step === 2 || kind === 'Variable' && step === 2) {
- var namedInputType = (0, _graphql.getNamedType)(typeInfo.type);
- if (namedInputType instanceof _graphql.GraphQLInputObjectType) {
- return (0, _hintList2.default)(cur, token, [{ text: '{' }]);
- } else if (namedInputType instanceof _graphql.GraphQLEnumType) {
- var valueMap = namedInputType.getValues();
- var values = Object.keys(valueMap).map(function (name) {
- return valueMap[name];
- });
- return (0, _hintList2.default)(cur, token, values.map(function (value) {
- return {
- text: '"' + value.name + '"',
- type: namedInputType,
- description: value.description
- };
- }));
- } else if (namedInputType === _graphql.GraphQLBoolean) {
- return (0, _hintList2.default)(cur, token, [{ text: 'true', type: _graphql.GraphQLBoolean, description: 'Not false.' }, { text: 'false', type: _graphql.GraphQLBoolean, description: 'Not true.' }]);
- }
- }
- }
- // Utility for collecting rich type information given any token's state
- // from the graphql-variables-mode parser.
- function getTypeInfo(variableToType, tokenState) {
- var info = {
- type: null,
- fields: null
- };
- (0, _forEachState2.default)(tokenState, function (state) {
- if (state.kind === 'Variable') {
- info.type = variableToType[state.name];
- } else if (state.kind === 'ListValue') {
- var nullableType = (0, _graphql.getNullableType)(info.type);
- info.type = nullableType instanceof _graphql.GraphQLList ? nullableType.ofType : null;
- } else if (state.kind === 'ObjectValue') {
- var objectType = (0, _graphql.getNamedType)(info.type);
- info.fields = objectType instanceof _graphql.GraphQLInputObjectType ? objectType.getFields() : null;
- } else if (state.kind === 'ObjectField') {
- var objectField = state.name && info.fields ? info.fields[state.name] : null;
- info.type = objectField && objectField.type;
- }
- });
- return info;
- }
- },{"../utils/forEachState":393,"../utils/hintList":395,"codemirror":16,"graphql":285}],400:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- var _graphql = require('graphql');
- var _jsonParse = require('../utils/jsonParse');
- var _jsonParse2 = _interopRequireDefault(_jsonParse);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * Registers a "lint" helper for CodeMirror.
- *
- * Using CodeMirror's "lint" addon: https://codemirror.net/demo/lint.html
- * Given the text within an editor, this helper will take that text and return
- * a list of linter issues ensuring that correct variables were provided.
- *
- * Options:
- *
- * - variableToType: { [variable: string]: GraphQLInputType }
- *
- */
- _codemirror2.default.registerHelper('lint', 'graphql-variables', function (text, options, editor) {
- // If there's no text, do nothing.
- if (!text) {
- return [];
- }
- // First, linter needs to determine if there are any parsing errors.
- var ast = void 0;
- try {
- ast = (0, _jsonParse2.default)(text);
- } catch (syntaxError) {
- if (syntaxError.stack) {
- throw syntaxError;
- }
- return [lintError(editor, syntaxError, syntaxError.message)];
- }
- // If there are not yet known variables, do nothing.
- var variableToType = options.variableToType;
- if (!variableToType) {
- return [];
- }
- // Then highlight any issues with the provided variables.
- return validateVariables(editor, variableToType, ast);
- });
- // Given a variableToType object, a source text, and a JSON AST, produces a
- // list of CodeMirror annotations for any variable validation errors.
- /* eslint-disable max-len */
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- function validateVariables(editor, variableToType, variablesAST) {
- var errors = [];
- variablesAST.members.forEach(function (member) {
- var variableName = member.key.value;
- var type = variableToType[variableName];
- if (!type) {
- errors.push(lintError(editor, member.key, 'Variable "$' + variableName + '" does not appear in any GraphQL query.'));
- } else {
- validateValue(type, member.value).forEach(function (_ref) {
- var node = _ref[0],
- message = _ref[1];
- errors.push(lintError(editor, node, message));
- });
- }
- });
- return errors;
- }
- // Returns a list of validation errors in the form Array<[Node, String]>.
- function validateValue(type, valueAST) {
- // Validate non-nullable values.
- if (type instanceof _graphql.GraphQLNonNull) {
- if (valueAST.kind === 'Null') {
- return [[valueAST, 'Type "' + type + '" is non-nullable and cannot be null.']];
- }
- return validateValue(type.ofType, valueAST);
- }
- if (valueAST.kind === 'Null') {
- return [];
- }
- // Validate lists of values, accepting a non-list as a list of one.
- if (type instanceof _graphql.GraphQLList) {
- var itemType = type.ofType;
- if (valueAST.kind === 'Array') {
- return mapCat(valueAST.values, function (item) {
- return validateValue(itemType, item);
- });
- }
- return validateValue(itemType, valueAST);
- }
- // Validate input objects.
- if (type instanceof _graphql.GraphQLInputObjectType) {
- if (valueAST.kind !== 'Object') {
- return [[valueAST, 'Type "' + type + '" must be an Object.']];
- }
- // Validate each field in the input object.
- var providedFields = Object.create(null);
- var fieldErrors = mapCat(valueAST.members, function (member) {
- var fieldName = member.key.value;
- providedFields[fieldName] = true;
- var inputField = type.getFields()[fieldName];
- if (!inputField) {
- return [[member.key, 'Type "' + type + '" does not have a field "' + fieldName + '".']];
- }
- var fieldType = inputField ? inputField.type : undefined;
- return validateValue(fieldType, member.value);
- });
- // Look for missing non-nullable fields.
- Object.keys(type.getFields()).forEach(function (fieldName) {
- if (!providedFields[fieldName]) {
- var fieldType = type.getFields()[fieldName].type;
- if (fieldType instanceof _graphql.GraphQLNonNull) {
- fieldErrors.push([valueAST, 'Object of type "' + type + '" is missing required field "' + fieldName + '".']);
- }
- }
- });
- return fieldErrors;
- }
- // Validate common scalars.
- if (type.name === 'Boolean' && valueAST.kind !== 'Boolean' || type.name === 'String' && valueAST.kind !== 'String' || type.name === 'ID' && valueAST.kind !== 'Number' && valueAST.kind !== 'String' || type.name === 'Float' && valueAST.kind !== 'Number' || type.name === 'Int' && (valueAST.kind !== 'Number' || (valueAST.value | 0) !== valueAST.value)) {
- return [[valueAST, 'Expected value of type "' + type + '".']];
- }
- // Validate enums and custom scalars.
- if (type instanceof _graphql.GraphQLEnumType || type instanceof _graphql.GraphQLScalarType) {
- if (valueAST.kind !== 'String' && valueAST.kind !== 'Number' && valueAST.kind !== 'Boolean' && valueAST.kind !== 'Null' || isNullish(type.parseValue(valueAST.value))) {
- return [[valueAST, 'Expected value of type "' + type + '".']];
- }
- }
- return [];
- }
- // Give a parent text, an AST node with location, and a message, produces a
- // CodeMirror annotation object.
- function lintError(editor, node, message) {
- return {
- message: message,
- severity: 'error',
- type: 'validation',
- from: editor.posFromIndex(node.start),
- to: editor.posFromIndex(node.end)
- };
- }
- function isNullish(value) {
- return value === null || value === undefined || value !== value;
- }
- function mapCat(array, mapper) {
- return Array.prototype.concat.apply([], array.map(mapper));
- }
- },{"../utils/jsonParse":397,"codemirror":16,"graphql":285}],401:[function(require,module,exports){
- 'use strict';
- var _codemirror = require('codemirror');
- var _codemirror2 = _interopRequireDefault(_codemirror);
- var _graphqlLanguageServiceParser = require('graphql-language-service-parser');
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- /**
- * This mode defines JSON, but provides a data-laden parser state to enable
- * better code intelligence.
- */
- /**
- * Copyright (c) 2015, Facebook, Inc.
- * All rights reserved.
- *
- * This source code is licensed under the BSD-style license found in the
- * LICENSE file in the root directory of this source tree. An additional grant
- * of patent rights can be found in the PATENTS file in the same directory.
- */
- _codemirror2.default.defineMode('graphql-variables', function (config) {
- var parser = (0, _graphqlLanguageServiceParser.onlineParser)({
- eatWhitespace: function eatWhitespace(stream) {
- return stream.eatSpace();
- },
- lexRules: LexRules,
- parseRules: ParseRules,
- editorConfig: { tabSize: config.tabSize }
- });
- return {
- config: config,
- startState: parser.startState,
- token: parser.token,
- indent: indent,
- electricInput: /^\s*[}\]]/,
- fold: 'brace',
- closeBrackets: {
- pairs: '[]{}""',
- explode: '[]{}'
- }
- };
- });
- function indent(state, textAfter) {
- var levels = state.levels;
- // If there is no stack of levels, use the current level.
- // Otherwise, use the top level, pre-emptively dedenting for close braces.
- var level = !levels || levels.length === 0 ? state.indentLevel : levels[levels.length - 1] - (this.electricInput.test(textAfter) ? 1 : 0);
- return level * this.config.indentUnit;
- }
- /**
- * The lexer rules. These are exactly as described by the spec.
- */
- var LexRules = {
- // All Punctuation used in JSON.
- Punctuation: /^\[|]|\{|\}|:|,/,
- // JSON Number.
- Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,
- // JSON String.
- String: /^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/,
- // JSON literal keywords.
- Keyword: /^true|false|null/
- };
- /**
- * The parser rules for JSON.
- */
- var ParseRules = {
- Document: [(0, _graphqlLanguageServiceParser.p)('{'), (0, _graphqlLanguageServiceParser.list)('Variable', (0, _graphqlLanguageServiceParser.opt)((0, _graphqlLanguageServiceParser.p)(','))), (0, _graphqlLanguageServiceParser.p)('}')],
- Variable: [namedKey('variable'), (0, _graphqlLanguageServiceParser.p)(':'), 'Value'],
- Value: function Value(token) {
- switch (token.kind) {
- case 'Number':
- return 'NumberValue';
- case 'String':
- return 'StringValue';
- case 'Punctuation':
- switch (token.value) {
- case '[':
- return 'ListValue';
- case '{':
- return 'ObjectValue';
- }
- return null;
- case 'Keyword':
- switch (token.value) {
- case 'true':
- case 'false':
- return 'BooleanValue';
- case 'null':
- return 'NullValue';
- }
- return null;
- }
- },
- NumberValue: [(0, _graphqlLanguageServiceParser.t)('Number', 'number')],
- StringValue: [(0, _graphqlLanguageServiceParser.t)('String', 'string')],
- BooleanValue: [(0, _graphqlLanguageServiceParser.t)('Keyword', 'builtin')],
- NullValue: [(0, _graphqlLanguageServiceParser.t)('Keyword', 'keyword')],
- ListValue: [(0, _graphqlLanguageServiceParser.p)('['), (0, _graphqlLanguageServiceParser.list)('Value', (0, _graphqlLanguageServiceParser.opt)((0, _graphqlLanguageServiceParser.p)(','))), (0, _graphqlLanguageServiceParser.p)(']')],
- ObjectValue: [(0, _graphqlLanguageServiceParser.p)('{'), (0, _graphqlLanguageServiceParser.list)('ObjectField', (0, _graphqlLanguageServiceParser.opt)((0, _graphqlLanguageServiceParser.p)(','))), (0, _graphqlLanguageServiceParser.p)('}')],
- ObjectField: [namedKey('attribute'), (0, _graphqlLanguageServiceParser.p)(':'), 'Value']
- };
- // A namedKey Token which will decorate the state with a `name`
- function namedKey(style) {
- return {
- style: style,
- match: function match(token) {
- return token.kind === 'String';
- },
- update: function update(state, token) {
- state.name = token.value.slice(1, -1); // Remove quotes.
- }
- };
- }
- },{"codemirror":16,"graphql-language-service-parser":269}]},{},[239])(239)
- });
|