From d38f28bd0775f9027a21d501b43d823135e9f4e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Blaise=20de=20Carn=C3=A9?= Date: Tue, 24 Apr 2018 15:25:06 +0200 Subject: [PATCH] Initial commit --- .gitignore | 3 + CHANGELOG.md | 16 + LICENSE.md | 21 + README.md | 106 + dataset/kb/RWStore.properties | 53 + dataset/kb/data/.gitkeep | 0 docker-compose.yml | 23 + docker/Dockerfile | 22 + docker/app/composer.json | 13 + .../app/www/graphiql/es6-promise.auto.min.js | 1 + docker/app/www/graphiql/fetch.min.js | 1 + docker/app/www/graphiql/graphiql.css | 1740 + docker/app/www/graphiql/graphiql.js | 39655 ++++++++++++++++ docker/app/www/graphiql/index.html | 149 + docker/app/www/graphiql/react-dom.min.js | 15 + docker/app/www/graphiql/react.min.js | 12 + docker/app/www/index.php | 26 + docker/app/www/voyager/index.html | 65 + 18 files changed, 41921 insertions(+) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 dataset/kb/RWStore.properties create mode 100644 dataset/kb/data/.gitkeep create mode 100644 docker-compose.yml create mode 100644 docker/Dockerfile create mode 100644 docker/app/composer.json create mode 100644 docker/app/www/graphiql/es6-promise.auto.min.js create mode 100644 docker/app/www/graphiql/fetch.min.js create mode 100644 docker/app/www/graphiql/graphiql.css create mode 100644 docker/app/www/graphiql/graphiql.js create mode 100644 docker/app/www/graphiql/index.html create mode 100644 docker/app/www/graphiql/react-dom.min.js create mode 100644 docker/app/www/graphiql/react.min.js create mode 100644 docker/app/www/index.php create mode 100644 docker/app/www/voyager/index.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..66ab02f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea +dataset/kb/data/* +!dataset/kb/data/.gitkeep \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..02b58cb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog +Tous les changements notables apportés à ce projet seront documentés dans ce fichier. + +Le format est basé sur [Keep a Changelog](http://keepachangelog.com/fr/1.0.0/) +et ce projet adhère à [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [1.0.0] - 2018-04-24 + +### Ajouts +- Code source initial +- Documentation + + + + + diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..eaf8c1d --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 DATAtourisme + +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. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..e322a76 --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ + +

+ + DATAtourisme + +

+ +

+ La plateforme OPEN DATA de l'information touristique +

+ +

https://www.datatourisme.gouv.fr

+ + +# Environnement full-stack Docker + +Ce projet contient un environnement [docker-compose](https://docs.docker.com/compose/) contenant les +services suivants : + +* La base de données [Blazegraph](http://www.blazegraph.com) +* L'[API DATAtourisme](https://framagit.org/datatourisme/api) associée à : + * Un point d'accès HTTP GraphQL + * [GraphiQL](https://github.com/graphql/graphiql), une interface visuelle de conception de requête + * [Voyager](https://github.com/APIs-guru/graphql-voyager), un visualisateur de schéma sous forme de graphe. + +Ce stack vous permet de mettre rapidement en place un environnement de restitution des données touristiques +téléchargées à partir de la [plateforme diffuseur](https://diffuseur.datatourisme.gouv.fr). + +## Utilisation + +### Pré-requis + +Pour utiliser l'environnement, doivent être installés et configurés : + +* [Docker-ce](https://docs.docker.com/engine/installation/) +* [docker-compose](https://docs.docker.com/compose/install/) + +Par défaut, vous devrez rendre disponible les ports 8080 et 9999. + +### Récupération d'un fichier de données + +Pour vous servir de l'environnement, vous devez d'abord récupérer des données touristiques : + +1. Connectez-vous à la [plateforme diffuseur](https://diffuseur.datatourisme.gouv.fr). Il sera nécessaire de +créer un compte s'il s'agit de votre première connexion. +2. Créez et configurez un flux de données à l'aide de l'éditeur visuel de requête. +3. Configurez le flux pour utiliser un format **compatible avec l'API** : + * RDF-XML + * Turtle + * NT +4. Téléchargez le fichier du flux une fois celui-ci disponible. + +Le fichier ainsi obtenu doit être copié dans le répertoire `dataset/kb/data` pour être chargé dans la base de +données lors de la création du conteneur Docker. + +À titre d'information, voici comment se décompose le dossier `dataset` : + +| Répertoire | description | +| -------------------------------- |-------------------------------------------------| +| dataset/ | Répertoire décrivant la configuration et les données à charger dans le namespace | +|    /kb/ | Namespace pour les données (kb étant le namespace par défaut) | +|    /data/ | Répertoire où copier les données sémantiques (ttl, nt, n3, xml, gz...) | +|    /RWSTore.properties | Configuration de la base de données pour ce namespace namespace | + +### Lancement de l'environnement + +Vous pouvez maintenant lancer l'environnement : + +``` +$ docker-compose up +``` + +Ces commandes lanceront deux serveurs : + - un serveur [Blazegraph](https://www.blazegraph.com/) sur le port 9999 chargé de vos données. + - un serveur incluant l'[API DATAtourisme](https://framagit.org/datatourisme/api) sur le port 8080. + +Vous pouvez accèder aux interfaces suivantes : + +* Interface d'administration Blazegraph : http://localhost:9999 +* Point d'accès HTTP GraphQL : http://localhost:8080 +* GraphiQL : http://localhost:8080/graphiql +* Voyager : http://localhost:8080/voyager + +### Utilisation de l'API + +Pour utiliser l'API, reportez vous à la [documentation officielle](https://datatourisme.frama.io/api/#/). + +### Mise à jour des données + +Lorsque vous souhaitez mettre à jour les données de votre environnement, vous devez procéder ainsi : + +1. Stoppez l'environnement s'il est actif : `docker-compose stop` +1. Téléchargez le nouveau fichier de donnée et remplacez le dans **dataset/kb/data** +2. Supprimez le conteneur Blazegraph : `docker-compose rm blazegraph` +3. Relancez l'environnement : `docker-compose up` + +## Liens + +* [API DATAtourisme](https://framagit.org/datatourisme/api) +* [Documentation de l'API](https://datatourisme.frama.io/api) +* [Plateforme diffuseur](https://diffuseur.datatourisme.gouv.fr) +* Centre de support + +## License + +MIT License \ No newline at end of file diff --git a/dataset/kb/RWStore.properties b/dataset/kb/RWStore.properties new file mode 100644 index 0000000..d37a50f --- /dev/null +++ b/dataset/kb/RWStore.properties @@ -0,0 +1,53 @@ +# +# Note: These options are applied when the journal and the triple store are +# first created. + +## +## Journal options. +## + +# The backing file. This contains all your data. You want to put this someplace +# safe. The default locator will wind up in the directory from which you start +# your servlet container. +com.bigdata.journal.AbstractJournal.file=/var/lib/blazegraph/blazegraph.jnl + +# The persistence engine. Use 'Disk' for the WORM or 'DiskRW' for the RWStore. +com.bigdata.journal.AbstractJournal.bufferMode=DiskRW + +# Setup for the RWStore recycler rather than session protection. +com.bigdata.service.AbstractTransactionService.minReleaseAge=1 + +# Enable group commit. See http://wiki.blazegraph.com/wiki/index.php/GroupCommit +# Note: Group commit is a beta feature in BlazeGraph release 1.5.1. +#com.bigdata.journal.Journal.groupCommit=true + +com.bigdata.btree.writeRetentionQueue.capacity=4000 +com.bigdata.btree.BTree.branchingFactor=128 + +# 200M initial extent +com.bigdata.journal.AbstractJournal.initialExtent=209715200 +com.bigdata.journal.AbstractJournal.maximumExtent=209715200 + +## +## Setup for QUADS mode without the full text index. +## +com.bigdata.rdf.sail.truthMaintenance=false +com.bigdata.rdf.store.AbstractTripleStore.quads=false +com.bigdata.rdf.store.AbstractTripleStore.statementIdentifiers=false +com.bigdata.rdf.store.AbstractTripleStore.textIndex=true +com.bigdata.rdf.store.AbstractTripleStore.axiomsClass=com.bigdata.rdf.axioms.NoAxioms + +# Bump up the branching factor for the lexicon indices on the default kb. +com.bigdata.namespace.kb.lex.com.bigdata.btree.BTree.branchingFactor=400 + +# Bump up the branching factor for the statement indices on the default kb. +com.bigdata.namespace.kb.spo.com.bigdata.btree.BTree.branchingFactor=1024 + +# Uncomment to enable collection of OS level performance counters. When +# collected they will be self-reported through the /counters servlet and +# the workbench "Performance" tab. +# +# com.bigdata.journal.Journal.collectPlatformStatistics=true + +# geospatial +com.bigdata.rdf.store.AbstractTripleStore.geoSpatial=true \ No newline at end of file diff --git a/dataset/kb/data/.gitkeep b/dataset/kb/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e5a6d1f --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,23 @@ +version: '3.1' + +services: + + blazegraph: + image: conjecto/blazegraph + ports: + - 9999:9999 + environment: + JAVA_XMS: 512m + JAVA_XMX: 1g + volumes: + - ./dataset:/docker-entrypoint-initdb.d + ports: + - "9999:9999" + + datatourisme: + build: docker + ports: + - "8080:80" + restart: always + depends_on: + - blazegraph diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..91dbbcf --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,22 @@ +FROM php +MAINTAINER Conjecto + +RUN apt-get update && apt-get install -y \ + --no-install-recommends git zip zlib1g-dev + +RUN docker-php-ext-install -j$(nproc) zip + +COPY app/ /var/app/ +WORKDIR /var/app/ + +# install composer +RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" +RUN php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" +RUN php composer-setup.php +RUN php -r "unlink('composer-setup.php');" + +# install vendors +RUN php composer.phar install + +# run server +CMD ["php", "-S", "0.0.0.0:80", "-t", "/var/app/www"] \ No newline at end of file diff --git a/docker/app/composer.json b/docker/app/composer.json new file mode 100644 index 0000000..16cc628 --- /dev/null +++ b/docker/app/composer.json @@ -0,0 +1,13 @@ +{ + "type": "project", + "authors": [ + { + "name": "Conjecto", + "email": "contact@conjecto.com" + } + ], + "require": { + "php": "^7.0", + "datatourisme/api": "^1.0" + } +} diff --git a/docker/app/www/graphiql/es6-promise.auto.min.js b/docker/app/www/graphiql/es6-promise.auto.min.js new file mode 100644 index 0000000..78e9c37 --- /dev/null +++ b/docker/app/www/graphiql/es6-promise.auto.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function e(t){return"function"==typeof t}function n(t){I=t}function r(t){J=t}function o(){return function(){return process.nextTick(a)}}function i(){return"undefined"!=typeof H?function(){H(a)}:c()}function s(){var t=0,e=new V(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;t-1?e:t}function f(t,e){if(e=e||{},this.url=t,this.credentials=e.credentials||"omit",this.headers=new r(e.headers),this.method=u(e.method||"GET"),this.mode=e.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&e.body)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(e.body)}function h(t){var e=new FormData;return t.trim().split("&").forEach(function(t){if(t){var r=t.split("="),o=r.shift().replace(/\+/g," "),n=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(n))}}),e}function d(t){var e=new r,o=t.getAllResponseHeaders().trim().split("\n");return o.forEach(function(t){var r=t.trim().split(":"),o=r.shift().trim(),n=r.join(":").trim();e.append(o,n)}),e}function l(t,e){e||(e={}),this._initBody(t),this.type="default",this.url=null,this.status=e.status,this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText,this.headers=e.headers instanceof r?e.headers:new r(e.headers),this.url=e.url||""}if(!self.fetch){r.prototype.append=function(r,o){r=t(r),o=e(o);var n=this.map[r];n||(n=[],this.map[r]=n),n.push(o)},r.prototype["delete"]=function(e){delete this.map[t(e)]},r.prototype.get=function(e){var r=this.map[t(e)];return r?r[0]:null},r.prototype.getAll=function(e){return this.map[t(e)]||[]},r.prototype.has=function(e){return this.map.hasOwnProperty(t(e))},r.prototype.set=function(r,o){this.map[t(r)]=[e(o)]},r.prototype.forEach=function(t,e){Object.getOwnPropertyNames(this.map).forEach(function(r){this.map[r].forEach(function(o){t.call(e,o,r,this)},this)},this)};var p={blob:"FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in self},c=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];a.call(f.prototype),a.call(l.prototype),self.Headers=r,self.Request=f,self.Response=l,self.fetch=function(t,e){var r;return r=f.prototype.isPrototypeOf(t)&&!e?t:new f(t,e),new Promise(function(t,e){function o(){return"responseURL"in n?n.responseURL:/^X-Request-URL:/m.test(n.getAllResponseHeaders())?n.getResponseHeader("X-Request-URL"):void 0}var n=new XMLHttpRequest;n.onload=function(){var r=1223===n.status?204:n.status;if(100>r||r>599)return void e(new TypeError("Network request failed"));var s={status:r,statusText:n.statusText,headers:d(n),url:o()},i="response"in n?n.response:n.responseText;t(new l(i,s))},n.onerror=function(){e(new TypeError("Network request failed"))},n.open(r.method,r.url,!0),"include"===r.credentials&&(n.withCredentials=!0),"responseType"in n&&p.blob&&(n.responseType="blob"),r.headers.forEach(function(t,e){n.setRequestHeader(e,t)}),n.send("undefined"==typeof r._bodyInit?null:r._bodyInit)})},self.fetch.polyfill=!0}}(); \ No newline at end of file diff --git a/docker/app/www/graphiql/graphiql.css b/docker/app/www/graphiql/graphiql.css new file mode 100644 index 0000000..4ac29c1 --- /dev/null +++ b/docker/app/www/graphiql/graphiql.css @@ -0,0 +1,1740 @@ +.graphiql-container, +.graphiql-container button, +.graphiql-container input { + color: #141823; + font-family: + system, + -apple-system, + 'San Francisco', + '.SFNSDisplay-Regular', + 'Segoe UI', + Segoe, + 'Segoe WP', + 'Helvetica Neue', + helvetica, + 'Lucida Grande', + arial, + sans-serif; + font-size: 14px; +} + +.graphiql-container { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + height: 100%; + margin: 0; + overflow: hidden; + width: 100%; +} + +.graphiql-container .editorWrap { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: vertical; + -webkit-box-direction: normal; + -ms-flex-direction: column; + flex-direction: column; + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1; + overflow-x: hidden; +} + +.graphiql-container .title { + font-size: 18px; +} + +.graphiql-container .title em { + font-family: georgia; + font-size: 19px; +} + +.graphiql-container .topBarWrap { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + overflow-x: hidden; +} + +.graphiql-container .topBar { + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; + background: -webkit-gradient(linear, left top, left bottom, from(#f7f7f7), to(#e2e2e2)); + background: linear-gradient(#f7f7f7, #e2e2e2); + border-bottom: 1px solid #d0d0d0; + cursor: default; + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1; + height: 34px; + padding: 7px 14px 6px; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.graphiql-container .toolbar { + overflow-x: visible; + display: -webkit-box; + display: -ms-flexbox; + display: flex; +} + +.graphiql-container .docExplorerShow, +.graphiql-container .historyShow { + background: -webkit-gradient(linear, left top, left bottom, from(#f7f7f7), to(#e2e2e2)); + background: linear-gradient(#f7f7f7, #e2e2e2); + border-bottom: 1px solid #d0d0d0; + border-right: none; + border-top: none; + color: #3B5998; + cursor: pointer; + font-size: 14px; + margin: 0; + outline: 0; + padding: 2px 20px 0 18px; +} + +.graphiql-container .docExplorerShow { + border-left: 1px solid rgba(0, 0, 0, 0.2); +} + +.graphiql-container .historyShow { + border-right: 1px solid rgba(0, 0, 0, 0.2); + border-left: 0; +} + +.graphiql-container .docExplorerShow:before { + border-left: 2px solid #3B5998; + border-top: 2px solid #3B5998; + content: ''; + display: inline-block; + height: 9px; + margin: 0 3px -1px 0; + position: relative; + -webkit-transform: rotate(-45deg); + transform: rotate(-45deg); + width: 9px; +} + +.graphiql-container .editorBar { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1; +} + +.graphiql-container .queryWrap { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: vertical; + -webkit-box-direction: normal; + -ms-flex-direction: column; + flex-direction: column; + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1; +} + +.graphiql-container .resultWrap { + border-left: solid 1px #e0e0e0; + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: vertical; + -webkit-box-direction: normal; + -ms-flex-direction: column; + flex-direction: column; + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1; + position: relative; +} + +.graphiql-container .docExplorerWrap, +.graphiql-container .historyPaneWrap { + background: white; + -webkit-box-shadow: 0 0 8px rgba(0, 0, 0, 0.15); + box-shadow: 0 0 8px rgba(0, 0, 0, 0.15); + position: relative; + z-index: 3; +} + +.graphiql-container .historyPaneWrap { + min-width: 230px; + z-index: 5; +} + +.graphiql-container .docExplorerResizer { + cursor: col-resize; + height: 100%; + left: -5px; + position: absolute; + top: 0; + width: 10px; + z-index: 10; +} + +.graphiql-container .docExplorerHide { + cursor: pointer; + font-size: 18px; + margin: -7px -8px -6px 0; + padding: 18px 16px 15px 12px; +} + +.graphiql-container div .query-editor { + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1; + position: relative; +} + +.graphiql-container .variable-editor { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: vertical; + -webkit-box-direction: normal; + -ms-flex-direction: column; + flex-direction: column; + height: 29px; + position: relative; +} + +.graphiql-container .variable-editor-title { + background: #eeeeee; + border-bottom: 1px solid #d6d6d6; + border-top: 1px solid #e0e0e0; + color: #777; + font-variant: small-caps; + font-weight: bold; + letter-spacing: 1px; + line-height: 14px; + padding: 6px 0 8px 43px; + text-transform: lowercase; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.graphiql-container .codemirrorWrap { + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1; + height: 100%; + position: relative; +} + +.graphiql-container .result-window { + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1; + height: 100%; + position: relative; +} + +.graphiql-container .footer { + background: #f6f7f8; + border-left: 1px solid #e0e0e0; + border-top: 1px solid #e0e0e0; + margin-left: 12px; + position: relative; +} + +.graphiql-container .footer:before { + background: #eeeeee; + bottom: 0; + content: " "; + left: -13px; + position: absolute; + top: -1px; + width: 12px; +} + +/* No `.graphiql-container` here so themes can overwrite */ +.result-window .CodeMirror { + background: #f6f7f8; +} + +.graphiql-container .result-window .CodeMirror-gutters { + background-color: #eeeeee; + border-color: #e0e0e0; + cursor: col-resize; +} + +.graphiql-container .result-window .CodeMirror-foldgutter, +.graphiql-container .result-window .CodeMirror-foldgutter-open:after, +.graphiql-container .result-window .CodeMirror-foldgutter-folded:after { + padding-left: 3px; +} + +.graphiql-container .toolbar-button { + background: #fdfdfd; + background: -webkit-gradient(linear, left top, left bottom, from(#f9f9f9), to(#ececec)); + background: linear-gradient(#f9f9f9, #ececec); + border-radius: 3px; + -webkit-box-shadow: + inset 0 0 0 1px rgba(0,0,0,0.20), + 0 1px 0 rgba(255,255,255, 0.7), + inset 0 1px #fff; + box-shadow: + inset 0 0 0 1px rgba(0,0,0,0.20), + 0 1px 0 rgba(255,255,255, 0.7), + inset 0 1px #fff; + color: #555; + cursor: pointer; + display: inline-block; + margin: 0 5px; + padding: 3px 11px 5px; + text-decoration: none; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 150px; +} + +.graphiql-container .toolbar-button:active { + background: -webkit-gradient(linear, left top, left bottom, from(#ececec), to(#d5d5d5)); + background: linear-gradient(#ececec, #d5d5d5); + -webkit-box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.7), + inset 0 0 0 1px rgba(0,0,0,0.10), + inset 0 1px 1px 1px rgba(0, 0, 0, 0.12), + inset 0 0 5px rgba(0, 0, 0, 0.1); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.7), + inset 0 0 0 1px rgba(0,0,0,0.10), + inset 0 1px 1px 1px rgba(0, 0, 0, 0.12), + inset 0 0 5px rgba(0, 0, 0, 0.1); +} + +.graphiql-container .toolbar-button.error { + background: -webkit-gradient(linear, left top, left bottom, from(#fdf3f3), to(#e6d6d7)); + background: linear-gradient(#fdf3f3, #e6d6d7); + color: #b00; +} + +.graphiql-container .toolbar-button-group { + margin: 0 5px; + white-space: nowrap; +} + +.graphiql-container .toolbar-button-group > * { + margin: 0; +} + +.graphiql-container .toolbar-button-group > *:not(:last-child) { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} + +.graphiql-container .toolbar-button-group > *:not(:first-child) { + border-top-left-radius: 0; + border-bottom-left-radius: 0; + margin-left: -1px; +} + +.graphiql-container .execute-button-wrap { + height: 34px; + margin: 0 14px 0 28px; + position: relative; +} + +.graphiql-container .execute-button { + background: -webkit-gradient(linear, left top, left bottom, from(#fdfdfd), to(#d2d3d6)); + background: linear-gradient(#fdfdfd, #d2d3d6); + border-radius: 17px; + border: 1px solid rgba(0,0,0,0.25); + -webkit-box-shadow: 0 1px 0 #fff; + box-shadow: 0 1px 0 #fff; + cursor: pointer; + fill: #444; + height: 34px; + margin: 0; + padding: 0; + width: 34px; +} + +.graphiql-container .execute-button svg { + pointer-events: none; +} + +.graphiql-container .execute-button:active { + background: -webkit-gradient(linear, left top, left bottom, from(#e6e6e6), to(#c3c3c3)); + background: linear-gradient(#e6e6e6, #c3c3c3); + -webkit-box-shadow: + 0 1px 0 #fff, + inset 0 0 2px rgba(0, 0, 0, 0.2), + inset 0 0 6px rgba(0, 0, 0, 0.1); + box-shadow: + 0 1px 0 #fff, + inset 0 0 2px rgba(0, 0, 0, 0.2), + inset 0 0 6px rgba(0, 0, 0, 0.1); +} + +.graphiql-container .execute-button:focus { + outline: 0; +} + +.graphiql-container .toolbar-menu, +.graphiql-container .toolbar-select { + position: relative; +} + +.graphiql-container .execute-options, +.graphiql-container .toolbar-menu-items, +.graphiql-container .toolbar-select-options { + background: #fff; + -webkit-box-shadow: + 0 0 0 1px rgba(0,0,0,0.1), + 0 2px 4px rgba(0,0,0,0.25); + box-shadow: + 0 0 0 1px rgba(0,0,0,0.1), + 0 2px 4px rgba(0,0,0,0.25); + margin: 0; + padding: 6px 0; + position: absolute; + z-index: 100; +} + +.graphiql-container .execute-options { + min-width: 100px; + top: 37px; + left: -1px; +} + +.graphiql-container .toolbar-menu-items { + left: 1px; + margin-top: -1px; + min-width: 110%; + top: 100%; + visibility: hidden; +} + +.graphiql-container .toolbar-menu-items.open { + visibility: visible; +} + +.graphiql-container .toolbar-select-options { + left: 0; + min-width: 100%; + top: -5px; + visibility: hidden; +} + +.graphiql-container .toolbar-select-options.open { + visibility: visible; +} + +.graphiql-container .execute-options > li, +.graphiql-container .toolbar-menu-items > li, +.graphiql-container .toolbar-select-options > li { + cursor: pointer; + display: block; + margin: none; + max-width: 300px; + overflow: hidden; + padding: 2px 20px 4px 11px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.graphiql-container .execute-options > li.selected, +.graphiql-container .toolbar-menu-items > li.hover, +.graphiql-container .toolbar-menu-items > li:active, +.graphiql-container .toolbar-menu-items > li:hover, +.graphiql-container .toolbar-select-options > li.hover, +.graphiql-container .toolbar-select-options > li:active, +.graphiql-container .toolbar-select-options > li:hover, +.graphiql-container .history-contents > p:hover, +.graphiql-container .history-contents > p:active { + background: #e10098; + color: #fff; +} + +.graphiql-container .toolbar-select-options > li > svg { + display: inline; + fill: #666; + margin: 0 -6px 0 6px; + pointer-events: none; + vertical-align: middle; +} + +.graphiql-container .toolbar-select-options > li.hover > svg, +.graphiql-container .toolbar-select-options > li:active > svg, +.graphiql-container .toolbar-select-options > li:hover > svg { + fill: #fff; +} + +.graphiql-container .CodeMirror-scroll { + overflow-scrolling: touch; +} + +.graphiql-container .CodeMirror { + color: #141823; + font-family: + 'Consolas', + 'Inconsolata', + 'Droid Sans Mono', + 'Monaco', + monospace; + font-size: 13px; + height: 100%; + left: 0; + position: absolute; + top: 0; + width: 100%; +} + +.graphiql-container .CodeMirror-lines { + padding: 20px 0; +} + +.CodeMirror-hint-information .content { + box-orient: vertical; + color: #141823; + display: -webkit-box; + display: -ms-flexbox; + display: flex; + font-family: system, -apple-system, 'San Francisco', '.SFNSDisplay-Regular', 'Segoe UI', Segoe, 'Segoe WP', 'Helvetica Neue', helvetica, 'Lucida Grande', arial, sans-serif; + font-size: 13px; + line-clamp: 3; + line-height: 16px; + max-height: 48px; + overflow: hidden; + text-overflow: -o-ellipsis-lastline; +} + +.CodeMirror-hint-information .content p:first-child { + margin-top: 0; +} + +.CodeMirror-hint-information .content p:last-child { + margin-bottom: 0; +} + +.CodeMirror-hint-information .infoType { + color: #CA9800; + cursor: pointer; + display: inline; + margin-right: 0.5em; +} + +.autoInsertedLeaf.cm-property { + -webkit-animation-duration: 6s; + animation-duration: 6s; + -webkit-animation-name: insertionFade; + animation-name: insertionFade; + border-bottom: 2px solid rgba(255, 255, 255, 0); + border-radius: 2px; + margin: -2px -4px -1px; + padding: 2px 4px 1px; +} + +@-webkit-keyframes insertionFade { + from, to { + background: rgba(255, 255, 255, 0); + border-color: rgba(255, 255, 255, 0); + } + + 15%, 85% { + background: #fbffc9; + border-color: #f0f3c0; + } +} + +@keyframes insertionFade { + from, to { + background: rgba(255, 255, 255, 0); + border-color: rgba(255, 255, 255, 0); + } + + 15%, 85% { + background: #fbffc9; + border-color: #f0f3c0; + } +} + +div.CodeMirror-lint-tooltip { + background-color: white; + border-radius: 2px; + border: 0; + color: #141823; + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.45); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.45); + font-family: + system, + -apple-system, + 'San Francisco', + '.SFNSDisplay-Regular', + 'Segoe UI', + Segoe, + 'Segoe WP', + 'Helvetica Neue', + helvetica, + 'Lucida Grande', + arial, + sans-serif; + font-size: 13px; + line-height: 16px; + max-width: 430px; + opacity: 0; + padding: 8px 10px; + -webkit-transition: opacity 0.15s; + transition: opacity 0.15s; + white-space: pre-wrap; +} + +div.CodeMirror-lint-tooltip > * { + padding-left: 23px; +} + +div.CodeMirror-lint-tooltip > * + * { + margin-top: 12px; +} + +/* COLORS */ + +.graphiql-container .CodeMirror-foldmarker { + border-radius: 4px; + background: #08f; + background: -webkit-gradient(linear, left top, left bottom, from(#43A8FF), to(#0F83E8)); + background: linear-gradient(#43A8FF, #0F83E8); + -webkit-box-shadow: + 0 1px 1px rgba(0, 0, 0, 0.2), + inset 0 0 0 1px rgba(0, 0, 0, 0.1); + box-shadow: + 0 1px 1px rgba(0, 0, 0, 0.2), + inset 0 0 0 1px rgba(0, 0, 0, 0.1); + color: white; + font-family: arial; + font-size: 12px; + line-height: 0; + margin: 0 3px; + padding: 0px 4px 1px; + text-shadow: 0 -1px rgba(0, 0, 0, 0.1); +} + +.graphiql-container div.CodeMirror span.CodeMirror-matchingbracket { + color: #555; + text-decoration: underline; +} + +.graphiql-container div.CodeMirror span.CodeMirror-nonmatchingbracket { + color: #f00; +} + +/* Comment */ +.cm-comment { + color: #999; +} + +/* Punctuation */ +.cm-punctuation { + color: #555; +} + +/* Keyword */ +.cm-keyword { + color: #B11A04; +} + +/* OperationName, FragmentName */ +.cm-def { + color: #D2054E; +} + +/* FieldName */ +.cm-property { + color: #1F61A0; +} + +/* FieldAlias */ +.cm-qualifier { + color: #1C92A9; +} + +/* ArgumentName and ObjectFieldName */ +.cm-attribute { + color: #8B2BB9; +} + +/* Number */ +.cm-number { + color: #2882F9; +} + +/* String */ +.cm-string { + color: #D64292; +} + +/* Boolean */ +.cm-builtin { + color: #D47509; +} + +/* EnumValue */ +.cm-string-2 { + color: #0B7FC7; +} + +/* Variable */ +.cm-variable { + color: #397D13; +} + +/* Directive */ +.cm-meta { + color: #B33086; +} + +/* Type */ +.cm-atom { + color: #CA9800; +} +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + color: black; + font-family: monospace; + height: 300px; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + color: #999; + min-width: 20px; + padding: 0 3px 0 5px; + text-align: right; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror .CodeMirror-cursor { + border-left: 1px solid black; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.CodeMirror.cm-fat-cursor div.CodeMirror-cursor { + background: #7e7; + border: 0; + width: auto; +} +.CodeMirror.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} + +.cm-animate-fat-cursor { + -webkit-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; + border: 0; + width: auto; +} +@-webkit-keyframes blink { + 0% { background: #7e7; } + 50% { background: none; } + 100% { background: #7e7; } +} +@keyframes blink { + 0% { background: #7e7; } + 50% { background: none; } + 100% { background: #7e7; } +} + +/* Can style cursor different in overwrite (non-insert) mode */ +div.CodeMirror-overwrite div.CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-ruler { + border-left: 1px solid #ccc; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3 {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + background: white; + overflow: hidden; + position: relative; +} + +.CodeMirror-scroll { + height: 100%; + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -30px; margin-right: -30px; + outline: none; /* Prevent dragging from highlighting the element */ + overflow: scroll !important; /* Things will break if this is overridden */ + padding-bottom: 30px; + position: relative; +} +.CodeMirror-sizer { + border-right: 30px solid transparent; + position: relative; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actual scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + display: none; + position: absolute; + z-index: 6; +} +.CodeMirror-vscrollbar { + overflow-x: hidden; + overflow-y: scroll; + right: 0; top: 0; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-x: scroll; + overflow-y: hidden; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + min-height: 100%; + position: absolute; left: 0; top: 0; + z-index: 3; +} +.CodeMirror-gutter { + display: inline-block; + height: 100%; + margin-bottom: -30px; + vertical-align: top; + white-space: normal; + /* Hack to make IE7 behave */ + *zoom:1; + *display:inline; +} +.CodeMirror-gutter-wrapper { + background: none !important; + border: none !important; + position: absolute; + z-index: 4; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + cursor: default; + position: absolute; + z-index: 4; +} +.CodeMirror-gutter-wrapper { + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre { + -webkit-tap-highlight-color: transparent; + /* Reset some styles that the rest of the page might have set */ + background: transparent; + border-radius: 0; + border-width: 0; + color: inherit; + font-family: inherit; + font-size: inherit; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; + line-height: inherit; + margin: 0; + overflow: visible; + position: relative; + white-space: pre; + word-wrap: normal; + z-index: 2; +} +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + overflow: auto; + position: relative; + z-index: 2; +} + +.CodeMirror-widget {} + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -webkit-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + height: 0; + overflow: hidden; + position: absolute; + visibility: hidden; + width: 100%; +} + +.CodeMirror-cursor { position: absolute; } +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + position: relative; + visibility: hidden; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background: #ffa; + background: rgba(255, 255, 0, .4); +} + +/* IE7 hack to prevent it from returning funny offsetTops on the spans */ +.CodeMirror span { *vertical-align: text-bottom; } + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } + +.CodeMirror-dialog { + background: inherit; + color: inherit; + left: 0; right: 0; + overflow: hidden; + padding: .1em .8em; + position: absolute; + z-index: 15; +} + +.CodeMirror-dialog-top { + border-bottom: 1px solid #eee; + top: 0; +} + +.CodeMirror-dialog-bottom { + border-top: 1px solid #eee; + bottom: 0; +} + +.CodeMirror-dialog input { + background: transparent; + border: 1px solid #d3d6db; + color: inherit; + font-family: monospace; + outline: none; + width: 20em; +} + +.CodeMirror-dialog button { + font-size: 70%; +} +.graphiql-container .doc-explorer { + background: white; +} + +.graphiql-container .doc-explorer-title-bar, +.graphiql-container .history-title-bar { + cursor: default; + display: -webkit-box; + display: -ms-flexbox; + display: flex; + height: 34px; + line-height: 14px; + padding: 8px 8px 5px; + position: relative; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.graphiql-container .doc-explorer-title, +.graphiql-container .history-title { + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1; + font-weight: bold; + overflow-x: hidden; + padding: 10px 0 10px 10px; + text-align: center; + text-overflow: ellipsis; + -webkit-user-select: initial; + -moz-user-select: initial; + -ms-user-select: initial; + user-select: initial; + white-space: nowrap; +} + +.graphiql-container .doc-explorer-back { + color: #3B5998; + cursor: pointer; + margin: -7px 0 -6px -8px; + overflow-x: hidden; + padding: 17px 12px 16px 16px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.doc-explorer-narrow .doc-explorer-back { + width: 0; +} + +.graphiql-container .doc-explorer-back:before { + border-left: 2px solid #3B5998; + border-top: 2px solid #3B5998; + content: ''; + display: inline-block; + height: 9px; + margin: 0 3px -1px 0; + position: relative; + -webkit-transform: rotate(-45deg); + transform: rotate(-45deg); + width: 9px; +} + +.graphiql-container .doc-explorer-rhs { + position: relative; +} + +.graphiql-container .doc-explorer-contents, +.graphiql-container .history-contents { + background-color: #ffffff; + border-top: 1px solid #d6d6d6; + bottom: 0; + left: 0; + overflow-y: auto; + padding: 20px 15px; + position: absolute; + right: 0; + top: 47px; +} + +.graphiql-container .doc-explorer-contents { + min-width: 300px; +} + +.graphiql-container .doc-type-description p:first-child , +.graphiql-container .doc-type-description blockquote:first-child { + margin-top: 0; +} + +.graphiql-container .doc-explorer-contents a { + cursor: pointer; + text-decoration: none; +} + +.graphiql-container .doc-explorer-contents a:hover { + text-decoration: underline; +} + +.graphiql-container .doc-value-description > :first-child { + margin-top: 4px; +} + +.graphiql-container .doc-value-description > :last-child { + margin-bottom: 4px; +} + +.graphiql-container .doc-category { + margin: 20px 0; +} + +.graphiql-container .doc-category-title { + border-bottom: 1px solid #e0e0e0; + color: #777; + cursor: default; + font-size: 14px; + font-variant: small-caps; + font-weight: bold; + letter-spacing: 1px; + margin: 0 -15px 10px 0; + padding: 10px 0; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.graphiql-container .doc-category-item { + margin: 12px 0; + color: #555; +} + +.graphiql-container .keyword { + color: #B11A04; +} + +.graphiql-container .type-name { + color: #CA9800; +} + +.graphiql-container .field-name { + color: #1F61A0; +} + +.graphiql-container .field-short-description { + color: #999; + margin-left: 5px; + overflow: hidden; + text-overflow: ellipsis; +} + +.graphiql-container .enum-value { + color: #0B7FC7; +} + +.graphiql-container .arg-name { + color: #8B2BB9; +} + +.graphiql-container .arg { + display: block; + margin-left: 1em; +} + +.graphiql-container .arg:first-child:last-child, +.graphiql-container .arg:first-child:nth-last-child(2), +.graphiql-container .arg:first-child:nth-last-child(2) ~ .arg { + display: inherit; + margin: inherit; +} + +.graphiql-container .arg:first-child:nth-last-child(2):after { + content: ', '; +} + +.graphiql-container .arg-default-value { + color: #0B7FC7; +} + +.graphiql-container .doc-deprecation { + background: #fffae8; + -webkit-box-shadow: inset 0 0 1px #bfb063; + box-shadow: inset 0 0 1px #bfb063; + color: #867F70; + line-height: 16px; + margin: 8px -8px; + max-height: 80px; + overflow: hidden; + padding: 8px; + border-radius: 3px; +} + +.graphiql-container .doc-deprecation:before { + content: 'Deprecated:'; + color: #c79b2e; + cursor: default; + display: block; + font-size: 9px; + font-weight: bold; + letter-spacing: 1px; + line-height: 1; + padding-bottom: 5px; + text-transform: uppercase; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.graphiql-container .doc-deprecation > :first-child { + margin-top: 0; +} + +.graphiql-container .doc-deprecation > :last-child { + margin-bottom: 0; +} + +.graphiql-container .show-btn { + -webkit-appearance: initial; + display: block; + border-radius: 3px; + border: solid 1px #ccc; + text-align: center; + padding: 8px 12px 10px; + width: 100%; + -webkit-box-sizing: border-box; + box-sizing: border-box; + background: #fbfcfc; + color: #555; + cursor: pointer; +} + +.graphiql-container .search-box { + border-bottom: 1px solid #d3d6db; + display: block; + font-size: 14px; + margin: -15px -15px 12px 0; + position: relative; +} + +.graphiql-container .search-box:before { + content: '\26b2'; + cursor: pointer; + display: block; + font-size: 24px; + position: absolute; + top: -2px; + -webkit-transform: rotate(-45deg); + transform: rotate(-45deg); + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.graphiql-container .search-box .search-box-clear { + background-color: #d0d0d0; + border-radius: 12px; + color: #fff; + cursor: pointer; + font-size: 11px; + padding: 1px 5px 2px; + position: absolute; + right: 3px; + top: 8px; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.graphiql-container .search-box .search-box-clear:hover { + background-color: #b9b9b9; +} + +.graphiql-container .search-box > input { + border: none; + -webkit-box-sizing: border-box; + box-sizing: border-box; + font-size: 14px; + outline: none; + padding: 6px 24px 8px 20px; + width: 100%; +} + +.graphiql-container .error-container { + font-weight: bold; + left: 0; + letter-spacing: 1px; + opacity: 0.5; + position: absolute; + right: 0; + text-align: center; + text-transform: uppercase; + top: 50%; + -webkit-transform: translate(0, -50%); + transform: translate(0, -50%); +} +.CodeMirror-foldmarker { + color: blue; + cursor: pointer; + font-family: arial; + line-height: .3; + text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px; +} +.CodeMirror-foldgutter { + width: .7em; +} +.CodeMirror-foldgutter-open, +.CodeMirror-foldgutter-folded { + cursor: pointer; +} +.CodeMirror-foldgutter-open:after { + content: "\25BE"; +} +.CodeMirror-foldgutter-folded:after { + content: "\25B8"; +} +.graphiql-container .history-contents { + font-family: 'Consolas', 'Inconsolata', 'Droid Sans Mono', 'Monaco', monospace; + padding: 0; +} + +.graphiql-container .history-contents p { + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + margin: 0; + padding: 8px; + border-bottom: 1px solid #e0e0e0; +} + +.graphiql-container .history-contents p:hover { + cursor: pointer; +} +.CodeMirror-info { + background: white; + border-radius: 2px; + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.45); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.45); + -webkit-box-sizing: border-box; + box-sizing: border-box; + color: #555; + font-family: + system, + -apple-system, + 'San Francisco', + '.SFNSDisplay-Regular', + 'Segoe UI', + Segoe, + 'Segoe WP', + 'Helvetica Neue', + helvetica, + 'Lucida Grande', + arial, + sans-serif; + font-size: 13px; + line-height: 16px; + margin: 8px -8px; + max-width: 400px; + opacity: 0; + overflow: hidden; + padding: 8px 8px; + position: fixed; + -webkit-transition: opacity 0.15s; + transition: opacity 0.15s; + z-index: 50; +} + +.CodeMirror-info :first-child { + margin-top: 0; +} + +.CodeMirror-info :last-child { + margin-bottom: 0; +} + +.CodeMirror-info p { + margin: 1em 0; +} + +.CodeMirror-info .info-description { + color: #777; + line-height: 16px; + margin-top: 1em; + max-height: 80px; + overflow: hidden; +} + +.CodeMirror-info .info-deprecation { + background: #fffae8; + -webkit-box-shadow: inset 0 1px 1px -1px #bfb063; + box-shadow: inset 0 1px 1px -1px #bfb063; + color: #867F70; + line-height: 16px; + margin: -8px; + margin-top: 8px; + max-height: 80px; + overflow: hidden; + padding: 8px; +} + +.CodeMirror-info .info-deprecation-label { + color: #c79b2e; + cursor: default; + display: block; + font-size: 9px; + font-weight: bold; + letter-spacing: 1px; + line-height: 1; + padding-bottom: 5px; + text-transform: uppercase; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.CodeMirror-info .info-deprecation-label + * { + margin-top: 0; +} + +.CodeMirror-info a { + text-decoration: none; +} + +.CodeMirror-info a:hover { + text-decoration: underline; +} + +.CodeMirror-info .type-name { + color: #CA9800; +} + +.CodeMirror-info .field-name { + color: #1F61A0; +} + +.CodeMirror-info .enum-value { + color: #0B7FC7; +} + +.CodeMirror-info .arg-name { + color: #8B2BB9; +} + +.CodeMirror-info .directive-name { + color: #B33086; +} +.CodeMirror-jump-token { + text-decoration: underline; + cursor: pointer; +} +/* The lint marker gutter */ +.CodeMirror-lint-markers { + width: 16px; +} + +.CodeMirror-lint-tooltip { + background-color: infobackground; + border-radius: 4px 4px 4px 4px; + border: 1px solid black; + color: infotext; + font-family: monospace; + font-size: 10pt; + max-width: 600px; + opacity: 0; + overflow: hidden; + padding: 2px 5px; + position: fixed; + -webkit-transition: opacity .4s; + transition: opacity .4s; + white-space: pre-wrap; + z-index: 100; +} + +.CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning { + background-position: left bottom; + background-repeat: repeat-x; +} + +.CodeMirror-lint-mark-error { + background-image: + url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==") + ; +} + +.CodeMirror-lint-mark-warning { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII="); +} + +.CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning { + background-position: center center; + background-repeat: no-repeat; + cursor: pointer; + display: inline-block; + height: 16px; + position: relative; + vertical-align: middle; + width: 16px; +} + +.CodeMirror-lint-message-error, .CodeMirror-lint-message-warning { + background-position: top left; + background-repeat: no-repeat; + padding-left: 18px; +} + +.CodeMirror-lint-marker-error, .CodeMirror-lint-message-error { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII="); +} + +.CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII="); +} + +.CodeMirror-lint-marker-multiple { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC"); + background-position: right bottom; + background-repeat: no-repeat; + width: 100%; height: 100%; +} +.graphiql-container .spinner-container { + height: 36px; + left: 50%; + position: absolute; + top: 50%; + -webkit-transform: translate(-50%, -50%); + transform: translate(-50%, -50%); + width: 36px; + z-index: 10; +} + +.graphiql-container .spinner { + -webkit-animation: rotation .6s infinite linear; + animation: rotation .6s infinite linear; + border-bottom: 6px solid rgba(150, 150, 150, .15); + border-left: 6px solid rgba(150, 150, 150, .15); + border-radius: 100%; + border-right: 6px solid rgba(150, 150, 150, .15); + border-top: 6px solid rgba(150, 150, 150, .8); + display: inline-block; + height: 24px; + position: absolute; + vertical-align: middle; + width: 24px; +} + +@-webkit-keyframes rotation { + from { -webkit-transform: rotate(0deg); transform: rotate(0deg); } + to { -webkit-transform: rotate(359deg); transform: rotate(359deg); } +} + +@keyframes rotation { + from { -webkit-transform: rotate(0deg); transform: rotate(0deg); } + to { -webkit-transform: rotate(359deg); transform: rotate(359deg); } +} +.CodeMirror-hints { + background: white; + -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.45); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.45); + font-family: 'Consolas', 'Inconsolata', 'Droid Sans Mono', 'Monaco', monospace; + font-size: 13px; + list-style: none; + margin-left: -6px; + margin: 0; + max-height: 14.5em; + overflow-y: auto; + overflow: hidden; + padding: 0; + position: absolute; + z-index: 10; +} + +.CodeMirror-hint { + border-top: solid 1px #f7f7f7; + color: #141823; + cursor: pointer; + margin: 0; + max-width: 300px; + overflow: hidden; + padding: 2px 6px; + white-space: pre; +} + +li.CodeMirror-hint-active { + background-color: #08f; + border-top-color: white; + color: white; +} + +.CodeMirror-hint-information { + border-top: solid 1px #c0c0c0; + max-width: 300px; + padding: 4px 6px; + position: relative; + z-index: 1; +} + +.CodeMirror-hint-information:first-child { + border-bottom: solid 1px #c0c0c0; + border-top: none; + margin-bottom: -1px; +} + +.CodeMirror-hint-deprecation { + background: #fffae8; + -webkit-box-shadow: inset 0 1px 1px -1px #bfb063; + box-shadow: inset 0 1px 1px -1px #bfb063; + color: #867F70; + font-family: + system, + -apple-system, + 'San Francisco', + '.SFNSDisplay-Regular', + 'Segoe UI', + Segoe, + 'Segoe WP', + 'Helvetica Neue', + helvetica, + 'Lucida Grande', + arial, + sans-serif; + font-size: 13px; + line-height: 16px; + margin-top: 4px; + max-height: 80px; + overflow: hidden; + padding: 6px; +} + +.CodeMirror-hint-deprecation .deprecation-label { + color: #c79b2e; + cursor: default; + display: block; + font-size: 9px; + font-weight: bold; + letter-spacing: 1px; + line-height: 1; + padding-bottom: 5px; + text-transform: uppercase; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.CodeMirror-hint-deprecation .deprecation-label + * { + margin-top: 0; +} + +.CodeMirror-hint-deprecation :last-child { + margin-bottom: 0; +} diff --git a/docker/app/www/graphiql/graphiql.js b/docker/app/www/graphiql/graphiql.js new file mode 100644 index 0000000..0b0490e --- /dev/null +++ b/docker/app/www/graphiql/graphiql.js @@ -0,0 +1,39655 @@ +(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 1) { + _this.setState({ navStack: _this.state.navStack.slice(0, -1) }); + } + }; + + _this.handleClickTypeOrField = function (typeOrField) { + _this.showDoc(typeOrField); + }; + + _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 = void 0; + if (schema === undefined) { + // Schema is undefined when it is being loaded via introspection. + content = _react2.default.createElement( + 'div', + { className: 'spinner-container' }, + _react2.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 = _react2.default.createElement( + 'div', + { className: 'error-container' }, + 'No Schema Available' + ); + } else if (navItem.search) { + content = _react2.default.createElement(_SearchResults2.default, { + searchValue: navItem.search, + withinType: navItem.def, + schema: schema, + onClickType: this.handleClickTypeOrField, + onClickField: this.handleClickTypeOrField + }); + } else if (navStack.length === 1) { + content = _react2.default.createElement(_SchemaDoc2.default, { schema: schema, onClickType: this.handleClickTypeOrField }); + } else if ((0, _graphql.isType)(navItem.def)) { + content = _react2.default.createElement(_TypeDoc2.default, { + schema: schema, + type: navItem.def, + onClickType: this.handleClickTypeOrField, + onClickField: this.handleClickTypeOrField + }); + } else { + content = _react2.default.createElement(_FieldDoc2.default, { + field: navItem.def, + onClickType: this.handleClickTypeOrField + }); + } + + var shouldSearchBoxAppear = navStack.length === 1 || (0, _graphql.isType)(navItem.def) && navItem.def.getFields; + + var prevName = void 0; + if (navStack.length > 1) { + prevName = navStack[navStack.length - 2].name; + } + + return _react2.default.createElement( + 'div', + { className: 'doc-explorer', key: navItem.name }, + _react2.default.createElement( + 'div', + { className: 'doc-explorer-title-bar' }, + prevName && _react2.default.createElement( + 'div', + { + className: 'doc-explorer-back', + onClick: this.handleNavBackClick }, + prevName + ), + _react2.default.createElement( + 'div', + { className: 'doc-explorer-title' }, + navItem.title || navItem.name + ), + _react2.default.createElement( + 'div', + { className: 'doc-explorer-rhs' }, + this.props.children + ) + ), + _react2.default.createElement( + 'div', + { className: 'doc-explorer-contents' }, + shouldSearchBoxAppear && _react2.default.createElement(_SearchBox2.default, { + value: navItem.search, + placeholder: 'Search ' + 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] = _extends({}, topNav, { search: search }); + this.setState({ navStack: navStack }); + } + }, { + key: 'reset', + value: function reset() { + this.setState({ navStack: [initialNav] }); + } + }]); + + return DocExplorer; +}(_react2.default.Component); + +DocExplorer.propTypes = { + schema: _propTypes2.default.instanceOf(_graphql.GraphQLSchema) +}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./DocExplorer/FieldDoc":3,"./DocExplorer/SchemaDoc":5,"./DocExplorer/SearchBox":6,"./DocExplorer/SearchResults":7,"./DocExplorer/TypeDoc":8,"graphql":92,"prop-types":172}],2:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = Argument; + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _graphql = require('graphql'); + +var _TypeLink = require('./TypeLink'); + +var _TypeLink2 = _interopRequireDefault(_TypeLink); + +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. + */ + +function Argument(_ref) { + var arg = _ref.arg, + onClickType = _ref.onClickType, + showDefaultValue = _ref.showDefaultValue; + + return _react2.default.createElement( + 'span', + { className: 'arg' }, + _react2.default.createElement( + 'span', + { className: 'arg-name' }, + arg.name + ), + ': ', + _react2.default.createElement(_TypeLink2.default, { type: arg.type, onClick: onClickType }), + arg.defaultValue !== undefined && showDefaultValue !== false && _react2.default.createElement( + 'span', + null, + ' = ', + _react2.default.createElement( + 'span', + { className: 'arg-default-value' }, + (0, _graphql.print)((0, _graphql.astFromValue)(arg.defaultValue, arg.type)) + ) + ) + ); +} + +Argument.propTypes = { + arg: _propTypes2.default.object.isRequired, + onClickType: _propTypes2.default.func.isRequired, + showDefaultValue: _propTypes2.default.bool +}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./TypeLink":9,"graphql":92,"prop-types":172}],3:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _Argument = require('./Argument'); + +var _Argument2 = _interopRequireDefault(_Argument); + +var _MarkdownContent = require('./MarkdownContent'); + +var _MarkdownContent2 = _interopRequireDefault(_MarkdownContent); + +var _TypeLink = require('./TypeLink'); + +var _TypeLink2 = _interopRequireDefault(_TypeLink); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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 FieldDoc = function (_React$Component) { + _inherits(FieldDoc, _React$Component); + + function FieldDoc() { + _classCallCheck(this, FieldDoc); + + return _possibleConstructorReturn(this, (FieldDoc.__proto__ || Object.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 _this2 = this; + + var field = this.props.field; + + var argsDef = void 0; + if (field.args && field.args.length > 0) { + argsDef = _react2.default.createElement( + 'div', + { className: 'doc-category' }, + _react2.default.createElement( + 'div', + { className: 'doc-category-title' }, + 'arguments' + ), + field.args.map(function (arg) { + return _react2.default.createElement( + 'div', + { key: arg.name, className: 'doc-category-item' }, + _react2.default.createElement( + 'div', + null, + _react2.default.createElement(_Argument2.default, { arg: arg, onClickType: _this2.props.onClickType }) + ), + _react2.default.createElement(_MarkdownContent2.default, { + className: 'doc-value-description', + markdown: arg.description + }) + ); + }) + ); + } + + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement(_MarkdownContent2.default, { + className: 'doc-type-description', + markdown: field.description || 'No Description' + }), + field.deprecationReason && _react2.default.createElement(_MarkdownContent2.default, { + className: 'doc-deprecation', + markdown: field.deprecationReason + }), + _react2.default.createElement( + 'div', + { className: 'doc-category' }, + _react2.default.createElement( + 'div', + { className: 'doc-category-title' }, + 'type' + ), + _react2.default.createElement(_TypeLink2.default, { type: field.type, onClick: this.props.onClickType }) + ), + argsDef + ); + } + }]); + + return FieldDoc; +}(_react2.default.Component); + +FieldDoc.propTypes = { + field: _propTypes2.default.object, + onClickType: _propTypes2.default.func +}; +exports.default = FieldDoc; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./Argument":2,"./MarkdownContent":4,"./TypeLink":9,"prop-types":172}],4:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _marked = require('marked'); + +var _marked2 = _interopRequireDefault(_marked); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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 MarkdownContent = function (_React$Component) { + _inherits(MarkdownContent, _React$Component); + + function MarkdownContent() { + _classCallCheck(this, MarkdownContent); + + return _possibleConstructorReturn(this, (MarkdownContent.__proto__ || Object.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 _react2.default.createElement('div', null); + } + + var html = (0, _marked2.default)(markdown, { sanitize: true }); + return _react2.default.createElement('div', { + className: this.props.className, + dangerouslySetInnerHTML: { __html: html } + }); + } + }]); + + return MarkdownContent; +}(_react2.default.Component); + +MarkdownContent.propTypes = { + markdown: _propTypes2.default.string, + className: _propTypes2.default.string +}; +exports.default = MarkdownContent; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"marked":167,"prop-types":172}],5:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _TypeLink = require('./TypeLink'); + +var _TypeLink2 = _interopRequireDefault(_TypeLink); + +var _MarkdownContent = require('./MarkdownContent'); + +var _MarkdownContent2 = _interopRequireDefault(_MarkdownContent); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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. + */ + +// Render the top level Schema +var SchemaDoc = function (_React$Component) { + _inherits(SchemaDoc, _React$Component); + + function SchemaDoc() { + _classCallCheck(this, SchemaDoc); + + return _possibleConstructorReturn(this, (SchemaDoc.__proto__ || Object.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 _react2.default.createElement( + 'div', + null, + _react2.default.createElement(_MarkdownContent2.default, { + className: 'doc-type-description', + markdown: 'A GraphQL schema provides a root type for each kind of operation.' + }), + _react2.default.createElement( + 'div', + { className: 'doc-category' }, + _react2.default.createElement( + 'div', + { className: 'doc-category-title' }, + 'root types' + ), + _react2.default.createElement( + 'div', + { className: 'doc-category-item' }, + _react2.default.createElement( + 'span', + { className: 'keyword' }, + 'query' + ), + ': ', + _react2.default.createElement(_TypeLink2.default, { type: queryType, onClick: this.props.onClickType }) + ), + mutationType && _react2.default.createElement( + 'div', + { className: 'doc-category-item' }, + _react2.default.createElement( + 'span', + { className: 'keyword' }, + 'mutation' + ), + ': ', + _react2.default.createElement(_TypeLink2.default, { type: mutationType, onClick: this.props.onClickType }) + ), + subscriptionType && _react2.default.createElement( + 'div', + { className: 'doc-category-item' }, + _react2.default.createElement( + 'span', + { className: 'keyword' }, + 'subscription' + ), + ': ', + _react2.default.createElement(_TypeLink2.default, { + type: subscriptionType, + onClick: this.props.onClickType + }) + ) + ) + ); + } + }]); + + return SchemaDoc; +}(_react2.default.Component); + +SchemaDoc.propTypes = { + schema: _propTypes2.default.object, + onClickType: _propTypes2.default.func +}; +exports.default = SchemaDoc; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./MarkdownContent":4,"./TypeLink":9,"prop-types":172}],6:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _debounce = require('../../utility/debounce'); + +var _debounce2 = _interopRequireDefault(_debounce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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 SearchBox = function (_React$Component) { + _inherits(SearchBox, _React$Component); + + function SearchBox(props) { + _classCallCheck(this, SearchBox); + + var _this = _possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this, props)); + + _this.handleChange = function (event) { + var value = event.target.value; + _this.setState({ value: value }); + _this.debouncedOnSearch(value); + }; + + _this.handleClear = function () { + _this.setState({ value: '' }); + _this.props.onSearch(''); + }; + + _this.state = { value: props.value || '' }; + _this.debouncedOnSearch = (0, _debounce2.default)(200, _this.props.onSearch); + return _this; + } + + _createClass(SearchBox, [{ + key: 'render', + value: function render() { + return _react2.default.createElement( + 'label', + { className: 'search-box' }, + _react2.default.createElement('input', { + value: this.state.value, + onChange: this.handleChange, + type: 'text', + placeholder: this.props.placeholder + }), + this.state.value && _react2.default.createElement( + 'div', + { className: 'search-box-clear', onClick: this.handleClear }, + '\u2715' + ) + ); + } + }]); + + return SearchBox; +}(_react2.default.Component); + +SearchBox.propTypes = { + value: _propTypes2.default.string, + placeholder: _propTypes2.default.string, + onSearch: _propTypes2.default.func +}; +exports.default = SearchBox; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../../utility/debounce":25,"prop-types":172}],7:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _Argument = require('./Argument'); + +var _Argument2 = _interopRequireDefault(_Argument); + +var _TypeLink = require('./TypeLink'); + +var _TypeLink2 = _interopRequireDefault(_TypeLink); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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 SearchResults = function (_React$Component) { + _inherits(SearchResults, _React$Component); + + function SearchResults() { + _classCallCheck(this, SearchResults); + + return _possibleConstructorReturn(this, (SearchResults.__proto__ || Object.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(_react2.default.createElement( + 'div', + { className: 'doc-category-item', key: typeName }, + _react2.default.createElement(_TypeLink2.default, { type: type, onClick: onClickType }) + )); + } + + if (type.getFields) { + var fields = type.getFields(); + Object.keys(fields).forEach(function (fieldName) { + var field = fields[fieldName]; + var matchingArgs = void 0; + + 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 = _react2.default.createElement( + 'div', + { className: 'doc-category-item', key: typeName + '.' + fieldName }, + withinType !== type && [_react2.default.createElement(_TypeLink2.default, { key: 'type', type: type, onClick: onClickType }), '.'], + _react2.default.createElement( + 'a', + { + className: 'field-name', + onClick: function onClick(event) { + return onClickField(field, type, event); + } }, + field.name + ), + matchingArgs && ['(', _react2.default.createElement( + 'span', + { key: 'args' }, + matchingArgs.map(function (arg) { + return _react2.default.createElement(_Argument2.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) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + if (matchedWithin.length + matchedTypes.length + matchedFields.length === 0) { + return _react2.default.createElement( + 'span', + { className: 'doc-alert-text' }, + 'No results found.' + ); + } + + if (withinType && matchedTypes.length + matchedFields.length > 0) { + return _react2.default.createElement( + 'div', + null, + matchedWithin, + _react2.default.createElement( + 'div', + { className: 'doc-category' }, + _react2.default.createElement( + 'div', + { className: 'doc-category-title' }, + 'other results' + ), + matchedTypes, + matchedFields + ) + ); + } + + return _react2.default.createElement( + 'div', + null, + matchedWithin, + matchedTypes, + matchedFields + ); + } + }]); + + return SearchResults; +}(_react2.default.Component); + +SearchResults.propTypes = { + schema: _propTypes2.default.object, + withinType: _propTypes2.default.object, + searchValue: _propTypes2.default.string, + onClickType: _propTypes2.default.func, + onClickField: _propTypes2.default.func +}; +exports.default = SearchResults; + + +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":2,"./TypeLink":9,"prop-types":172}],8:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _graphql = require('graphql'); + +var _Argument = require('./Argument'); + +var _Argument2 = _interopRequireDefault(_Argument); + +var _MarkdownContent = require('./MarkdownContent'); + +var _MarkdownContent2 = _interopRequireDefault(_MarkdownContent); + +var _TypeLink = require('./TypeLink'); + +var _TypeLink2 = _interopRequireDefault(_TypeLink); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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 TypeDoc = function (_React$Component) { + _inherits(TypeDoc, _React$Component); + + function TypeDoc(props) { + _classCallCheck(this, TypeDoc); + + var _this = _possibleConstructorReturn(this, (TypeDoc.__proto__ || Object.getPrototypeOf(TypeDoc)).call(this, props)); + + _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 = void 0; + var types = void 0; + 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 = void 0; + if (types && types.length > 0) { + typesDef = _react2.default.createElement( + 'div', + { className: 'doc-category' }, + _react2.default.createElement( + 'div', + { className: 'doc-category-title' }, + typesTitle + ), + types.map(function (subtype) { + return _react2.default.createElement( + 'div', + { key: subtype.name, className: 'doc-category-item' }, + _react2.default.createElement(_TypeLink2.default, { type: subtype, onClick: onClickType }) + ); + }) + ); + } + + // InputObject and Object + var fieldsDef = void 0; + var deprecatedFieldsDef = void 0; + if (type.getFields) { + var fieldMap = type.getFields(); + var fields = Object.keys(fieldMap).map(function (name) { + return fieldMap[name]; + }); + fieldsDef = _react2.default.createElement( + 'div', + { className: 'doc-category' }, + _react2.default.createElement( + 'div', + { className: 'doc-category-title' }, + 'fields' + ), + fields.filter(function (field) { + return !field.isDeprecated; + }).map(function (field) { + return _react2.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 = _react2.default.createElement( + 'div', + { className: 'doc-category' }, + _react2.default.createElement( + 'div', + { className: 'doc-category-title' }, + 'deprecated fields' + ), + !this.state.showDeprecated ? _react2.default.createElement( + 'button', + { + className: 'show-btn', + onClick: this.handleShowDeprecated }, + 'Show deprecated fields...' + ) : deprecatedFields.map(function (field) { + return _react2.default.createElement(Field, { + key: field.name, + type: type, + field: field, + onClickType: onClickType, + onClickField: onClickField + }); + }) + ); + } + } + + var valuesDef = void 0; + var deprecatedValuesDef = void 0; + if (type instanceof _graphql.GraphQLEnumType) { + var values = type.getValues(); + valuesDef = _react2.default.createElement( + 'div', + { className: 'doc-category' }, + _react2.default.createElement( + 'div', + { className: 'doc-category-title' }, + 'values' + ), + values.filter(function (value) { + return !value.isDeprecated; + }).map(function (value) { + return _react2.default.createElement(EnumValue, { key: value.name, value: value }); + }) + ); + + var deprecatedValues = values.filter(function (value) { + return value.isDeprecated; + }); + if (deprecatedValues.length > 0) { + deprecatedValuesDef = _react2.default.createElement( + 'div', + { className: 'doc-category' }, + _react2.default.createElement( + 'div', + { className: 'doc-category-title' }, + 'deprecated values' + ), + !this.state.showDeprecated ? _react2.default.createElement( + 'button', + { + className: 'show-btn', + onClick: this.handleShowDeprecated }, + 'Show deprecated values...' + ) : deprecatedValues.map(function (value) { + return _react2.default.createElement(EnumValue, { key: value.name, value: value }); + }) + ); + } + } + + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement(_MarkdownContent2.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; +}(_react2.default.Component); + +TypeDoc.propTypes = { + schema: _propTypes2.default.instanceOf(_graphql.GraphQLSchema), + type: _propTypes2.default.object, + onClickType: _propTypes2.default.func, + onClickField: _propTypes2.default.func +}; +exports.default = TypeDoc; + + +function Field(_ref) { + var type = _ref.type, + field = _ref.field, + onClickType = _ref.onClickType, + onClickField = _ref.onClickField; + + return _react2.default.createElement( + 'div', + { className: 'doc-category-item' }, + _react2.default.createElement( + 'a', + { + className: 'field-name', + onClick: function onClick(event) { + return onClickField(field, type, event); + } }, + field.name + ), + field.args && field.args.length > 0 && ['(', _react2.default.createElement( + 'span', + { key: 'args' }, + field.args.map(function (arg) { + return _react2.default.createElement(_Argument2.default, { key: arg.name, arg: arg, onClickType: onClickType }); + }) + ), ')'], + ': ', + _react2.default.createElement(_TypeLink2.default, { type: field.type, onClick: onClickType }), + field.description && _react2.default.createElement( + 'p', + { className: 'field-short-description' }, + field.description + ), + field.deprecationReason && _react2.default.createElement(_MarkdownContent2.default, { + className: 'doc-deprecation', + markdown: field.deprecationReason + }) + ); +} + +Field.propTypes = { + type: _propTypes2.default.object, + field: _propTypes2.default.object, + onClickType: _propTypes2.default.func, + onClickField: _propTypes2.default.func +}; + +function EnumValue(_ref2) { + var value = _ref2.value; + + return _react2.default.createElement( + 'div', + { className: 'doc-category-item' }, + _react2.default.createElement( + 'div', + { className: 'enum-value' }, + value.name + ), + _react2.default.createElement(_MarkdownContent2.default, { + className: 'doc-value-description', + markdown: value.description + }), + value.deprecationReason && _react2.default.createElement(_MarkdownContent2.default, { + className: 'doc-deprecation', + markdown: value.deprecationReason + }) + ); +} + +EnumValue.propTypes = { + value: _propTypes2.default.object +}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./Argument":2,"./MarkdownContent":4,"./TypeLink":9,"graphql":92,"prop-types":172}],9:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _graphql = require('graphql'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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 TypeLink = function (_React$Component) { + _inherits(TypeLink, _React$Component); + + function TypeLink() { + _classCallCheck(this, TypeLink); + + return _possibleConstructorReturn(this, (TypeLink.__proto__ || Object.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; +}(_react2.default.Component); + +TypeLink.propTypes = { + type: _propTypes2.default.object, + onClick: _propTypes2.default.func +}; +exports.default = TypeLink; + + +function renderType(type, _onClick) { + if (type instanceof _graphql.GraphQLNonNull) { + return _react2.default.createElement( + 'span', + null, + renderType(type.ofType, _onClick), + '!' + ); + } + if (type instanceof _graphql.GraphQLList) { + return _react2.default.createElement( + 'span', + null, + '[', + renderType(type.ofType, _onClick), + ']' + ); + } + return _react2.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":92,"prop-types":172}],10:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ExecuteButton = undefined; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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. + */ + +/** + * ExecuteButton + * + * What a nice round shiny button. Shows a drop-down when there are multiple + * queries to run. + */ +var ExecuteButton = exports.ExecuteButton = function (_React$Component) { + _inherits(ExecuteButton, _React$Component); + + function ExecuteButton(props) { + _classCallCheck(this, ExecuteButton); + + var _this = _possibleConstructorReturn(this, (ExecuteButton.__proto__ || Object.getPrototypeOf(ExecuteButton)).call(this, props)); + + _this._onClick = function () { + if (_this.props.isRunning) { + _this.props.onStop(); + } else { + _this.props.onRun(); + } + }; + + _this._onOptionSelected = function (operation) { + _this.setState({ optionsOpen: false }); + _this.props.onRun(operation.name && operation.name.value); + }; + + _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 = _react2.default.createElement( + 'ul', + { className: 'execute-options' }, + operations.map(function (operation) { + return _react2.default.createElement( + 'li', + { + key: operation.name ? operation.name.value : '*', + className: operation === highlight && 'selected', + 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 : '' + ); + }) + ); + } + + // Allow click event if there is a running query or if there are not options + // for which operation to run. + var onClick = void 0; + 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 = void 0; + if (!this.props.isRunning && hasOptions && !optionsOpen) { + onMouseDown = this._onOptionsOpen; + } + + var pathJSX = this.props.isRunning ? _react2.default.createElement('path', { d: 'M 10 10 L 23 10 L 23 23 L 10 23 z' }) : _react2.default.createElement('path', { d: 'M 11 9 L 24 16 L 11 23 z' }); + + return _react2.default.createElement( + 'div', + { className: 'execute-button-wrap' }, + _react2.default.createElement( + 'button', + { + type: 'button', + className: 'execute-button', + onMouseDown: onMouseDown, + onClick: onClick, + title: 'Execute Query (Ctrl-Enter)' }, + _react2.default.createElement( + 'svg', + { width: '34', height: '34' }, + pathJSX + ) + ), + options + ); + } + }]); + + return ExecuteButton; +}(_react2.default.Component); + +ExecuteButton.propTypes = { + onRun: _propTypes2.default.func, + onStop: _propTypes2.default.func, + isRunning: _propTypes2.default.bool, + operations: _propTypes2.default.array +}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"prop-types":172}],11:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GraphiQL = undefined; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +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; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _reactDom = (typeof window !== "undefined" ? window['ReactDOM'] : typeof global !== "undefined" ? global['ReactDOM'] : null); + +var _reactDom2 = _interopRequireDefault(_reactDom); + +var _graphql = require('graphql'); + +var _ExecuteButton = require('./ExecuteButton'); + +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 = require('../utility/CodeMirrorSizer'); + +var _CodeMirrorSizer2 = _interopRequireDefault(_CodeMirrorSizer); + +var _StorageAPI = require('../utility/StorageAPI'); + +var _StorageAPI2 = _interopRequireDefault(_StorageAPI); + +var _getQueryFacts = require('../utility/getQueryFacts'); + +var _getQueryFacts2 = _interopRequireDefault(_getQueryFacts); + +var _getSelectedOperationName = require('../utility/getSelectedOperationName'); + +var _getSelectedOperationName2 = _interopRequireDefault(_getSelectedOperationName); + +var _debounce = require('../utility/debounce'); + +var _debounce2 = _interopRequireDefault(_debounce); + +var _find = require('../utility/find'); + +var _find2 = _interopRequireDefault(_find); + +var _fillLeafs2 = require('../utility/fillLeafs'); + +var _elementPosition = require('../utility/elementPosition'); + +var _introspectionQueries = require('../utility/introspectionQueries'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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 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 = exports.GraphiQL = function (_React$Component) { + _inherits(GraphiQL, _React$Component); + + function GraphiQL(props) { + _classCallCheck(this, GraphiQL); + + // Ensure props are correct + var _this = _possibleConstructorReturn(this, (GraphiQL.__proto__ || Object.getPrototypeOf(GraphiQL)).call(this, props)); + + _initialiseProps.call(_this); + + if (typeof props.fetcher !== 'function') { + throw new TypeError('GraphiQL requires a fetcher function.'); + } + + // Cache the storage instance + _this._storage = new _StorageAPI2.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, _getQueryFacts2.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, _getSelectedOperationName2.default)(null, _this._storage.get('operationName'), queryFacts && queryFacts.operations); + + // Initialize state + _this.state = _extends({ + schema: props.schema, + query: query, + variables: variables, + operationName: operationName, + response: props.response, + editorFlex: Number(_this._storage.get('editorFlex')) || 1, + variableEditorOpen: Boolean(variables), + variableEditorHeight: Number(_this._storage.get('variableEditorHeight')) || 200, + docExplorerOpen: _this._storage.get('docExplorerOpen') === 'true' || false, + 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 _CodeMirrorSizer2.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 = _react2.default.Children.toArray(this.props.children); + + var logo = (0, _find2.default)(children, function (child) { + return child.type === GraphiQL.Logo; + }) || _react2.default.createElement(GraphiQL.Logo, null); + + var toolbar = (0, _find2.default)(children, function (child) { + return child.type === GraphiQL.Toolbar; + }) || _react2.default.createElement( + GraphiQL.Toolbar, + null, + _react2.default.createElement(_ToolbarButton.ToolbarButton, { + onClick: this.handlePrettifyQuery, + title: 'Prettify Query (Shift-Ctrl-P)', + label: 'Prettify' + }), + _react2.default.createElement(_ToolbarButton.ToolbarButton, { + onClick: this.handleToggleHistory, + title: 'Show History', + label: 'History' + }) + ); + + var footer = (0, _find2.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 _react2.default.createElement( + 'div', + { className: 'graphiql-container' }, + _react2.default.createElement( + 'div', + { className: 'historyPaneWrap', style: historyPaneStyle }, + _react2.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 }, + _react2.default.createElement( + 'div', + { className: 'docExplorerHide', onClick: this.handleToggleHistory }, + '\u2715' + ) + ) + ), + _react2.default.createElement( + 'div', + { className: 'editorWrap' }, + _react2.default.createElement( + 'div', + { className: 'topBarWrap' }, + _react2.default.createElement( + 'div', + { className: 'topBar' }, + logo, + _react2.default.createElement(_ExecuteButton.ExecuteButton, { + isRunning: Boolean(this.state.subscription), + onRun: this.handleRunQuery, + onStop: this.handleStopQuery, + operations: this.state.operations + }), + toolbar + ), + !this.state.docExplorerOpen && _react2.default.createElement( + 'button', + { + className: 'docExplorerShow', + onClick: this.handleToggleDocs }, + 'Docs' + ) + ), + _react2.default.createElement( + 'div', + { + ref: function ref(n) { + _this3.editorBarComponent = n; + }, + className: 'editorBar', + onDoubleClick: this.handleResetResize, + onMouseDown: this.handleResizeStart }, + _react2.default.createElement( + 'div', + { className: 'queryWrap', style: queryWrapStyle }, + _react2.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, + onPrettifyQuery: this.handlePrettifyQuery, + onRunQuery: this.handleEditorRunQuery, + editorTheme: this.props.editorTheme + }), + _react2.default.createElement( + 'div', + { className: 'variable-editor', style: variableStyle }, + _react2.default.createElement( + 'div', + { + className: 'variable-editor-title', + style: { cursor: variableOpen ? 'row-resize' : 'n-resize' }, + onMouseDown: this.handleVariableResizeStart }, + 'Query Variables' + ), + _react2.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, + onRunQuery: this.handleEditorRunQuery, + editorTheme: this.props.editorTheme + }) + ) + ), + _react2.default.createElement( + 'div', + { className: 'resultWrap' }, + this.state.isWaitingForResponse && _react2.default.createElement( + 'div', + { className: 'spinner-container' }, + _react2.default.createElement('div', { className: 'spinner' }) + ), + _react2.default.createElement(_ResultViewer.ResultViewer, { + ref: function ref(c) { + _this3.resultComponent = c; + }, + value: this.state.response, + editorTheme: this.props.editorTheme, + ResultsTooltip: this.props.ResultsTooltip + }), + footer + ) + ) + ), + _react2.default.createElement( + 'div', + { className: docExplorerWrapClasses, style: docWrapStyle }, + _react2.default.createElement('div', { + className: 'docExplorerResizer', + onDoubleClick: this.handleDocsResetResize, + onMouseDown: this.handleDocsResizeStart + }), + _react2.default.createElement( + _DocExplorer.DocExplorer, + { + ref: function ref(c) { + _this3.docExplorerComponent = c; + }, + schema: this.state.schema }, + _react2.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 })); + 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 + })); + 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, _getQueryFacts2.default)(schema, _this4.state.query); + _this4.setState(_extends({ 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) { + _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: ' + error.message + '.'); + } + + if ((typeof jsonVariables === 'undefined' ? 'undefined' : _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 = void 0; + 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 = _reactDom2.default.findDOMNode(this.resultComponent); + while (target) { + if (target === resultWindow) { + return true; + } + target = target.parentNode; + } + return false; + } + }]); + + return GraphiQL; +}(_react2.default.Component); + +// Configure the UI by providing this Component as a child of GraphiQL. + + +GraphiQL.propTypes = { + fetcher: _propTypes2.default.func.isRequired, + schema: _propTypes2.default.instanceOf(_graphql.GraphQLSchema), + query: _propTypes2.default.string, + variables: _propTypes2.default.string, + operationName: _propTypes2.default.string, + response: _propTypes2.default.string, + storage: _propTypes2.default.shape({ + getItem: _propTypes2.default.func, + setItem: _propTypes2.default.func, + removeItem: _propTypes2.default.func + }), + defaultQuery: _propTypes2.default.string, + onEditQuery: _propTypes2.default.func, + onEditVariables: _propTypes2.default.func, + onEditOperationName: _propTypes2.default.func, + onToggleDocs: _propTypes2.default.func, + getDefaultFieldNames: _propTypes2.default.func, + editorTheme: _propTypes2.default.string, + onToggleHistory: _propTypes2.default.func, + ResultsTooltip: _propTypes2.default.any +}; + +var _initialiseProps = function _initialiseProps() { + var _this6 = this; + + this.handleClickReference = function (reference) { + _this6.setState({ docExplorerOpen: true }, function () { + _this6.docExplorerComponent.showDocForReference(reference); + }); + }; + + this.handleRunQuery = function (selectedOperationName) { + _this6._editorQueryID++; + var queryID = _this6._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 = _this6.autoCompleteLeafs() || _this6.state.query; + var variables = _this6.state.variables; + var operationName = _this6.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; + _this6.handleEditOperationName(operationName); + } + + try { + _this6.setState({ + isWaitingForResponse: true, + response: null, + operationName: operationName + }); + + // _fetchQuery may return a subscription. + var subscription = _this6._fetchQuery(editedQuery, variables, operationName, function (result) { + if (queryID === _this6._editorQueryID) { + _this6.setState({ + isWaitingForResponse: false, + response: JSON.stringify(result, null, 2) + }); + } + }); + + _this6.setState({ subscription: subscription }); + } catch (error) { + _this6.setState({ + isWaitingForResponse: false, + response: error.message + }); + } + }; + + this.handleStopQuery = function () { + var subscription = _this6.state.subscription; + _this6.setState({ + isWaitingForResponse: false, + subscription: null + }); + if (subscription) { + subscription.unsubscribe(); + } + }; + + this.handlePrettifyQuery = function () { + var editor = _this6.getQueryEditor(); + editor.setValue((0, _graphql.print)((0, _graphql.parse)(editor.getValue()))); + }; + + this.handleEditQuery = (0, _debounce2.default)(100, function (value) { + var queryFacts = _this6._updateQueryFacts(value, _this6.state.operationName, _this6.state.operations, _this6.state.schema); + _this6.setState(_extends({ + query: value + }, queryFacts)); + if (_this6.props.onEditQuery) { + return _this6.props.onEditQuery(value); + } + }); + + this._updateQueryFacts = function (query, operationName, prevOperations, schema) { + var queryFacts = (0, _getQueryFacts2.default)(schema, query); + if (queryFacts) { + // Update operation name should any query names change. + var updatedOperationName = (0, _getSelectedOperationName2.default)(prevOperations, operationName, queryFacts.operations); + + // Report changing of operationName if it changed. + var onEditOperationName = _this6.props.onEditOperationName; + if (onEditOperationName && operationName !== updatedOperationName) { + onEditOperationName(updatedOperationName); + } + + return _extends({ + operationName: updatedOperationName + }, queryFacts); + } + }; + + this.handleEditVariables = function (value) { + _this6.setState({ variables: value }); + if (_this6.props.onEditVariables) { + _this6.props.onEditVariables(value); + } + }; + + this.handleEditOperationName = function (operationName) { + var onEditOperationName = _this6.props.onEditOperationName; + if (onEditOperationName) { + onEditOperationName(operationName); + } + }; + + this.handleHintInformationRender = function (elem) { + elem.addEventListener('click', _this6._onClickHintInformation); + + var _onRemoveFn = void 0; + elem.addEventListener('DOMNodeRemoved', _onRemoveFn = function onRemoveFn() { + elem.removeEventListener('DOMNodeRemoved', _onRemoveFn); + elem.removeEventListener('click', _this6._onClickHintInformation); + }); + }; + + this.handleEditorRunQuery = function () { + _this6._runQueryAtCursor(); + }; + + this._onClickHintInformation = function (event) { + if (event.target.className === 'typeName') { + var typeName = event.target.innerHTML; + var schema = _this6.state.schema; + if (schema) { + var type = schema.getType(typeName); + if (type) { + _this6.setState({ docExplorerOpen: true }, function () { + _this6.docExplorerComponent.showDoc(type); + }); + } + } + } + }; + + this.handleToggleDocs = function () { + if (typeof _this6.props.onToggleDocs === 'function') { + _this6.props.onToggleDocs(!_this6.state.docExplorerOpen); + } + _this6.setState({ docExplorerOpen: !_this6.state.docExplorerOpen }); + }; + + this.handleToggleHistory = function () { + if (typeof _this6.props.onToggleHistory === 'function') { + _this6.props.onToggleHistory(!_this6.state.historyPaneOpen); + } + _this6.setState({ historyPaneOpen: !_this6.state.historyPaneOpen }); + }; + + this.handleSelectHistoryQuery = function (query, variables, operationName) { + _this6.handleEditQuery(query); + _this6.handleEditVariables(variables); + _this6.handleEditOperationName(operationName); + }; + + this.handleResizeStart = function (downEvent) { + if (!_this6._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 = _reactDom2.default.findDOMNode(_this6.editorBarComponent); + var leftSize = moveEvent.clientX - (0, _elementPosition.getLeft)(editorBar) - offset; + var rightSize = editorBar.clientWidth - leftSize; + _this6.setState({ editorFlex: leftSize / rightSize }); + }; + + var onMouseUp = function (_onMouseUp) { + function onMouseUp() { + return _onMouseUp.apply(this, arguments); + } + + onMouseUp.toString = function () { + return _onMouseUp.toString(); + }; + + return onMouseUp; + }(function () { + document.removeEventListener('mousemove', onMouseMove); + document.removeEventListener('mouseup', onMouseUp); + onMouseMove = null; + onMouseUp = null; + }); + + document.addEventListener('mousemove', onMouseMove); + document.addEventListener('mouseup', onMouseUp); + }; + + this.handleResetResize = function () { + _this6.setState({ editorFlex: 1 }); + }; + + this.handleDocsResizeStart = function (downEvent) { + downEvent.preventDefault(); + + var hadWidth = _this6.state.docExplorerWidth; + var offset = downEvent.clientX - (0, _elementPosition.getLeft)(downEvent.target); + + var onMouseMove = function onMouseMove(moveEvent) { + if (moveEvent.buttons === 0) { + return onMouseUp(); + } + + var app = _reactDom2.default.findDOMNode(_this6); + var cursorPos = moveEvent.clientX - (0, _elementPosition.getLeft)(app) - offset; + var docsSize = app.clientWidth - cursorPos; + + if (docsSize < 100) { + _this6.setState({ docExplorerOpen: false }); + } else { + _this6.setState({ + docExplorerOpen: true, + docExplorerWidth: Math.min(docsSize, 650) + }); + } + }; + + var onMouseUp = function (_onMouseUp2) { + function onMouseUp() { + return _onMouseUp2.apply(this, arguments); + } + + onMouseUp.toString = function () { + return _onMouseUp2.toString(); + }; + + return onMouseUp; + }(function () { + if (!_this6.state.docExplorerOpen) { + _this6.setState({ docExplorerWidth: hadWidth }); + } + + document.removeEventListener('mousemove', onMouseMove); + document.removeEventListener('mouseup', onMouseUp); + onMouseMove = null; + onMouseUp = null; + }); + + document.addEventListener('mousemove', onMouseMove); + document.addEventListener('mouseup', onMouseUp); + }; + + this.handleDocsResetResize = function () { + _this6.setState({ + docExplorerWidth: DEFAULT_DOC_EXPLORER_WIDTH + }); + }; + + this.handleVariableResizeStart = function (downEvent) { + downEvent.preventDefault(); + + var didMove = false; + var wasOpen = _this6.state.variableEditorOpen; + var hadHeight = _this6.state.variableEditorHeight; + var offset = downEvent.clientY - (0, _elementPosition.getTop)(downEvent.target); + + var onMouseMove = function onMouseMove(moveEvent) { + if (moveEvent.buttons === 0) { + return onMouseUp(); + } + + didMove = true; + + var editorBar = _reactDom2.default.findDOMNode(_this6.editorBarComponent); + var topSize = moveEvent.clientY - (0, _elementPosition.getTop)(editorBar) - offset; + var bottomSize = editorBar.clientHeight - topSize; + if (bottomSize < 60) { + _this6.setState({ + variableEditorOpen: false, + variableEditorHeight: hadHeight + }); + } else { + _this6.setState({ + variableEditorOpen: true, + variableEditorHeight: bottomSize + }); + } + }; + + var onMouseUp = function (_onMouseUp3) { + function onMouseUp() { + return _onMouseUp3.apply(this, arguments); + } + + onMouseUp.toString = function () { + return _onMouseUp3.toString(); + }; + + return onMouseUp; + }(function () { + if (!didMove) { + _this6.setState({ variableEditorOpen: !wasOpen }); + } + + document.removeEventListener('mousemove', onMouseMove); + document.removeEventListener('mouseup', onMouseUp); + onMouseMove = null; + onMouseUp = null; + }); + + document.addEventListener('mousemove', onMouseMove); + document.addEventListener('mouseup', onMouseUp); + }; +}; + +GraphiQL.Logo = function GraphiQLLogo(props) { + return _react2.default.createElement( + 'div', + { className: 'title' }, + props.children || _react2.default.createElement( + 'span', + null, + 'Graph', + _react2.default.createElement( + 'em', + null, + 'i' + ), + 'QL' + ) + ); +}; + +// Configure the UI by providing this Component as a child of GraphiQL. +GraphiQL.Toolbar = function GraphiQLToolbar(props) { + return _react2.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 _react2.default.createElement( + 'div', + { className: 'footer' }, + props.children + ); +}; + +var defaultQuery = '# Welcome to GraphiQL\n#\n# GraphiQL is an in-browser tool for writing, validating, and\n# testing GraphQL queries.\n#\n# Type queries into this side of the screen, and you will see intelligent\n# typeaheads aware of the current GraphQL type schema and live syntax and\n# validation errors highlighted within the text.\n#\n# GraphQL queries typically start with a "{" character. Lines that starts\n# with a # are ignored.\n#\n# An example GraphQL query might look like:\n#\n# {\n# field(arg: "value") {\n# subField\n# }\n# }\n#\n# Keyboard shortcuts:\n#\n# Prettify Query: Shift-Ctrl-P (or press the prettify button above)\n#\n# Run Query: Ctrl-Enter (or press the play button above)\n#\n# Auto Complete: Ctrl-Space (or just start typing)\n#\n\n'; + +// Duck-type promise detection. +function isPromise(value) { + return (typeof value === 'undefined' ? 'undefined' : _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 === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && typeof value.subscribe === 'function'; +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utility/CodeMirrorSizer":22,"../utility/StorageAPI":24,"../utility/debounce":25,"../utility/elementPosition":26,"../utility/fillLeafs":27,"../utility/find":28,"../utility/getQueryFacts":29,"../utility/getSelectedOperationName":30,"../utility/introspectionQueries":31,"./DocExplorer":1,"./ExecuteButton":10,"./QueryEditor":13,"./QueryHistory":14,"./ResultViewer":15,"./ToolbarButton":16,"./ToolbarGroup":17,"./ToolbarMenu":18,"./ToolbarSelect":19,"./VariableEditor":20,"graphql":92,"prop-types":172}],12:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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 HistoryQuery = function (_React$Component) { + _inherits(HistoryQuery, _React$Component); + + function HistoryQuery(props) { + _classCallCheck(this, HistoryQuery); + + var _this = _possibleConstructorReturn(this, (HistoryQuery.__proto__ || Object.getPrototypeOf(HistoryQuery)).call(this, props)); + + var starVisibility = _this.props.favorite ? 'visible' : 'hidden'; + _this.state = { starVisibility: starVisibility }; + return _this; + } + + _createClass(HistoryQuery, [{ + key: 'render', + value: function render() { + if (this.props.favorite && this.state.starVisibility === 'hidden') { + this.setState({ starVisibility: 'visible' }); + } + var starStyles = { + float: 'right', + visibility: this.state.starVisibility + }; + var displayName = this.props.operationName || this.props.query.split('\n').filter(function (line) { + return line.indexOf('#') !== 0; + }).join(''); + var starIcon = this.props.favorite ? '\u2605' : '\u2606'; + return _react2.default.createElement( + 'p', + { + onClick: this.handleClick.bind(this), + onMouseEnter: this.handleMouseEnter.bind(this), + onMouseLeave: this.handleMouseLeave.bind(this) }, + _react2.default.createElement( + 'span', + null, + displayName + ), + _react2.default.createElement( + 'span', + { onClick: this.handleStarClick.bind(this), style: starStyles }, + starIcon + ) + ); + } + }, { + key: 'handleMouseEnter', + value: function handleMouseEnter() { + if (!this.props.favorite) { + this.setState({ starVisibility: 'visible' }); + } + } + }, { + key: 'handleMouseLeave', + value: function handleMouseLeave() { + if (!this.props.favorite) { + this.setState({ starVisibility: 'hidden' }); + } + } + }, { + key: 'handleClick', + value: function handleClick() { + this.props.onSelect(this.props.query, this.props.variables, this.props.operationName); + } + }, { + key: 'handleStarClick', + value: function handleStarClick(e) { + e.stopPropagation(); + this.props.handleToggleFavorite(this.props.query, this.props.variables, this.props.operationName, this.props.favorite); + } + }]); + + return HistoryQuery; +}(_react2.default.Component); + +HistoryQuery.propTypes = { + favorite: _propTypes2.default.bool, + favoriteSize: _propTypes2.default.number, + handleToggleFavorite: _propTypes2.default.func, + operationName: _propTypes2.default.string, + onSelect: _propTypes2.default.func, + query: _propTypes2.default.string, + variables: _propTypes2.default.string +}; +exports.default = HistoryQuery; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"prop-types":172}],13:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.QueryEditor = undefined; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _graphql = require('graphql'); + +var _marked = require('marked'); + +var _marked2 = _interopRequireDefault(_marked); + +var _normalizeWhitespace = require('../utility/normalizeWhitespace'); + +var _onHasCompletion = require('../utility/onHasCompletion'); + +var _onHasCompletion2 = _interopRequireDefault(_onHasCompletion); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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 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. + * + */ + +var QueryEditor = exports.QueryEditor = function (_React$Component) { + _inherits(QueryEditor, _React$Component); + + function QueryEditor(props) { + _classCallCheck(this, QueryEditor); + + // 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. + var _this = _possibleConstructorReturn(this, (QueryEditor.__proto__ || Object.getPrototypeOf(QueryEditor)).call(this)); + + _this._onKeyUp = function (cm, event) { + if (AUTO_COMPLETE_AFTER_KEY.test(event.key)) { + _this.editor.execCommand('autocomplete'); + } + }; + + _this._onEdit = function () { + if (!_this.ignoreChangeEvent) { + _this.cachedValue = _this.editor.getValue(); + if (_this.props.onEdit) { + _this.props.onEdit(_this.cachedValue); + } + } + }; + + _this._onHasCompletion = function (cm, data) { + (0, _onHasCompletion2.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/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, + foldGutter: { + minFoldSize: 4 + }, + lint: { + schema: this.props.schema + }, + hintOptions: { + schema: this.props.schema, + closeOnUnfocus: false, + completeSingle: false + }, + info: { + schema: this.props.schema, + renderDescription: function renderDescription(text) { + return (0, _marked2.default)(text, { sanitize: true }); + }, + 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 }); + }, + 'Ctrl-Space': function CtrlSpace() { + return _this2.editor.showHint({ completeSingle: true }); + }, + 'Alt-Space': function AltSpace() { + return _this2.editor.showHint({ completeSingle: true }); + }, + 'Shift-Space': function ShiftSpace() { + return _this2.editor.showHint({ completeSingle: true }); + }, + + '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(); + } + }, + + // 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 _react2.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; + } + + /** + * Render a custom UI for CodeMirror's hint which includes additional info + * about the type and description for the selected context. + */ + + }, { + 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; +}(_react2.default.Component); + +QueryEditor.propTypes = { + schema: _propTypes2.default.instanceOf(_graphql.GraphQLSchema), + value: _propTypes2.default.string, + onEdit: _propTypes2.default.func, + onHintInformationRender: _propTypes2.default.func, + onClickReference: _propTypes2.default.func, + onPrettifyQuery: _propTypes2.default.func, + onRunQuery: _propTypes2.default.func, + editorTheme: _propTypes2.default.string +}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utility/normalizeWhitespace":32,"../utility/onHasCompletion":33,"codemirror":63,"codemirror-graphql/hint":35,"codemirror-graphql/info":36,"codemirror-graphql/jump":37,"codemirror-graphql/lint":38,"codemirror-graphql/mode":39,"codemirror/addon/comment/comment":51,"codemirror/addon/edit/closebrackets":53,"codemirror/addon/edit/matchbrackets":54,"codemirror/addon/fold/brace-fold":55,"codemirror/addon/fold/foldgutter":57,"codemirror/addon/hint/show-hint":58,"codemirror/addon/lint/lint":59,"codemirror/keymap/sublime":62,"graphql":92,"marked":167,"prop-types":172}],14:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.QueryHistory = undefined; + +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; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _graphql = require('graphql'); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _QueryStore = require('../utility/QueryStore'); + +var _QueryStore2 = _interopRequireDefault(_QueryStore); + +var _HistoryQuery = require('./HistoryQuery'); + +var _HistoryQuery2 = _interopRequireDefault(_HistoryQuery); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +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 = exports.QueryHistory = function (_React$Component) { + _inherits(QueryHistory, _React$Component); + + function QueryHistory(props) { + _classCallCheck(this, QueryHistory); + + var _this = _possibleConstructorReturn(this, (QueryHistory.__proto__ || Object.getPrototypeOf(QueryHistory)).call(this, props)); + + _initialiseProps.call(_this); + + _this.historyStore = new _QueryStore2.default('queries', props.storage); + _this.favoriteStore = new _QueryStore2.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 _react2.default.createElement(_HistoryQuery2.default, _extends({ + handleToggleFavorite: _this2.toggleFavorite, + key: i, + onSelect: _this2.props.onSelectQuery + }, query)); + }); + return _react2.default.createElement( + 'div', + null, + _react2.default.createElement( + 'div', + { className: 'history-title-bar' }, + _react2.default.createElement( + 'div', + { className: 'history-title' }, + 'History' + ), + _react2.default.createElement( + 'div', + { className: 'doc-explorer-rhs' }, + this.props.children + ) + ), + _react2.default.createElement( + 'div', + { className: 'history-contents' }, + queryNodes + ) + ); + } + }]); + + return QueryHistory; +}(_react2.default.Component); + +QueryHistory.propTypes = { + query: _propTypes2.default.string, + variables: _propTypes2.default.string, + operationName: _propTypes2.default.string, + queryID: _propTypes2.default.number, + onSelectQuery: _propTypes2.default.func, + storage: _propTypes2.default.object +}; + +var _initialiseProps = function _initialiseProps() { + var _this3 = this; + + this.toggleFavorite = function (query, variables, operationName, favorite) { + var item = { + query: query, + variables: variables, + operationName: operationName + }; + if (!_this3.favoriteStore.contains(item)) { + item.favorite = true; + _this3.favoriteStore.push(item); + } else if (favorite) { + item.favorite = false; + _this3.favoriteStore.delete(item); + } + var historyQueries = _this3.historyStore.items; + var favoriteQueries = _this3.favoriteStore.items; + var queries = historyQueries.concat(favoriteQueries); + _this3.setState({ queries: queries }); + }; +}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utility/QueryStore":23,"./HistoryQuery":12,"graphql":92,"prop-types":172}],15:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ResultViewer = undefined; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _reactDom = (typeof window !== "undefined" ? window['ReactDOM'] : typeof global !== "undefined" ? global['ReactDOM'] : null); + +var _reactDom2 = _interopRequireDefault(_reactDom); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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. + */ + +/** + * ResultViewer + * + * Maintains an instance of CodeMirror for viewing a GraphQL response. + * + * Props: + * + * - value: The text of the editor. + * + */ +var ResultViewer = exports.ResultViewer = function (_React$Component) { + _inherits(ResultViewer, _React$Component); + + function ResultViewer() { + _classCallCheck(this, ResultViewer); + + return _possibleConstructorReturn(this, (ResultViewer.__proto__ || Object.getPrototypeOf(ResultViewer)).call(this)); + } + + _createClass(ResultViewer, [{ + 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/fold/foldgutter'); + require('codemirror/addon/fold/brace-fold'); + require('codemirror/addon/dialog/dialog'); + require('codemirror/addon/search/search'); + require('codemirror/keymap/sublime'); + require('codemirror-graphql/results/mode'); + + if (this.props.ResultsTooltip) { + require('codemirror-graphql/utils/info-addon'); + var tooltipDiv = document.createElement('div'); + CodeMirror.registerHelper('info', 'graphql-results', function (token, options, cm, pos) { + var Tooltip = _this2.props.ResultsTooltip; + _reactDom2.default.render(_react2.default.createElement(Tooltip, { pos: pos }), 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), + extraKeys: { + // 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 _this3 = this; + + return _react2.default.createElement('div', { + className: 'result-window', + 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.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; +}(_react2.default.Component); + +ResultViewer.propTypes = { + value: _propTypes2.default.string, + editorTheme: _propTypes2.default.string, + ResultsTooltip: _propTypes2.default.any +}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"codemirror":63,"codemirror-graphql/results/mode":40,"codemirror-graphql/utils/info-addon":45,"codemirror/addon/dialog/dialog":52,"codemirror/addon/fold/brace-fold":55,"codemirror/addon/fold/foldgutter":57,"codemirror/addon/search/search":60,"codemirror/keymap/sublime":62,"prop-types":172}],16:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ToolbarButton = undefined; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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. + */ + +/** + * ToolbarButton + * + * A button to use within the Toolbar. + */ +var ToolbarButton = exports.ToolbarButton = function (_React$Component) { + _inherits(ToolbarButton, _React$Component); + + function ToolbarButton(props) { + _classCallCheck(this, ToolbarButton); + + var _this = _possibleConstructorReturn(this, (ToolbarButton.__proto__ || Object.getPrototypeOf(ToolbarButton)).call(this, props)); + + _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 _react2.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; +}(_react2.default.Component); + +ToolbarButton.propTypes = { + onClick: _propTypes2.default.func, + title: _propTypes2.default.string, + label: _propTypes2.default.string +}; + + +function preventDefault(e) { + e.preventDefault(); +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"prop-types":172}],17:[function(require,module,exports){ +(function (global){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ToolbarGroup = ToolbarGroup; + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * ToolbarGroup + * + * A group of associated controls. + */ +function ToolbarGroup(_ref) { + var children = _ref.children; + + return _react2.default.createElement( + "div", + { className: "toolbar-button-group" }, + children + ); +} /** + * 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. + */ +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],18:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ToolbarMenu = undefined; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +exports.ToolbarMenuItem = ToolbarMenuItem; + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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. + */ + +/** + * ToolbarMenu + * + * A menu style button to use within the Toolbar. + */ +var ToolbarMenu = exports.ToolbarMenu = function (_React$Component) { + _inherits(ToolbarMenu, _React$Component); + + function ToolbarMenu(props) { + _classCallCheck(this, ToolbarMenu); + + var _this = _possibleConstructorReturn(this, (ToolbarMenu.__proto__ || Object.getPrototypeOf(ToolbarMenu)).call(this, props)); + + _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 _react2.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, + _react2.default.createElement( + 'svg', + { width: '14', height: '8' }, + _react2.default.createElement('path', { fill: '#666', d: 'M 5 1.5 L 14 1.5 L 9.5 7 z' }) + ), + _react2.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; +}(_react2.default.Component); + +ToolbarMenu.propTypes = { + title: _propTypes2.default.string, + label: _propTypes2.default.string +}; +function ToolbarMenuItem(_ref) { + var onSelect = _ref.onSelect, + title = _ref.title, + label = _ref.label; + + return _react2.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: _propTypes2.default.func, + title: _propTypes2.default.string, + label: _propTypes2.default.string +}; + +function preventDefault(e) { + e.preventDefault(); +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"prop-types":172}],19:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ToolbarSelect = undefined; + +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; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +exports.ToolbarSelectOption = ToolbarSelectOption; + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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. + */ + +/** + * ToolbarSelect + * + * A select-option style button to use within the Toolbar. + * + */ + +var ToolbarSelect = exports.ToolbarSelect = function (_React$Component) { + _inherits(ToolbarSelect, _React$Component); + + function ToolbarSelect(props) { + _classCallCheck(this, ToolbarSelect); + + var _this = _possibleConstructorReturn(this, (ToolbarSelect.__proto__ || Object.getPrototypeOf(ToolbarSelect)).call(this, props)); + + _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 = void 0; + var visible = this.state.visible; + var optionChildren = _react2.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 _react2.default.createElement(ToolbarSelectOption, _extends({}, child.props, { onSelect: onChildSelect })); + }); + return _react2.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, + _react2.default.createElement( + 'svg', + { width: '13', height: '10' }, + _react2.default.createElement('path', { fill: '#666', d: 'M 5 5 L 13 5 L 9 1 z' }), + _react2.default.createElement('path', { fill: '#666', d: 'M 5 6 L 13 6 L 9 10 z' }) + ), + _react2.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; +}(_react2.default.Component); + +ToolbarSelect.propTypes = { + title: _propTypes2.default.string, + label: _propTypes2.default.string, + onSelect: _propTypes2.default.func +}; +function ToolbarSelectOption(_ref) { + var onSelect = _ref.onSelect, + label = _ref.label, + selected = _ref.selected; + + return _react2.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 && _react2.default.createElement( + 'svg', + { width: '13', height: '13' }, + _react2.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: _propTypes2.default.func, + selected: _propTypes2.default.bool, + label: _propTypes2.default.string, + value: _propTypes2.default.any +}; + +function preventDefault(e) { + e.preventDefault(); +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"prop-types":172}],20:[function(require,module,exports){ +(function (global){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.VariableEditor = undefined; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null); + +var _react2 = _interopRequireDefault(_react); + +var _propTypes = require('prop-types'); + +var _propTypes2 = _interopRequireDefault(_propTypes); + +var _onHasCompletion = require('../utility/onHasCompletion'); + +var _onHasCompletion2 = _interopRequireDefault(_onHasCompletion); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** + * 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. + */ + +/** + * 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. + * + */ +var VariableEditor = exports.VariableEditor = function (_React$Component) { + _inherits(VariableEditor, _React$Component); + + function VariableEditor(props) { + _classCallCheck(this, VariableEditor); + + // 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. + var _this = _possibleConstructorReturn(this, (VariableEditor.__proto__ || Object.getPrototypeOf(VariableEditor)).call(this)); + + _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'); + } + }; + + _this._onEdit = function () { + if (!_this.ignoreChangeEvent) { + _this.cachedValue = _this.editor.getValue(); + if (_this.props.onEdit) { + _this.props.onEdit(_this.cachedValue); + } + } + }; + + _this._onHasCompletion = function (cm, data) { + (0, _onHasCompletion2.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/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, + foldGutter: { + minFoldSize: 4 + }, + lint: { + variableToType: this.props.variableToType + }, + hintOptions: { + variableToType: this.props.variableToType + }, + gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'], + extraKeys: { + 'Cmd-Space': function CmdSpace() { + return _this2.editor.showHint({ completeSingle: false }); + }, + 'Ctrl-Space': function CtrlSpace() { + return _this2.editor.showHint({ completeSingle: false }); + }, + 'Alt-Space': function AltSpace() { + return _this2.editor.showHint({ completeSingle: false }); + }, + 'Shift-Space': function ShiftSpace() { + return _this2.editor.showHint({ completeSingle: false }); + }, + + '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(); + } + }, + + // 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) { + 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 _react2.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; +}(_react2.default.Component); + +VariableEditor.propTypes = { + variableToType: _propTypes2.default.object, + value: _propTypes2.default.string, + onEdit: _propTypes2.default.func, + onHintInformationRender: _propTypes2.default.func, + onPrettifyQuery: _propTypes2.default.func, + onRunQuery: _propTypes2.default.func, + editorTheme: _propTypes2.default.string +}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../utility/onHasCompletion":33,"codemirror":63,"codemirror-graphql/variables/hint":48,"codemirror-graphql/variables/lint":49,"codemirror-graphql/variables/mode":50,"codemirror/addon/edit/closebrackets":53,"codemirror/addon/edit/matchbrackets":54,"codemirror/addon/fold/brace-fold":55,"codemirror/addon/fold/foldgutter":57,"codemirror/addon/hint/show-hint":58,"codemirror/addon/lint/lint":59,"codemirror/keymap/sublime":62,"prop-types":172}],21:[function(require,module,exports){ +'use strict'; + +/** + * 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. + */ + +// The primary React component to use. +module.exports = require('./components/GraphiQL').GraphiQL; +},{"./components/GraphiQL":11}],22:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +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. + */ + +/** + * 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 = 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; +},{}],23:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +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"); } } + +var QueryStore = 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: "delete", + value: function _delete(item) { + var index = this.items.findIndex(function (x) { + return x.query === item.query && x.variables === item.variables && x.operationName === item.operationName; + }); + if (index !== -1) { + this.items.splice(index, 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; +},{}],24:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +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 StorageAPI = 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:' + 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; + } +} +},{}],25:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = debounce; +/** + * 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. + */ + +/** + * 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 = void 0; + return function () { + var _this = this, + _arguments = arguments; + + clearTimeout(timeout); + timeout = setTimeout(function () { + timeout = null; + fn.apply(_this, _arguments); + }, duration); + }; +} +},{}],26:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getLeft = getLeft; +exports.getTop = getTop; +/** + * 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. + */ + +/** + * 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; +} +},{}],27:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fillLeafs = fillLeafs; + +var _graphql = require('graphql'); + +/** + * 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 = void 0; + 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. +/** + * 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 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":92}],28:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = find; + +/* eslint-disable no-undef */ +/** + * 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 find(list, predicate) { + for (var i = 0; i < list.length; i++) { + if (predicate(list[i])) { + return list[i]; + } + } +} +},{}],29:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = getQueryFacts; +exports.collectVariables = collectVariables; + +var _graphql = require('graphql'); + +/** + * 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 = void 0; + 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. + */ +/** + * 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 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":92}],30:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = getSelectedOperationName; +/** + * 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. + */ + +/** + * 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]; +} +},{}],31:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _graphql = require('graphql'); + +Object.defineProperty(exports, 'introspectionQuery', { + enumerable: true, + get: function get() { + return _graphql.introspectionQuery; + } +}); + + +// 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. +var introspectionQuerySansSubscriptions = exports.introspectionQuerySansSubscriptions = '\n query IntrospectionQuery {\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'; +},{"graphql":92}],32:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.normalizeWhitespace = normalizeWhitespace; +/** + * 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. + */ + +// Unicode whitespace characters that break the interface. +var invalidCharacters = exports.invalidCharacters = Array.from({ length: 11 }, function (x, i) { + // \u2000 -> \u200a + return String.fromCharCode(0x2000 + i); +}).concat(['\u2028', '\u2029', '\u202F']); + +var sanitizeRegex = new RegExp('[' + invalidCharacters.join('|') + ']', 'g'); + +function normalizeWhitespace(line) { + return line.replace(sanitizeRegex, ' '); +} +},{}],33:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = onHasCompletion; + +var _graphql = require('graphql'); + +var _marked = require('marked'); + +var _marked2 = _interopRequireDefault(_marked); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Render a custom UI for CodeMirror's hint which includes additional info + * about the type and description for the selected context. + */ +/** + * 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 onHasCompletion(cm, data, onHintInformationRender) { + var CodeMirror = require('codemirror'); + + var information = void 0; + var deprecation = void 0; + + // 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 = void 0; + 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 ? (0, _marked2.default)(ctx.description, { sanitize: true }) : 'Self descriptive.'; + var type = ctx.type ? '' + renderType(ctx.type) + '' : ''; + + information.innerHTML = '
' + (description.slice(0, 3) === '

' ? '

' + type + description.slice(3) : type + description) + '

'; + + if (ctx.isDeprecated) { + var reason = ctx.deprecationReason ? (0, _marked2.default)(ctx.deprecationReason, { sanitize: true }) : ''; + deprecation.innerHTML = 'Deprecated' + 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 renderType(type.ofType) + '!'; + } + if (type instanceof _graphql.GraphQLList) { + return '[' + renderType(type.ofType) + ']'; + } + return '' + type.name + ''; +} +},{"codemirror":63,"graphql":92,"marked":167}],34:[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 + * @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/":176}],35:[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":63,"graphql-language-service-interface":73}],36:[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":41,"./utils/getTypeInfo":43,"./utils/info-addon":45,"codemirror":63,"graphql":92}],37:[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":41,"./utils/getTypeInfo":43,"./utils/jump-addon":47,"codemirror":63}],38:[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":63,"graphql-language-service-interface":73}],39:[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":63,"graphql-language-service-parser":77}],40:[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":63,"graphql-language-service-parser":77}],41:[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":92}],42:[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]); + } +} +},{}],43:[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":42,"graphql":92,"graphql/type/introspection":115}],44:[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]; +} +},{}],45:[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); + 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":63}],46:[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 +} +},{}],47:[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":63}],48:[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":42,"../utils/hintList":44,"codemirror":63,"graphql":92}],49:[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":46,"codemirror":63,"graphql":92}],50:[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":63,"graphql-language-service-parser":77}],51:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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); + if (close == -1 && start != end) { + endLine = self.getLine(--end); + close = endLine.indexOf(endString); + } + 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":63}],52:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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); + } + 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; + 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; + 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); + 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":63}],53:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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: "()[]{}''\"\"", + 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) { + 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 bind = defaults.pairs + "`"; + var keyMap = {Backspace: handleBackspace, Enter: handleEnter}; + for (var i = 0; i < bind.length; i++) + keyMap["'" + bind.charAt(i) + "'"] = handler(bind.charAt(i)); + + 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() { + cm.replaceSelection("\n\n", 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 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 && + (cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != ch)) { + curType = "addFour"; + } else if (identical) { + if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, ch)) curType = "both"; + else return CodeMirror.Pass; + } else if (opening && (cm.getLine(cur.line).length == cur.ch || + isClosingBracket(next, pairs) || + /\s/.test(next))) { + 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 isClosingBracket(ch, pairs) { + var pos = pairs.lastIndexOf(ch); + return pos > -1 && pos % 2 == 1; + } + + 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; + } + + // Project the token type that will exists after the given char is + // typed, and use it to determine whether it would cause the start + // of a string token. + function enteringString(cm, pos, ch) { + var line = cm.getLine(pos.line); + var token = cm.getTokenAt(pos); + if (/\bstring2?\b/.test(token.type) || stringStartsAfter(cm, pos)) return false; + var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4); + stream.pos = stream.start = token.start; + for (;;) { + var type1 = cm.getMode().token(stream, token.state); + if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1); + stream.start = stream.pos; + } + } + + function stringStartsAfter(cm, pos) { + var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)) + return /\bstring/.test(token.type) && token.start == pos.ch + } +}); + +},{"../../lib/codemirror":63}],54:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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 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) + + // 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 && matching[line.text.charAt(pos)]) || + 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 = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/; + 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.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; + } + } + + var currentlyHighlighted = null; + function doMatchBrackets(cm) { + cm.operation(function() { + if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} + 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 (currentlyHighlighted) {currentlyHighlighted(); 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":63}],55:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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 && endCh == startCh) 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":63}],56:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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"; + } + 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":63}],57:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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":63,"./foldcode":56}],58:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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); + }); + + 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(); + + if (data && this.data && isNewCompletion(this.data, data)) return; + 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 isNewCompletion(old, nw) { + var moved = CodeMirror.cmpPos(nw.from, old.from) + return moved > 0 && old.to.ch - old.from.ch != nw.to.ch - nw.from.ch + } + + 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 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 hints = this.hints = document.createElement("ul"); + hints.className = "CodeMirror-hints"; + this.selectedHint = data.selectedHint || 0; + + var completions = data.list; + for (var i = 0; i < completions.length; ++i) { + var elt = hints.appendChild(document.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(document.createTextNode(cur.displayText || getText(cur))); + elt.hintId = i; + } + + var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); + var left = pos.left, top = pos.bottom, below = true; + hints.style.left = left + "px"; + hints.style.top = top + "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 = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); + var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); + (completion.options.container || document.body).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) + "px"; + below = false; + } else if (height > winH) { + hints.style.height = (winH - 5) + "px"; + hints.style.top = (top = pos.bottom - box.top) + "px"; + var cursor = cm.getCursor(); + if (data.from.ch != cursor.ch) { + pos = cm.cursorCoords(cursor); + hints.style.left = (left = pos.left) + "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) + "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 - (window.pageYOffset || (document.documentElement || document.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[0], hints.firstChild); + 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]; + 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 to = CodeMirror.Pos(cur.line, token.end); + if (token.string && /\w/.test(token.string[token.string.length - 1])) { + var term = token.string, from = CodeMirror.Pos(cur.line, token.start); + } else { + var term = "", from = to; + } + 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":63}],59:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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; + 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 + updateLinting(cm, annotations) + }, passOptions, cm); + } + + function startLinting(cm) { + var state = cm.state.lint, options = state.options; + var passOptions = options.options || options; // Support deprecated passing of `options` property in 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) { + updateLinting(cm, issues); + }); + else 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":63}],60:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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; + } + + var queryDialog = + 'Search: (Use /re/ syntax for regexp search)'; + + 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 (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, queryDialog, q, searchNext, function(event, query) { + var keyName = CodeMirror.keyName(event) + var cmd = CodeMirror.keyMap[cm.getOption("keyMap")][keyName] + if (!cmd) cmd = cm.getOption('extraKeys')[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, queryDialog, "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; } + });} + + var replaceQueryDialog = + ' (Use /re/ syntax for regexp search)'; + var replacementQueryDialog = 'With: '; + var doReplaceConfirm = 'Replace? '; + + 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 = '' + (all ? 'Replace all:' : 'Replace:') + ''; + dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) { + if (!query) return; + query = parseQuery(query); + dialog(cm, replacementQueryDialog, "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, doReplaceConfirm, "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":63,"../dialog/dialog":52,"./searchcursor":61}],61:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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 ensureGlobal(regexp) { + return regexp.global ? regexp : new RegExp(regexp.source, regexpFlags(regexp) + "g") + } + + function maybeMultiline(regexp) { + return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source) + } + + function searchRegexpForward(doc, regexp, start) { + regexp = ensureGlobal(regexp) + 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 = ensureGlobal(regexp) + 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++) { + 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 = ensureGlobal(regexp) + 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 = ensureGlobal(regexp) + 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) { + if (orig.length == folded.length) return pos + for (var pos1 = Math.min(pos, orig.length);;) { + var len1 = orig.slice(0, pos1).toLowerCase().length + if (len1 < pos) ++pos1 + else if (len1 > pos) --pos1 + else return pos1 + } + } + + 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) + ch + return {from: Pos(line, adjustPos(orig, string, found) + ch), + to: Pos(line, adjustPos(orig, string, found + lines[0].length) + 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 (end.slice(0, lastLine.length) != lastLine) continue search + return {from: Pos(line, adjustPos(orig, string, cutFrom) + ch), + to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length))} + } + } + } + + 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)), + to: Pos(line, adjustPos(orig, string, found + lines[0].length))} + } 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)), + to: Pos(line, adjustPos(orig, string, lastLine.length))} + } + } + } + + 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 = ensureGlobal(query) + 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":63}],62:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://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 map = CodeMirror.keyMap.sublime = {fallthrough: "default"}; + var cmds = CodeMirror.commands; + var Pos = CodeMirror.Pos; + var mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault; + var ctrl = mac ? "Cmd-" : "Ctrl-"; + + // 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(); + }); + } + + var goSubwordCombo = mac ? "Ctrl-" : "Alt-"; + + cmds[map[goSubwordCombo + "Left"] = "goSubwordLeft"] = function(cm) { moveSubword(cm, -1); }; + cmds[map[goSubwordCombo + "Right"] = "goSubwordRight"] = function(cm) { moveSubword(cm, 1); }; + + if (mac) map["Cmd-Left"] = "goLineStartSmart"; + + var scrollLineCombo = mac ? "Ctrl-Alt-" : "Ctrl-"; + + cmds[map[scrollLineCombo + "Up"] = "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[map[scrollLineCombo + "Down"] = "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[map["Shift-" + ctrl + "L"] = "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); + }; + + map["Shift-Tab"] = "indentLess"; + + cmds[map["Esc"] = "singleSelectionTop"] = function(cm) { + var range = cm.listSelections()[0]; + cm.setSelection(range.anchor, range.head, {scroll: false}); + }; + + cmds[map[ctrl + "L"] = "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); + }; + + map["Shift-Ctrl-K"] = "deleteLine"; + + 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[map[ctrl + "Enter"] = "insertLineAfter"] = function(cm) { return insertLine(cm, false); }; + + cmds[map["Shift-" + ctrl + "Enter"] = "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[map[ctrl + "D"] = "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 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)) { + newRanges.push({anchor: Pos(opening.pos.line, opening.pos.ch + 1), + head: closing.pos}); + break; + } + pos = Pos(closing.pos.line, closing.pos.ch + 1); + } + } + cm.setSelections(newRanges); + return true; + } + + cmds[map["Shift-" + ctrl + "Space"] = "selectScope"] = function(cm) { + selectBetweenBrackets(cm) || cm.execCommand("selectAll"); + }; + cmds[map["Shift-" + ctrl + "M"] = "selectBetweenBrackets"] = function(cm) { + if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; + }; + + cmds[map[ctrl + "M"] = "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; + }); + }; + + var swapLineCombo = mac ? "Cmd-Ctrl-" : "Shift-Ctrl-"; + + cmds[map[swapLineCombo + "Up"] = "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[map[swapLineCombo + "Down"] = "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[map[ctrl + "/"] = "toggleCommentIndented"] = function(cm) { + cm.toggleComment({ indent: true }); + } + + cmds[map[ctrl + "J"] = "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[map["Shift-" + ctrl + "D"] = "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(); + }); + }; + + if (!mac) map[ctrl + "T"] = "transposeChars"; + + 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[map["F9"] = "sortLines"] = function(cm) { sortLines(cm, true); }; + cmds[map[ctrl + "F9"] = "sortLinesInsensitive"] = function(cm) { sortLines(cm, false); }; + + cmds[map["F2"] = "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[map["Shift-F2"] = "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[map[ctrl + "F2"] = "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 = 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[map["Shift-" + ctrl + "F2"] = "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[map["Alt-F2"] = "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); + }; + + map["Alt-Q"] = "wrapLines"; + + var cK = ctrl + "K "; + + 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); + } + }); + } + + map[cK + ctrl + "Backspace"] = "delLineLeft"; + + cmds[map["Backspace"] = "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[map[cK + ctrl + "K"] = "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[map[cK + ctrl + "U"] = "upcaseAtCursor"] = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); }); + }; + cmds[map[cK + ctrl + "L"] = "downcaseAtCursor"] = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); }); + }; + + cmds[map[cK + ctrl + "Space"] = "setSublimeMark"] = function(cm) { + if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + }; + cmds[map[cK + ctrl + "A"] = "selectToSublimeMark"] = function(cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) cm.setSelection(cm.getCursor(), found); + }; + cmds[map[cK + ctrl + "W"] = "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[map[cK + ctrl + "X"] = "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[map[cK + ctrl + "Y"] = "sublimeYank"] = function(cm) { + if (cm.state.sublimeKilled != null) + cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); + }; + + map[cK + ctrl + "G"] = "clearBookmarks"; + cmds[map[cK + ctrl + "C"] = "showInCenter"] = function(cm) { + var pos = cm.cursorCoords(null, "local"); + cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); + }; + + var selectLinesCombo = mac ? "Ctrl-Shift-" : "Ctrl-Alt-"; + cmds[map[selectLinesCombo + "Up"] = "selectLinesUpward"] = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line > cm.firstLine()) + cm.addSelection(Pos(range.head.line - 1, range.head.ch)); + } + }); + }; + cmds[map[selectLinesCombo + "Down"] = "selectLinesDownward"] = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line < cm.lastLine()) + cm.addSelection(Pos(range.head.line + 1, range.head.ch)); + } + }); + }; + + 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[map[ctrl + "F3"] = "findUnder"] = function(cm) { findAndGoTo(cm, true); }; + cmds[map["Shift-" + ctrl + "F3"] = "findUnderPrevious"] = function(cm) { findAndGoTo(cm,false); }; + cmds[map["Alt-F3"] = "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); + }; + + map["Shift-" + ctrl + "["] = "fold"; + map["Shift-" + ctrl + "]"] = "unfold"; + map[cK + ctrl + "0"] = map[cK + ctrl + "J"] = "unfoldAll"; + + map[ctrl + "I"] = "findIncremental"; + map["Shift-" + ctrl + "I"] = "findIncrementalReverse"; + map[ctrl + "H"] = "replace"; + map["F3"] = "findNext"; + map["Shift-F3"] = "findPrev"; + + CodeMirror.normalizeKeyMap(map); +}); + +},{"../addon/edit/matchbrackets":54,"../addon/search/searchcursor":61,"../lib/codemirror":63}],63:[function(require,module,exports){ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// This is CodeMirror (http://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}; +var sel_mouse = {origin: "*mouse"}; +var 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`. +function findFirst(pred, from, to) { + for (;;) { + if (Math.abs(from - to) <= 1) { return pred(from) ? from : to } + var mid = Math.floor((from + to) / 2); + if (pred(mid)) { to = mid; } + else { from = mid; } + } +} + +// 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) { + 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; + + input.init(d); +} + +// 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 +} + +// Optimize some code when these features are not used. +var sawReadOnlySpans = false; +var 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) } + +// 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; + } + }); +} + +// BIDI HELPERS + +function iterateBidiSections(order, from, to, f) { + if (!order) { return f(from, to, "ltr") } + 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"); + 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 (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 +} + +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) { + 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 +} + +// 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 = {}; +var 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) +}; + +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; +}; + +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.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.saved), 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 ) { + 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); + }; + + for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); + context.state = state; + + 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); +} + +// 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 = {}; +var 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: (ie || webkit) && 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, title, css) { + 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 (title) { token.title = title; } + return builder.content.appendChild(token) + } + builder.content.appendChild(content); +} + +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, title, css) { + 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, title, css) } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); + 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, title, collapsed; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = ""; + 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); } + if (m.title && !title) { title = m.title; } + 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 : "", title, css); + } + 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.options.gutters.length; ++k) { + var id = cm.options.gutters[k], 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 +} + +// 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 && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]); + rect.top += size; rect.bottom += size; + } } } + 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 % 2) != 0; + 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 merged = collapsedSpanAtEnd(lineObj); + var mergedPos = merged && merged.find(0, true); + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) + { lineN = lineNo(lineObj = mergedPos.to.line); } + else + { return found } + } +} + +function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { + var measure = function (ch) { return intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); }; + var end = lineObj.text.length; + var begin = findFirst(function (ch) { return measure(ch - 1).bottom <= y; }, end, 0); + end = findFirst(function (ch) { return measure(ch).top > y; }, begin, end); + return {begin: begin, end: end} +} + +function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { + var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; + return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) +} + +function coordsCharInner(cm, lineObj, lineNo$$1, x, y) { + y -= heightAtLine(lineObj); + var begin = 0, end = lineObj.text.length; + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + var pos; + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + if (cm.options.lineWrapping) { + var assign; + ((assign = wrappedLineExtent(cm, lineObj, preparedMeasure, y), begin = assign.begin, end = assign.end, assign)); + } + pos = new Pos(lineNo$$1, Math.floor(begin + (end - begin) / 2)); + var beginLeft = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left; + var dir = beginLeft < x ? 1 : -1; + var prevDiff, diff = beginLeft - x, prevPos; + var steps = Math.ceil((end - begin) / 4); + outer: do { + prevDiff = diff; + prevPos = pos; + var i = 0; + for (; i < steps; ++i) { + var prevPos$1 = pos; + pos = moveVisually(cm, lineObj, pos, dir); + if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) { + pos = prevPos$1; + break outer + } + } + diff = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left - x; + if (steps > 1) { + var diff_change_per_step = Math.abs(diff - prevDiff) / steps; + steps = Math.min(steps, Math.ceil(Math.abs(diff) / diff_change_per_step)); + dir = diff < 0 ? 1 : -1; + } + } while (diff != 0 && (steps > 1 || ((dir < 0) != (diff < 0) && (Math.abs(diff) <= Math.abs(prevDiff))))) + if (Math.abs(diff) > Math.abs(prevDiff)) { + if ((diff < 0) == (prevDiff < 0)) { throw new Error("Broke out of infinite loop in coordsCharInner") } + pos = prevPos; + } + } else { + var ch = findFirst(function (ch) { + var box = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); + if (box.top > y) { + // For the cursor stickiness + end = Math.min(ch, end); + return true + } + else if (box.bottom <= y) { return false } + else if (box.left > x) { return true } + else if (box.right < x) { return false } + else { return (x - box.left < box.right - x) } + }, begin, end); + ch = skipExtendingChars(lineObj.text, ch, 1); + pos = new Pos(lineNo$$1, ch, ch == end ? "before" : "after"); + } + var coords = cursorCoords(cm, pos, "line", lineObj, preparedMeasure); + if (y < coords.top || coords.bottom < y) { pos.outside = true; } + pos.xRel = x < coords.left ? -1 : (x > coords.right ? 1 : 0); + return pos +} + +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) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; + width[cm.options.gutters[i]] = 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 } + } +} + +function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); +} + +function prepareSelection(cm, primary) { + 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 === false && 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"; + } +} + +// 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; + + 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) + } + + iterateBidiSections(getOrder(lineObj, doc.direction), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right; + if (from == to) { + rightPos = leftPos; + left = right = leftPos.left; + } else { + rightPos = coords(to - 1, "right"); + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } + left = leftPos.left; + right = rightPos.right; + } + if (fromArg == null && from == 0) { left = leftSide; } + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom); + left = leftSide; + if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top); } + } + if (toArg == null && to == lineLen) { right = rightSide; } + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) + { start = leftPos; } + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) + { end = rightPos; } + if (left < leftSide + 1) { left = leftSide; } + add(left, rightPos.top, right - left, rightPos.bottom); + }); + 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], height = (void 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; + } + var diff = cur.line.height - height; + if (height < 2) { height = textHeight(display); } + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) + { updateWidgetHeight(cur.rest[j]); } } + } + } +} + +// 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) + { line.widgets[i].height = line.widgets[i].node.parentNode.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)} +} + +// 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); + return true + } + return false +} + +// 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; + 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(), from = cur, to = cur; + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; + to = Pos(cur.line, cur.ch + 1); + } + cm.curOp.scrollToPos = {from: from, to: to, 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"); + 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: null, // 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; + 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(op.focus); } +} + +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() && (!document.hasFocus || document.hasFocus()); + 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); } + } +} + +// 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 +} + +// 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(cm) { + var width = cm.display.gutters.offsetWidth; + cm.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"; +} + +// Rebuild the gutter elements, ensure the margin to the left of the +// code matches their width. +function updateGutters(cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters; + removeChildren(gutters); + var i = 0; + for (; i < specs.length; ++i) { + var gutterClass = specs[i]; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt; + gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = i ? "" : "none"; + updateGutterSpace(cm); +} + +// Make sure the gutters options contains the element +// "CodeMirror-linenumbers" when the lineNumbers option is true. +function setGuttersForLineNumbers(options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers"); + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0); + options.gutters.splice(found, 1); + } +} + +// 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; +var 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(ranges, primIndex) { + 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]; + if (cmp(prev.to(), cur.from()) >= 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(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) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + 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(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(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(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 = 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(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) { 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}); } + } 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) { + if (doc.cm && doc.cm.state.suppressEdits && !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 { 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) { + if (!to) { to = from; } + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } + 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 chunkSize() { return this.lines.length }, + + // Remove the n lines at offset 'at'. + removeInner: function removeInner(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 collapse(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 insertInner(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 iterN(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 chunkSize() { return this.size }, + + removeInner: function removeInner(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 collapse(lines) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } + }, + + insertInner: function insertInner(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 maybeSpill() { + 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 iterN(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 } + 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 + }); + 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.title || marker.startStyle || marker.endStyle || marker.css) + { 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(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(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$1) { 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"); + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror; + if (cm) { f(cm); } + } +} + +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; + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) + { return } + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); +} + +var keyNames = { + 3: "Enter", 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: "/", 127: "Delete", + 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 } + 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); + }); +} + +// 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.charCoords(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.charCoords(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.charCoords(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" } + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + name = seq + " " + name; + } + 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); + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e); + return true + } + 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; +var 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) { onContextMenu(cm, 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(document, "mouseup", dragEnd); + off(document, "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 () {document.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(document, "mouseup", dragEnd); + on(document, "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(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { + setSelection(doc, normalizeSelection(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(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] = new Range(clipPos(doc, anchor), head); + setSelection(doc, normalizeSelection(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; + e_preventDefault(e); + display.input.focus(); + off(document, "mousemove", move); + off(document, "mouseup", up); + doc.history.lastSelOrigin = null; + } + + var move = operation(cm, function (e) { + if (!e_button(e)) { done(e); } + else { extend(e); } + }); + var up = operation(cm, done); + cm.state.selectingText = up; + on(document, "mousemove", move); + on(document, "mouseup", up); +} + + +// 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; + 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.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.options.gutters[i]; + signal(cm, type, cm, line, gutter, 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 } + 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("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + + option("theme", "default", function (cm) { + themeChanged(cm); + guttersChanged(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) { + setGuttersForLineNumbers(cm.options); + guttersChanged(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) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("firstLineNumber", 1, guttersChanged, true); + option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + option("pasteLinesPerSelection", true); + + 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); +} + +function guttersChanged(cm) { + updateGutters(cm); + regChange(cm); + alignHorizontally(cm); +} + +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$1(place, options) { + var this$1 = this; + + if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) } + + this.options = options = options ? copyObj(options) : {}; + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false); + setGuttersForLineNumbers(options); + + var doc = options.value; + if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } + this.doc = doc; + + var input = new CodeMirror$1.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input); + display.wrapper.CodeMirror = this; + updateGutters(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: false, cutIncoming: false, // 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$1.defaults = defaults; +// Functions to run when options are changed. +CodeMirror$1.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. + if (!captureRightClick) { 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)) { + 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$1.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 paste = cm.state.pasteIncoming || origin == "paste"; + var textLines = splitLinesAuto(inserted), multiPaste = null; + // When pasing 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; + // 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 (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + { from = to = Pos(from.line, 0); } + } + updateInput = cm.curOp.updateInput; + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) + { triggerElectric(cm, inserted); } + + ensureCursorVisible(cm); + cm.curOp.updateInput = updateInput; + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = false; +} + +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) { + field.setAttribute("autocorrect", "off"); + field.setAttribute("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. + +var addEditorMethods = function(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)}, + + 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); + 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; + 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 + }), + + 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); + + 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.showPrimarySelection = function () { + var sel = window.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 = window.getSelection(); + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; +}; + +ContentEditableInput.prototype.selectionInEditor = function () { + var sel = window.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 = window.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 = window.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.options.gutters.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) { 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(); + function recognizeMarker(id) { return function (marker) { return marker.id == id; } } + function close() { + if (closing) { + text += lineSep; + closing = false; + } + } + function addText(str) { + if (str) { + close(); + text += str; + } + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText != null) { + addText(cmText || node.textContent.replace(/\u200b/g, "")); + 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())) + { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); } + return + } + if (node.getAttribute("contenteditable") == "false") { return } + var isBlock = /^(pre|div|p)$/i.test(node.nodeName); + if (isBlock) { close(); } + for (var i = 0; i < node.childNodes.length; i++) + { walk(node.childNodes[i]); } + if (isBlock) { closing = true; } + } else if (node.nodeType == 3) { + addText(node.nodeValue); + } + } + for (;;) { + walk(from); + if (from == to) { break } + from = from.nextSibling; + } + 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(); + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false; + // 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; + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea(); + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild; + display.wrapper.insertBefore(div, 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 = true; + input.fastPoll(); + }); + + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}); + if (input.inaccurateSelection) { + input.prevInput = ""; + input.inaccurateSelection = false; + te.value = lastCopied.text.join("\n"); + selectInput(te); + } + } 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 = true; } + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } + cm.state.pasteIncoming = true; + input.focus(); + }); + + // 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.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 minimal, selected, cm = this.cm, doc = cm.doc; + if (cm.somethingSelected()) { + this.prevInput = ""; + var range$$1 = doc.sel.primary(); + minimal = hasCopyEvent && + (range$$1.to().line - range$$1.from().line > 100 || (selected = cm.getSelection()).length > 1000); + var content = minimal ? "-" : selected || 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; } + } + this.inaccurateSelection = minimal; +}; + +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; + 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; + input.wrapper.style.cssText = "position: absolute"; + var wrapperBox = input.wrapper.getBoundingClientRect(); + 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 = true; + 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() { + 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$1(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$1); + +addEditorMethods(CodeMirror$1); + +// 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$1.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments)} + })(Doc.prototype[prop]); } } + +eventMixin(Doc); + +// INPUT HANDLING + +CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; + +// MODE DEFINITION AND QUERYING + +// 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$1.defineMode = function(name/*, mode, …*/) { + if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; } + defineMode.apply(this, arguments); +}; + +CodeMirror$1.defineMIME = defineMIME; + +// Minimal default mode. +CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); +CodeMirror$1.defineMIME("text/plain", "null"); + +// EXTENSIONS + +CodeMirror$1.defineExtension = function (name, func) { + CodeMirror$1.prototype[name] = func; +}; +CodeMirror$1.defineDocExtension = function (name, func) { + Doc.prototype[name] = func; +}; + +CodeMirror$1.fromTextArea = fromTextArea; + +addLegacyProps(CodeMirror$1); + +CodeMirror$1.version = "5.27.2"; + +return CodeMirror$1; + +}))); + +},{}],64:[function(require,module,exports){ +"use strict"; + +/** + * Copyright (c) 2013-present, 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 makeEmptyFunction(arg) { + return function () { + return arg; + }; +} + +/** + * This function accepts and discards inputs; it has no side effects. This is + * primarily useful idiomatically for overridable function endpoints which + * always need to be callable, since JS lacks a null-call idiom ala Cocoa. + */ +var emptyFunction = function emptyFunction() {}; + +emptyFunction.thatReturns = makeEmptyFunction; +emptyFunction.thatReturnsFalse = makeEmptyFunction(false); +emptyFunction.thatReturnsTrue = makeEmptyFunction(true); +emptyFunction.thatReturnsNull = makeEmptyFunction(null); +emptyFunction.thatReturnsThis = function () { + return this; +}; +emptyFunction.thatReturnsArgument = function (arg) { + return arg; +}; + +module.exports = emptyFunction; +},{}],65:[function(require,module,exports){ +(function (process){ +/** + * Copyright (c) 2013-present, 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. + * + */ + +'use strict'; + +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ + +var validateFormat = function validateFormat(format) {}; + +if (process.env.NODE_ENV !== 'production') { + validateFormat = function validateFormat(format) { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + }; +} + +function invariant(condition, format, a, b, c, d, e, f) { + validateFormat(format); + + if (!condition) { + var error; + if (format === undefined) { + error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error(format.replace(/%s/g, function () { + return args[argIndex++]; + })); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } +} + +module.exports = invariant; +}).call(this,require('_process')) +},{"_process":168}],66:[function(require,module,exports){ +(function (process){ +/** + * Copyright 2014-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. + * + */ + +'use strict'; + +var emptyFunction = require('./emptyFunction'); + +/** + * 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 warning = emptyFunction; + +if (process.env.NODE_ENV !== 'production') { + (function () { + var printWarning = function printWarning(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.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) {} + }; + + warning = function warning(condition, format) { + if (format === undefined) { + throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); + } + + if (format.indexOf('Failed Composite propType: ') === 0) { + return; // Ignore CompositeComponent proptype check. + } + + 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)); + } + }; + })(); +} + +module.exports = warning; +}).call(this,require('_process')) +},{"./emptyFunction":64,"_process":168}],67:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GraphQLLanguageService = undefined; + +var _kinds = require('graphql/language/kinds'); + +var _graphql = require('graphql'); + +var _getAutocompleteSuggestions2 = require('./getAutocompleteSuggestions'); + +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 GraphQLLanguageService = exports.GraphQLLanguageService = function () { + function GraphQLLanguageService(cache) { + _classCallCheck(this, GraphQLLanguageService); + + this._graphQLCache = cache; + this._graphQLConfig = cache.getGraphQLConfig(); + } + + GraphQLLanguageService.prototype.getDiagnostics = function getDiagnostics(query, uri) { + var source, appName, schema, customRules, fragmentDefinitions, fragmentDependencies, dependenciesSource, customRulesModulePath, rulesPath; + return regeneratorRuntime.async(function getDiagnostics$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + source = query; + appName = this._graphQLConfig.getAppConfigNameByFilePath(uri); + // If there's a matching config, proceed to prepare to run validation + + schema = void 0; + customRules = void 0; + + if (!this._graphQLConfig.getSchemaPath(appName)) { + _context.next = 18; + break; + } + + _context.next = 7; + return regeneratorRuntime.awrap(this._graphQLCache.getSchema(this._graphQLConfig.getSchemaPath(appName))); + + case 7: + schema = _context.sent; + _context.next = 10; + return regeneratorRuntime.awrap(this._graphQLCache.getFragmentDefinitions(this._graphQLConfig, appName)); + + case 10: + fragmentDefinitions = _context.sent; + _context.next = 13; + return regeneratorRuntime.awrap(this._graphQLCache.getFragmentDependencies(query, fragmentDefinitions)); + + case 13: + fragmentDependencies = _context.sent; + dependenciesSource = fragmentDependencies.reduce(function (prev, cur) { + return prev + ' ' + (0, _graphql.print)(cur.definition); + }, ''); + + + source = source + ' ' + dependenciesSource; + + // Check if there are custom validation rules to be used + customRulesModulePath = this._graphQLConfig.getCustomValidationRulesModulePath(appName); + + if (customRulesModulePath) { + /* eslint-disable no-implicit-coercion */ + rulesPath = require.resolve('' + customRulesModulePath); + + if (rulesPath) { + customRules = require('' + rulesPath)(this._graphQLConfig); + } + /* eslint-enable no-implicit-coercion */ + } + + case 18: + return _context.abrupt('return', (0, _getDiagnostics.getDiagnostics)(source, schema, customRules)); + + case 19: + case 'end': + return _context.stop(); + } + } + }, null, this); + }; + + GraphQLLanguageService.prototype.getAutocompleteSuggestions = function getAutocompleteSuggestions(query, position, filePath) { + var appName, schema; + return regeneratorRuntime.async(function getAutocompleteSuggestions$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + appName = this._graphQLConfig.getAppConfigNameByFilePath(filePath); + schema = void 0; + + if (!this._graphQLConfig.getSchemaPath(appName)) { + _context2.next = 8; + break; + } + + _context2.next = 5; + return regeneratorRuntime.awrap(this._graphQLCache.getSchema(this._graphQLConfig.getSchemaPath(appName))); + + case 5: + schema = _context2.sent; + + if (!schema) { + _context2.next = 8; + break; + } + + return _context2.abrupt('return', (0, _getAutocompleteSuggestions2.getAutocompleteSuggestions)(schema, query, position)); + + case 8: + return _context2.abrupt('return', []); + + case 9: + case 'end': + return _context2.stop(); + } + } + }, null, this); + }; + + GraphQLLanguageService.prototype.getDefinition = function getDefinition(query, position, filePath) { + var appName, ast, node; + return regeneratorRuntime.async(function getDefinition$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + appName = this._graphQLConfig.getAppConfigNameByFilePath(filePath); + ast = void 0; + _context3.prev = 2; + + ast = (0, _graphql.parse)(query); + _context3.next = 9; + break; + + case 6: + _context3.prev = 6; + _context3.t0 = _context3['catch'](2); + return _context3.abrupt('return', null); + + case 9: + node = (0, _graphqlLanguageServiceUtils.getASTNodeAtPosition)(query, ast, position); + + if (!node) { + _context3.next = 16; + break; + } + + _context3.t1 = node.kind; + _context3.next = _context3.t1 === _kinds.FRAGMENT_SPREAD ? 14 : _context3.t1 === _kinds.FRAGMENT_DEFINITION ? 15 : _context3.t1 === _kinds.OPERATION_DEFINITION ? 15 : 16; + break; + + case 14: + return _context3.abrupt('return', this._getDefinitionForFragmentSpread(query, ast, node, filePath, this._graphQLConfig, appName)); + + case 15: + return _context3.abrupt('return', (0, _getDefinition.getDefinitionQueryResultForDefinitionNode)(filePath, query, node)); + + case 16: + return _context3.abrupt('return', null); + + case 17: + case 'end': + return _context3.stop(); + } + } + }, null, this, [[2, 6]]); + }; + + GraphQLLanguageService.prototype._getDefinitionForFragmentSpread = function _getDefinitionForFragmentSpread(query, ast, node, filePath, graphQLConfig, appName) { + var fragmentDefinitions, dependencies, localFragDefinitions, typeCastedDefs, localFragInfos, result; + return regeneratorRuntime.async(function _getDefinitionForFragmentSpread$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return regeneratorRuntime.awrap(this._graphQLCache.getFragmentDefinitions(graphQLConfig, appName)); + + case 2: + fragmentDefinitions = _context4.sent; + _context4.next = 5; + return regeneratorRuntime.awrap(this._graphQLCache.getFragmentDependenciesForAST(ast, fragmentDefinitions)); + + case 5: + dependencies = _context4.sent; + localFragDefinitions = ast.definitions.filter(function (definition) { + return definition.kind === _kinds.FRAGMENT_DEFINITION; + }); + typeCastedDefs = localFragDefinitions; + localFragInfos = typeCastedDefs.map(function (definition) { + return { + filePath: filePath, + content: query, + definition: definition + }; + }); + _context4.next = 11; + return regeneratorRuntime.awrap((0, _getDefinition.getDefinitionQueryResultForFragmentSpread)(query, node, dependencies.concat(localFragInfos))); + + case 11: + result = _context4.sent; + return _context4.abrupt('return', result); + + case 13: + case 'end': + return _context4.stop(); + } + } + }, null, this); + }; + + return GraphQLLanguageService; +}(); +},{"./getAutocompleteSuggestions":69,"./getDefinition":70,"./getDiagnostics":71,"graphql":92,"graphql-language-service-utils":81,"graphql/language/kinds":102}],68:[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":92,"graphql/type/introspection":115}],69:[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; + +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":68,"graphql":92,"graphql-language-service-parser":77}],70:[function(require,module,exports){ +(function (process){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LANGUAGE = undefined; +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 getDefinitionQueryResultForFragmentSpread(text, fragment, dependencies) { + var name, defNodes, definitions; + return regeneratorRuntime.async(function getDefinitionQueryResultForFragmentSpread$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + name = fragment.name.value; + defNodes = dependencies.filter(function (_ref) { + var definition = _ref.definition; + return definition.name.value === name; + }); + + if (!(defNodes.length === 0)) { + _context.next = 5; + break; + } + + process.stderr.write('Definition not found for GraphQL fragment ' + 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 getDefinitionForFragmentDefinition(filePath || '', content, definition); + }); + return _context.abrupt('return', { + definitions: definitions, + queryRange: definitions.map(function (_) { + return getRange(text, fragment); + }) + }); + + case 7: + case 'end': + return _context.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, name), + 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":168,"assert":34,"graphql-language-service-utils":81}],71:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SEVERITY = undefined; +exports.getDiagnostics = getDiagnostics; + +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(queryText) { + var schema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var customRules = arguments[2]; + + var ast = null; + try { + ast = (0, _graphql.parse)(queryText); + } catch (error) { + var range = getRange(error.locations[0], queryText); + + return [{ + severity: SEVERITY.ERROR, + message: error.message, + source: 'GraphQL: Syntax', + range: range + }]; + } + + // We cannot validate the query unless a schema is provided. + if (!schema) { + return []; + } + + var validationErrorAnnotations = mapCat((0, _graphqlLanguageServiceUtils.validateWithCustomRules)(schema, ast, customRules), 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)) + }; + }); +} + +/** + * 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; +} + +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)); +} +},{"assert":34,"graphql":92,"graphql-language-service-parser":77,"graphql-language-service-utils":81}],72:[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 _kinds = require('graphql/language/kinds'); + +var _graphqlLanguageServiceUtils = require('graphql-language-service-utils'); + +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[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 === _kinds.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":92,"graphql-language-service-utils":81,"graphql/language/kinds":102}],73:[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; + } +}); + +var _getOutline = require('./getOutline'); + +Object.defineProperty(exports, 'getOutline', { + enumerable: true, + get: function get() { + return _getOutline.getOutline; + } +}); + +var _GraphQLLanguageService = require('./GraphQLLanguageService'); + +Object.defineProperty(exports, 'GraphQLLanguageService', { + enumerable: true, + get: function get() { + return _GraphQLLanguageService.GraphQLLanguageService; + } +}); +},{"./GraphQLLanguageService":67,"./autocompleteUtils":68,"./getAutocompleteSuggestions":69,"./getDefinition":70,"./getDiagnostics":71,"./getOutline":72}],74:[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; +},{}],75:[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; + } + }; +} +},{}],76:[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":75}],77:[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":74,"./RuleHelpers":75,"./Rules":76,"./onlineParser":78}],78:[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 }, 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":76}],79:[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); +} +},{}],80:[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.start <= offset && offset <= node.loc.end) { + nodeContainingPosition = node; + } else { + return false; + } + }, + leave: function leave(node) { + if (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":79,"graphql":92}],81:[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":79,"./getASTNodeAtPosition":80,"./validateWithCustomRules":82}],82:[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) { + // 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 rules = _graphql.specifiedRules.filter(function (rule) { + return rule !== NoUnusedFragments; + }); + + 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; + } + + 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":92,"graphql/validation/rules/NoUnusedFragments":149}],83:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GraphQLError = GraphQLError; + +var _location = require('../language/location'); + +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ +function GraphQLError( // eslint-disable-line no-redeclare +message, nodes, source, positions, path, originalError) { + // Compute locations in the source for the given nodes/positions. + var _source = source; + if (!_source && nodes && nodes.length > 0) { + var node = nodes[0]; + _source = node && node.loc && node.loc.source; + } + + var _positions = positions; + if (!_positions && nodes) { + _positions = nodes.filter(function (node) { + return Boolean(node.loc); + }).map(function (node) { + return node.loc.start; + }); + } + if (_positions && _positions.length === 0) { + _positions = undefined; + } + + var _locations = void 0; + var _source2 = _source; // seems here Flow need a const to resolve type. + if (_source2 && _positions) { + _locations = _positions.map(function (pos) { + return (0, _location.getLocation)(_source2, pos); + }); + } + + 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: true + }, + 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: true + }, + nodes: { + value: nodes || undefined + }, + source: { + value: _source || undefined + }, + positions: { + value: _positions || undefined + }, + originalError: { + value: originalError + } + }); + + // 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 + }); + } +} +/** + * 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. + */ + +GraphQLError.prototype = Object.create(Error.prototype, { + constructor: { value: GraphQLError }, + name: { value: 'GraphQLError' } +}); +},{"../language/location":104}],84:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.formatError = formatError; + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +function formatError(error) { + (0, _invariant2.default)(error, 'Received null or undefined error.'); + return { + message: error.message, + locations: error.locations, + path: error.path + }; +} +/** + * 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. + */ +},{"../jsutils/invariant":94}],85:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _GraphQLError = require('./GraphQLError'); + +Object.defineProperty(exports, 'GraphQLError', { + enumerable: true, + get: function get() { + return _GraphQLError.GraphQLError; + } +}); + +var _syntaxError = require('./syntaxError'); + +Object.defineProperty(exports, 'syntaxError', { + enumerable: true, + get: function get() { + return _syntaxError.syntaxError; + } +}); + +var _locatedError = require('./locatedError'); + +Object.defineProperty(exports, 'locatedError', { + enumerable: true, + get: function get() { + return _locatedError.locatedError; + } +}); + +var _formatError = require('./formatError'); + +Object.defineProperty(exports, 'formatError', { + enumerable: true, + get: function get() { + return _formatError.formatError; + } +}); +},{"./GraphQLError":83,"./formatError":84,"./locatedError":86,"./syntaxError":87}],86:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.locatedError = locatedError; + +var _GraphQLError = require('./GraphQLError'); + +/** + * 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 && originalError.path) { + return originalError; + } + + var message = originalError ? originalError.message || String(originalError) : 'An unknown error occurred.'; + return new _GraphQLError.GraphQLError(message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError); +} +/** + * 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. + */ +},{"./GraphQLError":83}],87:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.syntaxError = syntaxError; + +var _location = require('../language/location'); + +var _GraphQLError = require('./GraphQLError'); + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ + +/** + * 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 syntaxError(source, position, description) { + var location = (0, _location.getLocation)(source, position); + var error = new _GraphQLError.GraphQLError('Syntax Error ' + source.name + ' (' + location.line + ':' + location.column + ') ' + description + '\n\n' + highlightSourceAtLocation(source, location), undefined, source, [position]); + return error; +} + +/** + * Render a helpful description of the location of the error in the GraphQL + * Source document. + */ +function highlightSourceAtLocation(source, location) { + var line = location.line; + var prevLineNum = (line - 1).toString(); + var lineNum = line.toString(); + var nextLineNum = (line + 1).toString(); + var padLen = nextLineNum.length; + var lines = source.body.split(/\r\n|[\n\r]/g); + return (line >= 2 ? lpad(padLen, prevLineNum) + ': ' + lines[line - 2] + '\n' : '') + lpad(padLen, lineNum) + ': ' + lines[line - 1] + '\n' + Array(2 + padLen + location.column).join(' ') + '^\n' + (line < lines.length ? lpad(padLen, nextLineNum) + ': ' + lines[line] + '\n' : ''); +} + +function lpad(len, str) { + return Array(len - str.length + 1).join(' ') + str; +} +},{"../language/location":104,"./GraphQLError":83}],88:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.defaultFieldResolver = undefined; +exports.execute = execute; +exports.responsePathAsArray = responsePathAsArray; +exports.addPath = addPath; +exports.assertValidExecutionArguments = assertValidExecutionArguments; +exports.buildExecutionContext = buildExecutionContext; +exports.getOperationRootType = getOperationRootType; +exports.collectFields = collectFields; +exports.buildResolveInfo = buildResolveInfo; +exports.resolveFieldValueOrError = resolveFieldValueOrError; +exports.getFieldDef = getFieldDef; + +var _iterall = require('iterall'); + +var _error = require('../error'); + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isNullish = require('../jsutils/isNullish'); + +var _isNullish2 = _interopRequireDefault(_isNullish); + +var _typeFromAST = require('../utilities/typeFromAST'); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _values = require('./values'); + +var _definition = require('../type/definition'); + +var _schema = require('../type/schema'); + +var _introspection = require('../type/introspection'); + +var _directives = require('../type/directives'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g "a" + * 2) fragment "spreads" e.g. "...c" + * 3) inline fragment "spreads" e.g. "...on Type { a }" + */ + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ + + +/** + * The result of GraphQL execution. + * + * - `errors` is included when any errors occurred as a non-empty array. + * - `data` is the result of a successful execution of the query. + */ + + +/** + * Implements the "Evaluating requests" section of the GraphQL specification. + * + * Returns a Promise that will eventually be resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Accepts either an object with named arguments, or individual arguments. + */ + +/* eslint-disable no-redeclare */ +function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // Extract arguments from object args if provided. + var args = arguments.length === 1 ? argsOrSchema : undefined; + var schema = args ? args.schema : argsOrSchema; + return args ? executeImpl(schema, args.document, args.rootValue, args.contextValue, args.variableValues, args.operationName, args.fieldResolver) : executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); +} +/** + * 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 executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrect, throw an error. + assertValidExecutionArguments(schema, document, variableValues); + + // If a valid context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + var context = void 0; + try { + context = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); + } catch (error) { + return Promise.resolve({ errors: [error] }); + } + + // 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. + return Promise.resolve(executeOperation(context, context.operation, rootValue)).then(function (data) { + return context.errors.length === 0 ? { data: data } : { errors: context.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) { + (0, _invariant2.default)(schema, 'Must provide schema'); + (0, _invariant2.default)(document, 'Must provide document'); + (0, _invariant2.default)(schema instanceof _schema.GraphQLSchema, 'Schema must be an instance of GraphQLSchema. Also ensure that there are ' + 'not multiple versions of GraphQL installed in your node_modules directory.'); + + // Variables, if provided, must be an object. + (0, _invariant2.default)(!rawVariableValues || typeof rawVariableValues === 'object', '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.'); +} + +/** + * 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 = void 0; + var fragments = Object.create(null); + document.definitions.forEach(function (definition) { + switch (definition.kind) { + case Kind.OPERATION_DEFINITION: + if (!operationName && operation) { + throw new _error.GraphQLError('Must provide operation name if query contains multiple operations.'); + } + if (!operationName || definition.name && definition.name.value === operationName) { + operation = definition; + } + break; + case Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + default: + throw new _error.GraphQLError('GraphQL cannot execute a request containing a ' + definition.kind + '.', [definition]); + } + }); + if (!operation) { + if (operationName) { + throw new _error.GraphQLError('Unknown operation named "' + operationName + '".'); + } else { + throw new _error.GraphQLError('Must provide an operation.'); + } + } + var variableValues = (0, _values.getVariableValues)(schema, operation.variableDefinitions || [], rawVariableValues || {}); + + 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 = 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); + var promise = getPromise(result); + if (promise) { + return promise.then(undefined, function (error) { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} + +/** + * Extracts the root type of the operation from the schema. + */ +function getOperationRootType(schema, operation) { + switch (operation.operation) { + case 'query': + return schema.getQueryType(); + case 'mutation': + var mutationType = schema.getMutationType(); + if (!mutationType) { + throw new _error.GraphQLError('Schema is not configured for mutations', [operation]); + } + return mutationType; + case 'subscription': + var subscriptionType = schema.getSubscriptionType(); + if (!subscriptionType) { + throw new _error.GraphQLError('Schema is not configured for subscriptions', [operation]); + } + return subscriptionType; + default: + throw new _error.GraphQLError('Can only execute queries, mutations and subscriptions', [operation]); + } +} + +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ +function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { + return Object.keys(fields).reduce(function (prevPromise, responseName) { + return prevPromise.then(function (results) { + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + if (result === undefined) { + return results; + } + var promise = getPromise(result); + if (promise) { + return promise.then(function (resolvedResult) { + results[responseName] = resolvedResult; + return results; + }); + } + results[responseName] = result; + return results; + }); + }, Promise.resolve({})); +} + +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ +function executeFields(exeContext, parentType, sourceValue, path, fields) { + var containsPromise = false; + + var finalResults = Object.keys(fields).reduce(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; + } + results[responseName] = result; + if (getPromise(result)) { + containsPromise = true; + } + return results; + }, Object.create(null)); + + // If there are no promises, we can just return the object + if (!containsPromise) { + return finalResults; + } + + // 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 promiseForObject(finalResults); +} + +/** + * 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 Kind.FIELD: + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + var _name = getFieldEntryKey(selection); + if (!fields[_name]) { + fields[_name] = []; + } + fields[_name].push(selection); + break; + case Kind.INLINE_FRAGMENT: + if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) { + continue; + } + collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames); + break; + case 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 precidence 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; +} + +/** + * This function transforms a JS object `{[key: string]: Promise}` into + * a `Promise<{[key: string]: 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)); + }); +} + +/** + * 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: fieldNodes[0].name.value, + 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 context = exeContext.contextValue; + + return resolveFn(source, args, context, info); + } catch (error) { + // Sometimes a non-error is thrown, wrap it as an Error for a + // consistent interface. + return error instanceof Error ? error : new Error(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) { + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if (returnType instanceof _definition.GraphQLNonNull) { + return completeValueWithLocatedError(exeContext, returnType, fieldNodes, info, path, result); + } + + // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + try { + var completed = completeValueWithLocatedError(exeContext, returnType, fieldNodes, info, path, result); + var promise = getPromise(completed); + if (promise) { + // If `completeValueWithLocatedError` returned a rejected promise, log + // the rejection error and resolve to null. + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return promise.then(undefined, function (error) { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + return completed; + } catch (error) { + // If `completeValueWithLocatedError` returned abruptly (threw an error), + // log the error and return null. + exeContext.errors.push(error); + return null; + } +} + +// This is a small wrapper around completeValue which annotates errors with +// location information. +function completeValueWithLocatedError(exeContext, returnType, fieldNodes, info, path, result) { + try { + var completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); + var promise = getPromise(completed); + if (promise) { + return promise.then(undefined, function (error) { + return Promise.reject((0, _error.locatedError)(error, fieldNodes, responsePathAsArray(path))); + }); + } + return completed; + } catch (error) { + throw (0, _error.locatedError)(error, fieldNodes, responsePathAsArray(path)); + } +} + +/** + * 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 a Promise, apply-lift over completeValue. + var promise = getPromise(result); + if (promise) { + return promise.then(function (resolved) { + return completeValue(exeContext, returnType, fieldNodes, info, path, resolved); + }); + } + + // 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 (returnType instanceof _definition.GraphQLNonNull) { + var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); + if (completed === null) { + throw new Error('Cannot return null for non-nullable field ' + info.parentType.name + '.' + info.fieldName + '.'); + } + return completed; + } + + // If result value is null-ish (null, undefined, or NaN) then return null. + if ((0, _isNullish2.default)(result)) { + return null; + } + + // If field type is List, complete each item in the list with the inner type + if (returnType instanceof _definition.GraphQLList) { + 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 (returnType instanceof _definition.GraphQLObjectType) { + return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + } + + // Not reachable. All possible output types have been considered. + throw new Error('Cannot complete value of unexpected type "' + String(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, _invariant2.default)((0, _iterall.isCollection)(result), 'Expected Iterable, but did not find one for field ' + info.parentType.name + '.' + info.fieldName + '.'); + + // 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 && getPromise(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) { + (0, _invariant2.default)(returnType.serialize, 'Missing serialize method on type'); + var serializedResult = returnType.serialize(result); + if ((0, _isNullish2.default)(serializedResult)) { + throw new Error('Expected a value of type "' + String(returnType) + '" but ' + ('received: ' + String(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); + + var promise = getPromise(runtimeType); + if (promise) { + return promise.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 (!(runtimeType instanceof _definition.GraphQLObjectType)) { + throw new _error.GraphQLError('Abstract type ' + returnType.name + ' must resolve to an Object type at ' + ('runtime for field ' + info.parentType.name + '.' + info.fieldName + ' with ') + ('value "' + String(result) + '", received "' + String(runtimeType) + '".'), fieldNodes); + } + + if (!exeContext.schema.isPossibleType(returnType, runtimeType)) { + throw new _error.GraphQLError('Runtime Object type "' + runtimeType.name + '" is not a possible type ' + ('for "' + 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); + + var promise = getPromise(isTypeOf); + if (promise) { + return promise.then(function (isTypeOfResult) { + if (!isTypeOfResult) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, info, path, result); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, info, path, result); +} + +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new _error.GraphQLError('Expected value of type "' + returnType.name + '" but got: ' + String(result) + '.', fieldNodes); +} + +function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, info, path, result) { + // Collect sub-fields to execute to complete this value. + 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 executeFields(exeContext, returnType, result, path, subFieldNodes); +} + +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which tests each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ +function defaultResolveTypeFn(value, context, info, abstractType) { + 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, context, info); + + var promise = getPromise(isTypeOfResult); + if (promise) { + promisedIsTypeOfResults[i] = promise; + } 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. + */ +var defaultFieldResolver = exports.defaultFieldResolver = function defaultFieldResolver(source, args, context, 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, context, info); + } + return property; + } +}; + +/** + * Only returns the value if it acts like a Promise, i.e. has a "then" function, + * otherwise returns void. + */ +function getPromise(value) { + if (typeof value === 'object' && value !== null && typeof value.then === 'function') { + return value; + } +} + +/** + * This method looks up the field on the given type defintion. + * 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. + */ +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":85,"../jsutils/invariant":94,"../jsutils/isNullish":96,"../language/kinds":102,"../type/definition":112,"../type/directives":113,"../type/introspection":115,"../type/schema":117,"../utilities/typeFromAST":135,"./values":90,"iterall":166}],89:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _execute = require('./execute'); + +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; + } +}); + +var _values = require('./values'); + +Object.defineProperty(exports, 'getDirectiveValues', { + enumerable: true, + get: function get() { + return _values.getDirectiveValues; + } +}); +},{"./execute":88,"./values":90}],90:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getVariableValues = getVariableValues; +exports.getArgumentValues = getArgumentValues; +exports.getDirectiveValues = getDirectiveValues; + +var _iterall = require('iterall'); + +var _error = require('../error'); + +var _find = require('../jsutils/find'); + +var _find2 = _interopRequireDefault(_find); + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isNullish = require('../jsutils/isNullish'); + +var _isNullish2 = _interopRequireDefault(_isNullish); + +var _isInvalid = require('../jsutils/isInvalid'); + +var _isInvalid2 = _interopRequireDefault(_isInvalid); + +var _keyMap = require('../jsutils/keyMap'); + +var _keyMap2 = _interopRequireDefault(_keyMap); + +var _typeFromAST = require('../utilities/typeFromAST'); + +var _valueFromAST = require('../utilities/valueFromAST'); + +var _isValidJSValue = require('../utilities/isValidJSValue'); + +var _isValidLiteralValue = require('../utilities/isValidLiteralValue'); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _printer = require('../language/printer'); + +var _definition = require('../type/definition'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +/** + * 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. + */ + +/** + * 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 getVariableValues(schema, varDefNodes, inputs) { + var coercedValues = Object.create(null); + 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)) { + throw new _error.GraphQLError('Variable "$' + varName + '" expected value of type ' + ('"' + (0, _printer.print)(varDefNode.type) + '" which cannot be used as an input type.'), [varDefNode.type]); + } + + var value = inputs[varName]; + if ((0, _isInvalid2.default)(value)) { + var defaultValue = varDefNode.defaultValue; + if (defaultValue) { + coercedValues[varName] = (0, _valueFromAST.valueFromAST)(defaultValue, varType); + } + if (varType instanceof _definition.GraphQLNonNull) { + throw new _error.GraphQLError('Variable "$' + varName + '" of required type ' + ('"' + String(varType) + '" was not provided.'), [varDefNode]); + } + } else { + var errors = (0, _isValidJSValue.isValidJSValue)(value, varType); + if (errors.length) { + var message = errors ? '\n' + errors.join('\n') : ''; + throw new _error.GraphQLError('Variable "$' + varName + '" got invalid value ' + (JSON.stringify(value) + '.' + message), [varDefNode]); + } + + var coercedValue = coerceValue(varType, value); + (0, _invariant2.default)(!(0, _isInvalid2.default)(coercedValue), 'Should have reported error.'); + coercedValues[varName] = coercedValue; + } + } + return coercedValues; +} + +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + */ +function getArgumentValues(def, node, variableValues) { + var argDefs = def.args; + var argNodes = node.arguments; + if (!argDefs || !argNodes) { + return {}; + } + var coercedValues = Object.create(null); + var argNodeMap = (0, _keyMap2.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 defaultValue = argDef.defaultValue; + if (!argumentNode) { + if (!(0, _isInvalid2.default)(defaultValue)) { + coercedValues[name] = defaultValue; + } else if (argType instanceof _definition.GraphQLNonNull) { + throw new _error.GraphQLError('Argument "' + name + '" of required type ' + ('"' + String(argType) + '" was not provided.'), [node]); + } + } else if (argumentNode.value.kind === Kind.VARIABLE) { + var variableName = argumentNode.value.name.value; + if (variableValues && !(0, _isInvalid2.default)(variableValues[variableName])) { + // Note: this does not check that this variable value is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + coercedValues[name] = variableValues[variableName]; + } else if (!(0, _isInvalid2.default)(defaultValue)) { + coercedValues[name] = defaultValue; + } else if (argType instanceof _definition.GraphQLNonNull) { + throw new _error.GraphQLError('Argument "' + name + '" of required type "' + String(argType) + '" was ' + ('provided the variable "$' + variableName + '" which was not provided ') + 'a runtime value.', [argumentNode.value]); + } + } else { + var valueNode = argumentNode.value; + var coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues); + if ((0, _isInvalid2.default)(coercedValue)) { + var errors = (0, _isValidLiteralValue.isValidLiteralValue)(argType, valueNode); + var message = errors ? '\n' + errors.join('\n') : ''; + throw new _error.GraphQLError('Argument "' + name + '" got invalid value ' + (0, _printer.print)(valueNode) + '.' + message, [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. + */ +function getDirectiveValues(directiveDef, node, variableValues) { + var directiveNode = node.directives && (0, _find2.default)(node.directives, function (directive) { + return directive.name.value === directiveDef.name; + }); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +/** + * Given a type and any value, return a runtime value coerced to match the type. + */ +function coerceValue(type, value) { + // Ensure flow knows that we treat function params as const. + var _value = value; + + if ((0, _isInvalid2.default)(_value)) { + return; // Intentionally return no value. + } + + if (type instanceof _definition.GraphQLNonNull) { + if (_value === null) { + return; // Intentionally return no value. + } + return coerceValue(type.ofType, _value); + } + + if (_value === null) { + // Intentionally return the value null. + return null; + } + + if (type instanceof _definition.GraphQLList) { + var itemType = type.ofType; + if ((0, _iterall.isCollection)(_value)) { + var coercedValues = []; + var valueIter = (0, _iterall.createIterator)(_value); + if (!valueIter) { + return; // Intentionally return no value. + } + var step = void 0; + while (!(step = valueIter.next()).done) { + var itemValue = coerceValue(itemType, step.value); + if ((0, _isInvalid2.default)(itemValue)) { + return; // Intentionally return no value. + } + coercedValues.push(itemValue); + } + return coercedValues; + } + var coercedValue = coerceValue(itemType, _value); + if ((0, _isInvalid2.default)(coercedValue)) { + return; // Intentionally return no value. + } + return [coerceValue(itemType, _value)]; + } + + if (type instanceof _definition.GraphQLInputObjectType) { + if (typeof _value !== 'object') { + return; // Intentionally return no value. + } + var coercedObj = Object.create(null); + var fields = type.getFields(); + var fieldNames = Object.keys(fields); + for (var i = 0; i < fieldNames.length; i++) { + var fieldName = fieldNames[i]; + var field = fields[fieldName]; + if ((0, _isInvalid2.default)(_value[fieldName])) { + if (!(0, _isInvalid2.default)(field.defaultValue)) { + coercedObj[fieldName] = field.defaultValue; + } else if (field.type instanceof _definition.GraphQLNonNull) { + return; // Intentionally return no value. + } + continue; + } + var fieldValue = coerceValue(field.type, _value[fieldName]); + if ((0, _isInvalid2.default)(fieldValue)) { + return; // Intentionally return no value. + } + coercedObj[fieldName] = fieldValue; + } + return coercedObj; + } + + (0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must be input type'); + + var parsed = type.parseValue(_value); + if ((0, _isNullish2.default)(parsed)) { + // null or invalid values represent a failure to parse correctly, + // in which case no value is returned. + return; + } + + return parsed; +} +},{"../error":85,"../jsutils/find":93,"../jsutils/invariant":94,"../jsutils/isInvalid":95,"../jsutils/isNullish":96,"../jsutils/keyMap":97,"../language/kinds":102,"../language/printer":106,"../type/definition":112,"../utilities/isValidJSValue":130,"../utilities/isValidLiteralValue":131,"../utilities/typeFromAST":135,"../utilities/valueFromAST":136,"iterall":166}],91:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.graphql = graphql; + +var _parser = require('./language/parser'); + +var _validate = require('./validation/validate'); + +var _execute = require('./execution/execute'); + +/** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + */ + +/* eslint-disable no-redeclare */ +function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // Extract arguments from object args if provided. + var args = arguments.length === 1 ? argsOrSchema : undefined; + var schema = args ? args.schema : argsOrSchema; + return args ? graphqlImpl(schema, args.source, args.rootValue, args.contextValue, args.variableValues, args.operationName, args.fieldResolver) : graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver); +} +/** + * 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 graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + return new Promise(function (resolve) { + // Parse + var document = void 0; + try { + document = (0, _parser.parse)(source); + } catch (syntaxError) { + return resolve({ errors: [syntaxError] }); + } + + // Validate + var validationErrors = (0, _validate.validate)(schema, document); + if (validationErrors.length > 0) { + return resolve({ errors: validationErrors }); + } + + // Execute + resolve((0, _execute.execute)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver)); + }); +} +},{"./execution/execute":88,"./language/parser":105,"./validation/validate":165}],92:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _graphql = require('./graphql'); + +Object.defineProperty(exports, 'graphql', { + enumerable: true, + get: function get() { + return _graphql.graphql; + } +}); + +var _type = require('./type'); + +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, 'DirectiveLocation', { + enumerable: true, + get: function get() { + return _type.DirectiveLocation; + } +}); +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, '__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, 'isType', { + enumerable: true, + get: function get() { + return _type.isType; + } +}); +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, 'isNamedType', { + enumerable: true, + get: function get() { + return _type.isNamedType; + } +}); +Object.defineProperty(exports, 'assertType', { + enumerable: true, + get: function get() { + return _type.assertType; + } +}); +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, '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; + } +}); + +var _language = require('./language'); + +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, 'BREAK', { + enumerable: true, + get: function get() { + return _language.BREAK; + } +}); + +var _execution = require('./execution'); + +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; + } +}); + +var _subscription = require('./subscription'); + +Object.defineProperty(exports, 'subscribe', { + enumerable: true, + get: function get() { + return _subscription.subscribe; + } +}); +Object.defineProperty(exports, 'createSourceEventStream', { + enumerable: true, + get: function get() { + return _subscription.createSourceEventStream; + } +}); + +var _validation = require('./validation'); + +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, 'ArgumentsOfCorrectTypeRule', { + enumerable: true, + get: function get() { + return _validation.ArgumentsOfCorrectTypeRule; + } +}); +Object.defineProperty(exports, 'DefaultValuesOfCorrectTypeRule', { + enumerable: true, + get: function get() { + return _validation.DefaultValuesOfCorrectTypeRule; + } +}); +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, 'ProvidedNonNullArgumentsRule', { + enumerable: true, + get: function get() { + return _validation.ProvidedNonNullArgumentsRule; + } +}); +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, 'VariablesAreInputTypesRule', { + enumerable: true, + get: function get() { + return _validation.VariablesAreInputTypesRule; + } +}); +Object.defineProperty(exports, 'VariablesInAllowedPositionRule', { + enumerable: true, + get: function get() { + return _validation.VariablesInAllowedPositionRule; + } +}); + +var _error = require('./error'); + +Object.defineProperty(exports, 'GraphQLError', { + enumerable: true, + get: function get() { + return _error.GraphQLError; + } +}); +Object.defineProperty(exports, 'formatError', { + enumerable: true, + get: function get() { + return _error.formatError; + } +}); + +var _utilities = require('./utilities'); + +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, '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, 'extendSchema', { + enumerable: true, + get: function get() { + return _utilities.extendSchema; + } +}); +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, 'astFromValue', { + enumerable: true, + get: function get() { + return _utilities.astFromValue; + } +}); +Object.defineProperty(exports, 'TypeInfo', { + enumerable: true, + get: function get() { + return _utilities.TypeInfo; + } +}); +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, 'findBreakingChanges', { + enumerable: true, + get: function get() { + return _utilities.findBreakingChanges; + } +}); +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; + } +}); +},{"./error":85,"./execution":89,"./graphql":91,"./language":101,"./subscription":109,"./type":114,"./utilities":128,"./validation":137}],93:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = find; + +/** + * 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 find(list, predicate) { + for (var i = 0; i < list.length; i++) { + if (predicate(list[i])) { + return list[i]; + } + } +} +},{}],94:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = invariant; + +/** + * 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 invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} +},{}],95:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isInvalid; + +/** + * 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. + */ + +/** + * Returns true if a value is undefined, or NaN. + */ +function isInvalid(value) { + return value === undefined || value !== value; +} +},{}],96:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isNullish; + +/** + * 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. + */ + +/** + * Returns true if a value is null, undefined, or NaN. + */ +function isNullish(value) { + return value === null || value === undefined || value !== value; +} +},{}],97:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = keyMap; + +/** + * 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. + */ + +/** + * 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)); +} +},{}],98:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = keyValMap; + +/** + * 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. + */ + +/** + * 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)); +} +},{}],99:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = quotedOrList; + +/** + * 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 MAX_LENGTH = 5; + +/** + * Given [ A, B, C ] return '"A", "B", or "C"'. + */ +function quotedOrList(items) { + var selected = items.slice(0, MAX_LENGTH); + return selected.map(function (item) { + return '"' + item + '"'; + }).reduce(function (list, quoted, index) { + return list + (selected.length > 2 ? ', ' : ' ') + (index === selected.length - 1 ? 'or ' : '') + quoted; + }); +} +},{}],100:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = suggestionList; + +/** + * 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. + */ + +/** + * 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. + * + * 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]; +} +},{}],101:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BREAK = exports.getVisitFn = exports.visitWithTypeInfo = exports.visitInParallel = exports.visit = exports.Source = exports.print = exports.parseType = exports.parseValue = exports.parse = exports.TokenKind = exports.createLexer = exports.Kind = exports.getLocation = undefined; + +var _location = require('./location'); + +Object.defineProperty(exports, 'getLocation', { + enumerable: true, + get: function get() { + return _location.getLocation; + } +}); + +var _lexer = require('./lexer'); + +Object.defineProperty(exports, 'createLexer', { + enumerable: true, + get: function get() { + return _lexer.createLexer; + } +}); +Object.defineProperty(exports, 'TokenKind', { + enumerable: true, + get: function get() { + return _lexer.TokenKind; + } +}); + +var _parser = require('./parser'); + +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; + } +}); + +var _printer = require('./printer'); + +Object.defineProperty(exports, 'print', { + enumerable: true, + get: function get() { + return _printer.print; + } +}); + +var _source = require('./source'); + +Object.defineProperty(exports, 'Source', { + enumerable: true, + get: function get() { + return _source.Source; + } +}); + +var _visitor = require('./visitor'); + +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; + } +}); + +var _kinds = require('./kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +exports.Kind = Kind; +},{"./kinds":102,"./lexer":103,"./location":104,"./parser":105,"./printer":106,"./source":107,"./visitor":108}],102:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +/** + * 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. + */ + +// Name + +var NAME = exports.NAME = 'Name'; + +// Document + +var DOCUMENT = exports.DOCUMENT = 'Document'; +var OPERATION_DEFINITION = exports.OPERATION_DEFINITION = 'OperationDefinition'; +var VARIABLE_DEFINITION = exports.VARIABLE_DEFINITION = 'VariableDefinition'; +var VARIABLE = exports.VARIABLE = 'Variable'; +var SELECTION_SET = exports.SELECTION_SET = 'SelectionSet'; +var FIELD = exports.FIELD = 'Field'; +var ARGUMENT = exports.ARGUMENT = 'Argument'; + +// Fragments + +var FRAGMENT_SPREAD = exports.FRAGMENT_SPREAD = 'FragmentSpread'; +var INLINE_FRAGMENT = exports.INLINE_FRAGMENT = 'InlineFragment'; +var FRAGMENT_DEFINITION = exports.FRAGMENT_DEFINITION = 'FragmentDefinition'; + +// Values + +var INT = exports.INT = 'IntValue'; +var FLOAT = exports.FLOAT = 'FloatValue'; +var STRING = exports.STRING = 'StringValue'; +var BOOLEAN = exports.BOOLEAN = 'BooleanValue'; +var NULL = exports.NULL = 'NullValue'; +var ENUM = exports.ENUM = 'EnumValue'; +var LIST = exports.LIST = 'ListValue'; +var OBJECT = exports.OBJECT = 'ObjectValue'; +var OBJECT_FIELD = exports.OBJECT_FIELD = 'ObjectField'; + +// Directives + +var DIRECTIVE = exports.DIRECTIVE = 'Directive'; + +// Types + +var NAMED_TYPE = exports.NAMED_TYPE = 'NamedType'; +var LIST_TYPE = exports.LIST_TYPE = 'ListType'; +var NON_NULL_TYPE = exports.NON_NULL_TYPE = 'NonNullType'; + +// Type System Definitions + +var SCHEMA_DEFINITION = exports.SCHEMA_DEFINITION = 'SchemaDefinition'; +var OPERATION_TYPE_DEFINITION = exports.OPERATION_TYPE_DEFINITION = 'OperationTypeDefinition'; + +// Type Definitions + +var SCALAR_TYPE_DEFINITION = exports.SCALAR_TYPE_DEFINITION = 'ScalarTypeDefinition'; +var OBJECT_TYPE_DEFINITION = exports.OBJECT_TYPE_DEFINITION = 'ObjectTypeDefinition'; +var FIELD_DEFINITION = exports.FIELD_DEFINITION = 'FieldDefinition'; +var INPUT_VALUE_DEFINITION = exports.INPUT_VALUE_DEFINITION = 'InputValueDefinition'; +var INTERFACE_TYPE_DEFINITION = exports.INTERFACE_TYPE_DEFINITION = 'InterfaceTypeDefinition'; +var UNION_TYPE_DEFINITION = exports.UNION_TYPE_DEFINITION = 'UnionTypeDefinition'; +var ENUM_TYPE_DEFINITION = exports.ENUM_TYPE_DEFINITION = 'EnumTypeDefinition'; +var ENUM_VALUE_DEFINITION = exports.ENUM_VALUE_DEFINITION = 'EnumValueDefinition'; +var INPUT_OBJECT_TYPE_DEFINITION = exports.INPUT_OBJECT_TYPE_DEFINITION = 'InputObjectTypeDefinition'; + +// Type Extensions + +var TYPE_EXTENSION_DEFINITION = exports.TYPE_EXTENSION_DEFINITION = 'TypeExtensionDefinition'; + +// Directive Definitions + +var DIRECTIVE_DEFINITION = exports.DIRECTIVE_DEFINITION = 'DirectiveDefinition'; +},{}],103:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TokenKind = undefined; +exports.createLexer = createLexer; +exports.getTokenDesc = getTokenDesc; + +var _error = require('../error'); + +/** + * 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(SOF, 0, 0, 0, 0, null); + var lexer = { + source: source, + options: options, + lastToken: startOfFileToken, + token: startOfFileToken, + line: 1, + lineStart: 0, + advance: advanceLexer + }; + return lexer; +} /* / + /** + * 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 advanceLexer() { + var token = this.lastToken = this.token; + if (token.kind !== EOF) { + do { + token = token.next = readToken(this, token); + } while (token.kind === COMMENT); + this.token = token; + } + return token; +} + +/** + * The return type of createLexer. + */ + + +// Each kind of token. +var SOF = ''; +var EOF = ''; +var BANG = '!'; +var DOLLAR = '$'; +var PAREN_L = '('; +var PAREN_R = ')'; +var SPREAD = '...'; +var COLON = ':'; +var EQUALS = '='; +var AT = '@'; +var BRACKET_L = '['; +var BRACKET_R = ']'; +var BRACE_L = '{'; +var PIPE = '|'; +var BRACE_R = '}'; +var NAME = 'Name'; +var INT = 'Int'; +var FLOAT = 'Float'; +var STRING = 'String'; +var COMMENT = 'Comment'; + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +var TokenKind = exports.TokenKind = { + SOF: SOF, + EOF: EOF, + BANG: BANG, + DOLLAR: DOLLAR, + PAREN_L: PAREN_L, + PAREN_R: PAREN_R, + SPREAD: SPREAD, + COLON: COLON, + EQUALS: EQUALS, + AT: AT, + BRACKET_L: BRACKET_L, + BRACKET_R: BRACKET_R, + BRACE_L: BRACE_L, + PIPE: PIPE, + BRACE_R: BRACE_R, + NAME: NAME, + INT: INT, + FLOAT: FLOAT, + STRING: STRING, + COMMENT: COMMENT +}; + +/** + * A helper function to describe a token as a string for debugging + */ +function getTokenDesc(token) { + var value = token.value; + return value ? token.kind + ' "' + 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. +Tok.prototype.toJSON = Tok.prototype.inspect = function toJSON() { + 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) ? EOF : + // Trust JSON for ASCII. + code < 0x007F ? JSON.stringify(String.fromCharCode(code)) : + // Otherwise print the escaped form. + '"\\u' + ('00' + code.toString(16).toUpperCase()).slice(-4) + '"' + ); +} + +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace and comments 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 position = positionAfterWhitespace(body, prev.end, lexer); + var line = lexer.line; + var col = 1 + position - lexer.lineStart; + + if (position >= bodyLength) { + return new Tok(EOF, bodyLength, bodyLength, line, col, prev); + } + + var code = charCodeAt.call(body, position); + + // SourceCharacter + if (code < 0x0020 && code !== 0x0009 && code !== 0x000A && code !== 0x000D) { + throw (0, _error.syntaxError)(source, position, 'Cannot contain the invalid character ' + printCharCode(code) + '.'); + } + + switch (code) { + // ! + case 33: + return new Tok(BANG, position, position + 1, line, col, prev); + // # + case 35: + return readComment(source, position, line, col, prev); + // $ + case 36: + return new Tok(DOLLAR, position, position + 1, line, col, prev); + // ( + case 40: + return new Tok(PAREN_L, position, position + 1, line, col, prev); + // ) + case 41: + return new Tok(PAREN_R, position, position + 1, line, col, prev); + // . + case 46: + if (charCodeAt.call(body, position + 1) === 46 && charCodeAt.call(body, position + 2) === 46) { + return new Tok(SPREAD, position, position + 3, line, col, prev); + } + break; + // : + case 58: + return new Tok(COLON, position, position + 1, line, col, prev); + // = + case 61: + return new Tok(EQUALS, position, position + 1, line, col, prev); + // @ + case 64: + return new Tok(AT, position, position + 1, line, col, prev); + // [ + case 91: + return new Tok(BRACKET_L, position, position + 1, line, col, prev); + // ] + case 93: + return new Tok(BRACKET_R, position, position + 1, line, col, prev); + // { + case 123: + return new Tok(BRACE_L, position, position + 1, line, col, prev); + // | + case 124: + return new Tok(PIPE, position, position + 1, line, col, prev); + // } + case 125: + return new Tok(BRACE_R, position, position + 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, position, 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, position, code, line, col, prev); + // " + case 34: + return readString(source, position, line, col, prev); + } + + throw (0, _error.syntaxError)(source, position, unexpectedCharacterMessage(code)); +} + +/** + * Report a message that an unexpected character was encountered. + */ +function unexpectedCharacterMessage(code) { + if (code === 39) { + // ' + return 'Unexpected single quote character (\'), did you mean to use ' + 'a double quote (")?'; + } + + return 'Cannot parse the unexpected character ' + printCharCode(code) + '.'; +} + +/** + * Reads from body starting at startPosition until it finds a non-whitespace + * or commented 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 = void 0; + var position = start; + + do { + code = charCodeAt.call(body, ++position); + } while (code !== null && ( + // SourceCharacter but not LineTerminator + code > 0x001F || code === 0x0009)); + + return new Tok(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: ' + 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 ? FLOAT : 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: ' + 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 && + // not Quote (") + code !== 34) { + // SourceCharacter + if (code < 0x0020 && code !== 0x0009) { + throw (0, _error.syntaxError)(source, position, 'Invalid character within String: ' + 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' + body.slice(position + 1, position + 5) + '.')); + } + value += String.fromCharCode(charCode); + position += 4; + break; + default: + throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: \\' + String.fromCharCode(code) + '.'); + } + ++position; + chunkStart = position; + } + } + + if (code !== 34) { + // quote (") + throw (0, _error.syntaxError)(source, position, 'Unterminated string.'); + } + + value += slice.call(body, chunkStart, position); + return new Tok(STRING, start, position + 1, line, col, prev, value); +} + +/** + * Converts four hexidecimal 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, position, line, col, prev) { + var body = source.body; + var bodyLength = body.length; + var end = position + 1; + var code = 0; + while (end !== bodyLength && (code = charCodeAt.call(body, end)) !== null && (code === 95 || // _ + code >= 48 && code <= 57 || // 0-9 + code >= 65 && code <= 90 || // A-Z + code >= 97 && code <= 122 // a-z + )) { + ++end; + } + return new Tok(NAME, position, end, line, col, prev, slice.call(body, position, end)); +} +},{"../error":85}],104:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getLocation = getLocation; + + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ + +/** + * 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 getLocation(source, position) { + var lineRegexp = /\r\n|[\n\r]/g; + var line = 1; + var column = position + 1; + var match = void 0; + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + return { line: line, column: column }; +} + +/** + * Represents a location in a Source. + */ +},{}],105:[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 _source = require('./source'); + +var _error = require('../error'); + +var _lexer = require('./lexer'); + +var _kinds = require('./kinds'); + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ + + +/** + * Configuration options to control parser behavior + */ + +/** + * 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 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: ' + String(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.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; + expect(lexer, _lexer.TokenKind.SOF); + var definitions = []; + do { + definitions.push(parseDefinition(lexer)); + } while (!skip(lexer, _lexer.TokenKind.EOF)); + + return { + kind: _kinds.DOCUMENT, + definitions: definitions, + loc: loc(lexer, start) + }; +} + +/** + * Definition : + * - OperationDefinition + * - FragmentDefinition + * - TypeSystemDefinition + */ +function parseDefinition(lexer) { + if (peek(lexer, _lexer.TokenKind.BRACE_L)) { + return parseOperationDefinition(lexer); + } + + if (peek(lexer, _lexer.TokenKind.NAME)) { + switch (lexer.token.value) { + // Note: subscription is an experimental non-spec addition. + case 'query': + case 'mutation': + case 'subscription': + return parseOperationDefinition(lexer); + + case 'fragment': + return parseFragmentDefinition(lexer); + + // Note: the Type System IDL is an experimental non-spec addition. + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'extend': + case 'directive': + return parseTypeSystemDefinition(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.OPERATION_DEFINITION, + operation: 'query', + name: null, + variableDefinitions: null, + directives: [], + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; + } + var operation = parseOperationType(lexer); + var name = void 0; + if (peek(lexer, _lexer.TokenKind.NAME)) { + name = parseName(lexer); + } + return { + kind: _kinds.OPERATION_DEFINITION, + operation: operation, + name: name, + variableDefinitions: parseVariableDefinitions(lexer), + directives: parseDirectives(lexer), + 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'; + // Note: subscription is an experimental non-spec addition. + 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? + */ +function parseVariableDefinition(lexer) { + var start = lexer.token; + return { + kind: _kinds.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, _lexer.TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, _lexer.TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : null, + loc: loc(lexer, start) + }; +} + +/** + * Variable : $ Name + */ +function parseVariable(lexer) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.DOLLAR); + return { + kind: _kinds.VARIABLE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} + +/** + * SelectionSet : { Selection+ } + */ +function parseSelectionSet(lexer) { + var start = lexer.token; + return { + kind: _kinds.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 = void 0; + var name = void 0; + if (skip(lexer, _lexer.TokenKind.COLON)) { + alias = nameOrAlias; + name = parseName(lexer); + } else { + alias = null; + name = nameOrAlias; + } + + return { + kind: _kinds.FIELD, + alias: alias, + name: name, + arguments: parseArguments(lexer), + directives: parseDirectives(lexer), + selectionSet: peek(lexer, _lexer.TokenKind.BRACE_L) ? parseSelectionSet(lexer) : null, + loc: loc(lexer, start) + }; +} + +/** + * Arguments : ( Argument+ ) + */ +function parseArguments(lexer) { + return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, parseArgument, _lexer.TokenKind.PAREN_R) : []; +} + +/** + * Argument : Name : Value + */ +function parseArgument(lexer) { + var start = lexer.token; + return { + kind: _kinds.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, _lexer.TokenKind.COLON), parseValueLiteral(lexer, false)), + 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); + if (peek(lexer, _lexer.TokenKind.NAME) && lexer.token.value !== 'on') { + return { + kind: _kinds.FRAGMENT_SPREAD, + name: parseFragmentName(lexer), + directives: parseDirectives(lexer), + loc: loc(lexer, start) + }; + } + var typeCondition = null; + if (lexer.token.value === 'on') { + lexer.advance(); + typeCondition = parseNamedType(lexer); + } + return { + kind: _kinds.INLINE_FRAGMENT, + typeCondition: typeCondition, + directives: parseDirectives(lexer), + 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'); + return { + kind: _kinds.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer), + 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.INT, + value: token.value, + loc: loc(lexer, token) + }; + case _lexer.TokenKind.FLOAT: + lexer.advance(); + return { + kind: _kinds.FLOAT, + value: token.value, + loc: loc(lexer, token) + }; + case _lexer.TokenKind.STRING: + lexer.advance(); + return { + kind: _kinds.STRING, + value: token.value, + loc: loc(lexer, token) + }; + case _lexer.TokenKind.NAME: + if (token.value === 'true' || token.value === 'false') { + lexer.advance(); + return { + kind: _kinds.BOOLEAN, + value: token.value === 'true', + loc: loc(lexer, token) + }; + } else if (token.value === 'null') { + lexer.advance(); + return { + kind: _kinds.NULL, + loc: loc(lexer, token) + }; + } + lexer.advance(); + return { + kind: _kinds.ENUM, + value: token.value, + loc: loc(lexer, token) + }; + case _lexer.TokenKind.DOLLAR: + if (!isConst) { + return parseVariable(lexer); + } + break; + } + throw unexpected(lexer); +} + +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.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.OBJECT, + fields: fields, + loc: loc(lexer, start) + }; +} + +/** + * ObjectField[Const] : Name : Value[?Const] + */ +function parseObjectField(lexer, isConst) { + var start = lexer.token; + return { + kind: _kinds.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 : Directive+ + */ +function parseDirectives(lexer) { + var directives = []; + while (peek(lexer, _lexer.TokenKind.AT)) { + directives.push(parseDirective(lexer)); + } + return directives; +} + +/** + * Directive : @ Name Arguments? + */ +function parseDirective(lexer) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.AT); + return { + kind: _kinds.DIRECTIVE, + name: parseName(lexer), + arguments: parseArguments(lexer), + 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 = void 0; + if (skip(lexer, _lexer.TokenKind.BRACKET_L)) { + type = parseTypeReference(lexer); + expect(lexer, _lexer.TokenKind.BRACKET_R); + type = { + kind: _kinds.LIST_TYPE, + type: type, + loc: loc(lexer, start) + }; + } else { + type = parseNamedType(lexer); + } + if (skip(lexer, _lexer.TokenKind.BANG)) { + return { + kind: _kinds.NON_NULL_TYPE, + type: type, + loc: loc(lexer, start) + }; + } + return type; +} + +/** + * NamedType : Name + */ +function parseNamedType(lexer) { + var start = lexer.token; + return { + kind: _kinds.NAMED_TYPE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} + +// Implements the parsing rules in the Type Definition section. + +/** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - TypeExtensionDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ +function parseTypeSystemDefinition(lexer) { + if (peek(lexer, _lexer.TokenKind.NAME)) { + switch (lexer.token.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 'extend': + return parseTypeExtensionDefinition(lexer); + case 'directive': + return parseDirectiveDefinition(lexer); + } + } + + throw unexpected(lexer); +} + +/** + * SchemaDefinition : schema Directives? { OperationTypeDefinition+ } + * + * OperationTypeDefinition : OperationType : NamedType + */ +function parseSchemaDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'schema'); + var directives = parseDirectives(lexer); + var operationTypes = many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R); + return { + kind: _kinds.SCHEMA_DEFINITION, + directives: directives, + operationTypes: operationTypes, + loc: loc(lexer, start) + }; +} + +function parseOperationTypeDefinition(lexer) { + var start = lexer.token; + var operation = parseOperationType(lexer); + expect(lexer, _lexer.TokenKind.COLON); + var type = parseNamedType(lexer); + return { + kind: _kinds.OPERATION_TYPE_DEFINITION, + operation: operation, + type: type, + loc: loc(lexer, start) + }; +} + +/** + * ScalarTypeDefinition : scalar Name Directives? + */ +function parseScalarTypeDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'scalar'); + var name = parseName(lexer); + var directives = parseDirectives(lexer); + return { + kind: _kinds.SCALAR_TYPE_DEFINITION, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} + +/** + * ObjectTypeDefinition : + * - type Name ImplementsInterfaces? Directives? { FieldDefinition+ } + */ +function parseObjectTypeDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'type'); + var name = parseName(lexer); + var interfaces = parseImplementsInterfaces(lexer); + var directives = parseDirectives(lexer); + var fields = any(lexer, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R); + return { + kind: _kinds.OBJECT_TYPE_DEFINITION, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} + +/** + * ImplementsInterfaces : implements NamedType+ + */ +function parseImplementsInterfaces(lexer) { + var types = []; + if (lexer.token.value === 'implements') { + lexer.advance(); + do { + types.push(parseNamedType(lexer)); + } while (peek(lexer, _lexer.TokenKind.NAME)); + } + return types; +} + +/** + * FieldDefinition : Name ArgumentsDefinition? : Type Directives? + */ +function parseFieldDefinition(lexer) { + var start = lexer.token; + var name = parseName(lexer); + var args = parseArgumentDefs(lexer); + expect(lexer, _lexer.TokenKind.COLON); + var type = parseTypeReference(lexer); + var directives = parseDirectives(lexer); + return { + kind: _kinds.FIELD_DEFINITION, + 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 : Name : Type DefaultValue? Directives? + */ +function parseInputValueDef(lexer) { + var start = lexer.token; + var name = parseName(lexer); + expect(lexer, _lexer.TokenKind.COLON); + var type = parseTypeReference(lexer); + var defaultValue = null; + if (skip(lexer, _lexer.TokenKind.EQUALS)) { + defaultValue = parseConstValue(lexer); + } + var directives = parseDirectives(lexer); + return { + kind: _kinds.INPUT_VALUE_DEFINITION, + name: name, + type: type, + defaultValue: defaultValue, + directives: directives, + loc: loc(lexer, start) + }; +} + +/** + * InterfaceTypeDefinition : interface Name Directives? { FieldDefinition+ } + */ +function parseInterfaceTypeDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'interface'); + var name = parseName(lexer); + var directives = parseDirectives(lexer); + var fields = any(lexer, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R); + return { + kind: _kinds.INTERFACE_TYPE_DEFINITION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} + +/** + * UnionTypeDefinition : union Name Directives? = UnionMembers + */ +function parseUnionTypeDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'union'); + var name = parseName(lexer); + var directives = parseDirectives(lexer); + expect(lexer, _lexer.TokenKind.EQUALS); + var types = parseUnionMembers(lexer); + return { + kind: _kinds.UNION_TYPE_DEFINITION, + name: name, + directives: directives, + types: types, + loc: loc(lexer, start) + }; +} + +/** + * UnionMembers : + * - `|`? NamedType + * - UnionMembers | NamedType + */ +function parseUnionMembers(lexer) { + // Optional leading pipe + skip(lexer, _lexer.TokenKind.PIPE); + var members = []; + do { + members.push(parseNamedType(lexer)); + } while (skip(lexer, _lexer.TokenKind.PIPE)); + return members; +} + +/** + * EnumTypeDefinition : enum Name Directives? { EnumValueDefinition+ } + */ +function parseEnumTypeDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'enum'); + var name = parseName(lexer); + var directives = parseDirectives(lexer); + var values = many(lexer, _lexer.TokenKind.BRACE_L, parseEnumValueDefinition, _lexer.TokenKind.BRACE_R); + return { + kind: _kinds.ENUM_TYPE_DEFINITION, + name: name, + directives: directives, + values: values, + loc: loc(lexer, start) + }; +} + +/** + * EnumValueDefinition : EnumValue Directives? + * + * EnumValue : Name + */ +function parseEnumValueDefinition(lexer) { + var start = lexer.token; + var name = parseName(lexer); + var directives = parseDirectives(lexer); + return { + kind: _kinds.ENUM_VALUE_DEFINITION, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} + +/** + * InputObjectTypeDefinition : input Name Directives? { InputValueDefinition+ } + */ +function parseInputObjectTypeDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'input'); + var name = parseName(lexer); + var directives = parseDirectives(lexer); + var fields = any(lexer, _lexer.TokenKind.BRACE_L, parseInputValueDef, _lexer.TokenKind.BRACE_R); + return { + kind: _kinds.INPUT_OBJECT_TYPE_DEFINITION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} + +/** + * TypeExtensionDefinition : extend ObjectTypeDefinition + */ +function parseTypeExtensionDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + var definition = parseObjectTypeDefinition(lexer); + return { + kind: _kinds.TYPE_EXTENSION_DEFINITION, + definition: definition, + loc: loc(lexer, start) + }; +} + +/** + * DirectiveDefinition : + * - directive @ Name ArgumentsDefinition? on DirectiveLocations + */ +function parseDirectiveDefinition(lexer) { + var start = lexer.token; + 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.DIRECTIVE_DEFINITION, + name: name, + arguments: args, + locations: locations, + loc: loc(lexer, start) + }; +} + +/** + * DirectiveLocations : + * - `|`? Name + * - DirectiveLocations | Name + */ +function parseDirectiveLocations(lexer) { + // Optional leading pipe + skip(lexer, _lexer.TokenKind.PIPE); + var locations = []; + do { + locations.push(parseName(lexer)); + } while (skip(lexer, _lexer.TokenKind.PIPE)); + return locations; +} + +// 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. +Loc.prototype.toJSON = Loc.prototype.inspect = function toJSON() { + 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) { + var match = lexer.token.kind === kind; + if (match) { + lexer.advance(); + } + return match; +} + +/** + * 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 ' + kind + ', found ' + (0, _lexer.getTokenDesc)(token)); +} + +/** + * 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 return + * false. + */ +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 "' + value + '", found ' + (0, _lexer.getTokenDesc)(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 ' + (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":85,"./kinds":102,"./lexer":103,"./source":107}],106:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.print = print; + +var _visitor = require('./visitor'); + +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ +function print(ast) { + return (0, _visitor.visit)(ast, { leave: printDocASTReducer }); +} /** + * 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 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; + return variable + ': ' + type + wrap(' = ', defaultValue); + }, + + 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, + directives = _ref7.directives, + selectionSet = _ref7.selectionSet; + return 'fragment ' + name + ' on ' + typeCondition + ' ' + 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) { + var value = _ref10.value; + return JSON.stringify(value); + }, + BooleanValue: function BooleanValue(_ref11) { + var value = _ref11.value; + return JSON.stringify(value); + }, + 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: function ScalarTypeDefinition(_ref22) { + var name = _ref22.name, + directives = _ref22.directives; + return join(['scalar', name, join(directives, ' ')], ' '); + }, + + ObjectTypeDefinition: function ObjectTypeDefinition(_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: function FieldDefinition(_ref24) { + var name = _ref24.name, + args = _ref24.arguments, + type = _ref24.type, + directives = _ref24.directives; + return name + wrap('(', join(args, ', '), ')') + ': ' + type + wrap(' ', join(directives, ' ')); + }, + + InputValueDefinition: function InputValueDefinition(_ref25) { + var name = _ref25.name, + type = _ref25.type, + defaultValue = _ref25.defaultValue, + directives = _ref25.directives; + return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' '); + }, + + InterfaceTypeDefinition: function InterfaceTypeDefinition(_ref26) { + var name = _ref26.name, + directives = _ref26.directives, + fields = _ref26.fields; + return join(['interface', name, join(directives, ' '), block(fields)], ' '); + }, + + UnionTypeDefinition: function UnionTypeDefinition(_ref27) { + var name = _ref27.name, + directives = _ref27.directives, + types = _ref27.types; + return join(['union', name, join(directives, ' '), '= ' + join(types, ' | ')], ' '); + }, + + EnumTypeDefinition: function EnumTypeDefinition(_ref28) { + var name = _ref28.name, + directives = _ref28.directives, + values = _ref28.values; + return join(['enum', name, join(directives, ' '), block(values)], ' '); + }, + + EnumValueDefinition: function EnumValueDefinition(_ref29) { + var name = _ref29.name, + directives = _ref29.directives; + return join([name, join(directives, ' ')], ' '); + }, + + InputObjectTypeDefinition: function InputObjectTypeDefinition(_ref30) { + var name = _ref30.name, + directives = _ref30.directives, + fields = _ref30.fields; + return join(['input', name, join(directives, ' '), block(fields)], ' '); + }, + + TypeExtensionDefinition: function TypeExtensionDefinition(_ref31) { + var definition = _ref31.definition; + return 'extend ' + definition; + }, + + DirectiveDefinition: function DirectiveDefinition(_ref32) { + var name = _ref32.name, + args = _ref32.arguments, + locations = _ref32.locations; + return 'directive @' + name + wrap('(', join(args, ', '), ')') + ' on ' + join(locations, ' | '); + } +}; + +/** + * 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 ? indent('{\n' + 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 '); +} +},{"./visitor":108}],107:[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"); } } + +/** + * 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. + */ + +/** + * A representation of source input to GraphQL. The name is optional, + * but is mostly useful for clients who store GraphQL documents in + * source files; for example, if the GraphQL input is in a file Foo.graphql, + * it might be useful for name to be "Foo.graphql". + */ +var Source = exports.Source = function Source(body, name) { + _classCallCheck(this, Source); + + this.body = body; + this.name = name || 'GraphQL request'; +}; +},{}],108:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.visit = visit; +exports.visitInParallel = visitInParallel; +exports.visitWithTypeInfo = visitWithTypeInfo; +exports.getVisitFn = getVisitFn; +/** + * 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 QueryDocumentKeys = exports.QueryDocumentKeys = { + Name: [], + + Document: ['definitions'], + OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], + VariableDefinition: ['variable', 'type', 'defaultValue'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: ['name', '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: ['name', 'directives'], + ObjectTypeDefinition: ['name', 'interfaces', 'directives', 'fields'], + FieldDefinition: ['name', 'arguments', 'type', 'directives'], + InputValueDefinition: ['name', 'type', 'defaultValue', 'directives'], + InterfaceTypeDefinition: ['name', 'directives', 'fields'], + UnionTypeDefinition: ['name', 'directives', 'types'], + EnumTypeDefinition: ['name', 'directives', 'values'], + EnumValueDefinition: ['name', 'directives'], + InputObjectTypeDefinition: ['name', 'directives', 'fields'], + + TypeExtensionDefinition: ['definition'], + + DirectiveDefinition: ['name', 'arguments', 'locations'] +}; + +var BREAK = exports.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 + * } + * } + * }) + */ +function visit(root, visitor, keyMap) { + var visitorKeys = keyMap || QueryDocumentKeys; + + var stack = void 0; + var inArray = Array.isArray(root); + var keys = [root]; + var index = -1; + var edits = []; + var parent = void 0; + var path = []; + var ancestors = []; + var newRoot = root; + + do { + index++; + var isLeaving = index === keys.length; + var key = void 0; + var node = void 0; + var isEdited = isLeaving && edits.length !== 0; + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path.pop(); + node = parent; + parent = ancestors.pop(); + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + var clone = {}; + for (var k in node) { + if (node.hasOwnProperty(k)) { + 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: ' + JSON.stringify(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) { + 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 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 = void 0; + 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; + } + } + } +} +},{}],109:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _subscribe = require('./subscribe'); + +Object.defineProperty(exports, 'subscribe', { + enumerable: true, + get: function get() { + return _subscribe.subscribe; + } +}); +Object.defineProperty(exports, 'createSourceEventStream', { + enumerable: true, + get: function get() { + return _subscribe.createSourceEventStream; + } +}); +},{"./subscribe":111}],110:[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; } /** + * 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. + * + * + */ + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +function mapAsyncIterator(iterable, callback) { + var iterator = (0, _iterall.getAsyncIterator)(iterable); + var $return = void 0; + var abruptClose = void 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); + } + + return _defineProperty({ + next: function next() { + return iterator.next().then(mapResult); + }, + 'return': function _return() { + return $return ? $return.call(iterator).then(mapResult) : Promise.resolve({ value: undefined, done: true }); + }, + 'throw': function _throw(error) { + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult); + } + 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":166}],111:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.subscribe = subscribe; +exports.createSourceEventStream = createSourceEventStream; + +var _iterall = require('iterall'); + +var _execute = require('../execution/execute'); + +var _schema = require('../type/schema'); + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _mapAsyncIterator = require('./mapAsyncIterator'); + +var _mapAsyncIterator2 = _interopRequireDefault(_mapAsyncIterator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns an AsyncIterator + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Accepts either an object with named arguments, or individual arguments. + */ + +/* eslint-disable no-redeclare */ +function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + // Extract arguments from object args if provided. + var args = arguments.length === 1 ? argsOrSchema : undefined; + var schema = args ? args.schema : argsOrSchema; + return args ? subscribeImpl(schema, args.document, args.rootValue, args.contextValue, args.variableValues, args.operationName, args.fieldResolver, args.subscribeFieldResolver) : subscribeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver); +} /** + * 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 subscribeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + var subscription = 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. + return (0, _mapAsyncIterator2.default)(subscription, function (payload) { + return (0, _execute.execute)(schema, document, payload, contextValue, variableValues, operationName, fieldResolver); + }); +} + +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns an AsyncIterable, may through a GraphQLError. + * + * A Source Stream represents the sequence of events, each of which is + * expected to be used to trigger 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 incorrect, throw an error. + (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); + + // 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); + + var type = (0, _execute.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 fieldDef = (0, _execute.getFieldDef)(schema, type, fieldNode.name.value); + (0, _invariant2.default)(fieldDef, 'This subscription is not defined by the schema.'); + + // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + var resolveFn = fieldDef.subscribe || exeContext.fieldResolver; + + var info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, type, (0, _execute.addPath)(undefined, responseName)); + + // resolveFieldValueOrError implements the "ResolveFieldEventStream" + // algorithm from GraphQL specification. It differs from + // "ResolveFieldValue" due to providing a different `resolveFn`. + var subscription = (0, _execute.resolveFieldValueOrError)(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); + + if (subscription instanceof Error) { + throw subscription; + } + + if (!(0, _iterall.isAsyncIterable)(subscription)) { + throw new Error('Subscription must return Async Iterable. ' + 'Received: ' + String(subscription)); + } + + return subscription; +} +},{"../execution/execute":88,"../jsutils/invariant":94,"../type/schema":117,"./mapAsyncIterator":110,"iterall":166}],112:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GraphQLNonNull = exports.GraphQLList = exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = undefined; + +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; }; + +exports.isType = isType; +exports.assertType = assertType; +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.getNullableType = getNullableType; +exports.isNamedType = isNamedType; +exports.assertNamedType = assertNamedType; +exports.getNamedType = getNamedType; + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isNullish = require('../jsutils/isNullish'); + +var _isNullish2 = _interopRequireDefault(_isNullish); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _assertValidName = require('../utilities/assertValidName'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +/** + * 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. + */ + +// Predicates & Assertions + +/** + * These are all of the possible kinds of types. + */ +function isType(type) { + return type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType || type instanceof GraphQLList || type instanceof GraphQLNonNull; +} + +function assertType(type) { + (0, _invariant2.default)(isType(type), 'Expected ' + String(type) + ' to be a GraphQL type.'); + return type; +} + +/** + * These types may be used as input types for arguments and directives. + */ +function isInputType(type) { + return type instanceof GraphQLScalarType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType || type instanceof GraphQLNonNull && isInputType(type.ofType) || type instanceof GraphQLList && isInputType(type.ofType); +} + +function assertInputType(type) { + (0, _invariant2.default)(isInputType(type), 'Expected ' + String(type) + ' to be a GraphQL input type.'); + return type; +} + +/** + * These types may be used as output types as the result of fields. + */ +function isOutputType(type) { + return type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLNonNull && isOutputType(type.ofType) || type instanceof GraphQLList && isOutputType(type.ofType); +} + +function assertOutputType(type) { + (0, _invariant2.default)(isOutputType(type), 'Expected ' + String(type) + ' to be a GraphQL output type.'); + return type; +} + +/** + * These types may describe types which may be leaf values. + */ +function isLeafType(type) { + return type instanceof GraphQLScalarType || type instanceof GraphQLEnumType; +} + +function assertLeafType(type) { + (0, _invariant2.default)(isLeafType(type), 'Expected ' + String(type) + ' to be a GraphQL leaf type.'); + return type; +} + +/** + * These types may describe the parent context of a selection set. + */ +function isCompositeType(type) { + return type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType; +} + +function assertCompositeType(type) { + (0, _invariant2.default)(isCompositeType(type), 'Expected ' + String(type) + ' to be a GraphQL composite type.'); + return type; +} + +/** + * These types may describe the parent context of a selection set. + */ +function isAbstractType(type) { + return type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType; +} + +function assertAbstractType(type) { + (0, _invariant2.default)(isAbstractType(type), 'Expected ' + String(type) + ' to be a GraphQL abstract type.'); + return type; +} + +/** + * These types can all accept null as a value. + */ +function getNullableType(type) { + return type instanceof GraphQLNonNull ? type.ofType : type; +} + +/** + * These named types do not include modifiers like List or NonNull. + */ +function isNamedType(type) { + return type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType; +} + +function assertNamedType(type) { + (0, _invariant2.default)(isNamedType(type), 'Expected ' + String(type) + ' to be a GraphQL named type.'); + return type; +} + +/* eslint-disable no-redeclare */ +function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + var unmodifiedType = type; + while (unmodifiedType instanceof GraphQLList || unmodifiedType instanceof GraphQLNonNull) { + unmodifiedType = unmodifiedType.ofType; + } + return unmodifiedType; + } +} + +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ + + +function resolveThunk(thunk) { + 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. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * return value % 2 === 1 ? value : null; + * } + * }); + * + */ + +var GraphQLScalarType = exports.GraphQLScalarType = function () { + function GraphQLScalarType(config) { + _classCallCheck(this, GraphQLScalarType); + + (0, _assertValidName.assertValidName)(config.name); + this.name = config.name; + this.description = config.description; + (0, _invariant2.default)(typeof config.serialize === 'function', 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.'); + if (config.parseValue || config.parseLiteral) { + (0, _invariant2.default)(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function', this.name + ' must provide both "parseValue" and "parseLiteral" ' + 'functions.'); + } + this._scalarConfig = config; + } + + // Serializes an internal value to include in a response. + + + GraphQLScalarType.prototype.serialize = function serialize(value) { + var serializer = this._scalarConfig.serialize; + return serializer(value); + }; + + // Determines if an internal value is valid for this type. + // Equivalent to checking for if the parsedValue is nullish. + + + GraphQLScalarType.prototype.isValidValue = function isValidValue(value) { + return !(0, _isNullish2.default)(this.parseValue(value)); + }; + + // Parses an externally provided value to use as an input. + + + GraphQLScalarType.prototype.parseValue = function parseValue(value) { + var parser = this._scalarConfig.parseValue; + return parser && !(0, _isNullish2.default)(value) ? parser(value) : undefined; + }; + + // Determines if an internal value is valid for this type. + // Equivalent to checking for if the parsedLiteral is nullish. + + + GraphQLScalarType.prototype.isValidLiteral = function isValidLiteral(valueNode) { + return !(0, _isNullish2.default)(this.parseLiteral(valueNode)); + }; + + // Parses an externally provided literal value to use as an input. + + + GraphQLScalarType.prototype.parseLiteral = function parseLiteral(valueNode) { + var parser = this._scalarConfig.parseLiteral; + return parser ? parser(valueNode) : undefined; + }; + + GraphQLScalarType.prototype.toString = function toString() { + return this.name; + }; + + return GraphQLScalarType; +}(); + +// Also provide toJSON and inspect aliases for toString. + + +GraphQLScalarType.prototype.toJSON = GraphQLScalarType.prototype.inspect = GraphQLScalarType.prototype.toString; + +/** + * 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 = exports.GraphQLObjectType = function () { + function GraphQLObjectType(config) { + _classCallCheck(this, GraphQLObjectType); + + (0, _assertValidName.assertValidName)(config.name, config.isIntrospection); + this.name = config.name; + this.description = config.description; + if (config.isTypeOf) { + (0, _invariant2.default)(typeof config.isTypeOf === 'function', this.name + ' must provide "isTypeOf" as a function.'); + } + this.isTypeOf = config.isTypeOf; + this._typeConfig = config; + } + + GraphQLObjectType.prototype.getFields = function getFields() { + return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields)); + }; + + GraphQLObjectType.prototype.getInterfaces = function getInterfaces() { + return this._interfaces || (this._interfaces = defineInterfaces(this, this._typeConfig.interfaces)); + }; + + GraphQLObjectType.prototype.toString = function toString() { + return this.name; + }; + + return GraphQLObjectType; +}(); + +// Also provide toJSON and inspect aliases for toString. + + +GraphQLObjectType.prototype.toJSON = GraphQLObjectType.prototype.inspect = GraphQLObjectType.prototype.toString; + +function defineInterfaces(type, interfacesThunk) { + var interfaces = resolveThunk(interfacesThunk); + if (!interfaces) { + return []; + } + (0, _invariant2.default)(Array.isArray(interfaces), type.name + ' interfaces must be an Array or a function which returns ' + 'an Array.'); + + var implementedTypeNames = Object.create(null); + interfaces.forEach(function (iface) { + (0, _invariant2.default)(iface instanceof GraphQLInterfaceType, type.name + ' may only implement Interface types, it cannot ' + ('implement: ' + String(iface) + '.')); + (0, _invariant2.default)(!implementedTypeNames[iface.name], type.name + ' may declare it implements ' + iface.name + ' only once.'); + implementedTypeNames[iface.name] = true; + if (typeof iface.resolveType !== 'function') { + (0, _invariant2.default)(typeof type.isTypeOf === 'function', 'Interface Type ' + iface.name + ' does not provide a "resolveType" ' + ('function and implementing Type ' + type.name + ' does not provide a ') + '"isTypeOf" function. There is no way to resolve this implementing ' + 'type during execution.'); + } + }); + return interfaces; +} + +function defineFieldMap(type, fieldsThunk) { + var fieldMap = resolveThunk(fieldsThunk); + (0, _invariant2.default)(isPlainObj(fieldMap), type.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.'); + + var fieldNames = Object.keys(fieldMap); + (0, _invariant2.default)(fieldNames.length > 0, type.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.'); + + var resultFieldMap = Object.create(null); + fieldNames.forEach(function (fieldName) { + (0, _assertValidName.assertValidName)(fieldName); + var fieldConfig = fieldMap[fieldName]; + (0, _invariant2.default)(isPlainObj(fieldConfig), type.name + '.' + fieldName + ' field config must be an object'); + (0, _invariant2.default)(!fieldConfig.hasOwnProperty('isDeprecated'), type.name + '.' + fieldName + ' should provide "deprecationReason" instead ' + 'of "isDeprecated".'); + var field = _extends({}, fieldConfig, { + isDeprecated: Boolean(fieldConfig.deprecationReason), + name: fieldName + }); + (0, _invariant2.default)(isOutputType(field.type), type.name + '.' + fieldName + ' field type must be Output Type but ' + ('got: ' + String(field.type) + '.')); + (0, _invariant2.default)(isValidResolver(field.resolve), type.name + '.' + fieldName + ' field resolver must be a function if ' + ('provided, but got: ' + String(field.resolve) + '.')); + var argsConfig = fieldConfig.args; + if (!argsConfig) { + field.args = []; + } else { + (0, _invariant2.default)(isPlainObj(argsConfig), type.name + '.' + fieldName + ' args must be an object with argument ' + 'names as keys.'); + field.args = Object.keys(argsConfig).map(function (argName) { + (0, _assertValidName.assertValidName)(argName); + var arg = argsConfig[argName]; + (0, _invariant2.default)(isInputType(arg.type), type.name + '.' + fieldName + '(' + argName + ':) argument type must be ' + ('Input Type but got: ' + String(arg.type) + '.')); + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue + }; + }); + } + resultFieldMap[fieldName] = field; + }); + return resultFieldMap; +} + +function isPlainObj(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); +} + +// If a resolver is defined, it must be a function. +function isValidResolver(resolver) { + return resolver == null || typeof resolver === 'function'; +} + +/** + * 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 = exports.GraphQLInterfaceType = function () { + function GraphQLInterfaceType(config) { + _classCallCheck(this, GraphQLInterfaceType); + + (0, _assertValidName.assertValidName)(config.name); + this.name = config.name; + this.description = config.description; + if (config.resolveType) { + (0, _invariant2.default)(typeof config.resolveType === 'function', this.name + ' must provide "resolveType" as a function.'); + } + this.resolveType = config.resolveType; + this._typeConfig = config; + } + + GraphQLInterfaceType.prototype.getFields = function getFields() { + return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields)); + }; + + GraphQLInterfaceType.prototype.toString = function toString() { + return this.name; + }; + + return GraphQLInterfaceType; +}(); + +// Also provide toJSON and inspect aliases for toString. + + +GraphQLInterfaceType.prototype.toJSON = GraphQLInterfaceType.prototype.inspect = GraphQLInterfaceType.prototype.toString; + +/** + * 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 = exports.GraphQLUnionType = function () { + function GraphQLUnionType(config) { + _classCallCheck(this, GraphQLUnionType); + + (0, _assertValidName.assertValidName)(config.name); + this.name = config.name; + this.description = config.description; + if (config.resolveType) { + (0, _invariant2.default)(typeof config.resolveType === 'function', this.name + ' must provide "resolveType" as a function.'); + } + this.resolveType = config.resolveType; + this._typeConfig = config; + } + + GraphQLUnionType.prototype.getTypes = function getTypes() { + return this._types || (this._types = defineTypes(this, this._typeConfig.types)); + }; + + GraphQLUnionType.prototype.toString = function toString() { + return this.name; + }; + + return GraphQLUnionType; +}(); + +// Also provide toJSON and inspect aliases for toString. + + +GraphQLUnionType.prototype.toJSON = GraphQLUnionType.prototype.inspect = GraphQLUnionType.prototype.toString; + +function defineTypes(unionType, typesThunk) { + var types = resolveThunk(typesThunk); + + (0, _invariant2.default)(Array.isArray(types) && types.length > 0, 'Must provide Array of types or a function which returns ' + ('such an array for Union ' + unionType.name + '.')); + var includedTypeNames = Object.create(null); + types.forEach(function (objType) { + (0, _invariant2.default)(objType instanceof GraphQLObjectType, unionType.name + ' may only contain Object types, it cannot contain: ' + (String(objType) + '.')); + (0, _invariant2.default)(!includedTypeNames[objType.name], unionType.name + ' can include ' + objType.name + ' type only once.'); + includedTypeNames[objType.name] = true; + if (typeof unionType.resolveType !== 'function') { + (0, _invariant2.default)(typeof objType.isTypeOf === 'function', 'Union type "' + unionType.name + '" does not provide a "resolveType" ' + ('function and possible type "' + objType.name + '" does not provide an ') + '"isTypeOf" function. There is no way to resolve this possible type ' + 'during execution.'); + } + }); + + 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 /* */ = exports.GraphQLEnumType = function () { + function GraphQLEnumType(config /* */) { + _classCallCheck(this, GraphQLEnumType); + + this.name = config.name; + (0, _assertValidName.assertValidName)(config.name, config.isIntrospection); + this.description = config.description; + this._values = defineEnumValues(this, config.values); + this._enumConfig = config; + } + + GraphQLEnumType.prototype.getValues = function getValues() { + return this._values; + }; + + GraphQLEnumType.prototype.getValue = function getValue(name) { + return this._getNameLookup()[name]; + }; + + GraphQLEnumType.prototype.serialize = function serialize(value /* T */) { + var enumValue = this._getValueLookup().get(value); + return enumValue ? enumValue.name : null; + }; + + GraphQLEnumType.prototype.isValidValue = function isValidValue(value) { + return typeof value === 'string' && this._getNameLookup()[value] !== undefined; + }; + + GraphQLEnumType.prototype.parseValue = function parseValue(value) /* T */{ + if (typeof value === 'string') { + var enumValue = this._getNameLookup()[value]; + if (enumValue) { + return enumValue.value; + } + } + }; + + GraphQLEnumType.prototype.isValidLiteral = function isValidLiteral(valueNode) { + return valueNode.kind === Kind.ENUM && this._getNameLookup()[valueNode.value] !== undefined; + }; + + GraphQLEnumType.prototype.parseLiteral = function parseLiteral(valueNode) /* T */{ + if (valueNode.kind === Kind.ENUM) { + var enumValue = this._getNameLookup()[valueNode.value]; + if (enumValue) { + return enumValue.value; + } + } + }; + + GraphQLEnumType.prototype._getValueLookup = function _getValueLookup() { + if (!this._valueLookup) { + var lookup = new Map(); + this.getValues().forEach(function (value) { + lookup.set(value.value, value); + }); + this._valueLookup = lookup; + } + return this._valueLookup; + }; + + GraphQLEnumType.prototype._getNameLookup = function _getNameLookup() { + if (!this._nameLookup) { + var lookup = Object.create(null); + this.getValues().forEach(function (value) { + lookup[value.name] = value; + }); + this._nameLookup = lookup; + } + return this._nameLookup; + }; + + GraphQLEnumType.prototype.toString = function toString() { + return this.name; + }; + + return GraphQLEnumType; +}(); + +// Also provide toJSON and inspect aliases for toString. + + +GraphQLEnumType.prototype.toJSON = GraphQLEnumType.prototype.inspect = GraphQLEnumType.prototype.toString; + +function defineEnumValues(type, valueMap /* */ +) { + (0, _invariant2.default)(isPlainObj(valueMap), type.name + ' values must be an object with value names as keys.'); + var valueNames = Object.keys(valueMap); + (0, _invariant2.default)(valueNames.length > 0, type.name + ' values must be an object with value names as keys.'); + return valueNames.map(function (valueName) { + (0, _assertValidName.assertValidName)(valueName); + (0, _invariant2.default)(['true', 'false', 'null'].indexOf(valueName) === -1, 'Name "' + valueName + '" can not be used as an Enum value.'); + + var value = valueMap[valueName]; + (0, _invariant2.default)(isPlainObj(value), type.name + '.' + valueName + ' must refer to an object with a "value" key ' + ('representing an internal value but got: ' + String(value) + '.')); + (0, _invariant2.default)(!value.hasOwnProperty('isDeprecated'), type.name + '.' + valueName + ' should provide "deprecationReason" instead ' + 'of "isDeprecated".'); + return { + name: valueName, + description: value.description, + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + 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: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +var GraphQLInputObjectType = exports.GraphQLInputObjectType = function () { + function GraphQLInputObjectType(config) { + _classCallCheck(this, GraphQLInputObjectType); + + (0, _assertValidName.assertValidName)(config.name); + this.name = config.name; + this.description = config.description; + this._typeConfig = config; + } + + GraphQLInputObjectType.prototype.getFields = function getFields() { + return this._fields || (this._fields = this._defineFieldMap()); + }; + + GraphQLInputObjectType.prototype._defineFieldMap = function _defineFieldMap() { + var _this = this; + + var fieldMap = resolveThunk(this._typeConfig.fields); + (0, _invariant2.default)(isPlainObj(fieldMap), this.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.'); + var fieldNames = Object.keys(fieldMap); + (0, _invariant2.default)(fieldNames.length > 0, this.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.'); + var resultFieldMap = Object.create(null); + fieldNames.forEach(function (fieldName) { + (0, _assertValidName.assertValidName)(fieldName); + var field = _extends({}, fieldMap[fieldName], { + name: fieldName + }); + (0, _invariant2.default)(isInputType(field.type), _this.name + '.' + fieldName + ' field type must be Input Type but ' + ('got: ' + String(field.type) + '.')); + (0, _invariant2.default)(field.resolve == null, _this.name + '.' + fieldName + ' field type has a resolve property, but ' + 'Input Types cannot define resolvers.'); + resultFieldMap[fieldName] = field; + }); + return resultFieldMap; + }; + + GraphQLInputObjectType.prototype.toString = function toString() { + return this.name; + }; + + return GraphQLInputObjectType; +}(); + +// Also provide toJSON and inspect aliases for toString. + + +GraphQLInputObjectType.prototype.toJSON = GraphQLInputObjectType.prototype.inspect = GraphQLInputObjectType.prototype.toString; + +/** + * List Modifier + * + * A list is a kind of type marker, 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: new GraphQLList(Person) }, + * children: { type: new GraphQLList(Person) }, + * }) + * }) + * + */ +var GraphQLList = exports.GraphQLList = function () { + function GraphQLList(type) { + _classCallCheck(this, GraphQLList); + + (0, _invariant2.default)(isType(type), 'Can only create List of a GraphQLType but got: ' + String(type) + '.'); + this.ofType = type; + } + + GraphQLList.prototype.toString = function toString() { + return '[' + String(this.ofType) + ']'; + }; + + return GraphQLList; +}(); + +// Also provide toJSON and inspect aliases for toString. + + +GraphQLList.prototype.toJSON = GraphQLList.prototype.inspect = GraphQLList.prototype.toString; + +/** + * Non-Null Modifier + * + * A non-null is a kind of type marker, 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: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ + +var GraphQLNonNull = exports.GraphQLNonNull = function () { + function GraphQLNonNull(type) { + _classCallCheck(this, GraphQLNonNull); + + (0, _invariant2.default)(isType(type) && !(type instanceof GraphQLNonNull), 'Can only create NonNull of a Nullable GraphQLType but got: ' + (String(type) + '.')); + this.ofType = type; + } + + GraphQLNonNull.prototype.toString = function toString() { + return this.ofType.toString() + '!'; + }; + + return GraphQLNonNull; +}(); + +// Also provide toJSON and inspect aliases for toString. + + +GraphQLNonNull.prototype.toJSON = GraphQLNonNull.prototype.inspect = GraphQLNonNull.prototype.toString; +},{"../jsutils/invariant":94,"../jsutils/isNullish":96,"../language/kinds":102,"../utilities/assertValidName":119}],113:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.specifiedDirectives = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = exports.DirectiveLocation = undefined; + +var _definition = require('./definition'); + +var _scalars = require('./scalars'); + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _assertValidName = require('../utilities/assertValidName'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +/** + * 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 DirectiveLocation = exports.DirectiveLocation = { + // Operations + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + // Schema 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' +}; + +// eslint-disable-line + +/** + * 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 = exports.GraphQLDirective = function GraphQLDirective(config) { + _classCallCheck(this, GraphQLDirective); + + (0, _invariant2.default)(config.name, 'Directive must be named.'); + (0, _assertValidName.assertValidName)(config.name); + (0, _invariant2.default)(Array.isArray(config.locations), 'Must provide locations for directive.'); + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + + var args = config.args; + if (!args) { + this.args = []; + } else { + (0, _invariant2.default)(!Array.isArray(args), '@' + config.name + ' args must be an object with argument names as keys.'); + this.args = Object.keys(args).map(function (argName) { + (0, _assertValidName.assertValidName)(argName); + var arg = args[argName]; + (0, _invariant2.default)((0, _definition.isInputType)(arg.type), '@' + config.name + '(' + argName + ':) argument type must be ' + ('Input Type but got: ' + String(arg.type) + '.')); + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue + }; + }); + } +}; + +/** + * Used to conditionally include fields or fragments. + */ +var GraphQLIncludeDirective = exports.GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: 'Directs the executor to include this field or fragment only when ' + 'the `if` argument is true.', + locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT], + args: { + 'if': { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Included when true.' + } + } +}); + +/** + * Used to conditionally skip (exclude) fields or fragments. + */ +var GraphQLSkipDirective = exports.GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: 'Directs the executor to skip this field or fragment when the `if` ' + 'argument is true.', + locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT], + args: { + 'if': { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Skipped when true.' + } + } +}); + +/** + * Constant string used for default reason for a deprecation. + */ +var DEFAULT_DEPRECATION_REASON = exports.DEFAULT_DEPRECATION_REASON = 'No longer supported'; + +/** + * Used to declare element of a GraphQL schema as deprecated. + */ +var GraphQLDeprecatedDirective = exports.GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [DirectiveLocation.FIELD_DEFINITION, 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 ' + 'in [Markdown](https://daringfireball.net/projects/markdown/).', + defaultValue: DEFAULT_DEPRECATION_REASON + } + } +}); + +/** + * The full list of specified directives. + */ +var specifiedDirectives = exports.specifiedDirectives = [GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective]; +},{"../jsutils/invariant":94,"../utilities/assertValidName":119,"./definition":112,"./scalars":116}],114:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _schema = require('./schema'); + +Object.defineProperty(exports, 'GraphQLSchema', { + enumerable: true, + get: function get() { + return _schema.GraphQLSchema; + } +}); + +var _definition = require('./definition'); + +Object.defineProperty(exports, 'isType', { + enumerable: true, + get: function get() { + return _definition.isType; + } +}); +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, 'isNamedType', { + enumerable: true, + get: function get() { + return _definition.isNamedType; + } +}); +Object.defineProperty(exports, 'assertType', { + enumerable: true, + get: function get() { + return _definition.assertType; + } +}); +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, '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; + } +}); + +var _directives = require('./directives'); + +Object.defineProperty(exports, 'DirectiveLocation', { + enumerable: true, + get: function get() { + return _directives.DirectiveLocation; + } +}); +Object.defineProperty(exports, 'GraphQLDirective', { + enumerable: true, + get: function get() { + return _directives.GraphQLDirective; + } +}); +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; + } +}); + +var _scalars = require('./scalars'); + +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; + } +}); + +var _introspection = require('./introspection'); + +Object.defineProperty(exports, 'TypeKind', { + enumerable: true, + get: function get() { + return _introspection.TypeKind; + } +}); +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; + } +}); +},{"./definition":112,"./directives":113,"./introspection":115,"./scalars":116,"./schema":117}],115:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.__TypeKind = exports.TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = undefined; + +var _isInvalid = require('../jsutils/isInvalid'); + +var _isInvalid2 = _interopRequireDefault(_isInvalid); + +var _astFromValue = require('../utilities/astFromValue'); + +var _printer = require('../language/printer'); + +var _definition = require('./definition'); + +var _scalars = require('./scalars'); + +var _directives = require('./directives'); + +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 __Schema = exports.__Schema = new _definition.GraphQLObjectType({ + name: '__Schema', + isIntrospection: true, + 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: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type))), + resolve: function resolve(schema) { + var typeMap = schema.getTypeMap(); + return Object.keys(typeMap).map(function (key) { + return typeMap[key]; + }); + } + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: new _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: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Directive))), + resolve: function resolve(schema) { + return schema.getDirectives(); + } + } + }; + } +}); + +var __Directive = exports.__Directive = new _definition.GraphQLObjectType({ + name: '__Directive', + isIntrospection: true, + 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: new _definition.GraphQLNonNull(_scalars.GraphQLString) }, + description: { type: _scalars.GraphQLString }, + locations: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__DirectiveLocation))) + }, + args: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), + resolve: function resolve(directive) { + return directive.args || []; + } + }, + // NOTE: the following three fields are deprecated and are no longer part + // of the GraphQL specification. + onOperation: { + deprecationReason: 'Use `locations`.', + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: function resolve(d) { + return d.locations.indexOf(_directives.DirectiveLocation.QUERY) !== -1 || d.locations.indexOf(_directives.DirectiveLocation.MUTATION) !== -1 || d.locations.indexOf(_directives.DirectiveLocation.SUBSCRIPTION) !== -1; + } + }, + onFragment: { + deprecationReason: 'Use `locations`.', + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: function resolve(d) { + return d.locations.indexOf(_directives.DirectiveLocation.FRAGMENT_SPREAD) !== -1 || d.locations.indexOf(_directives.DirectiveLocation.INLINE_FRAGMENT) !== -1 || d.locations.indexOf(_directives.DirectiveLocation.FRAGMENT_DEFINITION) !== -1; + } + }, + onField: { + deprecationReason: 'Use `locations`.', + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: function resolve(d) { + return d.locations.indexOf(_directives.DirectiveLocation.FIELD) !== -1; + } + } + }; + } +}); + +var __DirectiveLocation = exports.__DirectiveLocation = new _definition.GraphQLEnumType({ + name: '__DirectiveLocation', + isIntrospection: true, + description: 'A Directive can be adjacent to many parts of the GraphQL language, a ' + '__DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: _directives.DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.' + }, + MUTATION: { + value: _directives.DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.' + }, + SUBSCRIPTION: { + value: _directives.DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.' + }, + FIELD: { + value: _directives.DirectiveLocation.FIELD, + description: 'Location adjacent to a field.' + }, + FRAGMENT_DEFINITION: { + value: _directives.DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.' + }, + FRAGMENT_SPREAD: { + value: _directives.DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.' + }, + INLINE_FRAGMENT: { + value: _directives.DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.' + }, + SCHEMA: { + value: _directives.DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.' + }, + SCALAR: { + value: _directives.DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.' + }, + OBJECT: { + value: _directives.DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.' + }, + FIELD_DEFINITION: { + value: _directives.DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.' + }, + ARGUMENT_DEFINITION: { + value: _directives.DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.' + }, + INTERFACE: { + value: _directives.DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.' + }, + UNION: { + value: _directives.DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.' + }, + ENUM: { + value: _directives.DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.' + }, + ENUM_VALUE: { + value: _directives.DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.' + }, + INPUT_OBJECT: { + value: _directives.DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.' + }, + INPUT_FIELD_DEFINITION: { + value: _directives.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.' + } + } +}); + +var __Type = exports.__Type = new _definition.GraphQLObjectType({ + name: '__Type', + isIntrospection: true, + 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: new _definition.GraphQLNonNull(__TypeKind), + resolve: function resolve(type) { + if (type instanceof _definition.GraphQLScalarType) { + return TypeKind.SCALAR; + } else if (type instanceof _definition.GraphQLObjectType) { + return TypeKind.OBJECT; + } else if (type instanceof _definition.GraphQLInterfaceType) { + return TypeKind.INTERFACE; + } else if (type instanceof _definition.GraphQLUnionType) { + return TypeKind.UNION; + } else if (type instanceof _definition.GraphQLEnumType) { + return TypeKind.ENUM; + } else if (type instanceof _definition.GraphQLInputObjectType) { + return TypeKind.INPUT_OBJECT; + } else if (type instanceof _definition.GraphQLList) { + return TypeKind.LIST; + } else if (type instanceof _definition.GraphQLNonNull) { + return TypeKind.NON_NULL; + } + throw new Error('Unknown kind of type: ' + type); + } + }, + name: { type: _scalars.GraphQLString }, + description: { type: _scalars.GraphQLString }, + fields: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Field)), + args: { + includeDeprecated: { type: _scalars.GraphQLBoolean, defaultValue: false } + }, + resolve: function resolve(type, _ref) { + var includeDeprecated = _ref.includeDeprecated; + + if (type instanceof _definition.GraphQLObjectType || type instanceof _definition.GraphQLInterfaceType) { + var fieldMap = type.getFields(); + var fields = Object.keys(fieldMap).map(function (fieldName) { + return fieldMap[fieldName]; + }); + if (!includeDeprecated) { + fields = fields.filter(function (field) { + return !field.deprecationReason; + }); + } + return fields; + } + return null; + } + }, + interfaces: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + resolve: function resolve(type) { + if (type instanceof _definition.GraphQLObjectType) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: new _definition.GraphQLList(new _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: new _definition.GraphQLList(new _definition.GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { type: _scalars.GraphQLBoolean, defaultValue: false } + }, + resolve: function resolve(type, _ref3) { + var includeDeprecated = _ref3.includeDeprecated; + + if (type instanceof _definition.GraphQLEnumType) { + var values = type.getValues(); + if (!includeDeprecated) { + values = values.filter(function (value) { + return !value.deprecationReason; + }); + } + return values; + } + } + }, + inputFields: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue)), + resolve: function resolve(type) { + if (type instanceof _definition.GraphQLInputObjectType) { + var fieldMap = type.getFields(); + return Object.keys(fieldMap).map(function (fieldName) { + return fieldMap[fieldName]; + }); + } + } + }, + ofType: { type: __Type } + }; + } +}); + +var __Field = exports.__Field = new _definition.GraphQLObjectType({ + name: '__Field', + isIntrospection: true, + 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: new _definition.GraphQLNonNull(_scalars.GraphQLString) }, + description: { type: _scalars.GraphQLString }, + args: { + type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))), + resolve: function resolve(field) { + return field.args || []; + } + }, + type: { type: new _definition.GraphQLNonNull(__Type) }, + isDeprecated: { type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean) }, + deprecationReason: { + type: _scalars.GraphQLString + } + }; + } +}); + +var __InputValue = exports.__InputValue = new _definition.GraphQLObjectType({ + name: '__InputValue', + isIntrospection: true, + 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: new _definition.GraphQLNonNull(_scalars.GraphQLString) }, + description: { type: _scalars.GraphQLString }, + type: { type: new _definition.GraphQLNonNull(__Type) }, + defaultValue: { + type: _scalars.GraphQLString, + description: 'A GraphQL-formatted string representing the default value for this ' + 'input value.', + resolve: function resolve(inputVal) { + return (0, _isInvalid2.default)(inputVal.defaultValue) ? null : (0, _printer.print)((0, _astFromValue.astFromValue)(inputVal.defaultValue, inputVal.type)); + } + } + }; + } +}); + +var __EnumValue = exports.__EnumValue = new _definition.GraphQLObjectType({ + name: '__EnumValue', + isIntrospection: true, + 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: new _definition.GraphQLNonNull(_scalars.GraphQLString) }, + description: { type: _scalars.GraphQLString }, + isDeprecated: { type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean) }, + deprecationReason: { + type: _scalars.GraphQLString + } + }; + } +}); + +var TypeKind = exports.TypeKind = { + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL' +}; + +var __TypeKind = exports.__TypeKind = new _definition.GraphQLEnumType({ + name: '__TypeKind', + isIntrospection: true, + 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. + */ + +var SchemaMetaFieldDef = exports.SchemaMetaFieldDef = { + name: '__schema', + type: new _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; + } +}; + +var TypeMetaFieldDef = exports.TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ name: 'name', type: new _definition.GraphQLNonNull(_scalars.GraphQLString) }], + resolve: function resolve(source, _ref5, context, _ref6) { + var name = _ref5.name; + var schema = _ref6.schema; + return schema.getType(name); + } +}; + +var TypeNameMetaFieldDef = exports.TypeNameMetaFieldDef = { + name: '__typename', + type: new _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; + } +}; +},{"../jsutils/isInvalid":95,"../language/printer":106,"../utilities/astFromValue":120,"./definition":112,"./directives":113,"./scalars":116}],116:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = undefined; + +var _definition = require('./definition'); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// 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. + +/** + * 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 MAX_INT = 2147483647; +var MIN_INT = -2147483648; + +function coerceInt(value) { + if (value === '') { + throw new TypeError('Int cannot represent non 32-bit signed integer value: (empty string)'); + } + var num = Number(value); + if (num !== num || num > MAX_INT || num < MIN_INT) { + throw new TypeError('Int cannot represent non 32-bit signed integer value: ' + String(value)); + } + var int = Math.floor(num); + if (int !== num) { + throw new TypeError('Int cannot represent non-integer value: ' + String(value)); + } + return int; +} + +var GraphQLInt = exports.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: coerceInt, + parseValue: coerceInt, + parseLiteral: function parseLiteral(ast) { + if (ast.kind === Kind.INT) { + var num = parseInt(ast.value, 10); + if (num <= MAX_INT && num >= MIN_INT) { + return num; + } + } + return null; + } +}); + +function coerceFloat(value) { + if (value === '') { + throw new TypeError('Float cannot represent non numeric value: (empty string)'); + } + var num = Number(value); + if (num === num) { + return num; + } + throw new TypeError('Float cannot represent non numeric value: ' + String(value)); +} + +var GraphQLFloat = exports.GraphQLFloat = new _definition.GraphQLScalarType({ + name: 'Float', + description: 'The `Float` scalar type represents signed double-precision fractional ' + 'values as specified by ' + '[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ', + serialize: coerceFloat, + parseValue: coerceFloat, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.FLOAT || ast.kind === Kind.INT ? parseFloat(ast.value) : null; + } +}); + +var GraphQLString = exports.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: String, + parseValue: String, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.STRING ? ast.value : null; + } +}); + +var GraphQLBoolean = exports.GraphQLBoolean = new _definition.GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: Boolean, + parseValue: Boolean, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.BOOLEAN ? ast.value : null; + } +}); + +var GraphQLID = exports.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: String, + parseValue: String, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.STRING || ast.kind === Kind.INT ? ast.value : null; + } +}); +},{"../language/kinds":102,"./definition":112}],117:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GraphQLSchema = undefined; + +var _definition = require('./definition'); + +var _directives = require('./directives'); + +var _introspection = require('./introspection'); + +var _find = require('../jsutils/find'); + +var _find2 = _interopRequireDefault(_find); + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _typeComparators = require('../utilities/typeComparators'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +/** + * 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. + */ + +/** + * 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 = exports.GraphQLSchema = function () { + function GraphQLSchema(config) { + var _this = this; + + _classCallCheck(this, GraphQLSchema); + + (0, _invariant2.default)(typeof config === 'object', 'Must provide configuration object.'); + + (0, _invariant2.default)(config.query instanceof _definition.GraphQLObjectType, 'Schema query must be Object Type but got: ' + String(config.query) + '.'); + this._queryType = config.query; + + (0, _invariant2.default)(!config.mutation || config.mutation instanceof _definition.GraphQLObjectType, 'Schema mutation must be Object Type if provided but got: ' + String(config.mutation) + '.'); + this._mutationType = config.mutation; + + (0, _invariant2.default)(!config.subscription || config.subscription instanceof _definition.GraphQLObjectType, 'Schema subscription must be Object Type if provided but got: ' + String(config.subscription) + '.'); + this._subscriptionType = config.subscription; + + (0, _invariant2.default)(!config.types || Array.isArray(config.types), 'Schema types must be Array if provided but got: ' + String(config.types) + '.'); + + (0, _invariant2.default)(!config.directives || Array.isArray(config.directives) && config.directives.every(function (directive) { + return directive instanceof _directives.GraphQLDirective; + }), 'Schema directives must be Array if provided but got: ' + String(config.directives) + '.'); + // Provide specified directives (e.g. @include and @skip) by default. + this._directives = config.directives || _directives.specifiedDirectives; + + // 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); + } + + this._typeMap = initialTypes.reduce(typeMapReducer, Object.create(null)); + + // Keep track of all implementations by interface name. + this._implementations = Object.create(null); + Object.keys(this._typeMap).forEach(function (typeName) { + var type = _this._typeMap[typeName]; + if (type instanceof _definition.GraphQLObjectType) { + type.getInterfaces().forEach(function (iface) { + var impls = _this._implementations[iface.name]; + if (impls) { + impls.push(type); + } else { + _this._implementations[iface.name] = [type]; + } + }); + } + }); + + // Enforce correct interface implementations. + Object.keys(this._typeMap).forEach(function (typeName) { + var type = _this._typeMap[typeName]; + if (type instanceof _definition.GraphQLObjectType) { + type.getInterfaces().forEach(function (iface) { + return assertObjectImplementsInterface(_this, type, iface); + }); + } + }); + } + + GraphQLSchema.prototype.getQueryType = function getQueryType() { + return this._queryType; + }; + + GraphQLSchema.prototype.getMutationType = function getMutationType() { + return this._mutationType; + }; + + GraphQLSchema.prototype.getSubscriptionType = function getSubscriptionType() { + return this._subscriptionType; + }; + + GraphQLSchema.prototype.getTypeMap = function getTypeMap() { + return this._typeMap; + }; + + GraphQLSchema.prototype.getType = function getType(name) { + return this.getTypeMap()[name]; + }; + + GraphQLSchema.prototype.getPossibleTypes = function getPossibleTypes(abstractType) { + if (abstractType instanceof _definition.GraphQLUnionType) { + return abstractType.getTypes(); + } + (0, _invariant2.default)(abstractType instanceof _definition.GraphQLInterfaceType); + return this._implementations[abstractType.name]; + }; + + GraphQLSchema.prototype.isPossibleType = function isPossibleType(abstractType, possibleType) { + var possibleTypeMap = this._possibleTypeMap; + if (!possibleTypeMap) { + this._possibleTypeMap = possibleTypeMap = Object.create(null); + } + + if (!possibleTypeMap[abstractType.name]) { + var possibleTypes = this.getPossibleTypes(abstractType); + (0, _invariant2.default)(Array.isArray(possibleTypes), 'Could not find possible implementing types for ' + abstractType.name + ' ' + 'in schema. Check that schema.types is defined and is an array of ' + 'all possible types in the schema.'); + possibleTypeMap[abstractType.name] = possibleTypes.reduce(function (map, type) { + return map[type.name] = true, map; + }, Object.create(null)); + } + + return Boolean(possibleTypeMap[abstractType.name][possibleType.name]); + }; + + GraphQLSchema.prototype.getDirectives = function getDirectives() { + return this._directives; + }; + + GraphQLSchema.prototype.getDirective = function getDirective(name) { + return (0, _find2.default)(this.getDirectives(), function (directive) { + return directive.name === name; + }); + }; + + return GraphQLSchema; +}(); + +function typeMapReducer(map, type) { + if (!type) { + return map; + } + if (type instanceof _definition.GraphQLList || type instanceof _definition.GraphQLNonNull) { + return typeMapReducer(map, type.ofType); + } + if (map[type.name]) { + (0, _invariant2.default)(map[type.name] === type, 'Schema must contain unique named types but contains multiple ' + ('types named "' + type.name + '".')); + return map; + } + map[type.name] = type; + + var reducedMap = map; + + if (type instanceof _definition.GraphQLUnionType) { + reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap); + } + + if (type instanceof _definition.GraphQLObjectType) { + reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap); + } + + if (type instanceof _definition.GraphQLObjectType || type instanceof _definition.GraphQLInterfaceType) { + var fieldMap = type.getFields(); + Object.keys(fieldMap).forEach(function (fieldName) { + var field = fieldMap[fieldName]; + + if (field.args) { + var fieldArgTypes = field.args.map(function (arg) { + return arg.type; + }); + reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap); + } + reducedMap = typeMapReducer(reducedMap, field.type); + }); + } + + if (type instanceof _definition.GraphQLInputObjectType) { + var _fieldMap = type.getFields(); + Object.keys(_fieldMap).forEach(function (fieldName) { + var field = _fieldMap[fieldName]; + reducedMap = typeMapReducer(reducedMap, field.type); + }); + } + + return reducedMap; +} + +function assertObjectImplementsInterface(schema, object, iface) { + var objectFieldMap = object.getFields(); + var ifaceFieldMap = iface.getFields(); + + // Assert each interface field is implemented. + Object.keys(ifaceFieldMap).forEach(function (fieldName) { + var objectField = objectFieldMap[fieldName]; + var ifaceField = ifaceFieldMap[fieldName]; + + // Assert interface field exists on object. + (0, _invariant2.default)(objectField, '"' + iface.name + '" expects field "' + fieldName + '" but "' + object.name + '" ' + 'does not provide it.'); + + // Assert interface field type is satisfied by object field type, by being + // a valid subtype. (covariant) + (0, _invariant2.default)((0, _typeComparators.isTypeSubTypeOf)(schema, objectField.type, ifaceField.type), iface.name + '.' + fieldName + ' expects type "' + String(ifaceField.type) + '" ' + 'but ' + (object.name + '.' + fieldName + ' provides type "' + String(objectField.type) + '".')); + + // Assert each interface field arg is implemented. + ifaceField.args.forEach(function (ifaceArg) { + var argName = ifaceArg.name; + var objectArg = (0, _find2.default)(objectField.args, function (arg) { + return arg.name === argName; + }); + + // Assert interface field arg exists on object field. + (0, _invariant2.default)(objectArg, iface.name + '.' + fieldName + ' expects argument "' + argName + '" but ' + (object.name + '.' + fieldName + ' does not provide it.')); + + // Assert interface field arg type matches object field arg type. + // (invariant) + (0, _invariant2.default)((0, _typeComparators.isEqualType)(ifaceArg.type, objectArg.type), iface.name + '.' + fieldName + '(' + argName + ':) expects type ' + ('"' + String(ifaceArg.type) + '" but ') + (object.name + '.' + fieldName + '(' + argName + ':) provides type ') + ('"' + String(objectArg.type) + '".')); + }); + + // Assert additional arguments must not be required. + objectField.args.forEach(function (objectArg) { + var argName = objectArg.name; + var ifaceArg = (0, _find2.default)(ifaceField.args, function (arg) { + return arg.name === argName; + }); + if (!ifaceArg) { + (0, _invariant2.default)(!(objectArg.type instanceof _definition.GraphQLNonNull), object.name + '.' + fieldName + '(' + argName + ':) is of required type ' + ('"' + String(objectArg.type) + '" but is not also provided by the ') + ('interface ' + iface.name + '.' + fieldName + '.')); + } + }); + }); +} +},{"../jsutils/find":93,"../jsutils/invariant":94,"../utilities/typeComparators":134,"./definition":112,"./directives":113,"./introspection":115}],118:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TypeInfo = undefined; + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _definition = require('../type/definition'); + +var _introspection = require('../type/introspection'); + +var _typeFromAST = require('./typeFromAST'); + +var _find = require('../jsutils/find'); + +var _find2 = _interopRequireDefault(_find); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +/** + * 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. + */ + +/** + * 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 = exports.TypeInfo = 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) { + _classCallCheck(this, TypeInfo); + + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = getFieldDefFn || getFieldDef; + } + + TypeInfo.prototype.getType = function getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + }; + + TypeInfo.prototype.getParentType = function getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + }; + + TypeInfo.prototype.getInputType = function getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + }; + + TypeInfo.prototype.getFieldDef = function getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + }; + + TypeInfo.prototype.getDirective = function getDirective() { + return this._directive; + }; + + TypeInfo.prototype.getArgument = function getArgument() { + return this._argument; + }; + + TypeInfo.prototype.getEnumValue = function getEnumValue() { + return this._enumValue; + }; + + // Flow does not yet handle this case. + + + TypeInfo.prototype.enter = function enter(node /* ASTNode */) { + var schema = this._schema; + switch (node.kind) { + case Kind.SELECTION_SET: + var namedType = (0, _definition.getNamedType)(this.getType()); + this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined); + break; + case Kind.FIELD: + var parentType = this.getParentType(); + var fieldDef = void 0; + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + } + this._fieldDefStack.push(fieldDef); + this._typeStack.push(fieldDef && fieldDef.type); + break; + case Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + case Kind.OPERATION_DEFINITION: + var type = void 0; + 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(type); + break; + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + var typeConditionAST = node.typeCondition; + var outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : this.getType(); + this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined); + break; + case Kind.VARIABLE_DEFINITION: + var inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); + this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined); + break; + case Kind.ARGUMENT: + var argDef = void 0; + var argType = void 0; + var fieldOrDirective = this.getDirective() || this.getFieldDef(); + if (fieldOrDirective) { + argDef = (0, _find2.default)(fieldOrDirective.args, function (arg) { + return arg.name === node.name.value; + }); + if (argDef) { + argType = argDef.type; + } + } + this._argument = argDef; + this._inputTypeStack.push(argType); + break; + case Kind.LIST: + var listType = (0, _definition.getNullableType)(this.getInputType()); + this._inputTypeStack.push(listType instanceof _definition.GraphQLList ? listType.ofType : undefined); + break; + case Kind.OBJECT_FIELD: + var objectType = (0, _definition.getNamedType)(this.getInputType()); + var fieldType = void 0; + if (objectType instanceof _definition.GraphQLInputObjectType) { + var inputField = objectType.getFields()[node.name.value]; + fieldType = inputField ? inputField.type : undefined; + } + this._inputTypeStack.push(fieldType); + break; + case Kind.ENUM: + var enumType = (0, _definition.getNamedType)(this.getInputType()); + var enumValue = void 0; + if (enumType instanceof _definition.GraphQLEnumType) { + enumValue = enumType.getValue(node.value); + } + this._enumValue = enumValue; + break; + } + }; + + TypeInfo.prototype.leave = function leave(node) { + switch (node.kind) { + case Kind.SELECTION_SET: + this._parentTypeStack.pop(); + break; + case Kind.FIELD: + this._fieldDefStack.pop(); + this._typeStack.pop(); + break; + case Kind.DIRECTIVE: + this._directive = null; + break; + case Kind.OPERATION_DEFINITION: + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + break; + case Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + break; + case Kind.ARGUMENT: + this._argument = null; + this._inputTypeStack.pop(); + break; + case Kind.LIST: + case Kind.OBJECT_FIELD: + this._inputTypeStack.pop(); + break; + case 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. + */ + + +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 (parentType instanceof _definition.GraphQLObjectType || parentType instanceof _definition.GraphQLInterfaceType) { + return parentType.getFields()[name]; + } +} +},{"../jsutils/find":93,"../language/kinds":102,"../type/definition":112,"../type/introspection":115,"./typeFromAST":135}],119:[function(require,module,exports){ +(function (process){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assertValidName = assertValidName; +exports.formatWarning = formatWarning; + +/** + * 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 NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +var ERROR_PREFIX_RX = /^Error: /; + +// Silences warnings if an environment flag is enabled +var noNameWarning = Boolean(process && process.env && process.env.GRAPHQL_NO_NAME_WARNING); + +// Ensures console warnings are only issued once. +var hasWarnedAboutDunder = false; + +/** + * Upholds the spec rules about naming. + */ +function assertValidName(name, isIntrospection) { + if (!name || typeof name !== 'string') { + throw new Error('Must be named. Unexpected name: ' + name + '.'); + } + if (!isIntrospection && !hasWarnedAboutDunder && !noNameWarning && name.slice(0, 2) === '__') { + hasWarnedAboutDunder = true; + /* eslint-disable no-console */ + if (console && console.warn) { + var error = new Error('Name "' + name + '" must not begin with "__", which is reserved by ' + 'GraphQL introspection. In a future release of graphql this will ' + 'become a hard error.'); + console.warn(formatWarning(error)); + } + /* eslint-enable no-console */ + } + if (!NAME_RX.test(name)) { + throw new Error('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "' + name + '" does not.'); + } +} + +/** + * Returns a human-readable warning based an the supplied Error object, + * including stack trace information if available. + */ +function formatWarning(error) { + var formatted = ''; + var errorString = String(error).replace(ERROR_PREFIX_RX, ''); + var stack = error.stack; + if (stack) { + formatted = stack.replace(ERROR_PREFIX_RX, ''); + } + if (formatted.indexOf(errorString) === -1) { + formatted = errorString + '\n' + formatted; + } + return formatted.trim(); +} +}).call(this,require('_process')) +},{"_process":168}],120:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.astFromValue = astFromValue; + +var _iterall = require('iterall'); + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isNullish = require('../jsutils/isNullish'); + +var _isNullish2 = _interopRequireDefault(_isNullish); + +var _isInvalid = require('../jsutils/isInvalid'); + +var _isInvalid2 = _interopRequireDefault(_isInvalid); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _definition = require('../type/definition'); + +var _scalars = require('../type/scalars'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': 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) { + // Ensure flow knows that we treat function params as const. + var _value = value; + + if (type instanceof _definition.GraphQLNonNull) { + var astValue = astFromValue(_value, type.ofType); + if (astValue && astValue.kind === Kind.NULL) { + return null; + } + return astValue; + } + + // only explicit null, not undefined, NaN + if (_value === null) { + return { kind: Kind.NULL }; + } + + // undefined, NaN + if ((0, _isInvalid2.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 (type instanceof _definition.GraphQLList) { + 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: 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 (type instanceof _definition.GraphQLInputObjectType) { + if (_value === null || typeof _value !== 'object') { + return null; + } + var fields = type.getFields(); + var fieldNodes = []; + Object.keys(fields).forEach(function (fieldName) { + var fieldType = fields[fieldName].type; + var fieldValue = astFromValue(_value[fieldName], fieldType); + if (fieldValue) { + fieldNodes.push({ + kind: Kind.OBJECT_FIELD, + name: { kind: Kind.NAME, value: fieldName }, + value: fieldValue + }); + } + }); + return { kind: Kind.OBJECT, fields: fieldNodes }; + } + + (0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must provide Input Type, cannot use: ' + String(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, _isNullish2.default)(serialized)) { + return null; + } + + // Others serialize based on their corresponding JavaScript scalar types. + if (typeof serialized === 'boolean') { + return { kind: Kind.BOOLEAN, value: serialized }; + } + + // JavaScript numbers can be Int or Float values. + if (typeof serialized === 'number') { + var stringNum = String(serialized); + return (/^[0-9]+$/.test(stringNum) ? { kind: Kind.INT, value: stringNum } : { kind: Kind.FLOAT, value: stringNum } + ); + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if (type instanceof _definition.GraphQLEnumType) { + return { kind: Kind.ENUM, value: serialized }; + } + + // ID types can use Int literals. + if (type === _scalars.GraphQLID && /^[0-9]+$/.test(serialized)) { + return { kind: Kind.INT, value: serialized }; + } + + // Use JSON stringify, which uses the same string encoding as GraphQL, + // then remove the quotes. + return { + kind: Kind.STRING, + value: JSON.stringify(serialized).slice(1, -1) + }; + } + + throw new TypeError('Cannot convert value to AST: ' + String(serialized)); +} +/** + * 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. + */ +},{"../jsutils/invariant":94,"../jsutils/isInvalid":95,"../jsutils/isNullish":96,"../language/kinds":102,"../type/definition":112,"../type/scalars":116,"iterall":166}],121:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildASTSchema = buildASTSchema; +exports.getDeprecationReason = getDeprecationReason; +exports.getDescription = getDescription; +exports.buildSchema = buildSchema; + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _keyValMap = require('../jsutils/keyValMap'); + +var _keyValMap2 = _interopRequireDefault(_keyValMap); + +var _valueFromAST = require('./valueFromAST'); + +var _lexer = require('../language/lexer'); + +var _parser = require('../language/parser'); + +var _values = require('../execution/values'); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _schema = require('../type/schema'); + +var _scalars = require('../type/scalars'); + +var _definition = require('../type/definition'); + +var _directives = require('../type/directives'); + +var _introspection = require('../type/introspection'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +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. + */ + +function buildWrappedType(innerType, inputTypeNode) { + if (inputTypeNode.kind === Kind.LIST_TYPE) { + return new _definition.GraphQLList(buildWrappedType(innerType, inputTypeNode.type)); + } + if (inputTypeNode.kind === Kind.NON_NULL_TYPE) { + var wrappedType = buildWrappedType(innerType, inputTypeNode.type); + (0, _invariant2.default)(!(wrappedType instanceof _definition.GraphQLNonNull), 'No nesting nonnull.'); + return new _definition.GraphQLNonNull(wrappedType); + } + return innerType; +} + +function getNamedTypeNode(typeNode) { + var namedType = typeNode; + while (namedType.kind === Kind.LIST_TYPE || namedType.kind === Kind.NON_NULL_TYPE) { + namedType = namedType.type; + } + return namedType; +} + +/** + * 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. + */ +function buildASTSchema(ast) { + if (!ast || ast.kind !== Kind.DOCUMENT) { + throw new Error('Must provide a document ast.'); + } + + var schemaDef = void 0; + + var typeDefs = []; + var nodeMap = Object.create(null); + var directiveDefs = []; + for (var i = 0; i < ast.definitions.length; i++) { + var d = ast.definitions[i]; + switch (d.kind) { + case Kind.SCHEMA_DEFINITION: + if (schemaDef) { + throw new Error('Must provide only one schema definition.'); + } + schemaDef = d; + break; + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.ENUM_TYPE_DEFINITION: + case Kind.UNION_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + var typeName = d.name.value; + if (nodeMap[typeName]) { + throw new Error('Type "' + typeName + '" was defined more than once.'); + } + typeDefs.push(d); + nodeMap[typeName] = d; + break; + case Kind.DIRECTIVE_DEFINITION: + directiveDefs.push(d); + break; + } + } + + var queryTypeName = void 0; + var mutationTypeName = void 0; + var subscriptionTypeName = void 0; + if (schemaDef) { + schemaDef.operationTypes.forEach(function (operationType) { + var typeName = operationType.type.name.value; + if (operationType.operation === 'query') { + if (queryTypeName) { + throw new Error('Must provide only one query type in schema.'); + } + if (!nodeMap[typeName]) { + throw new Error('Specified query type "' + typeName + '" not found in document.'); + } + queryTypeName = typeName; + } else if (operationType.operation === 'mutation') { + if (mutationTypeName) { + throw new Error('Must provide only one mutation type in schema.'); + } + if (!nodeMap[typeName]) { + throw new Error('Specified mutation type "' + typeName + '" not found in document.'); + } + mutationTypeName = typeName; + } else if (operationType.operation === 'subscription') { + if (subscriptionTypeName) { + throw new Error('Must provide only one subscription type in schema.'); + } + if (!nodeMap[typeName]) { + throw new Error('Specified subscription type "' + typeName + '" not found in document.'); + } + subscriptionTypeName = typeName; + } + }); + } else { + if (nodeMap.Query) { + queryTypeName = 'Query'; + } + if (nodeMap.Mutation) { + mutationTypeName = 'Mutation'; + } + if (nodeMap.Subscription) { + subscriptionTypeName = 'Subscription'; + } + } + + if (!queryTypeName) { + throw new Error('Must provide schema definition with query type or a type named Query.'); + } + + var innerTypeMap = { + String: _scalars.GraphQLString, + Int: _scalars.GraphQLInt, + Float: _scalars.GraphQLFloat, + Boolean: _scalars.GraphQLBoolean, + ID: _scalars.GraphQLID, + __Schema: _introspection.__Schema, + __Directive: _introspection.__Directive, + __DirectiveLocation: _introspection.__DirectiveLocation, + __Type: _introspection.__Type, + __Field: _introspection.__Field, + __InputValue: _introspection.__InputValue, + __EnumValue: _introspection.__EnumValue, + __TypeKind: _introspection.__TypeKind + }; + + var types = typeDefs.map(function (def) { + return typeDefNamed(def.name.value); + }); + + var directives = directiveDefs.map(getDirective); + + // 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({ + query: getObjectType(nodeMap[queryTypeName]), + mutation: mutationTypeName ? getObjectType(nodeMap[mutationTypeName]) : null, + subscription: subscriptionTypeName ? getObjectType(nodeMap[subscriptionTypeName]) : null, + types: types, + directives: directives + }); + + function getDirective(directiveNode) { + return new _directives.GraphQLDirective({ + name: directiveNode.name.value, + description: getDescription(directiveNode), + locations: directiveNode.locations.map(function (node) { + return node.value; + }), + args: directiveNode.arguments && makeInputValues(directiveNode.arguments) + }); + } + + function getObjectType(typeNode) { + var type = typeDefNamed(typeNode.name.value); + (0, _invariant2.default)(type instanceof _definition.GraphQLObjectType, 'AST must provide object type.'); + return type; + } + + function produceType(typeNode) { + var typeName = getNamedTypeNode(typeNode).name.value; + var typeDef = typeDefNamed(typeName); + return buildWrappedType(typeDef, typeNode); + } + + function produceInputType(typeNode) { + return (0, _definition.assertInputType)(produceType(typeNode)); + } + + function produceOutputType(typeNode) { + return (0, _definition.assertOutputType)(produceType(typeNode)); + } + + function produceObjectType(typeNode) { + var type = produceType(typeNode); + (0, _invariant2.default)(type instanceof _definition.GraphQLObjectType, 'Expected Object type.'); + return type; + } + + function produceInterfaceType(typeNode) { + var type = produceType(typeNode); + (0, _invariant2.default)(type instanceof _definition.GraphQLInterfaceType, 'Expected Interface type.'); + return type; + } + + function typeDefNamed(typeName) { + if (innerTypeMap[typeName]) { + return innerTypeMap[typeName]; + } + + if (!nodeMap[typeName]) { + throw new Error('Type "' + typeName + '" not found in document.'); + } + + var innerTypeDef = makeSchemaDef(nodeMap[typeName]); + if (!innerTypeDef) { + throw new Error('Nothing constructed for "' + typeName + '".'); + } + innerTypeMap[typeName] = innerTypeDef; + return innerTypeDef; + } + + function makeSchemaDef(def) { + if (!def) { + throw new Error('def must be defined'); + } + switch (def.kind) { + case Kind.OBJECT_TYPE_DEFINITION: + return makeTypeDef(def); + case Kind.INTERFACE_TYPE_DEFINITION: + return makeInterfaceDef(def); + case Kind.ENUM_TYPE_DEFINITION: + return makeEnumDef(def); + case Kind.UNION_TYPE_DEFINITION: + return makeUnionDef(def); + case Kind.SCALAR_TYPE_DEFINITION: + return makeScalarDef(def); + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + return makeInputObjectDef(def); + default: + throw new Error('Type kind "' + def.kind + '" not supported.'); + } + } + + function makeTypeDef(def) { + var typeName = def.name.value; + return new _definition.GraphQLObjectType({ + name: typeName, + description: getDescription(def), + fields: function fields() { + return makeFieldDefMap(def); + }, + interfaces: function interfaces() { + return makeImplementedInterfaces(def); + } + }); + } + + function makeFieldDefMap(def) { + return (0, _keyValMap2.default)(def.fields, function (field) { + return field.name.value; + }, function (field) { + return { + type: produceOutputType(field.type), + description: getDescription(field), + args: makeInputValues(field.arguments), + deprecationReason: getDeprecationReason(field) + }; + }); + } + + function makeImplementedInterfaces(def) { + return def.interfaces && def.interfaces.map(function (iface) { + return produceInterfaceType(iface); + }); + } + + function makeInputValues(values) { + return (0, _keyValMap2.default)(values, function (value) { + return value.name.value; + }, function (value) { + var type = produceInputType(value.type); + return { + type: type, + description: getDescription(value), + defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type) + }; + }); + } + + function makeInterfaceDef(def) { + var typeName = def.name.value; + return new _definition.GraphQLInterfaceType({ + name: typeName, + description: getDescription(def), + fields: function fields() { + return makeFieldDefMap(def); + }, + resolveType: cannotExecuteSchema + }); + } + + function makeEnumDef(def) { + var enumType = new _definition.GraphQLEnumType({ + name: def.name.value, + description: getDescription(def), + values: (0, _keyValMap2.default)(def.values, function (enumValue) { + return enumValue.name.value; + }, function (enumValue) { + return { + description: getDescription(enumValue), + deprecationReason: getDeprecationReason(enumValue) + }; + }) + }); + + return enumType; + } + + function makeUnionDef(def) { + return new _definition.GraphQLUnionType({ + name: def.name.value, + description: getDescription(def), + types: def.types.map(function (t) { + return produceObjectType(t); + }), + resolveType: cannotExecuteSchema + }); + } + + function makeScalarDef(def) { + return new _definition.GraphQLScalarType({ + name: def.name.value, + description: getDescription(def), + serialize: function serialize() { + return null; + }, + // Note: validation calls the parse functions to determine if a + // literal value is correct. Returning null would cause use of custom + // scalars to always fail validation. Returning false causes them to + // always pass validation. + parseValue: function parseValue() { + return false; + }, + parseLiteral: function parseLiteral() { + return false; + } + }); + } + + function makeInputObjectDef(def) { + return new _definition.GraphQLInputObjectType({ + name: def.name.value, + description: getDescription(def), + fields: function fields() { + return makeInputValues(def.fields); + } + }); + } +} + +/** + * 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 based on a contiguous + * block full-line of comments preceding it. + */ +function getDescription(node) { + var loc = node.loc; + if (!loc) { + return; + } + var comments = []; + var minSpaces = void 0; + 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); + var spaces = leadingSpaces(value); + if (minSpaces === undefined || spaces < minSpaces) { + minSpaces = spaces; + } + comments.push(value); + token = token.prev; + } + return comments.reverse().map(function (comment) { + return comment.slice(minSpaces); + }).join('\n'); +} + +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ +function buildSchema(source) { + return buildASTSchema((0, _parser.parse)(source)); +} + +// Count the number of spaces on the starting side of a string. +function leadingSpaces(str) { + var i = 0; + for (; i < str.length; i++) { + if (str[i] !== ' ') { + break; + } + } + return i; +} + +function cannotExecuteSchema() { + throw new Error('Generated Schema cannot use Interface or Union types for execution.'); +} +},{"../execution/values":90,"../jsutils/invariant":94,"../jsutils/keyValMap":98,"../language/kinds":102,"../language/lexer":103,"../language/parser":105,"../type/definition":112,"../type/directives":113,"../type/introspection":115,"../type/scalars":116,"../type/schema":117,"./valueFromAST":136}],122:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildClientSchema = buildClientSchema; + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _keyMap = require('../jsutils/keyMap'); + +var _keyMap2 = _interopRequireDefault(_keyMap); + +var _keyValMap = require('../jsutils/keyValMap'); + +var _keyValMap2 = _interopRequireDefault(_keyValMap); + +var _valueFromAST = require('./valueFromAST'); + +var _parser = require('../language/parser'); + +var _schema = require('../type/schema'); + +var _definition = require('../type/definition'); + +var _introspection = require('../type/introspection'); + +var _scalars = require('../type/scalars'); + +var _directives = require('../type/directives'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +/** + * 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. + */ +function buildClientSchema(introspection) { + + // 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, _keyMap2.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 = { + String: _scalars.GraphQLString, + Int: _scalars.GraphQLInt, + Float: _scalars.GraphQLFloat, + Boolean: _scalars.GraphQLBoolean, + ID: _scalars.GraphQLID, + __Schema: _introspection.__Schema, + __Directive: _introspection.__Directive, + __DirectiveLocation: _introspection.__DirectiveLocation, + __Type: _introspection.__Type, + __Field: _introspection.__Field, + __InputValue: _introspection.__InputValue, + __EnumValue: _introspection.__EnumValue, + __TypeKind: _introspection.__TypeKind + }; + + // 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 new _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); + (0, _invariant2.default)(!(nullableType instanceof _definition.GraphQLNonNull), 'No nesting nonnull.'); + return new _definition.GraphQLNonNull(nullableType); + } + 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: ' + 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, _invariant2.default)((0, _definition.isInputType)(type), 'Introspection must provide input type for arguments.'); + return type; + } + + function getOutputType(typeRef) { + var type = getType(typeRef); + (0, _invariant2.default)((0, _definition.isOutputType)(type), 'Introspection must provide output type for fields.'); + return type; + } + + function getObjectType(typeRef) { + var type = getType(typeRef); + (0, _invariant2.default)(type instanceof _definition.GraphQLObjectType, 'Introspection must provide object type for possibleTypes.'); + return type; + } + + function getInterfaceType(typeRef) { + var type = getType(typeRef); + (0, _invariant2.default)(type instanceof _definition.GraphQLInterfaceType, 'Introspection must provide interface type for interfaces.'); + return type; + } + + // Given a type's introspection result, construct the correct + // GraphQLType instance. + function buildType(type) { + 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); + default: + throw new Error('Invalid or incomplete schema, unknown kind: ' + type.kind + '. Ensure ' + 'that a full introspection query is used in order to build a ' + 'client schema.'); + } + } + + function buildScalarDef(scalarIntrospection) { + return new _definition.GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + serialize: function serialize(id) { + return id; + }, + // Note: validation calls the parse functions to determine if a + // literal value is correct. Returning null would cause use of custom + // scalars to always fail validation. Returning false causes them to + // always pass validation. + parseValue: function parseValue() { + return false; + }, + parseLiteral: function parseLiteral() { + return false; + } + }); + } + + function buildObjectDef(objectIntrospection) { + return new _definition.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: 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); + }, + resolveType: cannotExecuteClientSchema + }); + } + + function buildUnionDef(unionIntrospection) { + return new _definition.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: unionIntrospection.possibleTypes.map(getObjectType), + resolveType: cannotExecuteClientSchema + }); + } + + function buildEnumDef(enumIntrospection) { + return new _definition.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, _keyValMap2.default)(enumIntrospection.enumValues, function (valueIntrospection) { + return valueIntrospection.name; + }, function (valueIntrospection) { + return { + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + }; + }) + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + return new _definition.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: function fields() { + return buildInputValueDefMap(inputObjectIntrospection.inputFields); + } + }); + } + + function buildFieldDefMap(typeIntrospection) { + return (0, _keyValMap2.default)(typeIntrospection.fields, function (fieldIntrospection) { + return fieldIntrospection.name; + }, function (fieldIntrospection) { + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type: getOutputType(fieldIntrospection.type), + args: buildInputValueDefMap(fieldIntrospection.args) + }; + }); + } + + function buildInputValueDefMap(inputValueIntrospections) { + return (0, _keyValMap2.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 { + name: inputValueIntrospection.name, + description: inputValueIntrospection.description, + type: type, + defaultValue: defaultValue + }; + } + + function buildDirective(directiveIntrospection) { + // Support deprecated `on****` fields for building `locations`, as this + // is used by GraphiQL which may need to support outdated servers. + var locations = directiveIntrospection.locations ? directiveIntrospection.locations.slice() : [].concat(!directiveIntrospection.onField ? [] : [_directives.DirectiveLocation.FIELD], !directiveIntrospection.onOperation ? [] : [_directives.DirectiveLocation.QUERY, _directives.DirectiveLocation.MUTATION, _directives.DirectiveLocation.SUBSCRIPTION], !directiveIntrospection.onFragment ? [] : [_directives.DirectiveLocation.FRAGMENT_DEFINITION, _directives.DirectiveLocation.FRAGMENT_SPREAD, _directives.DirectiveLocation.INLINE_FRAGMENT]); + return new _directives.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + locations: locations, + 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 = getObjectType(schemaIntrospection.queryType); + + 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 + }); +} +/** + * 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 cannotExecuteClientSchema() { + throw new Error('Client Schema cannot use Interface or Union types for execution.'); +} +},{"../jsutils/invariant":94,"../jsutils/keyMap":97,"../jsutils/keyValMap":98,"../language/parser":105,"../type/definition":112,"../type/directives":113,"../type/introspection":115,"../type/scalars":116,"../type/schema":117,"./valueFromAST":136}],123:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.concatAST = concatAST; + + +/** + * 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 + }; +} +/** + * 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. + */ +},{}],124:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.extendSchema = extendSchema; + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _keyMap = require('../jsutils/keyMap'); + +var _keyMap2 = _interopRequireDefault(_keyMap); + +var _keyValMap = require('../jsutils/keyValMap'); + +var _keyValMap2 = _interopRequireDefault(_keyValMap); + +var _buildASTSchema = require('./buildASTSchema'); + +var _valueFromAST = require('./valueFromAST'); + +var _GraphQLError = require('../error/GraphQLError'); + +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'); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': 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. + */ + +/** + * 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 extendSchema(schema, documentAST) { + (0, _invariant2.default)(schema instanceof _schema.GraphQLSchema, 'Must provide valid GraphQLSchema'); + + (0, _invariant2.default)(documentAST && documentAST.kind === Kind.DOCUMENT, 'Must provide valid Document AST'); + + // 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 = []; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var def = documentAST.definitions[i]; + switch (def.kind) { + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.ENUM_TYPE_DEFINITION: + case Kind.UNION_TYPE_DEFINITION: + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + // Sanity check that none of the defined types conflict with the + // schema's existing types. + var typeName = def.name.value; + if (schema.getType(typeName)) { + throw new _GraphQLError.GraphQLError('Type "' + typeName + '" already exists in the schema. It cannot also ' + 'be defined in this type definition.', [def]); + } + typeDefinitionMap[typeName] = def; + break; + case Kind.TYPE_EXTENSION_DEFINITION: + // Sanity check that this type extension exists within the + // schema's existing types. + var extendedTypeName = def.definition.name.value; + var existingType = schema.getType(extendedTypeName); + if (!existingType) { + throw new _GraphQLError.GraphQLError('Cannot extend type "' + extendedTypeName + '" because it does not ' + 'exist in the existing schema.', [def.definition]); + } + if (!(existingType instanceof _definition.GraphQLObjectType)) { + throw new _GraphQLError.GraphQLError('Cannot extend non-object type "' + extendedTypeName + '".', [def.definition]); + } + var extensions = typeExtensionsMap[extendedTypeName]; + if (extensions) { + extensions.push(def); + } else { + extensions = [def]; + } + typeExtensionsMap[extendedTypeName] = extensions; + break; + case Kind.DIRECTIVE_DEFINITION: + var directiveName = def.name.value; + var existingDirective = schema.getDirective(directiveName); + if (existingDirective) { + throw new _GraphQLError.GraphQLError('Directive "' + directiveName + '" already exists in the schema. It ' + 'cannot be redefined.', [def]); + } + directiveDefinitions.push(def); + break; + } + } + + // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + if (Object.keys(typeExtensionsMap).length === 0 && Object.keys(typeDefinitionMap).length === 0 && directiveDefinitions.length === 0) { + return schema; + } + + // A cache to use to store the actual GraphQLType definition objects by name. + // Initialize to the GraphQL built in scalars and introspection types. All + // functions below are inline so that this type def cache is within the scope + // of the closure. + var typeDefCache = { + String: _scalars.GraphQLString, + Int: _scalars.GraphQLInt, + Float: _scalars.GraphQLFloat, + Boolean: _scalars.GraphQLBoolean, + ID: _scalars.GraphQLID, + __Schema: _introspection.__Schema, + __Directive: _introspection.__Directive, + __DirectiveLocation: _introspection.__DirectiveLocation, + __Type: _introspection.__Type, + __Field: _introspection.__Field, + __InputValue: _introspection.__InputValue, + __EnumValue: _introspection.__EnumValue, + __TypeKind: _introspection.__TypeKind + }; + + // Get the root Query, Mutation, and Subscription object types. + var queryType = getTypeFromDef(schema.getQueryType()); + + var existingMutationType = schema.getMutationType(); + var mutationType = existingMutationType ? getTypeFromDef(existingMutationType) : null; + + var existingSubscriptionType = schema.getSubscriptionType(); + var subscriptionType = existingSubscriptionType ? getTypeFromDef(existingSubscriptionType) : null; + + // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + var typeMap = schema.getTypeMap(); + var types = Object.keys(typeMap).map(function (typeName) { + return getTypeFromDef(typeMap[typeName]); + }); + + // Do the same with new types, appending to the list of defined types. + Object.keys(typeDefinitionMap).forEach(function (typeName) { + types.push(getTypeFromAST(typeDefinitionMap[typeName])); + }); + + // Then produce and return a Schema with these types. + return new _schema.GraphQLSchema({ + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: types, + directives: getMergedDirectives() + }); + + // 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(); + (0, _invariant2.default)(existingDirectives, 'schema must have default directives'); + + var newDirectives = directiveDefinitions.map(function (directiveNode) { + return getDirective(directiveNode); + }); + return existingDirectives.concat(newDirectives); + } + + function getTypeFromDef(typeDef) { + var type = _getNamedType(typeDef.name); + (0, _invariant2.default)(type, 'Missing type from schema'); + return type; + } + + function getTypeFromAST(node) { + var type = _getNamedType(node.name.value); + if (!type) { + throw new _GraphQLError.GraphQLError('Unknown type: "' + node.name.value + '". Ensure that this type exists ' + 'either in the original schema, or is added in a type definition.', [node]); + } + return type; + } + + function getObjectTypeFromAST(node) { + var type = getTypeFromAST(node); + (0, _invariant2.default)(type instanceof _definition.GraphQLObjectType, 'Must be Object type.'); + return type; + } + + function getInterfaceTypeFromAST(node) { + var type = getTypeFromAST(node); + (0, _invariant2.default)(type instanceof _definition.GraphQLInterfaceType, 'Must be Interface type.'); + return type; + } + + function getInputTypeFromAST(node) { + return (0, _definition.assertInputType)(getTypeFromAST(node)); + } + + function getOutputTypeFromAST(node) { + return (0, _definition.assertOutputType)(getTypeFromAST(node)); + } + + // Given a name, returns a type from either the existing schema or an + // added type. + function _getNamedType(typeName) { + var cachedTypeDef = typeDefCache[typeName]; + if (cachedTypeDef) { + return cachedTypeDef; + } + + var existingType = schema.getType(typeName); + if (existingType) { + var typeDef = extendType(existingType); + typeDefCache[typeName] = typeDef; + return typeDef; + } + + var typeNode = typeDefinitionMap[typeName]; + if (typeNode) { + var _typeDef = buildType(typeNode); + typeDefCache[typeName] = _typeDef; + return _typeDef; + } + } + + // Given a type's introspection result, construct the correct + // GraphQLType instance. + function extendType(type) { + if (type instanceof _definition.GraphQLObjectType) { + return extendObjectType(type); + } + if (type instanceof _definition.GraphQLInterfaceType) { + return extendInterfaceType(type); + } + if (type instanceof _definition.GraphQLUnionType) { + return extendUnionType(type); + } + return type; + } + + function extendObjectType(type) { + return new _definition.GraphQLObjectType({ + name: type.name, + description: type.description, + interfaces: function interfaces() { + return extendImplementedInterfaces(type); + }, + fields: function fields() { + return extendFieldMap(type); + }, + isTypeOf: type.isTypeOf + }); + } + + function extendInterfaceType(type) { + return new _definition.GraphQLInterfaceType({ + name: type.name, + description: type.description, + fields: function fields() { + return extendFieldMap(type); + }, + resolveType: type.resolveType + }); + } + + function extendUnionType(type) { + return new _definition.GraphQLUnionType({ + name: type.name, + description: type.description, + types: type.getTypes().map(getTypeFromDef), + resolveType: type.resolveType + }); + } + + function extendImplementedInterfaces(type) { + var interfaces = type.getInterfaces().map(getTypeFromDef); + + // If there are any extensions to the interfaces, apply those here. + var extensions = typeExtensionsMap[type.name]; + if (extensions) { + extensions.forEach(function (extension) { + extension.definition.interfaces.forEach(function (namedType) { + var interfaceName = namedType.name.value; + if (interfaces.some(function (def) { + return def.name === interfaceName; + })) { + throw new _GraphQLError.GraphQLError('Type "' + type.name + '" already implements "' + interfaceName + '". ' + 'It cannot also be implemented in this type extension.', [namedType]); + } + interfaces.push(getInterfaceTypeFromAST(namedType)); + }); + }); + } + + return interfaces; + } + + function extendFieldMap(type) { + var newFieldMap = Object.create(null); + var oldFieldMap = type.getFields(); + Object.keys(oldFieldMap).forEach(function (fieldName) { + var field = oldFieldMap[fieldName]; + newFieldMap[fieldName] = { + description: field.description, + deprecationReason: field.deprecationReason, + type: extendFieldType(field.type), + args: (0, _keyMap2.default)(field.args, function (arg) { + return arg.name; + }), + resolve: field.resolve + }; + }); + + // If there are any extensions to the fields, apply those here. + var extensions = typeExtensionsMap[type.name]; + if (extensions) { + extensions.forEach(function (extension) { + extension.definition.fields.forEach(function (field) { + var fieldName = field.name.value; + if (oldFieldMap[fieldName]) { + throw new _GraphQLError.GraphQLError('Field "' + type.name + '.' + fieldName + '" already exists in the ' + 'schema. It cannot also be defined in this type extension.', [field]); + } + newFieldMap[fieldName] = { + description: (0, _buildASTSchema.getDescription)(field), + type: buildOutputFieldType(field.type), + args: buildInputValues(field.arguments), + deprecationReason: (0, _buildASTSchema.getDeprecationReason)(field) + }; + }); + }); + } + + return newFieldMap; + } + + function extendFieldType(typeDef) { + if (typeDef instanceof _definition.GraphQLList) { + return new _definition.GraphQLList(extendFieldType(typeDef.ofType)); + } + if (typeDef instanceof _definition.GraphQLNonNull) { + return new _definition.GraphQLNonNull(extendFieldType(typeDef.ofType)); + } + return getTypeFromDef(typeDef); + } + + function buildType(typeNode) { + switch (typeNode.kind) { + case Kind.OBJECT_TYPE_DEFINITION: + return buildObjectType(typeNode); + case Kind.INTERFACE_TYPE_DEFINITION: + return buildInterfaceType(typeNode); + case Kind.UNION_TYPE_DEFINITION: + return buildUnionType(typeNode); + case Kind.SCALAR_TYPE_DEFINITION: + return buildScalarType(typeNode); + case Kind.ENUM_TYPE_DEFINITION: + return buildEnumType(typeNode); + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + return buildInputObjectType(typeNode); + } + throw new TypeError('Unknown type kind ' + typeNode.kind); + } + + function buildObjectType(typeNode) { + return new _definition.GraphQLObjectType({ + name: typeNode.name.value, + description: (0, _buildASTSchema.getDescription)(typeNode), + interfaces: function interfaces() { + return buildImplementedInterfaces(typeNode); + }, + fields: function fields() { + return buildFieldMap(typeNode); + } + }); + } + + function buildInterfaceType(typeNode) { + return new _definition.GraphQLInterfaceType({ + name: typeNode.name.value, + description: (0, _buildASTSchema.getDescription)(typeNode), + fields: function fields() { + return buildFieldMap(typeNode); + }, + resolveType: cannotExecuteExtendedSchema + }); + } + + function buildUnionType(typeNode) { + return new _definition.GraphQLUnionType({ + name: typeNode.name.value, + description: (0, _buildASTSchema.getDescription)(typeNode), + types: typeNode.types.map(getObjectTypeFromAST), + resolveType: cannotExecuteExtendedSchema + }); + } + + function buildScalarType(typeNode) { + return new _definition.GraphQLScalarType({ + name: typeNode.name.value, + description: (0, _buildASTSchema.getDescription)(typeNode), + serialize: function serialize(id) { + return id; + }, + // Note: validation calls the parse functions to determine if a + // literal value is correct. Returning null would cause use of custom + // scalars to always fail validation. Returning false causes them to + // always pass validation. + parseValue: function parseValue() { + return false; + }, + parseLiteral: function parseLiteral() { + return false; + } + }); + } + + function buildEnumType(typeNode) { + return new _definition.GraphQLEnumType({ + name: typeNode.name.value, + description: (0, _buildASTSchema.getDescription)(typeNode), + values: (0, _keyValMap2.default)(typeNode.values, function (enumValue) { + return enumValue.name.value; + }, function (enumValue) { + return { + description: (0, _buildASTSchema.getDescription)(enumValue), + deprecationReason: (0, _buildASTSchema.getDeprecationReason)(enumValue) + }; + }) + }); + } + + function buildInputObjectType(typeNode) { + return new _definition.GraphQLInputObjectType({ + name: typeNode.name.value, + description: (0, _buildASTSchema.getDescription)(typeNode), + fields: function fields() { + return buildInputValues(typeNode.fields); + } + }); + } + + function getDirective(directiveNode) { + return new _directives.GraphQLDirective({ + name: directiveNode.name.value, + locations: directiveNode.locations.map(function (node) { + return node.value; + }), + args: directiveNode.arguments && buildInputValues(directiveNode.arguments) + }); + } + + function buildImplementedInterfaces(typeNode) { + return typeNode.interfaces && typeNode.interfaces.map(getInterfaceTypeFromAST); + } + + function buildFieldMap(typeNode) { + return (0, _keyValMap2.default)(typeNode.fields, function (field) { + return field.name.value; + }, function (field) { + return { + type: buildOutputFieldType(field.type), + description: (0, _buildASTSchema.getDescription)(field), + args: buildInputValues(field.arguments), + deprecationReason: (0, _buildASTSchema.getDeprecationReason)(field) + }; + }); + } + + function buildInputValues(values) { + return (0, _keyValMap2.default)(values, function (value) { + return value.name.value; + }, function (value) { + var type = buildInputFieldType(value.type); + return { + type: type, + description: (0, _buildASTSchema.getDescription)(value), + defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type) + }; + }); + } + + function buildInputFieldType(typeNode) { + if (typeNode.kind === Kind.LIST_TYPE) { + return new _definition.GraphQLList(buildInputFieldType(typeNode.type)); + } + if (typeNode.kind === Kind.NON_NULL_TYPE) { + var nullableType = buildInputFieldType(typeNode.type); + (0, _invariant2.default)(!(nullableType instanceof _definition.GraphQLNonNull), 'Must be nullable'); + return new _definition.GraphQLNonNull(nullableType); + } + return getInputTypeFromAST(typeNode); + } + + function buildOutputFieldType(typeNode) { + if (typeNode.kind === Kind.LIST_TYPE) { + return new _definition.GraphQLList(buildOutputFieldType(typeNode.type)); + } + if (typeNode.kind === Kind.NON_NULL_TYPE) { + var nullableType = buildOutputFieldType(typeNode.type); + (0, _invariant2.default)(!(nullableType instanceof _definition.GraphQLNonNull), 'Must be nullable'); + return new _definition.GraphQLNonNull(nullableType); + } + return getOutputTypeFromAST(typeNode); + } +} + +function cannotExecuteExtendedSchema() { + throw new Error('Extended Schema cannot use Interface or Union types for execution.'); +} +},{"../error/GraphQLError":83,"../jsutils/invariant":94,"../jsutils/keyMap":97,"../jsutils/keyValMap":98,"../language/kinds":102,"../type/definition":112,"../type/directives":113,"../type/introspection":115,"../type/scalars":116,"../type/schema":117,"./buildASTSchema":121,"./valueFromAST":136}],125:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.DangerousChangeType = exports.BreakingChangeType = undefined; +exports.findBreakingChanges = findBreakingChanges; +exports.findDangerousChanges = findDangerousChanges; +exports.findRemovedTypes = findRemovedTypes; +exports.findTypesThatChangedKind = findTypesThatChangedKind; +exports.findArgChanges = findArgChanges; +exports.findFieldsThatChangedType = findFieldsThatChangedType; +exports.findFieldsThatChangedTypeOnInputObjectTypes = findFieldsThatChangedTypeOnInputObjectTypes; +exports.findTypesRemovedFromUnions = findTypesRemovedFromUnions; +exports.findValuesRemovedFromEnums = findValuesRemovedFromEnums; +exports.findInterfacesRemovedFromObjectTypes = findInterfacesRemovedFromObjectTypes; + +var _definition = require('../type/definition'); + +var _schema = require('../type/schema'); + +/** + * Copyright (c) 2016, 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 BreakingChangeType = exports.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', + NON_NULL_ARG_ADDED: 'NON_NULL_ARG_ADDED', + NON_NULL_INPUT_FIELD_ADDED: 'NON_NULL_INPUT_FIELD_ADDED', + INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT' +}; + +var DangerousChangeType = exports.DangerousChangeType = { + ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE' +}; + +/** + * 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), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(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); +} + +/** + * 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 = []; + Object.keys(oldTypeMap).forEach(function (typeName) { + if (!newTypeMap[typeName]) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: 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 = []; + Object.keys(oldTypeMap).forEach(function (typeName) { + if (!newTypeMap[typeName]) { + return; + } + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + if (!(oldType instanceof newType.constructor)) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + 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 = []; + + Object.keys(oldTypeMap).forEach(function (typeName) { + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) { + return; + } + + var oldTypeFields = oldType.getFields(); + var newTypeFields = newType.getFields(); + + Object.keys(oldTypeFields).forEach(function (fieldName) { + if (!newTypeFields[fieldName]) { + return; + } + + oldTypeFields[fieldName].args.forEach(function (oldArgDef) { + var newArgs = newTypeFields[fieldName].args; + var newArgDef = newArgs.find(function (arg) { + return arg.name === oldArgDef.name; + }); + + // Arg not present + if (!newArgDef) { + breakingChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' was removed') + }); + } else { + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type); + if (!isSafe) { + breakingChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed type from ') + (oldArgDef.type.toString() + ' to ' + newArgDef.type.toString()) + }); + } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) { + dangerousChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed defaultValue') + }); + } + } + }); + // Check if a non-null arg was added to the field + newTypeFields[fieldName].args.forEach(function (newArgDef) { + var oldArgs = oldTypeFields[fieldName].args; + var oldArgDef = oldArgs.find(function (arg) { + return arg.name === newArgDef.name; + }); + if (!oldArgDef && newArgDef.type instanceof _definition.GraphQLNonNull) { + breakingChanges.push({ + type: BreakingChangeType.NON_NULL_ARG_ADDED, + description: 'A non-null arg ' + newArgDef.name + ' on ' + (newType.name + '.' + fieldName + ' was added') + }); + } + }); + }); + }); + + return { + breakingChanges: breakingChanges, + dangerousChanges: dangerousChanges + }; +} + +function typeKindName(type) { + if (type instanceof _definition.GraphQLScalarType) { + return 'a Scalar type'; + } + if (type instanceof _definition.GraphQLObjectType) { + return 'an Object type'; + } + if (type instanceof _definition.GraphQLInterfaceType) { + return 'an Interface type'; + } + if (type instanceof _definition.GraphQLUnionType) { + return 'a Union type'; + } + if (type instanceof _definition.GraphQLEnumType) { + return 'an Enum type'; + } + if (type instanceof _definition.GraphQLInputObjectType) { + return 'an Input type'; + } + throw new TypeError('Unknown type ' + type.constructor.name); +} + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to the fields on a type. This includes if + * a field has been removed from a type, if a field has changed type, or if + * a non-null field is added to an input type. + */ +function findFieldsThatChangedType(oldSchema, newSchema) { + return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema)); +} + +function findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + + var breakingFieldChanges = []; + Object.keys(oldTypeMap).forEach(function (typeName) { + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) { + return; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + Object.keys(oldTypeFieldsDef).forEach(function (fieldName) { + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingFieldChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: typeName + '.' + 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(); + breakingFieldChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: typeName + '.' + fieldName + ' changed type from ' + (oldFieldTypeString + ' to ' + newFieldTypeString + '.') + }); + } + } + }); + }); + return breakingFieldChanges; +} + +function findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + + var breakingFieldChanges = []; + Object.keys(oldTypeMap).forEach(function (typeName) { + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + if (!(oldType instanceof _definition.GraphQLInputObjectType) || !(newType instanceof _definition.GraphQLInputObjectType)) { + return; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + Object.keys(oldTypeFieldsDef).forEach(function (fieldName) { + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingFieldChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: typeName + '.' + 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(); + breakingFieldChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: typeName + '.' + fieldName + ' changed type from ' + (oldFieldTypeString + ' to ' + newFieldTypeString + '.') + }); + } + } + }); + // Check if a non-null field was added to the input object type + Object.keys(newTypeFieldsDef).forEach(function (fieldName) { + if (!(fieldName in oldTypeFieldsDef) && newTypeFieldsDef[fieldName].type instanceof _definition.GraphQLNonNull) { + breakingFieldChanges.push({ + type: BreakingChangeType.NON_NULL_INPUT_FIELD_ADDED, + description: 'A non-null field ' + fieldName + ' on ' + ('input type ' + newType.name + ' was added.') + }); + } + }); + }); + return breakingFieldChanges; +} + +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 + newType instanceof _definition.GraphQLNonNull && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if (oldType instanceof _definition.GraphQLList) { + return ( + // if they're both lists, make sure the underlying types are compatible + newType instanceof _definition.GraphQLList && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || + // moving from nullable to non-null of the same underlying type is safe + newType instanceof _definition.GraphQLNonNull && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if (oldType instanceof _definition.GraphQLNonNull) { + // if they're both non-null, make sure the underlying types are compatible + return newType instanceof _definition.GraphQLNonNull && 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 (oldType instanceof _definition.GraphQLList) { + // if they're both lists, make sure the underlying types are compatible + return newType instanceof _definition.GraphQLList && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); + } else if (oldType instanceof _definition.GraphQLNonNull) { + return ( + // if they're both non-null, make sure the underlying types are + // compatible + newType instanceof _definition.GraphQLNonNull && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || + // moving from non-null to nullable of the same underlying type is safe + !(newType instanceof _definition.GraphQLNonNull) && 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 = []; + Object.keys(oldTypeMap).forEach(function (typeName) { + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) { + return; + } + var typeNamesInNewUnion = Object.create(null); + newType.getTypes().forEach(function (type) { + typeNamesInNewUnion[type.name] = true; + }); + oldType.getTypes().forEach(function (type) { + if (!typeNamesInNewUnion[type.name]) { + typesRemovedFromUnion.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: type.name + ' was removed from union type ' + typeName + '.' + }); + } + }); + }); + return typesRemovedFromUnion; +} + +/** + * 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 = []; + Object.keys(oldTypeMap).forEach(function (typeName) { + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + if (!(oldType instanceof _definition.GraphQLEnumType) || !(newType instanceof _definition.GraphQLEnumType)) { + return; + } + var valuesInNewEnum = Object.create(null); + newType.getValues().forEach(function (value) { + valuesInNewEnum[value.name] = true; + }); + oldType.getValues().forEach(function (value) { + if (!valuesInNewEnum[value.name]) { + valuesRemovedFromEnums.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: value.name + ' was removed from enum type ' + typeName + '.' + }); + } + }); + }); + return valuesRemovedFromEnums; +} + +function findInterfacesRemovedFromObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + Object.keys(oldTypeMap).forEach(function (typeName) { + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + if (!(oldType instanceof _definition.GraphQLObjectType) || !(newType instanceof _definition.GraphQLObjectType)) { + return; + } + + var oldInterfaces = oldType.getInterfaces(); + var newInterfaces = newType.getInterfaces(); + oldInterfaces.forEach(function (oldInterface) { + if (!newInterfaces.some(function (int) { + return int.name === oldInterface.name; + })) { + breakingChanges.push({ + type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT, + description: typeName + ' no longer implements interface ' + (oldInterface.name + '.') + }); + } + }); + }); + return breakingChanges; +} +},{"../type/definition":112,"../type/schema":117}],126:[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 _schema = require('../type/schema'); + +var _TypeInfo = require('./TypeInfo'); + +/** + * 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 ' + parentType.name + '.' + 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 ' + type.name + '.' + enumVal.name + ' is deprecated.' + (reason ? ' ' + reason : ''), [node])); + } + } + } + })); + + return errors; +} +/** + * 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. + */ +},{"../error/GraphQLError":83,"../language/visitor":108,"../type/definition":112,"../type/schema":117,"./TypeInfo":118}],127:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getOperationAST = getOperationAST; + +var _kinds = require('../language/kinds'); + +/** + * 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.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; +} +/** + * 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. + */ +},{"../language/kinds":102}],128:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _introspectionQuery = require('./introspectionQuery'); + +Object.defineProperty(exports, 'introspectionQuery', { + enumerable: true, + get: function get() { + return _introspectionQuery.introspectionQuery; + } +}); + +var _getOperationAST = require('./getOperationAST'); + +Object.defineProperty(exports, 'getOperationAST', { + enumerable: true, + get: function get() { + return _getOperationAST.getOperationAST; + } +}); + +var _buildClientSchema = require('./buildClientSchema'); + +Object.defineProperty(exports, 'buildClientSchema', { + enumerable: true, + get: function get() { + return _buildClientSchema.buildClientSchema; + } +}); + +var _buildASTSchema = require('./buildASTSchema'); + +Object.defineProperty(exports, 'buildASTSchema', { + enumerable: true, + get: function get() { + return _buildASTSchema.buildASTSchema; + } +}); +Object.defineProperty(exports, 'buildSchema', { + enumerable: true, + get: function get() { + return _buildASTSchema.buildSchema; + } +}); + +var _extendSchema = require('./extendSchema'); + +Object.defineProperty(exports, 'extendSchema', { + enumerable: true, + get: function get() { + return _extendSchema.extendSchema; + } +}); + +var _schemaPrinter = require('./schemaPrinter'); + +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; + } +}); + +var _typeFromAST = require('./typeFromAST'); + +Object.defineProperty(exports, 'typeFromAST', { + enumerable: true, + get: function get() { + return _typeFromAST.typeFromAST; + } +}); + +var _valueFromAST = require('./valueFromAST'); + +Object.defineProperty(exports, 'valueFromAST', { + enumerable: true, + get: function get() { + return _valueFromAST.valueFromAST; + } +}); + +var _astFromValue = require('./astFromValue'); + +Object.defineProperty(exports, 'astFromValue', { + enumerable: true, + get: function get() { + return _astFromValue.astFromValue; + } +}); + +var _TypeInfo = require('./TypeInfo'); + +Object.defineProperty(exports, 'TypeInfo', { + enumerable: true, + get: function get() { + return _TypeInfo.TypeInfo; + } +}); + +var _isValidJSValue = require('./isValidJSValue'); + +Object.defineProperty(exports, 'isValidJSValue', { + enumerable: true, + get: function get() { + return _isValidJSValue.isValidJSValue; + } +}); + +var _isValidLiteralValue = require('./isValidLiteralValue'); + +Object.defineProperty(exports, 'isValidLiteralValue', { + enumerable: true, + get: function get() { + return _isValidLiteralValue.isValidLiteralValue; + } +}); + +var _concatAST = require('./concatAST'); + +Object.defineProperty(exports, 'concatAST', { + enumerable: true, + get: function get() { + return _concatAST.concatAST; + } +}); + +var _separateOperations = require('./separateOperations'); + +Object.defineProperty(exports, 'separateOperations', { + enumerable: true, + get: function get() { + return _separateOperations.separateOperations; + } +}); + +var _typeComparators = require('./typeComparators'); + +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; + } +}); + +var _assertValidName = require('./assertValidName'); + +Object.defineProperty(exports, 'assertValidName', { + enumerable: true, + get: function get() { + return _assertValidName.assertValidName; + } +}); + +var _findBreakingChanges = require('./findBreakingChanges'); + +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; + } +}); + +var _findDeprecatedUsages = require('./findDeprecatedUsages'); + +Object.defineProperty(exports, 'findDeprecatedUsages', { + enumerable: true, + get: function get() { + return _findDeprecatedUsages.findDeprecatedUsages; + } +}); +},{"./TypeInfo":118,"./assertValidName":119,"./astFromValue":120,"./buildASTSchema":121,"./buildClientSchema":122,"./concatAST":123,"./extendSchema":124,"./findBreakingChanges":125,"./findDeprecatedUsages":126,"./getOperationAST":127,"./introspectionQuery":129,"./isValidJSValue":130,"./isValidLiteralValue":131,"./schemaPrinter":132,"./separateOperations":133,"./typeComparators":134,"./typeFromAST":135,"./valueFromAST":136}],129:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var introspectionQuery = exports.introspectionQuery = '\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { 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'; +/** + * 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. + */ +},{}],130:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isValidJSValue = isValidJSValue; + +var _iterall = require('iterall'); + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isNullish = require('../jsutils/isNullish'); + +var _isNullish2 = _interopRequireDefault(_isNullish); + +var _definition = require('../type/definition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +/** + * Given a JavaScript value and a GraphQL type, determine if the value will be + * accepted for that type. This is primarily useful for validating the + * runtime values of query variables. + */ + +/** + * 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 isValidJSValue(value, type) { + // A value must be provided if the type is non-null. + if (type instanceof _definition.GraphQLNonNull) { + if ((0, _isNullish2.default)(value)) { + return ['Expected "' + String(type) + '", found null.']; + } + return isValidJSValue(value, type.ofType); + } + + if ((0, _isNullish2.default)(value)) { + return []; + } + + // Lists accept a non-list value as a list of one. + if (type instanceof _definition.GraphQLList) { + var itemType = type.ofType; + if ((0, _iterall.isCollection)(value)) { + var errors = []; + (0, _iterall.forEach)(value, function (item, index) { + errors.push.apply(errors, isValidJSValue(item, itemType).map(function (error) { + return 'In element #' + index + ': ' + error; + })); + }); + return errors; + } + return isValidJSValue(value, itemType); + } + + // Input objects check each defined field. + if (type instanceof _definition.GraphQLInputObjectType) { + if (typeof value !== 'object' || value === null) { + return ['Expected "' + type.name + '", found not an object.']; + } + var fields = type.getFields(); + + var _errors = []; + + // Ensure every provided field is defined. + Object.keys(value).forEach(function (providedField) { + if (!fields[providedField]) { + _errors.push('In field "' + providedField + '": Unknown field.'); + } + }); + + // Ensure every defined field is valid. + Object.keys(fields).forEach(function (fieldName) { + var newErrors = isValidJSValue(value[fieldName], fields[fieldName].type); + _errors.push.apply(_errors, newErrors.map(function (error) { + return 'In field "' + fieldName + '": ' + error; + })); + }); + + return _errors; + } + + (0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must be input type'); + + // Scalar/Enum input checks to ensure the type can parse the value to + // a non-null value. + try { + var parseResult = type.parseValue(value); + if ((0, _isNullish2.default)(parseResult) && !type.isValidValue(value)) { + return ['Expected type "' + type.name + '", found ' + JSON.stringify(value) + '.']; + } + } catch (error) { + return ['Expected type "' + type.name + '", found ' + JSON.stringify(value) + ': ' + error.message]; + } + + return []; +} +},{"../jsutils/invariant":94,"../jsutils/isNullish":96,"../type/definition":112,"iterall":166}],131:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isValidLiteralValue = isValidLiteralValue; + +var _printer = require('../language/printer'); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _definition = require('../type/definition'); + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _keyMap = require('../jsutils/keyMap'); + +var _keyMap2 = _interopRequireDefault(_keyMap); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Utility for validators which determines if a value literal node is valid + * given an input type. + * + * Note that this only validates literal values, variables are assumed to + * provide values of the correct type. + */ +function isValidLiteralValue(type, valueNode) { + // A value must be provided if the type is non-null. + if (type instanceof _definition.GraphQLNonNull) { + if (!valueNode || valueNode.kind === Kind.NULL) { + return ['Expected "' + String(type) + '", found null.']; + } + return isValidLiteralValue(type.ofType, valueNode); + } + + if (!valueNode || valueNode.kind === Kind.NULL) { + return []; + } + + // This function only tests literals, and assumes variables will provide + // values of the correct type. + if (valueNode.kind === Kind.VARIABLE) { + return []; + } + + // Lists accept a non-list value as a list of one. + if (type instanceof _definition.GraphQLList) { + var itemType = type.ofType; + if (valueNode.kind === Kind.LIST) { + return valueNode.values.reduce(function (acc, item, index) { + var errors = isValidLiteralValue(itemType, item); + return acc.concat(errors.map(function (error) { + return 'In element #' + index + ': ' + error; + })); + }, []); + } + return isValidLiteralValue(itemType, valueNode); + } + + // Input objects check each defined field and look for undefined fields. + if (type instanceof _definition.GraphQLInputObjectType) { + if (valueNode.kind !== Kind.OBJECT) { + return ['Expected "' + type.name + '", found not an object.']; + } + var fields = type.getFields(); + + var errors = []; + + // Ensure every provided field is defined. + var fieldNodes = valueNode.fields; + fieldNodes.forEach(function (providedFieldNode) { + if (!fields[providedFieldNode.name.value]) { + errors.push('In field "' + providedFieldNode.name.value + '": Unknown field.'); + } + }); + + // Ensure every defined field is valid. + var fieldNodeMap = (0, _keyMap2.default)(fieldNodes, function (fieldNode) { + return fieldNode.name.value; + }); + Object.keys(fields).forEach(function (fieldName) { + var result = isValidLiteralValue(fields[fieldName].type, fieldNodeMap[fieldName] && fieldNodeMap[fieldName].value); + errors.push.apply(errors, result.map(function (error) { + return 'In field "' + fieldName + '": ' + error; + })); + }); + + return errors; + } + + (0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must be input type'); + + // Scalars determine if a literal values is valid. + if (!type.isValidLiteral(valueNode)) { + return ['Expected type "' + type.name + '", found ' + (0, _printer.print)(valueNode) + '.']; + } + + return []; +} +/** + * 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. + */ +},{"../jsutils/invariant":94,"../jsutils/keyMap":97,"../language/kinds":102,"../language/printer":106,"../type/definition":112}],132:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.printSchema = printSchema; +exports.printIntrospectionSchema = printIntrospectionSchema; +exports.printType = printType; + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isNullish = require('../jsutils/isNullish'); + +var _isNullish2 = _interopRequireDefault(_isNullish); + +var _isInvalid = require('../jsutils/isInvalid'); + +var _isInvalid2 = _interopRequireDefault(_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'); + +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. + */ + +function printSchema(schema) { + return printFilteredSchema(schema, function (n) { + return !isSpecDirective(n); + }, isDefinedType); +} + +function printIntrospectionSchema(schema) { + return printFilteredSchema(schema, isSpecDirective, isIntrospectionType); +} + +function isSpecDirective(directiveName) { + return directiveName === 'skip' || directiveName === 'include' || directiveName === 'deprecated'; +} + +function isDefinedType(typename) { + return !isIntrospectionType(typename) && !isBuiltInScalar(typename); +} + +function isIntrospectionType(typename) { + return typename.indexOf('__') === 0; +} + +function isBuiltInScalar(typename) { + return typename === 'String' || typename === 'Boolean' || typename === 'Int' || typename === 'Float' || typename === 'ID'; +} + +function printFilteredSchema(schema, directiveFilter, typeFilter) { + var directives = schema.getDirectives().filter(function (directive) { + return directiveFilter(directive.name); + }); + var typeMap = schema.getTypeMap(); + var types = Object.keys(typeMap).filter(typeFilter).sort(function (name1, name2) { + return name1.localeCompare(name2); + }).map(function (typeName) { + return typeMap[typeName]; + }); + + return [printSchemaDefinition(schema)].concat(directives.map(printDirective), types.map(printType)).filter(Boolean).join('\n\n') + '\n'; +} + +function printSchemaDefinition(schema) { + if (isSchemaOfCommonNames(schema)) { + return; + } + + var operationTypes = []; + + var queryType = schema.getQueryType(); + if (queryType) { + operationTypes.push(' query: ' + queryType.name); + } + + var mutationType = schema.getMutationType(); + if (mutationType) { + operationTypes.push(' mutation: ' + mutationType.name); + } + + var subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + operationTypes.push(' subscription: ' + subscriptionType.name); + } + + return 'schema {\n' + 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) { + if (type instanceof _definition.GraphQLScalarType) { + return printScalar(type); + } else if (type instanceof _definition.GraphQLObjectType) { + return printObject(type); + } else if (type instanceof _definition.GraphQLInterfaceType) { + return printInterface(type); + } else if (type instanceof _definition.GraphQLUnionType) { + return printUnion(type); + } else if (type instanceof _definition.GraphQLEnumType) { + return printEnum(type); + } + (0, _invariant2.default)(type instanceof _definition.GraphQLInputObjectType); + return printInputObject(type); +} + +function printScalar(type) { + return printDescription(type) + ('scalar ' + type.name); +} + +function printObject(type) { + var interfaces = type.getInterfaces(); + var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) { + return i.name; + }).join(', ') : ''; + return printDescription(type) + ('type ' + type.name + implementedInterfaces + ' {\n') + printFields(type) + '\n' + '}'; +} + +function printInterface(type) { + return printDescription(type) + ('interface ' + type.name + ' {\n') + printFields(type) + '\n' + '}'; +} + +function printUnion(type) { + return printDescription(type) + ('union ' + type.name + ' = ' + type.getTypes().join(' | ')); +} + +function printEnum(type) { + return printDescription(type) + ('enum ' + type.name + ' {\n') + printEnumValues(type.getValues()) + '\n' + '}'; +} + +function printEnumValues(values) { + return values.map(function (value, i) { + return printDescription(value, ' ', !i) + ' ' + value.name + printDeprecated(value); + }).join('\n'); +} + +function printInputObject(type) { + var fieldMap = type.getFields(); + var fields = Object.keys(fieldMap).map(function (fieldName) { + return fieldMap[fieldName]; + }); + return printDescription(type) + ('input ' + type.name + ' {\n') + fields.map(function (f, i) { + return printDescription(f, ' ', !i) + ' ' + printInputValue(f); + }).join('\n') + '\n' + '}'; +} + +function printFields(type) { + var fieldMap = type.getFields(); + var fields = Object.keys(fieldMap).map(function (fieldName) { + return fieldMap[fieldName]; + }); + return fields.map(function (f, i) { + return printDescription(f, ' ', !i) + ' ' + f.name + printArgs(f.args, ' ') + ': ' + String(f.type) + printDeprecated(f); + }).join('\n'); +} + +function printArgs(args) { + var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + + 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(arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg); + }).join('\n') + '\n' + indentation + ')'; +} + +function printInputValue(arg) { + var argDecl = arg.name + ': ' + String(arg.type); + if (!(0, _isInvalid2.default)(arg.defaultValue)) { + argDecl += ' = ' + (0, _printer.print)((0, _astFromValue.astFromValue)(arg.defaultValue, arg.type)); + } + return argDecl; +} + +function printDirective(directive) { + return printDescription(directive) + 'directive @' + directive.name + printArgs(directive.args) + ' on ' + directive.locations.join(' | '); +} + +function printDeprecated(fieldOrEnumVal) { + var reason = fieldOrEnumVal.deprecationReason; + if ((0, _isNullish2.default)(reason)) { + return ''; + } + if (reason === '' || reason === _directives.DEFAULT_DEPRECATION_REASON) { + return ' @deprecated'; + } + return ' @deprecated(reason: ' + (0, _printer.print)((0, _astFromValue.astFromValue)(reason, _scalars.GraphQLString)) + ')'; +} + +function printDescription(def) { + var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + var firstInBlock = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + + if (!def.description) { + return ''; + } + var lines = def.description.split('\n'); + var description = indentation && !firstInBlock ? '\n' : ''; + for (var i = 0; i < lines.length; i++) { + if (lines[i] === '') { + description += indentation + '#\n'; + } else { + // For > 120 character long lines, cut at space boundaries into sublines + // of ~80 chars. + var sublines = breakLine(lines[i], 120 - indentation.length); + for (var j = 0; j < sublines.length; j++) { + description += indentation + '# ' + sublines[j] + '\n'; + } + } + } + return description; +} + +function breakLine(line, len) { + if (line.length < len + 5) { + return [line]; + } + var parts = line.split(new RegExp('((?: |^).{15,' + (len - 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/invariant":94,"../jsutils/isInvalid":95,"../jsutils/isNullish":96,"../language/printer":106,"../type/definition":112,"../type/directives":113,"../type/scalars":116,"../utilities/astFromValue":120}],133:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.separateOperations = separateOperations; + +var _visitor = require('../language/visitor'); + +/** + * 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 = void 0; + 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); + operations.forEach(function (operation) { + 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]; + Object.keys(dependencies).forEach(function (name) { + 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; +} +/** + * 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. + */ + +// 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) { + Object.keys(immediateDeps).forEach(function (toName) { + if (!collected[toName]) { + collected[toName] = true; + collectTransitiveDependencies(collected, depGraph, toName); + } + }); + } +} +},{"../language/visitor":108}],134:[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'); + +/** + * 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 (typeA instanceof _definition.GraphQLNonNull && typeB instanceof _definition.GraphQLNonNull) { + return isEqualType(typeA.ofType, typeB.ofType); + } + + // If either type is a list, the other must also be a list. + if (typeA instanceof _definition.GraphQLList && typeB instanceof _definition.GraphQLList) { + 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). + */ + +/** + * 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 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 (superType instanceof _definition.GraphQLNonNull) { + if (maybeSubType instanceof _definition.GraphQLNonNull) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } else if (maybeSubType instanceof _definition.GraphQLNonNull) { + // 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 (superType instanceof _definition.GraphQLList) { + if (maybeSubType instanceof _definition.GraphQLList) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } else if (maybeSubType instanceof _definition.GraphQLList) { + // 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) && maybeSubType instanceof _definition.GraphQLObjectType && 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) { + // So flow is aware this is constant + var _typeB = 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":112}],135:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.typeFromAST = undefined; + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _definition = require('../type/definition'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +/** + * Given a Schema and an AST node describing a type, return a GraphQLType + * definition which applies to that type. For example, if provided the parsed + * AST node for `[User]`, a GraphQLList instance will be returned, containing + * the type called "User" found in the schema. If a type called "User" is not + * found in the schema, then undefined will be returned. + */ +/* eslint-disable no-redeclare */ +function typeFromASTImpl(schema, typeNode) { + /* eslint-enable no-redeclare */ + var innerType = void 0; + if (typeNode.kind === Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLList(innerType); + } + if (typeNode.kind === Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLNonNull(innerType); + } + (0, _invariant2.default)(typeNode.kind === Kind.NAMED_TYPE, 'Must be a named type.'); + return schema.getType(typeNode.name.value); +} +// This will export typeFromAST with the correct type, but currently exposes +// ~26 errors: https://gist.github.com/4a29403a99a8186fcb15064d69c5f3ae +// export var typeFromAST: typeof typeFromASTType = typeFromASTImpl; + +/** + * 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 typeFromAST = exports.typeFromAST = typeFromASTImpl; +},{"../jsutils/invariant":94,"../language/kinds":102,"../type/definition":112}],136:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.valueFromAST = valueFromAST; + +var _keyMap = require('../jsutils/keyMap'); + +var _keyMap2 = _interopRequireDefault(_keyMap); + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _isNullish = require('../jsutils/isNullish'); + +var _isNullish2 = _interopRequireDefault(_isNullish); + +var _isInvalid = require('../jsutils/isInvalid'); + +var _isInvalid2 = _interopRequireDefault(_isInvalid); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _definition = require('../type/definition'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +/** + * 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 | + * + */ + +/** + * 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 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 (type instanceof _definition.GraphQLNonNull) { + if (valueNode.kind === Kind.NULL) { + return; // Invalid: intentionally return no value. + } + return valueFromAST(valueNode, type.ofType, variables); + } + + if (valueNode.kind === Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + + if (valueNode.kind === Kind.VARIABLE) { + var variableName = valueNode.name.value; + if (!variables || (0, _isInvalid2.default)(variables[variableName])) { + // No valid return value. + return; + } + // Note: we're not doing any checking that this variable is correct. We're + // assuming that this query has been validated and the variable usage here + // is of the correct type. + return variables[variableName]; + } + + if (type instanceof _definition.GraphQLList) { + var itemType = type.ofType; + if (valueNode.kind === 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 (itemType instanceof _definition.GraphQLNonNull) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(null); + } else { + var itemValue = valueFromAST(itemNodes[i], itemType, variables); + if ((0, _isInvalid2.default)(itemValue)) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(itemValue); + } + } + return coercedValues; + } + var coercedValue = valueFromAST(valueNode, itemType, variables); + if ((0, _isInvalid2.default)(coercedValue)) { + return; // Invalid: intentionally return no value. + } + return [coercedValue]; + } + + if (type instanceof _definition.GraphQLInputObjectType) { + if (valueNode.kind !== Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + var coercedObj = Object.create(null); + var fields = type.getFields(); + var fieldNodes = (0, _keyMap2.default)(valueNode.fields, function (field) { + return field.name.value; + }); + var fieldNames = Object.keys(fields); + for (var _i = 0; _i < fieldNames.length; _i++) { + var fieldName = fieldNames[_i]; + var field = fields[fieldName]; + var fieldNode = fieldNodes[fieldName]; + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (!(0, _isInvalid2.default)(field.defaultValue)) { + coercedObj[fieldName] = field.defaultValue; + } else if (field.type instanceof _definition.GraphQLNonNull) { + return; // Invalid: intentionally return no value. + } + continue; + } + var fieldValue = valueFromAST(fieldNode.value, field.type, variables); + if ((0, _isInvalid2.default)(fieldValue)) { + return; // Invalid: intentionally return no value. + } + coercedObj[fieldName] = fieldValue; + } + return coercedObj; + } + + (0, _invariant2.default)(type instanceof _definition.GraphQLScalarType || type instanceof _definition.GraphQLEnumType, 'Must be input type'); + + var parsed = type.parseLiteral(valueNode); + if ((0, _isNullish2.default)(parsed) && !type.isValidLiteral(valueNode)) { + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + return; + } + + return parsed; +} + +// 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 === Kind.VARIABLE && (!variables || (0, _isInvalid2.default)(variables[valueNode.name.value])); +} +},{"../jsutils/invariant":94,"../jsutils/isInvalid":95,"../jsutils/isNullish":96,"../jsutils/keyMap":97,"../language/kinds":102,"../type/definition":112}],137:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _validate = require('./validate'); + +Object.defineProperty(exports, 'validate', { + enumerable: true, + get: function get() { + return _validate.validate; + } +}); +Object.defineProperty(exports, 'ValidationContext', { + enumerable: true, + get: function get() { + return _validate.ValidationContext; + } +}); + +var _specifiedRules = require('./specifiedRules'); + +Object.defineProperty(exports, 'specifiedRules', { + enumerable: true, + get: function get() { + return _specifiedRules.specifiedRules; + } +}); + +var _ArgumentsOfCorrectType = require('./rules/ArgumentsOfCorrectType'); + +Object.defineProperty(exports, 'ArgumentsOfCorrectTypeRule', { + enumerable: true, + get: function get() { + return _ArgumentsOfCorrectType.ArgumentsOfCorrectType; + } +}); + +var _DefaultValuesOfCorrectType = require('./rules/DefaultValuesOfCorrectType'); + +Object.defineProperty(exports, 'DefaultValuesOfCorrectTypeRule', { + enumerable: true, + get: function get() { + return _DefaultValuesOfCorrectType.DefaultValuesOfCorrectType; + } +}); + +var _FieldsOnCorrectType = require('./rules/FieldsOnCorrectType'); + +Object.defineProperty(exports, 'FieldsOnCorrectTypeRule', { + enumerable: true, + get: function get() { + return _FieldsOnCorrectType.FieldsOnCorrectType; + } +}); + +var _FragmentsOnCompositeTypes = require('./rules/FragmentsOnCompositeTypes'); + +Object.defineProperty(exports, 'FragmentsOnCompositeTypesRule', { + enumerable: true, + get: function get() { + return _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes; + } +}); + +var _KnownArgumentNames = require('./rules/KnownArgumentNames'); + +Object.defineProperty(exports, 'KnownArgumentNamesRule', { + enumerable: true, + get: function get() { + return _KnownArgumentNames.KnownArgumentNames; + } +}); + +var _KnownDirectives = require('./rules/KnownDirectives'); + +Object.defineProperty(exports, 'KnownDirectivesRule', { + enumerable: true, + get: function get() { + return _KnownDirectives.KnownDirectives; + } +}); + +var _KnownFragmentNames = require('./rules/KnownFragmentNames'); + +Object.defineProperty(exports, 'KnownFragmentNamesRule', { + enumerable: true, + get: function get() { + return _KnownFragmentNames.KnownFragmentNames; + } +}); + +var _KnownTypeNames = require('./rules/KnownTypeNames'); + +Object.defineProperty(exports, 'KnownTypeNamesRule', { + enumerable: true, + get: function get() { + return _KnownTypeNames.KnownTypeNames; + } +}); + +var _LoneAnonymousOperation = require('./rules/LoneAnonymousOperation'); + +Object.defineProperty(exports, 'LoneAnonymousOperationRule', { + enumerable: true, + get: function get() { + return _LoneAnonymousOperation.LoneAnonymousOperation; + } +}); + +var _NoFragmentCycles = require('./rules/NoFragmentCycles'); + +Object.defineProperty(exports, 'NoFragmentCyclesRule', { + enumerable: true, + get: function get() { + return _NoFragmentCycles.NoFragmentCycles; + } +}); + +var _NoUndefinedVariables = require('./rules/NoUndefinedVariables'); + +Object.defineProperty(exports, 'NoUndefinedVariablesRule', { + enumerable: true, + get: function get() { + return _NoUndefinedVariables.NoUndefinedVariables; + } +}); + +var _NoUnusedFragments = require('./rules/NoUnusedFragments'); + +Object.defineProperty(exports, 'NoUnusedFragmentsRule', { + enumerable: true, + get: function get() { + return _NoUnusedFragments.NoUnusedFragments; + } +}); + +var _NoUnusedVariables = require('./rules/NoUnusedVariables'); + +Object.defineProperty(exports, 'NoUnusedVariablesRule', { + enumerable: true, + get: function get() { + return _NoUnusedVariables.NoUnusedVariables; + } +}); + +var _OverlappingFieldsCanBeMerged = require('./rules/OverlappingFieldsCanBeMerged'); + +Object.defineProperty(exports, 'OverlappingFieldsCanBeMergedRule', { + enumerable: true, + get: function get() { + return _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged; + } +}); + +var _PossibleFragmentSpreads = require('./rules/PossibleFragmentSpreads'); + +Object.defineProperty(exports, 'PossibleFragmentSpreadsRule', { + enumerable: true, + get: function get() { + return _PossibleFragmentSpreads.PossibleFragmentSpreads; + } +}); + +var _ProvidedNonNullArguments = require('./rules/ProvidedNonNullArguments'); + +Object.defineProperty(exports, 'ProvidedNonNullArgumentsRule', { + enumerable: true, + get: function get() { + return _ProvidedNonNullArguments.ProvidedNonNullArguments; + } +}); + +var _ScalarLeafs = require('./rules/ScalarLeafs'); + +Object.defineProperty(exports, 'ScalarLeafsRule', { + enumerable: true, + get: function get() { + return _ScalarLeafs.ScalarLeafs; + } +}); + +var _SingleFieldSubscriptions = require('./rules/SingleFieldSubscriptions'); + +Object.defineProperty(exports, 'SingleFieldSubscriptionsRule', { + enumerable: true, + get: function get() { + return _SingleFieldSubscriptions.SingleFieldSubscriptions; + } +}); + +var _UniqueArgumentNames = require('./rules/UniqueArgumentNames'); + +Object.defineProperty(exports, 'UniqueArgumentNamesRule', { + enumerable: true, + get: function get() { + return _UniqueArgumentNames.UniqueArgumentNames; + } +}); + +var _UniqueDirectivesPerLocation = require('./rules/UniqueDirectivesPerLocation'); + +Object.defineProperty(exports, 'UniqueDirectivesPerLocationRule', { + enumerable: true, + get: function get() { + return _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation; + } +}); + +var _UniqueFragmentNames = require('./rules/UniqueFragmentNames'); + +Object.defineProperty(exports, 'UniqueFragmentNamesRule', { + enumerable: true, + get: function get() { + return _UniqueFragmentNames.UniqueFragmentNames; + } +}); + +var _UniqueInputFieldNames = require('./rules/UniqueInputFieldNames'); + +Object.defineProperty(exports, 'UniqueInputFieldNamesRule', { + enumerable: true, + get: function get() { + return _UniqueInputFieldNames.UniqueInputFieldNames; + } +}); + +var _UniqueOperationNames = require('./rules/UniqueOperationNames'); + +Object.defineProperty(exports, 'UniqueOperationNamesRule', { + enumerable: true, + get: function get() { + return _UniqueOperationNames.UniqueOperationNames; + } +}); + +var _UniqueVariableNames = require('./rules/UniqueVariableNames'); + +Object.defineProperty(exports, 'UniqueVariableNamesRule', { + enumerable: true, + get: function get() { + return _UniqueVariableNames.UniqueVariableNames; + } +}); + +var _VariablesAreInputTypes = require('./rules/VariablesAreInputTypes'); + +Object.defineProperty(exports, 'VariablesAreInputTypesRule', { + enumerable: true, + get: function get() { + return _VariablesAreInputTypes.VariablesAreInputTypes; + } +}); + +var _VariablesInAllowedPosition = require('./rules/VariablesInAllowedPosition'); + +Object.defineProperty(exports, 'VariablesInAllowedPositionRule', { + enumerable: true, + get: function get() { + return _VariablesInAllowedPosition.VariablesInAllowedPosition; + } +}); +},{"./rules/ArgumentsOfCorrectType":138,"./rules/DefaultValuesOfCorrectType":139,"./rules/FieldsOnCorrectType":140,"./rules/FragmentsOnCompositeTypes":141,"./rules/KnownArgumentNames":142,"./rules/KnownDirectives":143,"./rules/KnownFragmentNames":144,"./rules/KnownTypeNames":145,"./rules/LoneAnonymousOperation":146,"./rules/NoFragmentCycles":147,"./rules/NoUndefinedVariables":148,"./rules/NoUnusedFragments":149,"./rules/NoUnusedVariables":150,"./rules/OverlappingFieldsCanBeMerged":151,"./rules/PossibleFragmentSpreads":152,"./rules/ProvidedNonNullArguments":153,"./rules/ScalarLeafs":154,"./rules/SingleFieldSubscriptions":155,"./rules/UniqueArgumentNames":156,"./rules/UniqueDirectivesPerLocation":157,"./rules/UniqueFragmentNames":158,"./rules/UniqueInputFieldNames":159,"./rules/UniqueOperationNames":160,"./rules/UniqueVariableNames":161,"./rules/VariablesAreInputTypes":162,"./rules/VariablesInAllowedPosition":163,"./specifiedRules":164,"./validate":165}],138:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.badValueMessage = badValueMessage; +exports.ArgumentsOfCorrectType = ArgumentsOfCorrectType; + +var _error = require('../../error'); + +var _printer = require('../../language/printer'); + +var _isValidLiteralValue = require('../../utilities/isValidLiteralValue'); + +/** + * 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 badValueMessage(argName, type, value, verboseErrors) { + var message = verboseErrors ? '\n' + verboseErrors.join('\n') : ''; + return 'Argument "' + argName + '" has invalid value ' + value + '.' + message; +} + +/** + * Argument values of correct type + * + * A GraphQL document is only valid if all field argument literal values are + * of the type expected by their position. + */ +function ArgumentsOfCorrectType(context) { + return { + Argument: function Argument(node) { + var argDef = context.getArgument(); + if (argDef) { + var errors = (0, _isValidLiteralValue.isValidLiteralValue)(argDef.type, node.value); + if (errors && errors.length > 0) { + context.reportError(new _error.GraphQLError(badValueMessage(node.name.value, argDef.type, (0, _printer.print)(node.value), errors), [node.value])); + } + } + return false; + } + }; +} +},{"../../error":85,"../../language/printer":106,"../../utilities/isValidLiteralValue":131}],139:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.defaultForNonNullArgMessage = defaultForNonNullArgMessage; +exports.badValueForDefaultArgMessage = badValueForDefaultArgMessage; +exports.DefaultValuesOfCorrectType = DefaultValuesOfCorrectType; + +var _error = require('../../error'); + +var _printer = require('../../language/printer'); + +var _definition = require('../../type/definition'); + +var _isValidLiteralValue = require('../../utilities/isValidLiteralValue'); + +function defaultForNonNullArgMessage(varName, type, guessType) { + return 'Variable "$' + varName + '" of type "' + String(type) + '" is required and ' + 'will not use the default value. ' + ('Perhaps you meant to use type "' + String(guessType) + '".'); +} +/** + * 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 badValueForDefaultArgMessage(varName, type, value, verboseErrors) { + var message = verboseErrors ? '\n' + verboseErrors.join('\n') : ''; + return 'Variable "$' + varName + '" of type "' + String(type) + '" has invalid ' + ('default value ' + value + '.' + message); +} + +/** + * Variable default values of correct type + * + * A GraphQL document is only valid if all variable default values are of the + * type expected by their definition. + */ +function DefaultValuesOfCorrectType(context) { + return { + VariableDefinition: function VariableDefinition(node) { + var name = node.variable.name.value; + var defaultValue = node.defaultValue; + var type = context.getInputType(); + if (type instanceof _definition.GraphQLNonNull && defaultValue) { + context.reportError(new _error.GraphQLError(defaultForNonNullArgMessage(name, type, type.ofType), [defaultValue])); + } + if (type && defaultValue) { + var errors = (0, _isValidLiteralValue.isValidLiteralValue)(type, defaultValue); + if (errors && errors.length > 0) { + context.reportError(new _error.GraphQLError(badValueForDefaultArgMessage(name, type, (0, _printer.print)(defaultValue), errors), [defaultValue])); + } + } + return false; + }, + + SelectionSet: function SelectionSet() { + return false; + }, + FragmentDefinition: function FragmentDefinition() { + return false; + } + }; +} +},{"../../error":85,"../../language/printer":106,"../../type/definition":112,"../../utilities/isValidLiteralValue":131}],140:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.undefinedFieldMessage = undefinedFieldMessage; +exports.FieldsOnCorrectType = FieldsOnCorrectType; + +var _error = require('../../error'); + +var _suggestionList = require('../../jsutils/suggestionList'); + +var _suggestionList2 = _interopRequireDefault(_suggestionList); + +var _quotedOrList = require('../../jsutils/quotedOrList'); + +var _quotedOrList2 = _interopRequireDefault(_quotedOrList); + +var _definition = require('../../type/definition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function undefinedFieldMessage(fieldName, type, suggestedTypeNames, suggestedFieldNames) { + var message = 'Cannot query field "' + fieldName + '" on type "' + type + '".'; + if (suggestedTypeNames.length !== 0) { + var suggestions = (0, _quotedOrList2.default)(suggestedTypeNames); + message += ' Did you mean to use an inline fragment on ' + suggestions + '?'; + } else if (suggestedFieldNames.length !== 0) { + message += ' Did you mean ' + (0, _quotedOrList2.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. + */ + +/** + * 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 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 _error.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); + schema.getPossibleTypes(type).forEach(function (possibleType) { + if (!possibleType.getFields()[fieldName]) { + return; + } + // This object type defines this field. + suggestedObjectTypes.push(possibleType.name); + possibleType.getInterfaces().forEach(function (possibleInterface) { + if (!possibleInterface.getFields()[fieldName]) { + return; + } + // This interface type defines this field. + interfaceUsageCount[possibleInterface.name] = (interfaceUsageCount[possibleInterface.name] || 0) + 1; + }); + }); + + // Suggest interface types based on how common they are. + 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 (type instanceof _definition.GraphQLObjectType || type instanceof _definition.GraphQLInterfaceType) { + var possibleFieldNames = Object.keys(type.getFields()); + return (0, _suggestionList2.default)(fieldName, possibleFieldNames); + } + // Otherwise, must be a Union type, which does not define fields. + return []; +} +},{"../../error":85,"../../jsutils/quotedOrList":99,"../../jsutils/suggestionList":100,"../../type/definition":112}],141:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.inlineFragmentOnNonCompositeErrorMessage = inlineFragmentOnNonCompositeErrorMessage; +exports.fragmentOnNonCompositeErrorMessage = fragmentOnNonCompositeErrorMessage; +exports.FragmentsOnCompositeTypes = FragmentsOnCompositeTypes; + +var _error = require('../../error'); + +var _printer = require('../../language/printer'); + +var _definition = require('../../type/definition'); + +var _typeFromAST = require('../../utilities/typeFromAST'); + +function inlineFragmentOnNonCompositeErrorMessage(type) { + return 'Fragment cannot condition on non composite type "' + String(type) + '".'; +} +/** + * 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 fragmentOnNonCompositeErrorMessage(fragName, type) { + return 'Fragment "' + fragName + '" cannot condition on non composite ' + ('type "' + String(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) { + if (node.typeCondition) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition); + if (type && !(0, _definition.isCompositeType)(type)) { + context.reportError(new _error.GraphQLError(inlineFragmentOnNonCompositeErrorMessage((0, _printer.print)(node.typeCondition)), [node.typeCondition])); + } + } + }, + FragmentDefinition: function FragmentDefinition(node) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition); + if (type && !(0, _definition.isCompositeType)(type)) { + context.reportError(new _error.GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, (0, _printer.print)(node.typeCondition)), [node.typeCondition])); + } + } + }; +} +},{"../../error":85,"../../language/printer":106,"../../type/definition":112,"../../utilities/typeFromAST":135}],142:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownArgMessage = unknownArgMessage; +exports.unknownDirectiveArgMessage = unknownDirectiveArgMessage; +exports.KnownArgumentNames = KnownArgumentNames; + +var _error = require('../../error'); + +var _find = require('../../jsutils/find'); + +var _find2 = _interopRequireDefault(_find); + +var _invariant = require('../../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _suggestionList = require('../../jsutils/suggestionList'); + +var _suggestionList2 = _interopRequireDefault(_suggestionList); + +var _quotedOrList = require('../../jsutils/quotedOrList'); + +var _quotedOrList2 = _interopRequireDefault(_quotedOrList); + +var _kinds = require('../../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function unknownArgMessage(argName, fieldName, type, suggestedArgs) { + var message = 'Unknown argument "' + argName + '" on field "' + fieldName + '" of ' + ('type "' + String(type) + '".'); + if (suggestedArgs.length) { + message += ' Did you mean ' + (0, _quotedOrList2.default)(suggestedArgs) + '?'; + } + return message; +} +/** + * 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 unknownDirectiveArgMessage(argName, directiveName, suggestedArgs) { + var message = 'Unknown argument "' + argName + '" on directive "@' + directiveName + '".'; + if (suggestedArgs.length) { + message += ' Did you mean ' + (0, _quotedOrList2.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 { + Argument: function Argument(node, key, parent, path, ancestors) { + var argumentOf = ancestors[ancestors.length - 1]; + if (argumentOf.kind === Kind.FIELD) { + var fieldDef = context.getFieldDef(); + if (fieldDef) { + var fieldArgDef = (0, _find2.default)(fieldDef.args, function (arg) { + return arg.name === node.name.value; + }); + if (!fieldArgDef) { + var parentType = context.getParentType(); + (0, _invariant2.default)(parentType); + context.reportError(new _error.GraphQLError(unknownArgMessage(node.name.value, fieldDef.name, parentType.name, (0, _suggestionList2.default)(node.name.value, fieldDef.args.map(function (arg) { + return arg.name; + }))), [node])); + } + } + } else if (argumentOf.kind === Kind.DIRECTIVE) { + var directive = context.getDirective(); + if (directive) { + var directiveArgDef = (0, _find2.default)(directive.args, function (arg) { + return arg.name === node.name.value; + }); + if (!directiveArgDef) { + context.reportError(new _error.GraphQLError(unknownDirectiveArgMessage(node.name.value, directive.name, (0, _suggestionList2.default)(node.name.value, directive.args.map(function (arg) { + return arg.name; + }))), [node])); + } + } + } + } + }; +} +},{"../../error":85,"../../jsutils/find":93,"../../jsutils/invariant":94,"../../jsutils/quotedOrList":99,"../../jsutils/suggestionList":100,"../../language/kinds":102}],143:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownDirectiveMessage = unknownDirectiveMessage; +exports.misplacedDirectiveMessage = misplacedDirectiveMessage; +exports.KnownDirectives = KnownDirectives; + +var _error = require('../../error'); + +var _find = require('../../jsutils/find'); + +var _find2 = _interopRequireDefault(_find); + +var _kinds = require('../../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _directives = require('../../type/directives'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function unknownDirectiveMessage(directiveName) { + return 'Unknown directive "' + directiveName + '".'; +} +/** + * 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 misplacedDirectiveMessage(directiveName, location) { + return 'Directive "' + directiveName + '" may not be used on ' + location + '.'; +} + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ +function KnownDirectives(context) { + return { + Directive: function Directive(node, key, parent, path, ancestors) { + var directiveDef = (0, _find2.default)(context.getSchema().getDirectives(), function (def) { + return def.name === node.name.value; + }); + if (!directiveDef) { + context.reportError(new _error.GraphQLError(unknownDirectiveMessage(node.name.value), [node])); + return; + } + var candidateLocation = getDirectiveLocationForASTPath(ancestors); + if (!candidateLocation) { + context.reportError(new _error.GraphQLError(misplacedDirectiveMessage(node.name.value, node.type), [node])); + } else if (directiveDef.locations.indexOf(candidateLocation) === -1) { + context.reportError(new _error.GraphQLError(misplacedDirectiveMessage(node.name.value, candidateLocation), [node])); + } + } + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + var appliedTo = ancestors[ancestors.length - 1]; + switch (appliedTo.kind) { + case Kind.OPERATION_DEFINITION: + switch (appliedTo.operation) { + case 'query': + return _directives.DirectiveLocation.QUERY; + case 'mutation': + return _directives.DirectiveLocation.MUTATION; + case 'subscription': + return _directives.DirectiveLocation.SUBSCRIPTION; + } + break; + case Kind.FIELD: + return _directives.DirectiveLocation.FIELD; + case Kind.FRAGMENT_SPREAD: + return _directives.DirectiveLocation.FRAGMENT_SPREAD; + case Kind.INLINE_FRAGMENT: + return _directives.DirectiveLocation.INLINE_FRAGMENT; + case Kind.FRAGMENT_DEFINITION: + return _directives.DirectiveLocation.FRAGMENT_DEFINITION; + case Kind.SCHEMA_DEFINITION: + return _directives.DirectiveLocation.SCHEMA; + case Kind.SCALAR_TYPE_DEFINITION: + return _directives.DirectiveLocation.SCALAR; + case Kind.OBJECT_TYPE_DEFINITION: + return _directives.DirectiveLocation.OBJECT; + case Kind.FIELD_DEFINITION: + return _directives.DirectiveLocation.FIELD_DEFINITION; + case Kind.INTERFACE_TYPE_DEFINITION: + return _directives.DirectiveLocation.INTERFACE; + case Kind.UNION_TYPE_DEFINITION: + return _directives.DirectiveLocation.UNION; + case Kind.ENUM_TYPE_DEFINITION: + return _directives.DirectiveLocation.ENUM; + case Kind.ENUM_VALUE_DEFINITION: + return _directives.DirectiveLocation.ENUM_VALUE; + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + return _directives.DirectiveLocation.INPUT_OBJECT; + case Kind.INPUT_VALUE_DEFINITION: + var parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directives.DirectiveLocation.INPUT_FIELD_DEFINITION : _directives.DirectiveLocation.ARGUMENT_DEFINITION; + } +} +},{"../../error":85,"../../jsutils/find":93,"../../language/kinds":102,"../../type/directives":113}],144:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownFragmentMessage = unknownFragmentMessage; +exports.KnownFragmentNames = KnownFragmentNames; + +var _error = require('../../error'); + +/** + * 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 unknownFragmentMessage(fragName) { + return 'Unknown fragment "' + 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 _error.GraphQLError(unknownFragmentMessage(fragmentName), [node.name])); + } + } + }; +} +},{"../../error":85}],145:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownTypeMessage = unknownTypeMessage; +exports.KnownTypeNames = KnownTypeNames; + +var _error = require('../../error'); + +var _suggestionList = require('../../jsutils/suggestionList'); + +var _suggestionList2 = _interopRequireDefault(_suggestionList); + +var _quotedOrList = require('../../jsutils/quotedOrList'); + +var _quotedOrList2 = _interopRequireDefault(_quotedOrList); + +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. + */ + +function unknownTypeMessage(type, suggestedTypes) { + var message = 'Unknown type "' + String(type) + '".'; + if (suggestedTypes.length) { + message += ' Did you mean ' + (0, _quotedOrList2.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) { + return { + // TODO: when validating IDL, re-enable these. Experimental version does not + // add unreferenced types, resulting in false-positive errors. Squelched + // errors for now. + ObjectTypeDefinition: function ObjectTypeDefinition() { + return false; + }, + InterfaceTypeDefinition: function InterfaceTypeDefinition() { + return false; + }, + UnionTypeDefinition: function UnionTypeDefinition() { + return false; + }, + InputObjectTypeDefinition: function InputObjectTypeDefinition() { + return false; + }, + NamedType: function NamedType(node) { + var schema = context.getSchema(); + var typeName = node.name.value; + var type = schema.getType(typeName); + if (!type) { + context.reportError(new _error.GraphQLError(unknownTypeMessage(typeName, (0, _suggestionList2.default)(typeName, Object.keys(schema.getTypeMap()))), [node])); + } + } + }; +} +},{"../../error":85,"../../jsutils/quotedOrList":99,"../../jsutils/suggestionList":100}],146:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.anonOperationNotAloneMessage = anonOperationNotAloneMessage; +exports.LoneAnonymousOperation = LoneAnonymousOperation; + +var _error = require('../../error'); + +var _kinds = require('../../language/kinds'); + +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. + */ + +/** + * 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 LoneAnonymousOperation(context) { + var operationCount = 0; + return { + Document: function Document(node) { + operationCount = node.definitions.filter(function (definition) { + return definition.kind === _kinds.OPERATION_DEFINITION; + }).length; + }, + OperationDefinition: function OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new _error.GraphQLError(anonOperationNotAloneMessage(), [node])); + } + } + }; +} +},{"../../error":85,"../../language/kinds":102}],147:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.cycleErrorMessage = cycleErrorMessage; +exports.NoFragmentCycles = NoFragmentCycles; + +var _error = require('../../error'); + +/** + * 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 cycleErrorMessage(fragName, spreadNames) { + var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : ''; + return 'Cannot spread fragment "' + fragName + '" within itself' + 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) { + if (!visitedFrags[node.name.value]) { + 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) { + 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]; + + if (cycleIndex === undefined) { + spreadPath.push(spreadNode); + if (!visitedFrags[spreadName]) { + var spreadFragment = context.getFragment(spreadName); + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } + spreadPath.pop(); + } else { + var cyclePath = spreadPath.slice(cycleIndex); + context.reportError(new _error.GraphQLError(cycleErrorMessage(spreadName, cyclePath.map(function (s) { + return s.name.value; + })), cyclePath.concat(spreadNode))); + } + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} +},{"../../error":85}],148:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.undefinedVarMessage = undefinedVarMessage; +exports.NoUndefinedVariables = NoUndefinedVariables; + +var _error = require('../../error'); + +/** + * 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 undefinedVarMessage(varName, opName) { + return opName ? 'Variable "$' + varName + '" is not defined by operation "' + opName + '".' : 'Variable "$' + 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); + + usages.forEach(function (_ref) { + var node = _ref.node; + + var varName = node.name.value; + if (variableNameDefined[varName] !== true) { + context.reportError(new _error.GraphQLError(undefinedVarMessage(varName, operation.name && operation.name.value), [node, operation])); + } + }); + } + }, + VariableDefinition: function VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + } + }; +} +},{"../../error":85}],149:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unusedFragMessage = unusedFragMessage; +exports.NoUnusedFragments = NoUnusedFragments; + +var _error = require('../../error'); + +/** + * 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 unusedFragMessage(fragName) { + return 'Fragment "' + 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); + operationDefs.forEach(function (operation) { + context.getRecursivelyReferencedFragments(operation).forEach(function (fragment) { + fragmentNameUsed[fragment.name.value] = true; + }); + }); + + fragmentDefs.forEach(function (fragmentDef) { + var fragName = fragmentDef.name.value; + if (fragmentNameUsed[fragName] !== true) { + context.reportError(new _error.GraphQLError(unusedFragMessage(fragName), [fragmentDef])); + } + }); + } + } + }; +} +},{"../../error":85}],150:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unusedVariableMessage = unusedVariableMessage; +exports.NoUnusedVariables = NoUnusedVariables; + +var _error = require('../../error'); + +/** + * 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 unusedVariableMessage(varName, opName) { + return opName ? 'Variable "$' + varName + '" is never used in operation "' + opName + '".' : 'Variable "$' + 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; + + usages.forEach(function (_ref) { + var node = _ref.node; + + variableNameUsed[node.name.value] = true; + }); + + variableDefs.forEach(function (variableDef) { + var variableName = variableDef.variable.name.value; + if (variableNameUsed[variableName] !== true) { + context.reportError(new _error.GraphQLError(unusedVariableMessage(variableName, opName), [variableDef])); + } + }); + } + }, + VariableDefinition: function VariableDefinition(def) { + variableDefs.push(def); + } + }; +} +},{"../../error":85}],151:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fieldsConflictMessage = fieldsConflictMessage; +exports.OverlappingFieldsCanBeMerged = OverlappingFieldsCanBeMerged; + +var _error = require('../../error'); + +var _find = require('../../jsutils/find'); + +var _find2 = _interopRequireDefault(_find); + +var _kinds = require('../../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _printer = require('../../language/printer'); + +var _definition = require('../../type/definition'); + +var _typeFromAST = require('../../utilities/typeFromAST'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +/** + * 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 fieldsConflictMessage(responseName, reason) { + return 'Fields "' + responseName + '" conflict because ' + 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 "' + responseName + '" conflict because ' + 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 comparedFragments = 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, comparedFragments, context.getParentType(), selectionSet); + conflicts.forEach(function (_ref2) { + var _ref2$ = _ref2[0], + responseName = _ref2$[0], + reason = _ref2$[1], + fields1 = _ref2[1], + fields2 = _ref2[2]; + return context.reportError(new _error.GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2))); + }); + } + }; +} +// Field name and reason. + +// Reason is a string, or a nested list of conflicts. + +// Tuple defining a field node in a context. + +// Map of array of those. + + +/** + * 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, comparedFragments, 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, comparedFragments, fieldMap); + + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (var i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, 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, comparedFragments, 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, areMutuallyExclusive, fieldMap, fragmentName) { + var fragment = context.getFragment(fragmentName); + if (!fragment) { + return; + } + + var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment), + fieldMap2 = _getReferencedFieldsA[0], + fragmentNames2 = _getReferencedFieldsA[1]; + + // (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, comparedFragments, 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, areMutuallyExclusive, fieldMap, fragmentNames2[i]); + } +} + +// Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. +function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, areMutuallyExclusive, fragmentName1, fragmentName2) { + var fragment1 = context.getFragment(fragmentName1); + var fragment2 = context.getFragment(fragmentName2); + if (!fragment1 || !fragment2) { + return; + } + + // No need to compare a fragment to itself. + if (fragment1 === fragment2) { + return; + } + + // Memoize so two fragments are not compared for conflicts more than once. + if (comparedFragments.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { + return; + } + comparedFragments.add(fragmentName1, fragmentName2, areMutuallyExclusive); + + 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, comparedFragments, 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, comparedFragments, 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, comparedFragments, 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, comparedFragments, 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, comparedFragments, areMutuallyExclusive, fieldMap1, fieldMap2); + + // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, 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. + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, 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 _i = 0; _i < fragmentNames1.length; _i++) { + for (var _j = 0; _j < fragmentNames2.length; _j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, areMutuallyExclusive, fragmentNames1[_i], fragmentNames2[_j]); + } + } + return conflicts; +} + +// Collect all Conflicts "within" one collection of fields. +function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, 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. + Object.keys(fieldMap).forEach(function (responseName) { + var fields = fieldMap[responseName]; + // 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, comparedFragments, false, // within one collection is never mutually exclusive + responseName, fields[i], fields[j]); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + }); +} + +// 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, comparedFragments, 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. + Object.keys(fieldMap1).forEach(function (responseName) { + 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, comparedFragments, 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, comparedFragments, 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 && parentType1 instanceof _definition.GraphQLObjectType && parentType2 instanceof _definition.GraphQLObjectType; + + // 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, name1 + ' and ' + 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 ' + String(type1) + ' and ' + String(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, comparedFragments, 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, _find2.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 (type1 instanceof _definition.GraphQLList) { + return type2 instanceof _definition.GraphQLList ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + if (type2 instanceof _definition.GraphQLList) { + return type1 instanceof _definition.GraphQLList ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + if (type1 instanceof _definition.GraphQLNonNull) { + return type2 instanceof _definition.GraphQLNonNull ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + if (type2 instanceof _definition.GraphQLNonNull) { + return type1 instanceof _definition.GraphQLNonNull ? doTypesConflict(type1.ofType, type2.ofType) : 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 Kind.FIELD: + var fieldName = selection.name.value; + var fieldDef = void 0; + if (parentType instanceof _definition.GraphQLObjectType || parentType instanceof _definition.GraphQLInterfaceType) { + 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 Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + case 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 (_ref3) { + var reason = _ref3[0]; + return reason; + })], conflicts.reduce(function (allFields, _ref4) { + var fields1 = _ref4[1]; + return allFields.concat(fields1); + }, [node1]), conflicts.reduce(function (allFields, _ref5) { + var fields2 = _ref5[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 = function () { + function PairSet() { + _classCallCheck(this, PairSet); + + this._data = Object.create(null); + } + + PairSet.prototype.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; + }; + + PairSet.prototype.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":85,"../../jsutils/find":93,"../../language/kinds":102,"../../language/printer":106,"../../type/definition":112,"../../utilities/typeFromAST":135}],152:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.typeIncompatibleSpreadMessage = typeIncompatibleSpreadMessage; +exports.typeIncompatibleAnonSpreadMessage = typeIncompatibleAnonSpreadMessage; +exports.PossibleFragmentSpreads = PossibleFragmentSpreads; + +var _error = require('../../error'); + +var _typeComparators = require('../../utilities/typeComparators'); + +var _typeFromAST = require('../../utilities/typeFromAST'); + +/** + * 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 typeIncompatibleSpreadMessage(fragName, parentType, fragType) { + return 'Fragment "' + fragName + '" cannot be spread here as objects of ' + ('type "' + String(parentType) + '" can never be of type "' + String(fragType) + '".'); +} + +function typeIncompatibleAnonSpreadMessage(parentType, fragType) { + return 'Fragment cannot be spread here as objects of ' + ('type "' + String(parentType) + '" can never be of type "' + String(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 (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + context.reportError(new _error.GraphQLError(typeIncompatibleAnonSpreadMessage(parentType, 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 _error.GraphQLError(typeIncompatibleSpreadMessage(fragName, parentType, fragType), [node])); + } + } + }; +} + +function getFragmentType(context, name) { + var frag = context.getFragment(name); + return frag && (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition); +} +},{"../../error":85,"../../utilities/typeComparators":134,"../../utilities/typeFromAST":135}],153:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.missingFieldArgMessage = missingFieldArgMessage; +exports.missingDirectiveArgMessage = missingDirectiveArgMessage; +exports.ProvidedNonNullArguments = ProvidedNonNullArguments; + +var _error = require('../../error'); + +var _keyMap = require('../../jsutils/keyMap'); + +var _keyMap2 = _interopRequireDefault(_keyMap); + +var _definition = require('../../type/definition'); + +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. + */ + +function missingFieldArgMessage(fieldName, argName, type) { + return 'Field "' + fieldName + '" argument "' + argName + '" of type ' + ('"' + String(type) + '" is required but not provided.'); +} + +function missingDirectiveArgMessage(directiveName, argName, type) { + return 'Directive "@' + directiveName + '" argument "' + argName + '" of type ' + ('"' + String(type) + '" is required but not provided.'); +} + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null) field arguments + * have been provided. + */ +function ProvidedNonNullArguments(context) { + return { + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(node) { + var fieldDef = context.getFieldDef(); + if (!fieldDef) { + return false; + } + var argNodes = node.arguments || []; + + var argNodeMap = (0, _keyMap2.default)(argNodes, function (arg) { + return arg.name.value; + }); + fieldDef.args.forEach(function (argDef) { + var argNode = argNodeMap[argDef.name]; + if (!argNode && argDef.type instanceof _definition.GraphQLNonNull) { + context.reportError(new _error.GraphQLError(missingFieldArgMessage(node.name.value, argDef.name, argDef.type), [node])); + } + }); + } + }, + + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(node) { + var directiveDef = context.getDirective(); + if (!directiveDef) { + return false; + } + var argNodes = node.arguments || []; + + var argNodeMap = (0, _keyMap2.default)(argNodes, function (arg) { + return arg.name.value; + }); + directiveDef.args.forEach(function (argDef) { + var argNode = argNodeMap[argDef.name]; + if (!argNode && argDef.type instanceof _definition.GraphQLNonNull) { + context.reportError(new _error.GraphQLError(missingDirectiveArgMessage(node.name.value, argDef.name, argDef.type), [node])); + } + }); + } + } + }; +} +},{"../../error":85,"../../jsutils/keyMap":97,"../../type/definition":112}],154:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.noSubselectionAllowedMessage = noSubselectionAllowedMessage; +exports.requiredSubselectionMessage = requiredSubselectionMessage; +exports.ScalarLeafs = ScalarLeafs; + +var _error = require('../../error'); + +var _definition = require('../../type/definition'); + +function noSubselectionAllowedMessage(fieldName, type) { + return 'Field "' + fieldName + '" must not have a selection since ' + ('type "' + String(type) + '" has no subfields.'); +} +/** + * 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 requiredSubselectionMessage(fieldName, type) { + return 'Field "' + fieldName + '" of type "' + String(type) + '" must have a ' + ('selection of subfields. Did you mean "' + 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(); + if (type) { + if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { + if (node.selectionSet) { + context.reportError(new _error.GraphQLError(noSubselectionAllowedMessage(node.name.value, type), [node.selectionSet])); + } + } else if (!node.selectionSet) { + context.reportError(new _error.GraphQLError(requiredSubselectionMessage(node.name.value, type), [node])); + } + } + } + }; +} +},{"../../error":85,"../../type/definition":112}],155:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.singleFieldOnlyMessage = singleFieldOnlyMessage; +exports.SingleFieldSubscriptions = SingleFieldSubscriptions; + +var _error = require('../../error'); + +/** + * 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 singleFieldOnlyMessage(name) { + return (name ? 'Subscription "' + 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 _error.GraphQLError(singleFieldOnlyMessage(node.name && node.name.value), node.selectionSet.selections.slice(1))); + } + } + } + }; +} +},{"../../error":85}],156:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateArgMessage = duplicateArgMessage; +exports.UniqueArgumentNames = UniqueArgumentNames; + +var _error = require('../../error'); + +/** + * 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 duplicateArgMessage(argName) { + return 'There can be only one argument named "' + 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 _error.GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name])); + } else { + knownArgNames[argName] = node.name; + } + return false; + } + }; +} +},{"../../error":85}],157:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateDirectiveMessage = duplicateDirectiveMessage; +exports.UniqueDirectivesPerLocation = UniqueDirectivesPerLocation; + +var _error = require('../../error'); + +/** + * 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 duplicateDirectiveMessage(directiveName) { + return 'The directive "' + 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) { + if (node.directives) { + var knownDirectives = Object.create(null); + node.directives.forEach(function (directive) { + var directiveName = directive.name.value; + if (knownDirectives[directiveName]) { + context.reportError(new _error.GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], directive])); + } else { + knownDirectives[directiveName] = directive; + } + }); + } + } + }; +} +},{"../../error":85}],158:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateFragmentNameMessage = duplicateFragmentNameMessage; +exports.UniqueFragmentNames = UniqueFragmentNames; + +var _error = require('../../error'); + +/** + * 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 duplicateFragmentNameMessage(fragName) { + return 'There can be only one fragment named "' + 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 _error.GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name])); + } else { + knownFragmentNames[fragmentName] = node.name; + } + return false; + } + }; +} +},{"../../error":85}],159:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateInputFieldMessage = duplicateInputFieldMessage; +exports.UniqueInputFieldNames = UniqueInputFieldNames; + +var _error = require('../../error'); + +/** + * 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 duplicateInputFieldMessage(fieldName) { + return 'There can be only one input field named "' + 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 _error.GraphQLError(duplicateInputFieldMessage(fieldName), [knownNames[fieldName], node.name])); + } else { + knownNames[fieldName] = node.name; + } + return false; + } + }; +} +},{"../../error":85}],160:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateOperationNameMessage = duplicateOperationNameMessage; +exports.UniqueOperationNames = UniqueOperationNames; + +var _error = require('../../error'); + +/** + * 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 duplicateOperationNameMessage(operationName) { + return 'There can be only one operation named "' + 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 _error.GraphQLError(duplicateOperationNameMessage(operationName.value), [knownOperationNames[operationName.value], operationName])); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + return false; + }, + + FragmentDefinition: function FragmentDefinition() { + return false; + } + }; +} +},{"../../error":85}],161:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateVariableMessage = duplicateVariableMessage; +exports.UniqueVariableNames = UniqueVariableNames; + +var _error = require('../../error'); + +function duplicateVariableMessage(variableName) { + return 'There can be only one variable named "' + variableName + '".'; +} + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ + +/** + * 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 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 _error.GraphQLError(duplicateVariableMessage(variableName), [knownVariableNames[variableName], node.variable.name])); + } else { + knownVariableNames[variableName] = node.variable.name; + } + } + }; +} +},{"../../error":85}],162:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nonInputTypeOnVarMessage = nonInputTypeOnVarMessage; +exports.VariablesAreInputTypes = VariablesAreInputTypes; + +var _error = require('../../error'); + +var _printer = require('../../language/printer'); + +var _definition = require('../../type/definition'); + +var _typeFromAST = require('../../utilities/typeFromAST'); + +function nonInputTypeOnVarMessage(variableName, typeName) { + return 'Variable "$' + variableName + '" cannot be non-input type "' + 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). + */ + +/** + * 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 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 _error.GraphQLError(nonInputTypeOnVarMessage(variableName, (0, _printer.print)(node.type)), [node.type])); + } + } + }; +} +},{"../../error":85,"../../language/printer":106,"../../type/definition":112,"../../utilities/typeFromAST":135}],163:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.badVarPosMessage = badVarPosMessage; +exports.VariablesInAllowedPosition = VariablesInAllowedPosition; + +var _error = require('../../error'); + +var _definition = require('../../type/definition'); + +var _typeComparators = require('../../utilities/typeComparators'); + +var _typeFromAST = require('../../utilities/typeFromAST'); + +function badVarPosMessage(varName, varType, expectedType) { + return 'Variable "$' + varName + '" of type "' + String(varType) + '" used in ' + ('position expecting type "' + String(expectedType) + '".'); +} + +/** + * Variables passed to field arguments conform to type + */ + +/** + * 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 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); + + usages.forEach(function (_ref) { + var node = _ref.node, + type = _ref.type; + + 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 && !(0, _typeComparators.isTypeSubTypeOf)(schema, effectiveType(varType, varDef), type)) { + context.reportError(new _error.GraphQLError(badVarPosMessage(varName, varType, type), [varDef, node])); + } + } + }); + } + }, + VariableDefinition: function VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + } + }; +} + +// If a variable definition has a default value, it's effectively non-null. +function effectiveType(varType, varDef) { + return !varDef.defaultValue || varType instanceof _definition.GraphQLNonNull ? varType : new _definition.GraphQLNonNull(varType); +} +},{"../../error":85,"../../type/definition":112,"../../utilities/typeComparators":134,"../../utilities/typeFromAST":135}],164:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.specifiedRules = undefined; + +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 _ArgumentsOfCorrectType = require('./rules/ArgumentsOfCorrectType'); + +var _ProvidedNonNullArguments = require('./rules/ProvidedNonNullArguments'); + +var _DefaultValuesOfCorrectType = require('./rules/DefaultValuesOfCorrectType'); + +var _VariablesInAllowedPosition = require('./rules/VariablesInAllowedPosition'); + +var _OverlappingFieldsCanBeMerged = require('./rules/OverlappingFieldsCanBeMerged'); + +var _UniqueInputFieldNames = require('./rules/UniqueInputFieldNames'); + +/** + * 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. + */ + + +// Spec Section: "Field Selection Merging" + + +// Spec Section: "Variable Default Values Are Correctly Typed" + + +// Spec Section: "Argument Values Type Correctness" + + +// Spec Section: "Argument Names" + + +// Spec Section: "Directives Are Defined" + + +// Spec Section: "All Variable Used Defined" + + +// Spec Section: "Fragments must not form cycles" + + +// Spec Section: "Fragments must be used" + + +// Spec Section: "Fragment Name Uniqueness" + + +// Spec Section: "Leaf Field Selections" + + +// Spec Section: "Fragments on Composite Types" + + +// Spec Section: "Subscriptions with Single Root Field" + +/** + * 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. + */ + +// Spec Section: "Operation Name Uniqueness" +var specifiedRules = exports.specifiedRules = [_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, _ArgumentsOfCorrectType.ArgumentsOfCorrectType, _ProvidedNonNullArguments.ProvidedNonNullArguments, _DefaultValuesOfCorrectType.DefaultValuesOfCorrectType, _VariablesInAllowedPosition.VariablesInAllowedPosition, _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged, _UniqueInputFieldNames.UniqueInputFieldNames]; + +// Spec Section: "Input Object Field Uniqueness" + + +// Spec Section: "All Variable Usages Are Allowed" + + +// Spec Section: "Argument Optionality" + + +// Spec Section: "Argument Uniqueness" + + +// Spec Section: "Directives Are Unique Per Location" + + +// Spec Section: "All Variables Used" + + +// Spec Section: "Variable Uniqueness" + + +// Spec Section: "Fragment spread is possible" + + +// Spec Section: "Fragment spread target defined" + + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + + +// Spec Section: "Variables are Input Types" + + +// Spec Section: "Fragment Spread Type Existence" + + +// Spec Section: "Lone Anonymous Operation" +},{"./rules/ArgumentsOfCorrectType":138,"./rules/DefaultValuesOfCorrectType":139,"./rules/FieldsOnCorrectType":140,"./rules/FragmentsOnCompositeTypes":141,"./rules/KnownArgumentNames":142,"./rules/KnownDirectives":143,"./rules/KnownFragmentNames":144,"./rules/KnownTypeNames":145,"./rules/LoneAnonymousOperation":146,"./rules/NoFragmentCycles":147,"./rules/NoUndefinedVariables":148,"./rules/NoUnusedFragments":149,"./rules/NoUnusedVariables":150,"./rules/OverlappingFieldsCanBeMerged":151,"./rules/PossibleFragmentSpreads":152,"./rules/ProvidedNonNullArguments":153,"./rules/ScalarLeafs":154,"./rules/SingleFieldSubscriptions":155,"./rules/UniqueArgumentNames":156,"./rules/UniqueDirectivesPerLocation":157,"./rules/UniqueFragmentNames":158,"./rules/UniqueInputFieldNames":159,"./rules/UniqueOperationNames":160,"./rules/UniqueVariableNames":161,"./rules/VariablesAreInputTypes":162,"./rules/VariablesInAllowedPosition":163}],165:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ValidationContext = undefined; +exports.validate = validate; + +var _invariant = require('../jsutils/invariant'); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _error = require('../error'); + +var _visitor = require('../language/visitor'); + +var _kinds = require('../language/kinds'); + +var Kind = _interopRequireWildcard(_kinds); + +var _schema = require('../type/schema'); + +var _TypeInfo = require('../utilities/TypeInfo'); + +var _specifiedRules = require('./specifiedRules'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +/** + * 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. + */ + +/** + * 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, ast, rules, typeInfo) { + (0, _invariant2.default)(schema, 'Must provide schema'); + (0, _invariant2.default)(ast, 'Must provide document'); + (0, _invariant2.default)(schema instanceof _schema.GraphQLSchema, 'Schema must be an instance of GraphQLSchema. Also ensure that there are ' + 'not multiple versions of GraphQL installed in your node_modules directory.'); + return visitUsingRules(schema, typeInfo || new _TypeInfo.TypeInfo(schema), ast, rules || _specifiedRules.specifiedRules); +} + +/** + * This uses a specialized visitor which runs multiple visitors in parallel, + * while maintaining the visitor skip and break API. + * + * @internal + */ +function visitUsingRules(schema, typeInfo, documentAST, rules) { + var context = new ValidationContext(schema, documentAST, typeInfo); + var visitors = 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, (0, _visitor.visitInParallel)(visitors))); + return context.getErrors(); +} + +/** + * 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 ValidationContext = exports.ValidationContext = function () { + function ValidationContext(schema, ast, typeInfo) { + _classCallCheck(this, ValidationContext); + + this._schema = schema; + this._ast = ast; + this._typeInfo = typeInfo; + this._errors = []; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } + + ValidationContext.prototype.reportError = function reportError(error) { + this._errors.push(error); + }; + + ValidationContext.prototype.getErrors = function getErrors() { + return this._errors; + }; + + ValidationContext.prototype.getSchema = function getSchema() { + return this._schema; + }; + + ValidationContext.prototype.getDocument = function getDocument() { + return this._ast; + }; + + ValidationContext.prototype.getFragment = function getFragment(name) { + var fragments = this._fragments; + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) { + if (statement.kind === Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + return frags; + }, Object.create(null)); + } + return fragments[name]; + }; + + ValidationContext.prototype.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 === Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + this._fragmentSpreads.set(node, spreads); + } + return spreads; + }; + + ValidationContext.prototype.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; + }; + + ValidationContext.prototype.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() }); + } + })); + usages = newUsages; + this._variableUsages.set(node, usages); + } + return usages; + }; + + ValidationContext.prototype.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; + }; + + ValidationContext.prototype.getType = function getType() { + return this._typeInfo.getType(); + }; + + ValidationContext.prototype.getParentType = function getParentType() { + return this._typeInfo.getParentType(); + }; + + ValidationContext.prototype.getInputType = function getInputType() { + return this._typeInfo.getInputType(); + }; + + ValidationContext.prototype.getFieldDef = function getFieldDef() { + return this._typeInfo.getFieldDef(); + }; + + ValidationContext.prototype.getDirective = function getDirective() { + return this._typeInfo.getDirective(); + }; + + ValidationContext.prototype.getArgument = function getArgument() { + return this._typeInfo.getArgument(); + }; + + return ValidationContext; +}(); +},{"../error":85,"../jsutils/invariant":94,"../language/kinds":102,"../language/visitor":108,"../type/schema":117,"../utilities/TypeInfo":118,"./specifiedRules":164}],166:[function(require,module,exports){ +/** + * Copyright (c) 2016, Lee Byron + * All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @ignore + */ + +/** + * [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator) + * is a *protocol* which describes a standard way to produce a sequence of + * values, typically the values of the Iterable represented by this Iterator. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface) + * it can be utilized by any version of JavaScript. + * + * @typedef {Object} Iterator + * @template T The type of each iterated value + * @property {function (): { value: T, done: boolean }} next + * A method which produces either the next value in a sequence or a result + * where the `done` property is `true` indicating the end of the Iterator. + */ + +/** + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable) + * is a *protocol* which when implemented allows a JavaScript object to define + * their iteration behavior, such as what values are looped over in a `for..of` + * loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables) + * implement the Iterable protocol, including `Array` and `Map`. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface) + * it can be utilized by any version of JavaScript. + * + * @typedef {Object} Iterable + * @template T The type of each iterated value + * @property {function (): Iterator} Symbol.iterator + * A method which produces an Iterator for this Iterable. + */ + +// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator +var SYMBOL_ITERATOR = typeof Symbol === 'function' && Symbol.iterator + +/** + * A property name to be used as the name of an Iterable's method responsible + * for producing an Iterator, referred to as `@@iterator`. Typically represents + * the value `Symbol.iterator` but falls back to the string `"@@iterator"` when + * `Symbol.iterator` is not defined. + * + * Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`, + * but do not use it for accessing existing Iterables, instead use + * `getIterator()` or `isIterable()`. + * + * @example + * + * var $$iterator = require('iterall').$$iterator + * + * function Counter (to) { + * this.to = to + * } + * + * Counter.prototype[$$iterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * if (this.num >= this.to) { + * return { value: undefined, done: true } + * } + * return { value: this.num++, done: false } + * } + * } + * } + * + * var counter = new Counter(3) + * for (var number of counter) { + * console.log(number) // 0 ... 1 ... 2 + * } + * + * @type {Symbol|string} + */ +var $$iterator = SYMBOL_ITERATOR || '@@iterator' +exports.$$iterator = $$iterator + +/** + * Returns true if the provided object implements the Iterator protocol via + * either implementing a `Symbol.iterator` or `"@@iterator"` method. + * + * @example + * + * var isIterable = require('iterall').isIterable + * isIterable([ 1, 2, 3 ]) // true + * isIterable('ABC') // true + * isIterable({ length: 1, 0: 'Alpha' }) // false + * isIterable({ key: 'value' }) // false + * isIterable(new Map()) // true + * + * @param obj + * A value which might implement the Iterable protocol. + * @return {boolean} true if Iterable. + */ +function isIterable(obj) { + return !!getIteratorMethod(obj) +} +exports.isIterable = isIterable + +/** + * Returns true if the provided object implements the Array-like protocol via + * defining a positive-integer `length` property. + * + * @example + * + * var isArrayLike = require('iterall').isArrayLike + * isArrayLike([ 1, 2, 3 ]) // true + * isArrayLike('ABC') // true + * isArrayLike({ length: 1, 0: 'Alpha' }) // true + * isArrayLike({ key: 'value' }) // false + * isArrayLike(new Map()) // false + * + * @param obj + * A value which might implement the Array-like protocol. + * @return {boolean} true if Array-like. + */ +function isArrayLike(obj) { + var length = obj != null && obj.length + return typeof length === 'number' && length >= 0 && length % 1 === 0 +} +exports.isArrayLike = isArrayLike + +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and is either Iterable or Array-like. + * + * This may be used in place of [Array.isArray()][isArray] to determine if an + * object should be iterated-over. It always excludes string literals and + * includes Arrays (regardless of if it is Iterable). It also includes other + * Array-like objects such as NodeList, TypedArray, and Buffer. + * + * @example + * + * var isCollection = require('iterall').isCollection + * isCollection([ 1, 2, 3 ]) // true + * isCollection('ABC') // false + * isCollection({ length: 1, 0: 'Alpha' }) // true + * isCollection({ key: 'value' }) // false + * isCollection(new Map()) // true + * + * @example + * + * var forEach = require('iterall').forEach + * if (isCollection(obj)) { + * forEach(obj, function (value) { + * console.log(value) + * }) + * } + * + * @param obj + * An Object value which might implement the Iterable or Array-like protocols. + * @return {boolean} true if Iterable or Array-like Object. + */ +function isCollection(obj) { + return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj)) +} +exports.isCollection = isCollection + +/** + * If the provided object implements the Iterator protocol, its Iterator object + * is returned. Otherwise returns undefined. + * + * @example + * + * var getIterator = require('iterall').getIterator + * var iterator = getIterator([ 1, 2, 3 ]) + * iterator.next() // { value: 1, done: false } + * iterator.next() // { value: 2, done: false } + * iterator.next() // { value: 3, done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which is the source of an Iterator. + * @return {Iterator} new Iterator instance. + */ +function getIterator(iterable) { + var method = getIteratorMethod(iterable) + if (method) { + return method.call(iterable) + } +} +exports.getIterator = getIterator + +/** + * If the provided object implements the Iterator protocol, the method + * responsible for producing its Iterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getIteratorMethod = require('iterall').getIteratorMethod + * var myArray = [ 1, 2, 3 ] + * var method = getIteratorMethod(myArray) + * if (method) { + * var iterator = method.call(myArray) + * } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which defines an `@@iterator` method. + * @return {function(): Iterator} `@@iterator` method. + */ +function getIteratorMethod(iterable) { + if (iterable != null) { + var method = + (SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR]) || iterable['@@iterator'] + if (typeof method === 'function') { + return method + } + } +} +exports.getIteratorMethod = getIteratorMethod + +/** + * Similar to `getIterator()`, this method returns a new Iterator given an + * Iterable. However it will also create an Iterator for a non-Iterable + * Array-like collection, such as Array in a non-ES2015 environment. + * + * `createIterator` is complimentary to `forEach`, but allows a "pull"-based + * iteration as opposed to `forEach`'s "push"-based iteration. + * + * `createIterator` produces an Iterator for Array-likes with the same behavior + * as ArrayIteratorPrototype described in the ECMAScript specification, and + * does *not* skip over "holes". + * + * @example + * + * var createIterator = require('iterall').createIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createIterator(myArraylike) + * iterator.next() // { value: 'Alpha', done: false } + * iterator.next() // { value: 'Bravo', done: false } + * iterator.next() // { value: 'Charlie', done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * An Iterable or Array-like object to produce an Iterator. + * @return {Iterator} new Iterator instance. + */ +function createIterator(collection) { + if (collection != null) { + var iterator = getIterator(collection) + if (iterator) { + return iterator + } + if (isArrayLike(collection)) { + return new ArrayLikeIterator(collection) + } + } +} +exports.createIterator = createIterator + +// When the object provided to `createIterator` is not Iterable but is +// Array-like, this simple Iterator is created. +function ArrayLikeIterator(obj) { + this._o = obj + this._i = 0 +} + +// Note: all Iterators are themselves Iterable. +ArrayLikeIterator.prototype[$$iterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +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 } +} + +/** + * Given an object which either implements the Iterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forEach` where you would expect to use a `for ... of` loop in ES6. + * However `forEach` adheres to the behavior of [Array#forEach][] described in + * the ECMAScript specification, skipping over "holes" in Array-likes. It will + * also delegate to a `forEach` method on `collection` if one is defined, + * ensuring native performance for `Arrays`. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * Note: providing an infinite Iterator to forEach will produce an error. + * + * [Array#forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach + * + * @example + * + * var forEach = require('iterall').forEach + * + * forEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES6: + * for (let value of myIterable) { + * console.log(value) + * } + * + * // Any JavaScript environment: + * forEach(myIterable, function (value) { + * console.log(value) + * }) + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * The Iterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +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) + // Infinite Iterators could cause forEach to run forever. + // After a very large number of iterations, produce an error. + /* istanbul ignore if */ + 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) + } + } + } + } +} +exports.forEach = forEach + +///////////////////////////////////////////////////// +// // +// ASYNC ITERATORS // +// // +///////////////////////////////////////////////////// + +/** + * [AsyncIterator](https://tc39.github.io/proposal-async-iteration/) + * is a *protocol* which describes a standard way to produce and consume an + * asynchronous sequence of values, typically the values of the AsyncIterable + * represented by this AsyncIterator. + * + * AsyncIterator is similar to Observable or Stream. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @typedef {Object} AsyncIterator + * @template T The type of each iterated value + * @property {function (): Promise<{ value: T, done: boolean }>} next + * A method which produces a Promise which resolves to either the next value + * in a sequence or a result where the `done` property is `true` indicating + * the end of the sequence of values. It may also produce a Promise which + * becomes rejected, indicating a failure. + */ + +/** + * AsyncIterable is a *protocol* which when implemented allows a JavaScript + * object to define their asynchronous iteration behavior, such as what values + * are looped over in a `for-await-of` loop or `iterall`'s `forAwaitEach` + * function. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @typedef {Object} AsyncIterable + * @template T The type of each iterated value + * @property {function (): AsyncIterator} Symbol.asyncIterator + * A method which produces an AsyncIterator for this AsyncIterable. + */ + +// In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator +var SYMBOL_ASYNC_ITERATOR = typeof Symbol === 'function' && Symbol.asyncIterator + +/** + * A property name to be used as the name of an AsyncIterable's method + * responsible for producing an Iterator, referred to as `@@asyncIterator`. + * Typically represents the value `Symbol.asyncIterator` but falls back to the + * string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined. + * + * Use `$$asyncIterator` for defining new AsyncIterables instead of + * `Symbol.asyncIterator`, but do not use it for accessing existing Iterables, + * instead use `getAsyncIterator()` or `isAsyncIterable()`. + * + * @example + * + * var $$asyncIterator = require('iterall').$$asyncIterator + * + * function Chirper (to) { + * this.to = to + * } + * + * Chirper.prototype[$$asyncIterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * return new Promise(function (resolve) { + * if (this.num >= this.to) { + * resolve({ value: undefined, done: true }) + * } else { + * setTimeout(function () { + * resolve({ value: this.num++, done: false }) + * }, 1000) + * } + * } + * } + * } + * } + * + * var chirper = new Chirper(3) + * for await (var number of chirper) { + * console.log(number) // 0 ...wait... 1 ...wait... 2 + * } + * + * @type {Symbol|string} + */ +var $$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator' +exports.$$asyncIterator = $$asyncIterator + +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method. + * + * @example + * + * var isAsyncIterable = require('iterall').isAsyncIterable + * isAsyncIterable(myStream) // true + * isAsyncIterable('ABC') // false + * + * @param obj + * A value which might implement the AsyncIterable protocol. + * @return {boolean} true if AsyncIterable. + */ +function isAsyncIterable(obj) { + return !!getAsyncIteratorMethod(obj) +} +exports.isAsyncIterable = isAsyncIterable + +/** + * If the provided object implements the AsyncIterator protocol, its + * AsyncIterator object is returned. Otherwise returns undefined. + * + * @example + * + * var getAsyncIterator = require('iterall').getAsyncIterator + * var asyncIterator = getAsyncIterator(myStream) + * asyncIterator.next().then(console.log) // { value: 1, done: false } + * asyncIterator.next().then(console.log) // { value: 2, done: false } + * asyncIterator.next().then(console.log) // { value: 3, done: false } + * asyncIterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which is the source of an AsyncIterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +function getAsyncIterator(asyncIterable) { + var method = getAsyncIteratorMethod(asyncIterable) + if (method) { + return method.call(asyncIterable) + } +} +exports.getAsyncIterator = getAsyncIterator + +/** + * If the provided object implements the AsyncIterator protocol, the method + * responsible for producing its AsyncIterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod + * var method = getAsyncIteratorMethod(myStream) + * if (method) { + * var asyncIterator = method.call(myStream) + * } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which defines an `@@asyncIterator` method. + * @return {function(): AsyncIterator} `@@asyncIterator` method. + */ +function getAsyncIteratorMethod(asyncIterable) { + if (asyncIterable != null) { + var method = + (SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR]) || + asyncIterable['@@asyncIterator'] + if (typeof method === 'function') { + return method + } + } +} +exports.getAsyncIteratorMethod = getAsyncIteratorMethod + +/** + * Similar to `getAsyncIterator()`, this method returns a new AsyncIterator + * given an AsyncIterable. However it will also create an AsyncIterator for a + * non-async Iterable as well as non-Iterable Array-like collection, such as + * Array in a pre-ES2015 environment. + * + * `createAsyncIterator` is complimentary to `forAwaitEach`, but allows a + * buffering "pull"-based iteration as opposed to `forAwaitEach`'s + * "push"-based iteration. + * + * `createAsyncIterator` produces an AsyncIterator for non-async Iterables as + * described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects). + * + * > Note: Creating `AsyncIterator`s requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var createAsyncIterator = require('iterall').createAsyncIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createAsyncIterator(myArraylike) + * iterator.next().then(console.log) // { value: 'Alpha', done: false } + * iterator.next().then(console.log) // { value: 'Bravo', done: false } + * iterator.next().then(console.log) // { value: 'Charlie', done: false } + * iterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable|{ length: number }} source + * An AsyncIterable, Iterable, or Array-like object to produce an Iterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +function createAsyncIterator(source) { + if (source != null) { + var asyncIterator = getAsyncIterator(source) + if (asyncIterator) { + return asyncIterator + } + var iterator = createIterator(source) + if (iterator) { + return new AsyncFromSyncIterator(iterator) + } + } +} +exports.createAsyncIterator = createAsyncIterator + +// When the object provided to `createAsyncIterator` is not AsyncIterable but is +// sync Iterable, this simple wrapper is created. +function AsyncFromSyncIterator(iterator) { + this._i = iterator +} + +// Note: all AsyncIterators are themselves AsyncIterable. +AsyncFromSyncIterator.prototype[$$asyncIterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +AsyncFromSyncIterator.prototype.next = function() { + var step = this._i.next() + return Promise.resolve(step.value).then(function(value) { + return { value: value, done: step.done } + }) +} + +/** + * Given an object which either implements the AsyncIterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forAwaitEach` where you would expect to use a `for-await-of` loop. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * > Note: Using `forAwaitEach` requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var forAwaitEach = require('iterall').forAwaitEach + * + * forAwaitEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES2017: + * for await (let value of myAsyncIterable) { + * console.log(await doSomethingAsync(value)) + * } + * console.log('done') + * + * // Any JavaScript environment: + * forAwaitEach(myAsyncIterable, function (value) { + * return doSomethingAsync(value).then(console.log) + * }).then(function () { + * console.log('done') + * }) + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable | T>|{ length: number }} source + * The AsyncIterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +function forAwaitEach(source, callback, thisArg) { + var asyncIterator = createAsyncIterator(source) + if (asyncIterator) { + var i = 0 + function next() { + return asyncIterator.next().then(function(step) { + if (!step.done) { + return Promise.resolve( + callback.call(thisArg, step.value, i++, source) + ).then(next) + } + }) + } + return next() + } +} +exports.forAwaitEach = forAwaitEach + +},{}],167:[function(require,module,exports){ +(function (global){ +/** + * marked - a markdown parser + * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) + * https://github.com/chjj/marked + */ + +;(function() { + +/** + * Block-Level Grammar + */ + +var block = { + newline: /^\n+/, + code: /^( {4}[^\n]+\n*)+/, + fences: noop, + hr: /^( *[-*_]){3,} *(?:\n+|$)/, + heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, + nptable: noop, + lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, + blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, + list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, + html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/, + def: /^ *\[([^\]]+)\]: *]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, + table: noop, + paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, + text: /^[^\n]+/ +}; + +block.bullet = /(?:[*+-]|\d+\.)/; +block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; +block.item = replace(block.item, 'gm') + (/bull/g, block.bullet) + (); + +block.list = replace(block.list) + (/bull/g, block.bullet) + ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))') + ('def', '\\n+(?=' + block.def.source + ')') + (); + +block.blockquote = replace(block.blockquote) + ('def', block.def) + (); + +block._tag = '(?!(?:' + + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' + + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' + + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b'; + +block.html = replace(block.html) + ('comment', //) + ('closed', /<(tag)[\s\S]+?<\/\1>/) + ('closing', /])*?>/) + (/tag/g, block._tag) + (); + +block.paragraph = replace(block.paragraph) + ('hr', block.hr) + ('heading', block.heading) + ('lheading', block.lheading) + ('blockquote', block.blockquote) + ('tag', '<' + block._tag) + ('def', block.def) + (); + +/** + * Normal Block Grammar + */ + +block.normal = merge({}, block); + +/** + * GFM Block Grammar + */ + +block.gfm = merge({}, block.normal, { + fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/, + paragraph: /^/, + heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/ +}); + +block.gfm.paragraph = replace(block.paragraph) + ('(?!', '(?!' + + block.gfm.fences.source.replace('\\1', '\\2') + '|' + + block.list.source.replace('\\1', '\\3') + '|') + (); + +/** + * GFM + Tables Block Grammar + */ + +block.tables = merge({}, block.gfm, { + nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, + table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ +}); + +/** + * Block Lexer + */ + +function Lexer(options) { + this.tokens = []; + this.tokens.links = {}; + this.options = options || marked.defaults; + this.rules = block.normal; + + if (this.options.gfm) { + if (this.options.tables) { + this.rules = block.tables; + } else { + this.rules = block.gfm; + } + } +} + +/** + * Expose Block Rules + */ + +Lexer.rules = block; + +/** + * Static Lex Method + */ + +Lexer.lex = function(src, options) { + var lexer = new Lexer(options); + return lexer.lex(src); +}; + +/** + * Preprocessing + */ + +Lexer.prototype.lex = function(src) { + src = src + .replace(/\r\n|\r/g, '\n') + .replace(/\t/g, ' ') + .replace(/\u00a0/g, ' ') + .replace(/\u2424/g, '\n'); + + return this.token(src, true); +}; + +/** + * Lexing + */ + +Lexer.prototype.token = function(src, top, bq) { + var src = src.replace(/^ +$/gm, '') + , next + , loose + , cap + , bull + , b + , item + , space + , i + , l; + + while (src) { + // newline + if (cap = this.rules.newline.exec(src)) { + src = src.substring(cap[0].length); + if (cap[0].length > 1) { + this.tokens.push({ + type: 'space' + }); + } + } + + // code + if (cap = this.rules.code.exec(src)) { + src = src.substring(cap[0].length); + cap = cap[0].replace(/^ {4}/gm, ''); + this.tokens.push({ + type: 'code', + text: !this.options.pedantic + ? cap.replace(/\n+$/, '') + : cap + }); + continue; + } + + // fences (gfm) + if (cap = this.rules.fences.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'code', + lang: cap[2], + text: cap[3] || '' + }); + continue; + } + + // heading + if (cap = this.rules.heading.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'heading', + depth: cap[1].length, + text: cap[2] + }); + continue; + } + + // table no leading pipe (gfm) + if (top && (cap = this.rules.nptable.exec(src))) { + src = src.substring(cap[0].length); + + item = { + type: 'table', + header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3].replace(/\n$/, '').split('\n') + }; + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right'; + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center'; + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left'; + } else { + item.align[i] = null; + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = item.cells[i].split(/ *\| */); + } + + this.tokens.push(item); + + continue; + } + + // lheading + if (cap = this.rules.lheading.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'heading', + depth: cap[2] === '=' ? 1 : 2, + text: cap[1] + }); + continue; + } + + // hr + if (cap = this.rules.hr.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'hr' + }); + continue; + } + + // blockquote + if (cap = this.rules.blockquote.exec(src)) { + src = src.substring(cap[0].length); + + this.tokens.push({ + type: 'blockquote_start' + }); + + cap = cap[0].replace(/^ *> ?/gm, ''); + + // Pass `top` to keep the current + // "toplevel" state. This is exactly + // how markdown.pl works. + this.token(cap, top, true); + + this.tokens.push({ + type: 'blockquote_end' + }); + + continue; + } + + // list + if (cap = this.rules.list.exec(src)) { + src = src.substring(cap[0].length); + bull = cap[2]; + + this.tokens.push({ + type: 'list_start', + ordered: bull.length > 1 + }); + + // Get each top-level item. + cap = cap[0].match(this.rules.item); + + next = false; + l = cap.length; + i = 0; + + for (; i < l; i++) { + item = cap[i]; + + // Remove the list item's bullet + // so it is seen as the next token. + space = item.length; + item = item.replace(/^ *([*+-]|\d+\.) +/, ''); + + // Outdent whatever the + // list item contains. Hacky. + if (~item.indexOf('\n ')) { + space -= item.length; + item = !this.options.pedantic + ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') + : item.replace(/^ {1,4}/gm, ''); + } + + // Determine whether the next list item belongs here. + // Backpedal if it does not belong in this list. + if (this.options.smartLists && i !== l - 1) { + b = block.bullet.exec(cap[i + 1])[0]; + if (bull !== b && !(bull.length > 1 && b.length > 1)) { + src = cap.slice(i + 1).join('\n') + src; + i = l - 1; + } + } + + // Determine whether item is loose or not. + // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ + // for discount behavior. + loose = next || /\n\n(?!\s*$)/.test(item); + if (i !== l - 1) { + next = item.charAt(item.length - 1) === '\n'; + if (!loose) loose = next; + } + + this.tokens.push({ + type: loose + ? 'loose_item_start' + : 'list_item_start' + }); + + // Recurse. + this.token(item, false, bq); + + this.tokens.push({ + type: 'list_item_end' + }); + } + + this.tokens.push({ + type: 'list_end' + }); + + continue; + } + + // html + if (cap = this.rules.html.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: this.options.sanitize + ? 'paragraph' + : 'html', + pre: !this.options.sanitizer + && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), + text: cap[0] + }); + continue; + } + + // def + if ((!bq && top) && (cap = this.rules.def.exec(src))) { + src = src.substring(cap[0].length); + this.tokens.links[cap[1].toLowerCase()] = { + href: cap[2], + title: cap[3] + }; + continue; + } + + // table (gfm) + if (top && (cap = this.rules.table.exec(src))) { + src = src.substring(cap[0].length); + + item = { + type: 'table', + header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') + }; + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right'; + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center'; + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left'; + } else { + item.align[i] = null; + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = item.cells[i] + .replace(/^ *\| *| *\| *$/g, '') + .split(/ *\| */); + } + + this.tokens.push(item); + + continue; + } + + // top-level paragraph + if (top && (cap = this.rules.paragraph.exec(src))) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'paragraph', + text: cap[1].charAt(cap[1].length - 1) === '\n' + ? cap[1].slice(0, -1) + : cap[1] + }); + continue; + } + + // text + if (cap = this.rules.text.exec(src)) { + // Top-level should never reach here. + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'text', + text: cap[0] + }); + continue; + } + + if (src) { + throw new + Error('Infinite loop on byte: ' + src.charCodeAt(0)); + } + } + + return this.tokens; +}; + +/** + * Inline-Level Grammar + */ + +var inline = { + escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, + autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, + url: noop, + tag: /^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, + link: /^!?\[(inside)\]\(href\)/, + reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, + nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, + strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, + em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, + code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, + br: /^ {2,}\n(?!\s*$)/, + del: noop, + text: /^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/; + +inline.link = replace(inline.link) + ('inside', inline._inside) + ('href', inline._href) + (); + +inline.reflink = replace(inline.reflink) + ('inside', inline._inside) + (); + +/** + * Normal Inline Grammar + */ + +inline.normal = merge({}, inline); + +/** + * Pedantic Inline Grammar + */ + +inline.pedantic = merge({}, inline.normal, { + strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, + em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ +}); + +/** + * GFM Inline Grammar + */ + +inline.gfm = merge({}, inline.normal, { + escape: replace(inline.escape)('])', '~|])')(), + url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, + del: /^~~(?=\S)([\s\S]*?\S)~~/, + text: replace(inline.text) + (']|', '~]|') + ('|', '|https?://|') + () +}); + +/** + * GFM + Line Breaks Inline Grammar + */ + +inline.breaks = merge({}, inline.gfm, { + br: replace(inline.br)('{2,}', '*')(), + text: replace(inline.gfm.text)('{2,}', '*')() +}); + +/** + * Inline Lexer & Compiler + */ + +function InlineLexer(links, options) { + this.options = options || marked.defaults; + this.links = links; + this.rules = inline.normal; + this.renderer = this.options.renderer || new Renderer; + this.renderer.options = this.options; + + if (!this.links) { + throw new + Error('Tokens array requires a `links` property.'); + } + + if (this.options.gfm) { + if (this.options.breaks) { + this.rules = inline.breaks; + } else { + this.rules = inline.gfm; + } + } else if (this.options.pedantic) { + this.rules = inline.pedantic; + } +} + +/** + * Expose Inline Rules + */ + +InlineLexer.rules = inline; + +/** + * Static Lexing/Compiling Method + */ + +InlineLexer.output = function(src, links, options) { + var inline = new InlineLexer(links, options); + return inline.output(src); +}; + +/** + * Lexing/Compiling + */ + +InlineLexer.prototype.output = function(src) { + var out = '' + , link + , text + , href + , cap; + + while (src) { + // escape + if (cap = this.rules.escape.exec(src)) { + src = src.substring(cap[0].length); + out += cap[1]; + continue; + } + + // autolink + if (cap = this.rules.autolink.exec(src)) { + src = src.substring(cap[0].length); + if (cap[2] === '@') { + text = cap[1].charAt(6) === ':' + ? this.mangle(cap[1].substring(7)) + : this.mangle(cap[1]); + href = this.mangle('mailto:') + text; + } else { + text = escape(cap[1]); + href = text; + } + out += this.renderer.link(href, null, text); + continue; + } + + // url (gfm) + if (!this.inLink && (cap = this.rules.url.exec(src))) { + src = src.substring(cap[0].length); + text = escape(cap[1]); + href = text; + out += this.renderer.link(href, null, text); + continue; + } + + // tag + if (cap = this.rules.tag.exec(src)) { + if (!this.inLink && /^/i.test(cap[0])) { + this.inLink = false; + } + src = src.substring(cap[0].length); + out += this.options.sanitize + ? this.options.sanitizer + ? this.options.sanitizer(cap[0]) + : escape(cap[0]) + : cap[0] + continue; + } + + // link + if (cap = this.rules.link.exec(src)) { + src = src.substring(cap[0].length); + this.inLink = true; + out += this.outputLink(cap, { + href: cap[2], + title: cap[3] + }); + this.inLink = false; + continue; + } + + // reflink, nolink + if ((cap = this.rules.reflink.exec(src)) + || (cap = this.rules.nolink.exec(src))) { + src = src.substring(cap[0].length); + link = (cap[2] || cap[1]).replace(/\s+/g, ' '); + link = this.links[link.toLowerCase()]; + if (!link || !link.href) { + out += cap[0].charAt(0); + src = cap[0].substring(1) + src; + continue; + } + this.inLink = true; + out += this.outputLink(cap, link); + this.inLink = false; + continue; + } + + // strong + if (cap = this.rules.strong.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.strong(this.output(cap[2] || cap[1])); + continue; + } + + // em + if (cap = this.rules.em.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.em(this.output(cap[2] || cap[1])); + continue; + } + + // code + if (cap = this.rules.code.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.codespan(escape(cap[2], true)); + continue; + } + + // br + if (cap = this.rules.br.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.br(); + continue; + } + + // del (gfm) + if (cap = this.rules.del.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.del(this.output(cap[1])); + continue; + } + + // text + if (cap = this.rules.text.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.text(escape(this.smartypants(cap[0]))); + continue; + } + + if (src) { + throw new + Error('Infinite loop on byte: ' + src.charCodeAt(0)); + } + } + + return out; +}; + +/** + * Compile Link + */ + +InlineLexer.prototype.outputLink = function(cap, link) { + var href = escape(link.href) + , title = link.title ? escape(link.title) : null; + + return cap[0].charAt(0) !== '!' + ? this.renderer.link(href, title, this.output(cap[1])) + : this.renderer.image(href, title, escape(cap[1])); +}; + +/** + * Smartypants Transformations + */ + +InlineLexer.prototype.smartypants = function(text) { + if (!this.options.smartypants) return text; + return text + // em-dashes + .replace(/---/g, '\u2014') + // en-dashes + .replace(/--/g, '\u2013') + // opening singles + .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') + // closing singles & apostrophes + .replace(/'/g, '\u2019') + // opening doubles + .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') + // closing doubles + .replace(/"/g, '\u201d') + // ellipses + .replace(/\.{3}/g, '\u2026'); +}; + +/** + * Mangle Links + */ + +InlineLexer.prototype.mangle = function(text) { + if (!this.options.mangle) return text; + var out = '' + , l = text.length + , i = 0 + , ch; + + for (; i < l; i++) { + ch = text.charCodeAt(i); + if (Math.random() > 0.5) { + ch = 'x' + ch.toString(16); + } + out += '&#' + ch + ';'; + } + + return out; +}; + +/** + * Renderer + */ + +function Renderer(options) { + this.options = options || {}; +} + +Renderer.prototype.code = function(code, lang, escaped) { + if (this.options.highlight) { + var out = this.options.highlight(code, lang); + if (out != null && out !== code) { + escaped = true; + code = out; + } + } + + if (!lang) { + return '
'
+      + (escaped ? code : escape(code, true))
+      + '\n
'; + } + + return '
'
+    + (escaped ? code : escape(code, true))
+    + '\n
\n'; +}; + +Renderer.prototype.blockquote = function(quote) { + return '
\n' + quote + '
\n'; +}; + +Renderer.prototype.html = function(html) { + return html; +}; + +Renderer.prototype.heading = function(text, level, raw) { + return '' + + text + + '\n'; +}; + +Renderer.prototype.hr = function() { + return this.options.xhtml ? '
\n' : '
\n'; +}; + +Renderer.prototype.list = function(body, ordered) { + var type = ordered ? 'ol' : 'ul'; + return '<' + type + '>\n' + body + '\n'; +}; + +Renderer.prototype.listitem = function(text) { + return '
  • ' + text + '
  • \n'; +}; + +Renderer.prototype.paragraph = function(text) { + return '

    ' + text + '

    \n'; +}; + +Renderer.prototype.table = function(header, body) { + return '\n' + + '\n' + + header + + '\n' + + '\n' + + body + + '\n' + + '
    \n'; +}; + +Renderer.prototype.tablerow = function(content) { + return '\n' + content + '\n'; +}; + +Renderer.prototype.tablecell = function(content, flags) { + var type = flags.header ? 'th' : 'td'; + var tag = flags.align + ? '<' + type + ' style="text-align:' + flags.align + '">' + : '<' + type + '>'; + return tag + content + '\n'; +}; + +// span level renderer +Renderer.prototype.strong = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.em = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.codespan = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.br = function() { + return this.options.xhtml ? '
    ' : '
    '; +}; + +Renderer.prototype.del = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.link = function(href, title, text) { + if (this.options.sanitize) { + try { + var prot = decodeURIComponent(unescape(href)) + .replace(/[^\w:]/g, '') + .toLowerCase(); + } catch (e) { + return ''; + } + if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) { + return ''; + } + } + var out = '
    '; + return out; +}; + +Renderer.prototype.image = function(href, title, text) { + var out = '' + text + '' : '>'; + return out; +}; + +Renderer.prototype.text = function(text) { + return text; +}; + +/** + * Parsing & Compiling + */ + +function Parser(options) { + this.tokens = []; + this.token = null; + this.options = options || marked.defaults; + this.options.renderer = this.options.renderer || new Renderer; + this.renderer = this.options.renderer; + this.renderer.options = this.options; +} + +/** + * Static Parse Method + */ + +Parser.parse = function(src, options, renderer) { + var parser = new Parser(options, renderer); + return parser.parse(src); +}; + +/** + * Parse Loop + */ + +Parser.prototype.parse = function(src) { + this.inline = new InlineLexer(src.links, this.options, this.renderer); + this.tokens = src.reverse(); + + var out = ''; + while (this.next()) { + out += this.tok(); + } + + return out; +}; + +/** + * Next Token + */ + +Parser.prototype.next = function() { + return this.token = this.tokens.pop(); +}; + +/** + * Preview Next Token + */ + +Parser.prototype.peek = function() { + return this.tokens[this.tokens.length - 1] || 0; +}; + +/** + * Parse Text Tokens + */ + +Parser.prototype.parseText = function() { + var body = this.token.text; + + while (this.peek().type === 'text') { + body += '\n' + this.next().text; + } + + return this.inline.output(body); +}; + +/** + * Parse Current Token + */ + +Parser.prototype.tok = function() { + switch (this.token.type) { + case 'space': { + return ''; + } + case 'hr': { + return this.renderer.hr(); + } + case 'heading': { + return this.renderer.heading( + this.inline.output(this.token.text), + this.token.depth, + this.token.text); + } + case 'code': { + return this.renderer.code(this.token.text, + this.token.lang, + this.token.escaped); + } + case 'table': { + var header = '' + , body = '' + , i + , row + , cell + , flags + , j; + + // header + cell = ''; + for (i = 0; i < this.token.header.length; i++) { + flags = { header: true, align: this.token.align[i] }; + cell += this.renderer.tablecell( + this.inline.output(this.token.header[i]), + { header: true, align: this.token.align[i] } + ); + } + header += this.renderer.tablerow(cell); + + for (i = 0; i < this.token.cells.length; i++) { + row = this.token.cells[i]; + + cell = ''; + for (j = 0; j < row.length; j++) { + cell += this.renderer.tablecell( + this.inline.output(row[j]), + { header: false, align: this.token.align[j] } + ); + } + + body += this.renderer.tablerow(cell); + } + return this.renderer.table(header, body); + } + case 'blockquote_start': { + var body = ''; + + while (this.next().type !== 'blockquote_end') { + body += this.tok(); + } + + return this.renderer.blockquote(body); + } + case 'list_start': { + var body = '' + , ordered = this.token.ordered; + + while (this.next().type !== 'list_end') { + body += this.tok(); + } + + return this.renderer.list(body, ordered); + } + case 'list_item_start': { + var body = ''; + + while (this.next().type !== 'list_item_end') { + body += this.token.type === 'text' + ? this.parseText() + : this.tok(); + } + + return this.renderer.listitem(body); + } + case 'loose_item_start': { + var body = ''; + + while (this.next().type !== 'list_item_end') { + body += this.tok(); + } + + return this.renderer.listitem(body); + } + case 'html': { + var html = !this.token.pre && !this.options.pedantic + ? this.inline.output(this.token.text) + : this.token.text; + return this.renderer.html(html); + } + case 'paragraph': { + return this.renderer.paragraph(this.inline.output(this.token.text)); + } + case 'text': { + return this.renderer.paragraph(this.parseText()); + } + } +}; + +/** + * Helpers + */ + +function escape(html, encode) { + return html + .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function unescape(html) { + // explicitly match decimal, hex, and named HTML entities + return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) { + n = n.toLowerCase(); + if (n === 'colon') return ':'; + if (n.charAt(0) === '#') { + return n.charAt(1) === 'x' + ? String.fromCharCode(parseInt(n.substring(2), 16)) + : String.fromCharCode(+n.substring(1)); + } + return ''; + }); +} + +function replace(regex, opt) { + regex = regex.source; + opt = opt || ''; + return function self(name, val) { + if (!name) return new RegExp(regex, opt); + val = val.source || val; + val = val.replace(/(^|[^\[])\^/g, '$1'); + regex = regex.replace(name, val); + return self; + }; +} + +function noop() {} +noop.exec = noop; + +function merge(obj) { + var i = 1 + , target + , key; + + for (; i < arguments.length; i++) { + target = arguments[i]; + for (key in target) { + if (Object.prototype.hasOwnProperty.call(target, key)) { + obj[key] = target[key]; + } + } + } + + return obj; +} + + +/** + * Marked + */ + +function marked(src, opt, callback) { + if (callback || typeof opt === 'function') { + if (!callback) { + callback = opt; + opt = null; + } + + opt = merge({}, marked.defaults, opt || {}); + + var highlight = opt.highlight + , tokens + , pending + , i = 0; + + try { + tokens = Lexer.lex(src, opt) + } catch (e) { + return callback(e); + } + + pending = tokens.length; + + var done = function(err) { + if (err) { + opt.highlight = highlight; + return callback(err); + } + + var out; + + try { + out = Parser.parse(tokens, opt); + } catch (e) { + err = e; + } + + opt.highlight = highlight; + + return err + ? callback(err) + : callback(null, out); + }; + + if (!highlight || highlight.length < 3) { + return done(); + } + + delete opt.highlight; + + if (!pending) return done(); + + for (; i < tokens.length; i++) { + (function(token) { + if (token.type !== 'code') { + return --pending || done(); + } + return highlight(token.text, token.lang, function(err, code) { + if (err) return done(err); + if (code == null || code === token.text) { + return --pending || done(); + } + token.text = code; + token.escaped = true; + --pending || done(); + }); + })(tokens[i]); + } + + return; + } + try { + if (opt) opt = merge({}, marked.defaults, opt); + return Parser.parse(Lexer.lex(src, opt), opt); + } catch (e) { + e.message += '\nPlease report this to https://github.com/chjj/marked.'; + if ((opt || marked.defaults).silent) { + return '

    An error occured:

    '
    +        + escape(e.message + '', true)
    +        + '
    '; + } + throw e; + } +} + +/** + * Options + */ + +marked.options = +marked.setOptions = function(opt) { + merge(marked.defaults, opt); + return marked; +}; + +marked.defaults = { + gfm: true, + tables: true, + breaks: false, + pedantic: false, + sanitize: false, + sanitizer: null, + mangle: true, + smartLists: false, + silent: false, + highlight: null, + langPrefix: 'lang-', + smartypants: false, + headerPrefix: '', + renderer: new Renderer, + xhtml: false +}; + +/** + * Expose + */ + +marked.Parser = Parser; +marked.parser = Parser.parse; + +marked.Renderer = Renderer; + +marked.Lexer = Lexer; +marked.lexer = Lexer.lex; + +marked.InlineLexer = InlineLexer; +marked.inlineLexer = InlineLexer.output; + +marked.parse = marked; + +if (typeof module !== 'undefined' && typeof exports === 'object') { + module.exports = marked; +} else if (typeof define === 'function' && define.amd) { + define(function() { return marked; }); +} else { + this.marked = marked; +} + +}).call(function() { + return this || (typeof window !== 'undefined' ? window : global); +}()); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],168:[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; }; + +},{}],169:[function(require,module,exports){ +(function (process){ +/** + * Copyright 2013-present, 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. + */ + +'use strict'; + +if (process.env.NODE_ENV !== 'production') { + var invariant = require('fbjs/lib/invariant'); + var warning = require('fbjs/lib/warning'); + var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); + var loggedTypeFailures = {}; +} + +/** + * 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 (typeSpecs.hasOwnProperty(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. + invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); + error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); + } catch (ex) { + error = ex; + } + warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error); + 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() : ''; + + warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); + } + } + } + } +} + +module.exports = checkPropTypes; + +}).call(this,require('_process')) +},{"./lib/ReactPropTypesSecret":173,"_process":168,"fbjs/lib/invariant":65,"fbjs/lib/warning":66}],170:[function(require,module,exports){ +/** + * Copyright 2013-present, 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. + */ + +'use strict'; + +var emptyFunction = require('fbjs/lib/emptyFunction'); +var invariant = require('fbjs/lib/invariant'); + +module.exports = function() { + // Important! + // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. + function shim() { + invariant( + false, + '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' + ); + }; + shim.isRequired = shim; + function getShim() { + return shim; + }; + var ReactPropTypes = { + array: shim, + bool: shim, + func: shim, + number: shim, + object: shim, + string: shim, + symbol: shim, + + any: shim, + arrayOf: getShim, + element: shim, + instanceOf: getShim, + node: shim, + objectOf: getShim, + oneOf: getShim, + oneOfType: getShim, + shape: getShim + }; + + ReactPropTypes.checkPropTypes = emptyFunction; + ReactPropTypes.PropTypes = ReactPropTypes; + + return ReactPropTypes; +}; + +},{"fbjs/lib/emptyFunction":64,"fbjs/lib/invariant":65}],171:[function(require,module,exports){ +(function (process){ +/** + * Copyright 2013-present, 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. + */ + +'use strict'; + +var emptyFunction = require('fbjs/lib/emptyFunction'); +var invariant = require('fbjs/lib/invariant'); +var warning = require('fbjs/lib/warning'); + +var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); +var checkPropTypes = require('./checkPropTypes'); + +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 = '<>'; + + // 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(), + instanceOf: createInstanceTypeChecker, + node: createNodeChecker(), + objectOf: createObjectOfTypeChecker, + oneOf: createEnumTypeChecker, + oneOfType: createUnionTypeChecker, + shape: createShapeTypeChecker + }; + + /** + * 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 + invariant( + false, + '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' + ); + } 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 + ) { + warning( + false, + 'You are manually calling a React.PropTypes validation ' + + 'function for the `%s` prop on `%s`. 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.', + propFullName, + componentName + ); + 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(emptyFunction.thatReturnsNull); + } + + 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 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)) { + process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; + return emptyFunction.thatReturnsNull; + } + + 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); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + 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 (propValue.hasOwnProperty(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' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; + return emptyFunction.thatReturnsNull; + } + + 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 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; + } + + // 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) { + var propType = getPropType(propValue); + if (propType === 'object') { + if (propValue instanceof Date) { + return 'date'; + } else if (propValue instanceof RegExp) { + return 'regexp'; + } + } + return propType; + } + + // 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.PropTypes = ReactPropTypes; + + return ReactPropTypes; +}; + +}).call(this,require('_process')) +},{"./checkPropTypes":169,"./lib/ReactPropTypesSecret":173,"_process":168,"fbjs/lib/emptyFunction":64,"fbjs/lib/invariant":65,"fbjs/lib/warning":66}],172:[function(require,module,exports){ +(function (process){ +/** + * Copyright 2013-present, 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. + */ + +if (process.env.NODE_ENV !== 'production') { + var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && + Symbol.for && + Symbol.for('react.element')) || + 0xeac7; + + var isValidElement = function(object) { + return typeof object === 'object' && + object !== null && + object.$$typeof === REACT_ELEMENT_TYPE; + }; + + // 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')(isValidElement, 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":170,"./factoryWithTypeCheckers":171,"_process":168}],173:[function(require,module,exports){ +/** + * Copyright 2013-present, 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. + */ + +'use strict'; + +var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; + +module.exports = ReactPropTypesSecret; + +},{}],174:[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 + } +} + +},{}],175:[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'; +} +},{}],176:[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":175,"_process":168,"inherits":174}]},{},[21])(21) +}); \ No newline at end of file diff --git a/docker/app/www/graphiql/index.html b/docker/app/www/graphiql/index.html new file mode 100644 index 0000000..d526286 --- /dev/null +++ b/docker/app/www/graphiql/index.html @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + +
    Loading...
    + + + diff --git a/docker/app/www/graphiql/react-dom.min.js b/docker/app/www/graphiql/react-dom.min.js new file mode 100644 index 0000000..480c7f9 --- /dev/null +++ b/docker/app/www/graphiql/react-dom.min.js @@ -0,0 +1,15 @@ +/** + * ReactDOM v15.4.2 + * + * Copyright 2013-present, 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(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e(require("react"));else if("function"==typeof define&&define.amd)define(["react"],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.ReactDOM=e(t.React)}}(function(e){return function(e){return e()}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a8&&b<=11),w=32,T=String.fromCharCode(w),k={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["topCompositionEnd","topKeyPress","topTextInput","topPaste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:["topBlur","topCompositionEnd","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:["topBlur","topCompositionStart","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:["topBlur","topCompositionUpdate","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]}},P=!1,N=null,S={eventTypes:k,extractEvents:function(e,t,n,r){return[l(e,t,n,r),d(e,t,n,r)]}};t.exports=S},{123:123,19:19,20:20,78:78,82:82}],4:[function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},i=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){i.forEach(function(t){o[r(t,e)]=o[e]})});var a={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},s={isUnitlessNumber:o,shorthandPropertyExpansions:a};t.exports=s},{}],5:[function(e,t,n){"use strict";var r=e(4),o=e(123),i=(e(58),e(125),e(94)),a=e(136),s=e(140),u=(e(142),s(function(e){return a(e)})),l=!1,c="cssFloat";if(o.canUseDOM){var p=document.createElement("div").style;try{p.font=""}catch(e){l=!0}void 0===document.documentElement.style.cssFloat&&(c="styleFloat")}var d={createMarkupForStyles:function(e,t){var n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];null!=o&&(n+=u(r)+":",n+=i(r,o,t)+";")}return n||null},setValueForStyles:function(e,t,n){var o=e.style;for(var a in t)if(t.hasOwnProperty(a)){var s=i(a,t[a],n);if("float"!==a&&"cssFloat"!==a||(a=c),s)o[a]=s;else{var u=l&&r.shorthandPropertyExpansions[a];if(u)for(var p in u)o[p]="";else o[a]=""}}}};t.exports=d},{123:123,125:125,136:136,140:140,142:142,4:4,58:58,94:94}],6:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=e(113),i=e(24),a=(e(137),function(){function e(t){r(this,e),this._callbacks=null,this._contexts=null,this._arg=t}return e.prototype.enqueue=function(e,t){this._callbacks=this._callbacks||[],this._callbacks.push(e),this._contexts=this._contexts||[],this._contexts.push(t)},e.prototype.notifyAll=function(){var e=this._callbacks,t=this._contexts,n=this._arg;if(e&&t){e.length!==t.length?o("24"):void 0,this._callbacks=null,this._contexts=null;for(var r=0;r8));var R=!1;C.canUseDOM&&(R=T("input")&&(!document.documentMode||document.documentMode>11));var A={get:function(){return I.get.call(this)},set:function(e){M=""+e,I.set.call(this,e)}},D={eventTypes:P,extractEvents:function(e,t,n,o){var i,a,s=t?b.getNodeFromInstance(t):window;if(r(s)?O?i=u:a=l:k(s)?R?i=f:(i=m,a=h):v(s)&&(i=g),i){var c=i(e,t);if(c){var p=x.getPooled(P.change,c,n,o);return p.type="change",_.accumulateTwoPhaseDispatches(p),p}}a&&a(e,s,t)}};t.exports=D},{102:102,110:110,111:111,123:123,16:16,19:19,33:33,71:71,80:80}],8:[function(e,t,n){"use strict";function r(e,t){return Array.isArray(t)&&(t=t[1]),t?t.nextSibling:e.firstChild}function o(e,t,n){c.insertTreeBefore(e,t,n)}function i(e,t,n){Array.isArray(t)?s(e,t[0],t[1],n):m(e,t,n)}function a(e,t){if(Array.isArray(t)){var n=t[1];t=t[0],u(e,t,n),e.removeChild(n)}e.removeChild(t)}function s(e,t,n,r){for(var o=t;;){var i=o.nextSibling;if(m(e,o,r),o===n)break;o=i}}function u(e,t,n){for(;;){var r=t.nextSibling;if(r===n)break;e.removeChild(r)}}function l(e,t,n){var r=e.parentNode,o=e.nextSibling;o===t?n&&m(r,document.createTextNode(n),o):n?(h(o,n),u(r,o,t)):u(r,e,t)}var c=e(9),p=e(13),d=(e(33),e(58),e(93)),f=e(115),h=e(116),m=d(function(e,t,n){e.insertBefore(t,n)}),v=p.dangerouslyReplaceNodeWithMarkup,g={dangerouslyReplaceNodeWithMarkup:v,replaceDelimitedText:l,processUpdates:function(e,t){for(var n=0;n-1?void 0:a("96",e),!l.plugins[n]){t.extractEvents?void 0:a("97",e),l.plugins[n]=t;var r=t.eventTypes;for(var i in r)o(r[i],t,i)?void 0:a("98",i,e)}}}function o(e,t,n){l.eventNameDispatchConfigs.hasOwnProperty(n)?a("99",n):void 0,l.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var s=r[o];i(s,t,n)}return!0}return!!e.registrationName&&(i(e.registrationName,t,n),!0)}function i(e,t,n){l.registrationNameModules[e]?a("100",e):void 0,l.registrationNameModules[e]=t,l.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=e(113),s=(e(137),null),u={},l={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(e){s?a("101"):void 0,s=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];u.hasOwnProperty(n)&&u[n]===o||(u[n]?a("102",n):void 0,u[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return l.registrationNameModules[t.registrationName]||null;if(void 0!==t.phasedRegistrationNames){var n=t.phasedRegistrationNames;for(var r in n)if(n.hasOwnProperty(r)){var o=l.registrationNameModules[n[r]];if(o)return o}}return null},_resetEventPlugins:function(){s=null;for(var e in u)u.hasOwnProperty(e)&&delete u[e];l.plugins.length=0;var t=l.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=l.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=l},{113:113,137:137}],18:[function(e,t,n){"use strict";function r(e){return"topMouseUp"===e||"topTouchEnd"===e||"topTouchCancel"===e}function o(e){return"topMouseMove"===e||"topTouchMove"===e}function i(e){return"topMouseDown"===e||"topTouchStart"===e}function a(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=g.getNodeFromInstance(r),t?m.invokeGuardedCallbackWithCatch(o,n,e):m.invokeGuardedCallback(o,n,e),e.currentTarget=null}function s(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(n))for(var o=0;o1?1-t:void 0;return this._fallbackText=o.slice(e,s),this._fallbackText}}),i.addPoolingTo(r),t.exports=r},{107:107,143:143,24:24}],21:[function(e,t,n){"use strict";var r=e(11),o=r.injection.MUST_USE_PROPERTY,i=r.injection.HAS_BOOLEAN_VALUE,a=r.injection.HAS_NUMERIC_VALUE,s=r.injection.HAS_POSITIVE_NUMERIC_VALUE,u=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE,l={isCustomAttribute:RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+r.ATTRIBUTE_NAME_CHAR+"]*$")),Properties:{accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:i,allowTransparency:0,alt:0,as:0,async:i,autoComplete:0,autoPlay:i,capture:i,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:o|i,cite:0,classID:0,className:0,cols:s,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:i,coords:0,crossOrigin:0,data:0,dateTime:0,default:i,defer:i,dir:0,disabled:i,download:u,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:i,formTarget:0,frameBorder:0,headers:0,height:0,hidden:i,high:0,href:0,hrefLang:0,htmlFor:0,httpEquiv:0,icon:0,id:0,inputMode:0,integrity:0,is:0,keyParams:0,keyType:0,kind:0,label:0,lang:0,list:0,loop:i,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:o|i,muted:o|i,name:0,nonce:0,noValidate:i,open:i,optimum:0,pattern:0,placeholder:0,playsInline:i,poster:0,preload:0,profile:0,radioGroup:0,readOnly:i,referrerPolicy:0,rel:0,required:i,reversed:i,role:0,rows:s,rowSpan:a,sandbox:0,scope:0,scoped:i,scrolling:0,seamless:i,selected:o|i,shape:0,size:s,sizes:0,span:s,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:a,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:0,width:0,wmode:0,wrap:0,about:0,datatype:0,inlist:0,prefix:0,property:0,resource:0,typeof:0,vocab:0,autoCapitalize:0,autoCorrect:0,autoSave:0,color:0,itemProp:0,itemScope:i,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{}};t.exports=l},{11:11}],22:[function(e,t,n){"use strict";function r(e){var t=/[=:]/g,n={"=":"=0",":":"=2"},r=(""+e).replace(t,function(e){return n[e]});return"$"+r}function o(e){var t=/(=0|=2)/g,n={"=0":"=","=2":":"},r="."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1);return(""+r).replace(t,function(e){return n[e]})}var i={escape:r,unescape:o};t.exports=i},{}],23:[function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink?s("87"):void 0}function o(e){r(e),null!=e.value||null!=e.onChange?s("88"):void 0}function i(e){r(e),null!=e.checked||null!=e.onChange?s("89"):void 0}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var s=e(113),u=e(121),l=e(64),c=(e(137),e(142),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),p={value:function(e,t,n){return!e[t]||c[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:u.PropTypes.func},d={},f={checkPropTypes:function(e,t,n){for(var r in p){if(p.hasOwnProperty(r))var o=p[r](t,r,e,"prop",null,l);o instanceof Error&&!(o.message in d)&&(d[o.message]=!0,a(n))}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(i(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(i(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};t.exports=f},{113:113,121:121,137:137,142:142,64:64}],24:[function(e,t,n){"use strict";var r=e(113),o=(e(137),function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)}),i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},s=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},u=function(e){var t=this;e instanceof t?void 0:r("25"),e.destructor(),t.instancePool.length=0||null!=t.is}function h(e){var t=e.type;d(t),this._currentElement=e,this._tag=t.toLowerCase(),this._namespaceURI=null,this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._hostNode=null,this._hostParent=null,this._rootNodeID=0,this._domID=0,this._hostContainerInfo=null,this._wrapperState=null,this._topLevelWrapper=null,this._flags=0}var m=e(113),v=e(143),g=e(2),y=e(5),_=e(9),C=e(10),b=e(11),E=e(12),x=e(16),w=e(17),T=e(25),k=e(32),P=e(33),N=e(38),S=e(39),M=e(40),I=e(43),O=(e(58),e(61)),R=e(68),A=(e(129),e(95)),D=(e(137),e(110),e(141),e(119),e(142),k),L=x.deleteListener,U=P.getNodeFromInstance,F=T.listenTo,V=w.registrationNameModules,B={string:!0,number:!0},j="style",W="__html",H={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null},q=11,K={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},z={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},Y={listing:!0,pre:!0,textarea:!0},X=v({menuitem:!0},z),Q=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,G={},$={}.hasOwnProperty,Z=1;h.displayName="ReactDOMComponent",h.Mixin={mountComponent:function(e,t,n,r){this._rootNodeID=Z++,this._domID=n._idCounter++,this._hostParent=t,this._hostContainerInfo=n;var i=this._currentElement.props;switch(this._tag){case"audio":case"form":case"iframe":case"img":case"link":case"object":case"source":case"video":this._wrapperState={listeners:null},e.getReactMountReady().enqueue(c,this);break;case"input":N.mountWrapper(this,i,t),i=N.getHostProps(this,i),e.getReactMountReady().enqueue(c,this);break;case"option":S.mountWrapper(this,i,t),i=S.getHostProps(this,i);break;case"select":M.mountWrapper(this,i,t),i=M.getHostProps(this,i),e.getReactMountReady().enqueue(c,this);break;case"textarea":I.mountWrapper(this,i,t),i=I.getHostProps(this,i),e.getReactMountReady().enqueue(c,this)}o(this,i);var a,p;null!=t?(a=t._namespaceURI,p=t._tag):n._tag&&(a=n._namespaceURI,p=n._tag),(null==a||a===C.svg&&"foreignobject"===p)&&(a=C.html),a===C.html&&("svg"===this._tag?a=C.svg:"math"===this._tag&&(a=C.mathml)),this._namespaceURI=a;var d;if(e.useCreateElement){var f,h=n._ownerDocument;if(a===C.html)if("script"===this._tag){var m=h.createElement("div"),v=this._currentElement.type;m.innerHTML="<"+v+">",f=m.removeChild(m.firstChild)}else f=i.is?h.createElement(this._currentElement.type,i.is):h.createElement(this._currentElement.type);else f=h.createElementNS(a,this._currentElement.type);P.precacheNode(this,f),this._flags|=D.hasCachedChildNodes,this._hostParent||E.setAttributeForRoot(f),this._updateDOMProperties(null,i,e);var y=_(f);this._createInitialChildren(e,i,r,y),d=y}else{var b=this._createOpenTagMarkupAndPutListeners(e,i),x=this._createContentMarkup(e,i,r);d=!x&&z[this._tag]?b+"/>":b+">"+x+""}switch(this._tag){case"input":e.getReactMountReady().enqueue(s,this),i.autoFocus&&e.getReactMountReady().enqueue(g.focusDOMComponent,this);break;case"textarea":e.getReactMountReady().enqueue(u,this),i.autoFocus&&e.getReactMountReady().enqueue(g.focusDOMComponent,this);break;case"select":i.autoFocus&&e.getReactMountReady().enqueue(g.focusDOMComponent,this);break;case"button":i.autoFocus&&e.getReactMountReady().enqueue(g.focusDOMComponent,this);break;case"option":e.getReactMountReady().enqueue(l,this)}return d},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r];if(null!=o)if(V.hasOwnProperty(r))o&&i(this,r,o,e);else{r===j&&(o&&(o=this._previousStyleCopy=v({},t.style)),o=y.createMarkupForStyles(o,this));var a=null;null!=this._tag&&f(this._tag,t)?H.hasOwnProperty(r)||(a=E.createMarkupForCustomAttribute(r,o)):a=E.createMarkupForProperty(r,o),a&&(n+=" "+a)}}return e.renderToStaticMarkup?n:(this._hostParent||(n+=" "+E.createMarkupForRoot()),n+=" "+E.createMarkupForID(this._domID))},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var i=B[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)r=A(i);else if(null!=a){var s=this.mountChildren(a,e,n);r=s.join("")}}return Y[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&_.queueHTML(r,o.__html);else{var i=B[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)""!==i&&_.queueText(r,i);else if(null!=a)for(var s=this.mountChildren(a,e,n),u=0;u"},receiveComponent:function(){},getHostNode:function(){return i.getNodeFromInstance(this)},unmountComponent:function(){i.uncacheNode(this)}}),t.exports=a},{143:143,33:33,9:9}],36:[function(e,t,n){"use strict";var r={useCreateElement:!0,useFiber:!1};t.exports=r},{}],37:[function(e,t,n){"use strict";var r=e(8),o=e(33),i={dangerouslyProcessChildrenUpdates:function(e,t){var n=o.getNodeFromInstance(e);r.processUpdates(n,t)}};t.exports=i},{33:33,8:8}],38:[function(e,t,n){"use strict";function r(){this._rootNodeID&&p.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=u.executeOnChange(t,e);c.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var a=l.getNodeFromInstance(this),s=a;s.parentNode;)s=s.parentNode;for(var p=s.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),d=0;dt.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function s(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i=void 0===t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=l(e,o),u=l(e,i);if(s&&u){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(u.node,u.offset)):(p.setEnd(u.node,u.offset),n.addRange(p))}}}var u=e(123),l=e(106),c=e(107),p=u.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?o:i,setOffsets:p?a:s};t.exports=d},{106:106,107:107,123:123}],42:[function(e,t,n){"use strict";var r=e(113),o=e(143),i=e(8),a=e(9),s=e(33),u=e(95),l=(e(137),e(119),function(e){this._currentElement=e,this._stringText=""+e,this._hostNode=null,this._hostParent=null,this._domID=0,this._mountIndex=0,this._closingComment=null,this._commentNodes=null});o(l.prototype,{mountComponent:function(e,t,n,r){var o=n._idCounter++,i=" react-text: "+o+" ",l=" /react-text ";if(this._domID=o,this._hostParent=t,e.useCreateElement){ +var c=n._ownerDocument,p=c.createComment(i),d=c.createComment(l),f=a(c.createDocumentFragment());return a.queueChild(f,a(p)),this._stringText&&a.queueChild(f,a(c.createTextNode(this._stringText))),a.queueChild(f,a(d)),s.precacheNode(this,p),this._closingComment=d,f}var h=u(this._stringText);return e.renderToStaticMarkup?h:""+h+""},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var r=this.getHostNode();i.replaceDelimitedText(r[0],r[1],n)}}},getHostNode:function(){var e=this._commentNodes;if(e)return e;if(!this._closingComment)for(var t=s.getNodeFromInstance(this),n=t.nextSibling;;){if(null==n?r("67",this._domID):void 0,8===n.nodeType&&" /react-text "===n.nodeValue){this._closingComment=n;break}n=n.nextSibling}return e=[this._hostNode,this._closingComment],this._commentNodes=e,e},unmountComponent:function(){this._closingComment=null,this._commentNodes=null,s.uncacheNode(this)}}),t.exports=l},{113:113,119:119,137:137,143:143,33:33,8:8,9:9,95:95}],43:[function(e,t,n){"use strict";function r(){this._rootNodeID&&c.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);return l.asap(r,this),n}var i=e(113),a=e(143),s=e(23),u=e(33),l=e(71),c=(e(137),e(142),{getHostProps:function(e,t){null!=t.dangerouslySetInnerHTML?i("91"):void 0;var n=a({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return n},mountWrapper:function(e,t){var n=s.getValue(t),r=n;if(null==n){var a=t.defaultValue,u=t.children;null!=u&&(null!=a?i("92"):void 0,Array.isArray(u)&&(u.length<=1?void 0:i("93"),u=u[0]),a=""+u),null==a&&(a=""),r=a}e._wrapperState={initialValue:""+r,listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=u.getNodeFromInstance(e),r=s.getValue(t);if(null!=r){var o=""+r;o!==n.value&&(n.value=o),null==t.defaultValue&&(n.defaultValue=o)}null!=t.defaultValue&&(n.defaultValue=t.defaultValue)},postMountWrapper:function(e){var t=u.getNodeFromInstance(e),n=t.textContent;n===e._wrapperState.initialValue&&(t.value=n)}});t.exports=c},{113:113,137:137,142:142,143:143,23:23,33:33,71:71}],44:[function(e,t,n){"use strict";function r(e,t){"_hostNode"in e?void 0:u("33"),"_hostNode"in t?void 0:u("33");for(var n=0,r=e;r;r=r._hostParent)n++;for(var o=0,i=t;i;i=i._hostParent)o++;for(;n-o>0;)e=e._hostParent,n--;for(;o-n>0;)t=t._hostParent,o--;for(var a=n;a--;){if(e===t)return e;e=e._hostParent,t=t._hostParent}return null}function o(e,t){"_hostNode"in e?void 0:u("35"),"_hostNode"in t?void 0:u("35");for(;t;){if(t===e)return!0;t=t._hostParent}return!1}function i(e){return"_hostNode"in e?void 0:u("36"),e._hostParent}function a(e,t,n){for(var r=[];e;)r.push(e),e=e._hostParent;var o;for(o=r.length;o-- >0;)t(r[o],"captured",n);for(o=0;o0;)n(u[l],"captured",i)}var u=e(113);e(137);t.exports={isAncestor:o,getLowestCommonAncestor:r,getParentInstance:i,traverseTwoPhase:a,traverseEnterLeave:s}},{113:113,137:137}],45:[function(e,t,n){"use strict";var r=e(121),o=e(30),i=o;r.addons&&(r.__SECRET_INJECTED_REACT_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=i),t.exports=i},{121:121,30:30}],46:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=e(143),i=e(71),a=e(89),s=e(129),u={initialize:s,close:function(){d.isBatchingUpdates=!1}},l={initialize:s,close:i.flushBatchedUpdates.bind(i)},c=[l,u];o(r.prototype,a,{getTransactionWrappers:function(){return c}});var p=new r,d={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,i){var a=d.isBatchingUpdates;return d.isBatchingUpdates=!0,a?e(t,n,r,o,i):p.perform(e,null,t,n,r,o,i)}};t.exports=d},{129:129,143:143,71:71,89:89}],47:[function(e,t,n){"use strict";function r(){x||(x=!0,y.EventEmitter.injectReactEventListener(g),y.EventPluginHub.injectEventPluginOrder(s),y.EventPluginUtils.injectComponentTree(d),y.EventPluginUtils.injectTreeTraversal(h),y.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:E,EnterLeaveEventPlugin:u,ChangeEventPlugin:a,SelectEventPlugin:b,BeforeInputEventPlugin:i}),y.HostComponent.injectGenericComponentClass(p),y.HostComponent.injectTextComponentClass(m),y.DOMProperty.injectDOMPropertyConfig(o),y.DOMProperty.injectDOMPropertyConfig(l),y.DOMProperty.injectDOMPropertyConfig(C),y.EmptyComponent.injectEmptyComponentFactory(function(e){return new f(e)}),y.Updates.injectReconcileTransaction(_),y.Updates.injectBatchingStrategy(v),y.Component.injectEnvironment(c))}var o=e(1),i=e(3),a=e(7),s=e(14),u=e(15),l=e(21),c=e(27),p=e(31),d=e(33),f=e(35),h=e(44),m=e(42),v=e(46),g=e(52),y=e(55),_=e(65),C=e(73),b=e(74),E=e(75),x=!1;t.exports={inject:r}},{1:1,14:14,15:15,21:21,27:27,3:3,31:31,33:33,35:35,42:42,44:44,46:46,52:52,55:55,65:65,7:7,73:73,74:74,75:75}],48:[function(e,t,n){"use strict";var r="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;t.exports=r},{}],49:[function(e,t,n){"use strict";var r,o={injectEmptyComponentFactory:function(e){r=e}},i={create:function(e){return r(e)}};i.injection=o,t.exports=i},{}],50:[function(e,t,n){"use strict";function r(e,t,n){try{t(n)}catch(e){null===o&&(o=e)}}var o=null,i={invokeGuardedCallback:r,invokeGuardedCallbackWithCatch:r,rethrowCaughtError:function(){if(o){var e=o;throw o=null,e}}};t.exports=i},{}],51:[function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=e(16),i={handleTopLevel:function(e,t,n,i){var a=o.extractEvents(e,t,n,i);r(a)}};t.exports=i},{16:16}],52:[function(e,t,n){"use strict";function r(e){for(;e._hostParent;)e=e._hostParent;var t=p.getNodeFromInstance(e),n=t.parentNode;return p.getClosestInstanceFromNode(n)}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){var t=f(e.nativeEvent),n=p.getClosestInstanceFromNode(t),o=n;do e.ancestors.push(o),o=o&&r(o);while(o);for(var i=0;i/,i=/^<\!\-\-/,a={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return i.test(e)?e:e.replace(o," "+a.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(a.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var o=r(e);return o===n}};t.exports=a},{92:92}],60:[function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;r.":"function"==typeof t?" Instead of passing a class like Foo, pass React.createElement(Foo) or .":null!=t&&void 0!==t.props?" This may be caused by unintentionally loading two independent copies of React.":"");var a,s=v.createElement(F,{child:t});if(e){var u=E.get(e);a=u._processChildContext(u._context)}else a=P;var c=d(n);if(c){var p=c._currentElement,h=p.props.child;if(M(h,t)){var m=c._renderedComponent.getPublicInstance(),g=r&&function(){r.call(m)};return V._updateRootComponent(c,s,a,n,g),m}V.unmountComponentAtNode(n)}var y=o(n),_=y&&!!i(y),C=l(n),b=_&&!c&&!C,x=V._renderNewRootComponent(s,n,b,a)._renderedComponent.getPublicInstance();return r&&r.call(x),x},render:function(e,t,n){return V._renderSubtreeIntoContainer(null,e,t,n)},unmountComponentAtNode:function(e){c(e)?void 0:f("40");var t=d(e);return t?(delete L[t._instance.rootID],k.batchedUpdates(u,t,e,!1),!0):(l(e),1===e.nodeType&&e.hasAttribute(O),!1)},_mountImageIntoNode:function(e,t,n,i,a){if(c(t)?void 0:f("41"),i){var s=o(t);if(x.canReuseMarkup(e,s))return void y.precacheNode(n,s);var u=s.getAttribute(x.CHECKSUM_ATTR_NAME);s.removeAttribute(x.CHECKSUM_ATTR_NAME);var l=s.outerHTML;s.setAttribute(x.CHECKSUM_ATTR_NAME,u);var p=e,d=r(p,l),m=" (client) "+p.substring(d-20,d+20)+"\n (server) "+l.substring(d-20,d+20);t.nodeType===A?f("42",m):void 0}if(t.nodeType===A?f("43"):void 0,a.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);h.insertTreeBefore(t,e,null)}else S(t,e),y.precacheNode(n,t.firstChild)}};t.exports=V},{109:109,11:11,113:113,115:115,117:117,120:120,121:121,130:130,137:137,142:142,25:25,33:33,34:34,36:36,53:53,57:57,58:58,59:59,66:66,70:70,71:71,9:9}],61:[function(e,t,n){"use strict";function r(e,t,n){return{type:"INSERT_MARKUP",content:e,fromIndex:null,fromNode:null,toIndex:n,afterNode:t}}function o(e,t,n){return{type:"MOVE_EXISTING",content:null,fromIndex:e._mountIndex,fromNode:d.getHostNode(e),toIndex:n,afterNode:t}}function i(e,t){return{type:"REMOVE_NODE",content:null,fromIndex:e._mountIndex,fromNode:t,toIndex:null,afterNode:null}}function a(e){return{type:"SET_MARKUP",content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function s(e){return{type:"TEXT_CONTENT",content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function u(e,t){return t&&(e=e||[],e.push(t)),e}function l(e,t){p.processChildrenUpdates(e,t)}var c=e(113),p=e(28),d=(e(57),e(58),e(120),e(66)),f=e(26),h=(e(129),e(97)),m=(e(137),{Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return f.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r,o,i){var a,s=0;return a=h(t,s),f.updateChildren(e,a,n,r,o,this,this._hostContainerInfo,i,s),a},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var s=r[a],u=0,l=d.mountComponent(s,t,this,this._hostContainerInfo,n,u);s._mountIndex=i++,o.push(l)}return o},updateTextContent:function(e){var t=this._renderedChildren;f.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&c("118");var r=[s(e)];l(this,r)},updateMarkup:function(e){var t=this._renderedChildren;f.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&c("118");var r=[a(e)];l(this,r)},updateChildren:function(e,t,n){this._updateChildren(e,t,n)},_updateChildren:function(e,t,n){var r=this._renderedChildren,o={},i=[],a=this._reconcilerUpdateChildren(r,e,i,o,t,n);if(a||r){var s,c=null,p=0,f=0,h=0,m=null;for(s in a)if(a.hasOwnProperty(s)){var v=r&&r[s],g=a[s];v===g?(c=u(c,this.moveChild(v,m,p,f)),f=Math.max(v._mountIndex,f),v._mountIndex=p):(v&&(f=Math.max(v._mountIndex,f)),c=u(c,this._mountChildAtIndex(g,i[h],m,p,t,n)),h++),p++,m=d.getHostNode(g)}for(s in o)o.hasOwnProperty(s)&&(c=u(c,this._unmountChild(r[s],o[s])));c&&l(this,c),this._renderedChildren=a}},unmountChildren:function(e){var t=this._renderedChildren;f.unmountChildren(t,e),this._renderedChildren=null},moveChild:function(e,t,n,r){if(e._mountIndex0&&r.length<20?n+" (keys: "+r.join(", ")+")":n}function i(e,t){var n=s.get(e);return n?n:null}var a=e(113),s=(e(120),e(57)),u=(e(58),e(71)),l=(e(137),e(142),{isMounted:function(e){var t=s.get(e);return!!t&&!!t._renderedComponent},enqueueCallback:function(e,t,n){l.validateCallback(t,n);var o=i(e);return o?(o._pendingCallbacks?o._pendingCallbacks.push(t):o._pendingCallbacks=[t],void r(o)):null},enqueueCallbackInternal:function(e,t){e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=i(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=i(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=i(e,"setState");if(n){var o=n._pendingStateQueue||(n._pendingStateQueue=[]);o.push(t),r(n)}},enqueueElementInternal:function(e,t,n){e._pendingElement=t,e._context=n,r(e)},validateCallback:function(e,t){e&&"function"!=typeof e?a("122",t,o(e)):void 0}});t.exports=l},{113:113,120:120,137:137,142:142,57:57,58:58,71:71}],71:[function(e,t,n){"use strict";function r(){P.ReactReconcileTransaction&&b?void 0:c("123")}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=d.getPooled(),this.reconcileTransaction=P.ReactReconcileTransaction.getPooled(!0)}function i(e,t,n,o,i,a){return r(),b.batchedUpdates(e,t,n,o,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function s(e){var t=e.dirtyComponentsLength;t!==g.length?c("124",t,g.length):void 0,g.sort(a),y++;for(var n=0;n]/;t.exports=o},{}],96:[function(e,t,n){"use strict";function r(e){if(null==e)return null;if(1===e.nodeType)return e;var t=a.get(e);return t?(t=s(t),t?i.getNodeFromInstance(t):null):void("function"==typeof e.render?o("44"):o("45",Object.keys(e)))}var o=e(113),i=(e(120),e(33)),a=e(57),s=e(103);e(137),e(142);t.exports=r},{103:103,113:113,120:120,137:137,142:142,33:33,57:57}],97:[function(e,t,n){(function(n){"use strict";function r(e,t,n,r){if(e&&"object"==typeof e){var o=e,i=void 0===o[n];i&&null!=t&&(o[n]=t)}}function o(e,t){if(null==e)return e;var n={};return i(e,r,n),n}var i=(e(22),e(118));e(142);"undefined"!=typeof n&&n.env,t.exports=o}).call(this,void 0)},{118:118,142:142,22:22}],98:[function(e,t,n){"use strict";function r(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}t.exports=r},{}],99:[function(e,t,n){"use strict";function r(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=r},{}],100:[function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=e(99),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=r},{99:99}],101:[function(e,t,n){"use strict";function r(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=i[e];return!!r&&!!n[r]}function o(e){return r}var i={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=o},{}],102:[function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return t.correspondingUseElement&&(t=t.correspondingUseElement),3===t.nodeType?t.parentNode:t}t.exports=r},{}],103:[function(e,t,n){"use strict";function r(e){for(var t;(t=e._renderedNodeType)===o.COMPOSITE;)e=e._renderedComponent;return t===o.HOST?e._renderedComponent:t===o.EMPTY?null:void 0}var o=e(62);t.exports=r},{62:62}],104:[function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[i]);if("function"==typeof t)return t}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";t.exports=r},{}],105:[function(e,t,n){"use strict";function r(){return o++}var o=1;t.exports=r},{}],106:[function(e,t,n){"use strict";function r(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function o(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function i(e,t){for(var n=r(e),i=0,a=0;n;){if(3===n.nodeType){if(a=i+n.textContent.length,i<=t&&a>=t)return{node:n,offset:t-i};i=a}n=r(o(n))}}t.exports=i},{}],107:[function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=e(123),i=null;t.exports=r},{123:123}],108:[function(e,t,n){"use strict";function r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}function o(e){if(s[e])return s[e];if(!a[e])return e;var t=a[e];for(var n in t)if(t.hasOwnProperty(n)&&n in u)return s[e]=t[n];return""}var i=e(123),a={animationend:r("Animation","AnimationEnd"),animationiteration:r("Animation","AnimationIteration"),animationstart:r("Animation","AnimationStart"),transitionend:r("Transition","TransitionEnd")},s={},u={};i.canUseDOM&&(u=document.createElement("div").style,"AnimationEvent"in window||(delete a.animationend.animation,delete a.animationiteration.animation,delete a.animationstart.animation),"TransitionEvent"in window||delete a.transitionend.transition),t.exports=o},{123:123}],109:[function(e,t,n){"use strict";function r(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}function o(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function i(e,t){var n;if(null===e||e===!1)n=l.create(i);else if("object"==typeof e){var s=e,u=s.type;if("function"!=typeof u&&"string"!=typeof u){var d="";d+=r(s._owner),a("130",null==u?u:typeof u,d)}"string"==typeof s.type?n=c.createInternalComponent(s):o(s.type)?(n=new s.type(s),n.getHostNode||(n.getHostNode=n.getNativeNode)):n=new p(s)}else"string"==typeof e||"number"==typeof e?n=c.createInstanceForText(e):a("131",typeof e);return n._mountIndex=0,n._mountImage=null,n}var a=e(113),s=e(143),u=e(29),l=e(49),c=e(54),p=(e(105),e(137),e(142),function(e){this.construct(e)});s(p.prototype,u,{_instantiateReactComponent:i}),t.exports=i},{105:105,113:113,137:137,142:142,143:143,29:29,49:49,54:54}],110:[function(e,t,n){"use strict";function r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=e(123);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=r},{123:123}],111:[function(e,t,n){"use strict";function r(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!o[e.type]:"textarea"===t}var o={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=r},{}],112:[function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=e(95);t.exports=r},{95:95}],113:[function(e,t,n){"use strict";function r(e){for(var t=arguments.length-1,n="Minified React error #"+e+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+e,r=0;r]/,u=e(93),l=u(function(e,t){if(e.namespaceURI!==i.svg||"innerHTML"in e)e.innerHTML=t;else{r=r||document.createElement("div"),r.innerHTML=""+t+"";for(var n=r.firstChild;n.firstChild;)e.appendChild(n.firstChild)}});if(o.canUseDOM){var c=document.createElement("div");c.innerHTML=" ",""===c.innerHTML&&(l=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),a.test(t)||"<"===t[0]&&s.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t}),c=null}t.exports=l},{10:10,123:123,93:93}],116:[function(e,t,n){"use strict";var r=e(123),o=e(95),i=e(115),a=function(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){return 3===e.nodeType?void(e.nodeValue=t):void i(e,o(t))})),t.exports=a},{115:115,123:123,95:95}],117:[function(e,t,n){"use strict";function r(e,t){var n=null===e||e===!1,r=null===t||t===!1;if(n||r)return n===r;var o=typeof e,i=typeof t;return"string"===o||"number"===o?"string"===i||"number"===i:"object"===i&&e.type===t.type&&e.key===t.key}t.exports=r},{}],118:[function(e,t,n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?l.escape(e.key):t.toString(36)}function o(e,t,n,i){var d=typeof e;if("undefined"!==d&&"boolean"!==d||(e=null),null===e||"string"===d||"number"===d||"object"===d&&e.$$typeof===s)return n(i,e,""===t?c+r(e,0):t),1;var f,h,m=0,v=""===t?c:t+p;if(Array.isArray(e))for(var g=0;g":a.innerHTML="<"+e+">",s[e]=!a.firstChild),s[e]?d[e]:null}var o=e(123),i=e(137),a=o.canUseDOM?document.createElement("div"):null,s={},u=[1,'"],l=[1,"","
    "],c=[3,"","
    "],p=[1,'',""],d={"*":[1,"?
    ","
    "],area:[1,"",""],col:[2,"","
    "],legend:[1,"
    ","
    "],param:[1,"",""],tr:[2,"","
    "],optgroup:u,option:u,caption:l,colgroup:l,tbody:l,tfoot:l,thead:l,td:c,th:c},f=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];f.forEach(function(e){d[e]=p,s[e]=!0}),t.exports=r},{123:123,137:137}],134:[function(e,t,n){"use strict";function r(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=r},{}],135:[function(e,t,n){"use strict";function r(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;t.exports=r},{}],136:[function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=e(135),i=/^ms-/;t.exports=r},{135:135}],137:[function(e,t,n){"use strict";function r(e,t,n,r,i,a,s,u){if(o(t),!e){var l;if(void 0===t)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,i,a,s,u],p=0;l=new Error(t.replace(/%s/g,function(){return c[p++]})),l.name="Invariant Violation"}throw l.framesToPop=1,l}}var o=function(e){};t.exports=r},{}],138:[function(e,t,n){"use strict";function r(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=r},{}],139:[function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=e(138);t.exports=r},{138:138}],140:[function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}t.exports=r},{}],141:[function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||0!==t||1/e===1/t:e!==e&&t!==t}function o(e,t){if(r(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(var a=0;a1){for(var h=Array(v),m=0;m1){for(var g=Array(b),E=0;E>"),O={array:u("array"),bool:u("boolean"),func:u("function"),number:u("number"),object:u("object"),string:u("string"),symbol:u("symbol"),any:a(),arrayOf:s,element:c(),instanceOf:l,node:y(),objectOf:p,oneOf:f,oneOfType:d,shape:v};o.prototype=Error.prototype,e.exports=O},{12:12,14:14,19:19,23:23,26:26,9:9}],14:[function(t,e,n){"use strict";var r="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";e.exports=r},{}],15:[function(t,e,n){"use strict";function r(t,e,n){this.props=t,this.context=e,this.refs=s,this.updater=n||a}function o(){}var i=t(27),u=t(6),a=t(11),s=t(24);o.prototype=u.prototype,r.prototype=new o,r.prototype.constructor=r,i(r.prototype,u.prototype),r.prototype.isPureReactComponent=!0,e.exports=r},{11:11,24:24,27:27,6:6}],16:[function(t,e,n){"use strict";var r=t(27),o=t(3),i=r({__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{ReactCurrentOwner:t(7)}},o);e.exports=i},{27:27,3:3,7:7}],17:[function(t,e,n){"use strict";e.exports="15.4.2"},{}],18:[function(t,e,n){"use strict";var r=!1;e.exports=r},{}],19:[function(t,e,n){"use strict";function r(t){var e=t&&(o&&t[o]||t[i]);if("function"==typeof e)return e}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";e.exports=r},{}],20:[function(t,e,n){"use strict";function r(t){return i.isValidElement(t)?void 0:o("143"),t}var o=t(21),i=t(9);t(25);e.exports=r},{21:21,25:25,9:9}],21:[function(t,e,n){"use strict";function r(t){for(var e=arguments.length-1,n="Minified React error #"+t+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+t,r=0;rprocess($payload); +header('Content-Type: application/json'); +echo json_encode($response); +exit; diff --git a/docker/app/www/voyager/index.html b/docker/app/www/voyager/index.html new file mode 100644 index 0000000..5f81558 --- /dev/null +++ b/docker/app/www/voyager/index.html @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + +
    Loading...
    + + + \ No newline at end of file