付智勇

添加包

要显示太多修改。

为保证性能只显示 32 of 32+ 个文件。

@@ -13,6 +13,8 @@ const users = require('./routes/users') @@ -13,6 +13,8 @@ const users = require('./routes/users')
13 const filterUrl = require(__dirname+'/util/filterUrl') 13 const filterUrl = require(__dirname+'/util/filterUrl')
14 var tokenUtil = require('./util/tokenUtil'); 14 var tokenUtil = require('./util/tokenUtil');
15 const _ = require('lodash'); 15 const _ = require('lodash');
  16 +var status = require('./util/resTemplate')
  17 +
16 // error handler 18 // error handler
17 onerror(app) 19 onerror(app)
18 20
@@ -36,8 +38,7 @@ app.use(async (ctx, next) => { @@ -36,8 +38,7 @@ app.use(async (ctx, next) => {
36 if(filterUrl.indexOf(ctx.request.url) != -1){ 38 if(filterUrl.indexOf(ctx.request.url) != -1){
37 await next(); 39 await next();
38 }else if(!ctx.header.token){ 40 }else if(!ctx.header.token){
39 - ctx.response.status = 200;  
40 - ctx.response.body = {code:0,msg:'请登录'} 41 + status.catchError(ctx,400,'请登录');
41 }else{ 42 }else{
42 let isToken = await tokenUtil.prverifySession(ctx.header.token); 43 let isToken = await tokenUtil.prverifySession(ctx.header.token);
43 await next(); 44 await next();
@@ -45,11 +46,8 @@ app.use(async (ctx, next) => { @@ -45,11 +46,8 @@ app.use(async (ctx, next) => {
45 const ms = new Date() - start; 46 const ms = new Date() - start;
46 console.log(`${ctx.method} ${ctx.url} - ${ms}ms`) 47 console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
47 }catch (e){ 48 }catch (e){
48 - console.log('返回的err',e.message)  
49 - ctx.response.status = 200;  
50 - ctx.response.body = {code:0,msg:e.message} 49 + status.catchError(ctx,400,e.message);
51 } 50 }
52 -  
53 }) 51 })
54 52
55 // routes 53 // routes
@@ -9,12 +9,16 @@ var userController =function (){ @@ -9,12 +9,16 @@ var userController =function (){
9 9
10 }; 10 };
11 11
  12 +/**
  13 + * Generate documentation output.
  14 + *
  15 + * @param {TAFFY} ctx
  16 + *
  17 + * @param {object} next
  18 + */
12 userController.prototype.addUser = async(ctx, next) =>{ 19 userController.prototype.addUser = async(ctx, next) =>{
13 var params = ctx.request.body; 20 var params = ctx.request.body;
14 const pw = saitMd5.md5AddSalt(params.password) 21 const pw = saitMd5.md5AddSalt(params.password)
15 - console.dir(params.password.length,7)  
16 - console.dir(params.password.length<6)  
17 -  
18 22
19 if(!params.loginName){ 23 if(!params.loginName){
20 return status.paramError('loginName'); 24 return status.paramError('loginName');
@@ -23,20 +27,26 @@ userController.prototype.addUser = async(ctx, next) =>{ @@ -23,20 +27,26 @@ userController.prototype.addUser = async(ctx, next) =>{
23 }if(params.password.length < 6){ 27 }if(params.password.length < 6){
24 return status.paramError('password','不得小于6位'); 28 return status.paramError('password','不得小于6位');
25 } 29 }
  30 +
26 var user = { 31 var user = {
27 loginName:params.loginName, 32 loginName:params.loginName,
28 password:pw.md5Pass, 33 password:pw.md5Pass,
29 salt:pw.salt, 34 salt:pw.salt,
30 userType:params.type 35 userType:params.type
31 } 36 }
  37 +
32 try{ 38 try{
33 return await userService.addUser(user) 39 return await userService.addUser(user)
34 }catch (e){ 40 }catch (e){
35 throw new Error(e); 41 throw new Error(e);
36 } 42 }
37 } 43 }
  44 +/**
  45 + * 用户登录
  46 + */
38 userController.prototype.login = async(ctx, next) =>{ 47 userController.prototype.login = async(ctx, next) =>{
39 const body = ctx.request.body; 48 const body = ctx.request.body;
  49 +
40 if(!body.name){ 50 if(!body.name){
41 return status.paramError('name'); 51 return status.paramError('name');
42 }else if(!body.password){ 52 }else if(!body.password){
  1 +../babylon/bin/babylon.js
  1 +../jsdoc/jsdoc.js
  1 +../marked/bin/marked
  1 +# Changelog
  2 +
  3 +> **Tags:**
  4 +> - :boom: [Breaking Change]
  5 +> - :eyeglasses: [Spec Compliancy]
  6 +> - :rocket: [New Feature]
  7 +> - :bug: [Bug Fix]
  8 +> - :memo: [Documentation]
  9 +> - :house: [Internal]
  10 +> - :nail_care: [Polish]
  11 +
  12 +> Semver Policy: https://github.com/babel/babylon#semver
  13 +
  14 +_Note: Gaps between patch versions are faulty, broken or test releases._
  15 +
  16 +See the [Babel Changelog](https://github.com/babel/babel/blob/master/CHANGELOG.md) for the pre-6.8.0 version Changelog.
  17 +
  18 +## 6.17.1 (2017-05-10)
  19 +
  20 +### :bug: Bug Fix
  21 + * Fix typo in flow spread operator error (Brian Ng)
  22 + * Fixed invalid number literal parsing ([#473](https://github.com/babel/babylon/pull/473)) (Alex Kuzmenko)
  23 + * Fix number parser ([#433](https://github.com/babel/babylon/pull/433)) (Alex Kuzmenko)
  24 + * Ensure non pattern shorthand props are checked for reserved words ([#479](https://github.com/babel/babylon/pull/479)) (Brian Ng)
  25 + * Remove jsx context when parsing arrow functions ([#475](https://github.com/babel/babylon/pull/475)) (Brian Ng)
  26 + * Allow super in class properties ([#499](https://github.com/babel/babylon/pull/499)) (Brian Ng)
  27 + * Allow flow class field to be named constructor ([#510](https://github.com/babel/babylon/pull/510)) (Brian Ng)
  28 +
  29 +## 6.17.0 (2017-04-20)
  30 +
  31 +### :bug: Bug Fix
  32 + * Cherry-pick #418 to 6.x ([#476](https://github.com/babel/babylon/pull/476)) (Sebastian McKenzie)
  33 + * Add support for invalid escapes in tagged templates ([#274](https://github.com/babel/babylon/pull/274)) (Kevin Gibbons)
  34 + * Throw error if new.target is used outside of a function ([#402](https://github.com/babel/babylon/pull/402)) (Brian Ng)
  35 + * Fix parsing of class properties ([#351](https://github.com/babel/babylon/pull/351)) (Kevin Gibbons)
  36 + * Fix parsing yield with dynamicImport ([#383](https://github.com/babel/babylon/pull/383)) (Brian Ng)
  37 + * Ensure consistent start args for parseParenItem ([#386](https://github.com/babel/babylon/pull/386)) (Brian Ng)
  38 +
  39 +## 7.0.0-beta.8 (2017-04-04)
  40 +
  41 +### New Feature
  42 +* Add support for flow type spread (#418) (Conrad Buck)
  43 +* Allow statics in flow interfaces (#427) (Brian Ng)
  44 +
  45 +### Bug Fix
  46 +* Fix predicate attachment to match flow parser (#428) (Brian Ng)
  47 +* Add extra.raw back to JSXText and JSXAttribute (#344) (Alex Rattray)
  48 +* Fix rest parameters with array and objects (#424) (Brian Ng)
  49 +* Fix number parser (#433) (Alex Kuzmenko)
  50 +
  51 +### Docs
  52 +* Fix CONTRIBUTING.md [skip ci] (#432) (Alex Kuzmenko)
  53 +
  54 +### Internal
  55 +* Use babel-register script when running babel smoke tests (#442) (Brian Ng)
  56 +
  57 +## 7.0.0-beta.7 (2017-03-22)
  58 +
  59 +### Spec Compliancy
  60 +* Remove babylon plugin for template revision since it's stage-4 (#426) (Henry Zhu)
  61 +
  62 +### Bug Fix
  63 +
  64 +* Fix push-pop logic in flow (#405) (Daniel Tschinder)
  65 +
  66 +## 7.0.0-beta.6 (2017-03-21)
  67 +
  68 +### New Feature
  69 +* Add support for invalid escapes in tagged templates (#274) (Kevin Gibbons)
  70 +
  71 +### Polish
  72 +* Improves error message when super is called outside of constructor (#408) (Arshabh Kumar Agarwal)
  73 +
  74 +### Docs
  75 +
  76 +* [7.0] Moved value field in spec from ObjectMember to ObjectProperty as ObjectMethod's don't have it (#415) [skip ci] (James Browning)
  77 +
  78 +## 7.0.0-beta.5 (2017-03-21)
  79 +
  80 +### Bug Fix
  81 +* Throw error if new.target is used outside of a function (#402) (Brian Ng)
  82 +* Fix parsing of class properties (#351) (Kevin Gibbons)
  83 +
  84 +### Other
  85 + * Test runner: Detect extra property in 'actual' but not in 'expected'. (#407) (Andy)
  86 + * Optimize travis builds (#419) (Daniel Tschinder)
  87 + * Update codecov to 2.0 (#412) (Daniel Tschinder)
  88 + * Fix spec for ClassMethod: It doesn't have a function, it *is* a function. (#406) [skip ci] (Andy)
  89 + * Changed Non-existent RestPattern to RestElement which is what is actually parsed (#409) [skip ci] (James Browning)
  90 + * Upgrade flow to 0.41 (Daniel Tschinder)
  91 + * Fix watch command (#403) (Brian Ng)
  92 + * Update yarn lock (Daniel Tschinder)
  93 + * Fix watch command (#403) (Brian Ng)
  94 + * chore(package): update flow-bin to version 0.41.0 (#395) (greenkeeper[bot])
  95 + * Add estree test for correct order of directives (Daniel Tschinder)
  96 + * Add DoExpression to spec (#364) (Alex Kuzmenko)
  97 + * Mention cloning of repository in CONTRIBUTING.md (#391) [skip ci] (Sumedh Nimkarde)
  98 + * Explain how to run only one test (#389) [skip ci] (Aaron Ang)
  99 +
  100 + ## 7.0.0-beta.4 (2017-03-01)
  101 +
  102 +* Don't consume async when checking for async func decl (#377) (Brian Ng)
  103 +* add `ranges` option [skip ci] (Henry Zhu)
  104 +* Don't parse class properties without initializers when classProperties is disabled and Flow is enabled (#300) (Andrew Levine)
  105 +
  106 +## 7.0.0-beta.3 (2017-02-28)
  107 +
  108 +- [7.0] Change RestProperty/SpreadProperty to RestElement/SpreadElement (#384)
  109 +- Merge changes from 6.x
  110 +
  111 +## 7.0.0-beta.2 (2017-02-20)
  112 +
  113 +- estree: correctly change literals in all cases (#368) (Daniel Tschinder)
  114 +
  115 +## 7.0.0-beta.1 (2017-02-20)
  116 +
  117 +- Fix negative number literal typeannotations (#366) (Daniel Tschinder)
  118 +- Update contributing with more test info [skip ci] (#355) (Brian Ng)
  119 +
  120 +## 7.0.0-beta.0 (2017-02-15)
  121 +
  122 +- Reintroduce Variance node (#333) (Daniel Tschinder)
  123 +- Rename NumericLiteralTypeAnnotation to NumberLiteralTypeAnnotation (#332) (Charles Pick)
  124 +- [7.0] Remove ForAwaitStatement, add await flag to ForOfStatement (#349) (Brandon Dail)
  125 +- chore(package): update ava to version 0.18.0 (#345) (greenkeeper[bot])
  126 +- chore(package): update babel-plugin-istanbul to version 4.0.0 (#350) (greenkeeper[bot])
  127 +- Change location of ObjectTypeIndexer to match flow (#228) (Daniel Tschinder)
  128 +- Rename flow AST Type ExistentialTypeParam to ExistsTypeAnnotation (#322) (Toru Kobayashi)
  129 +- Revert "Temporary rollback for erroring on trailing comma with spread (#154)" (#290) (Daniel Tschinder)
  130 +- Remove classConstructorCall plugin (#291) (Brian Ng)
  131 +- Update yarn.lock (Daniel Tschinder)
  132 +- Update cross-env to 3.x (Daniel Tschinder)
  133 +- [7.0] Remove node 0.10, 0.12 and 5 from Travis (#284) (Sergey Rubanov)
  134 +- Remove `String.fromCodePoint` shim (#279) (Mathias Bynens)
  135 +
  136 +## 6.16.1 (2017-02-23)
  137 +
  138 +### :bug: Regression
  139 +
  140 +- Revert "Fix export default async function to be FunctionDeclaration" ([#375](https://github.com/babel/babylon/pull/375))
  141 +
  142 +Need to modify Babel for this AST node change, so moving to 7.0.
  143 +
  144 +- Revert "Don't parse class properties without initializers when classProperties plugin is disabled, and Flow is enabled" ([#376](https://github.com/babel/babylon/pull/376))
  145 +
  146 +[react-native](https://github.com/facebook/react-native/issues/12542) broke with this so we reverted.
  147 +
  148 +## 6.16.0 (2017-02-23)
  149 +
  150 +### :rocket: New Feature
  151 +
  152 +***ESTree*** compatibility as plugin ([#277](https://github.com/babel/babylon/pull/277)) (Daniel Tschinder)
  153 +
  154 +We finally introduce a new compatibility layer for ESTree. To put babylon into ESTree-compatible mode the new plugin `estree` can be enabled. In this mode the parser will output an AST that is compliant to the specs of [ESTree](https://github.com/estree/estree/)
  155 +
  156 +We highly recommend everyone who uses babylon outside of babel to use this plugin. This will make it much easier for users to switch between different ESTree-compatible parsers. We so far tested several projects with different parsers and exchanged their parser to babylon and in nearly all cases it worked out of the box. Some other estree-compatible parsers include `acorn`, `esprima`, `espree`, `flow-parser`, etc.
  157 +
  158 +To enable `estree` mode simply add the plugin in the config:
  159 +```json
  160 +{
  161 + "plugins": [ "estree" ]
  162 +}
  163 +```
  164 +
  165 +If you want to migrate your project from non-ESTree mode to ESTree, have a look at our [Readme](https://github.com/babel/babylon/#output), where all deviations are mentioned.
  166 +
  167 +Add a parseExpression public method ([#213](https://github.com/babel/babylon/pull/213)) (jeromew)
  168 +
  169 +Babylon exports a new function to parse a single expression
  170 +
  171 +```js
  172 +import { parseExpression } from 'babylon';
  173 +
  174 +const ast = parseExpression('x || y && z', options);
  175 +```
  176 +
  177 +The returned AST will only consist of the expression. The options are the same as for `parse()`
  178 +
  179 +Add startLine option ([#346](https://github.com/babel/babylon/pull/346)) (Raphael Mu)
  180 +
  181 +A new option was added to babylon allowing to change the intial linenumber for the first line which is usually `1`.
  182 +Changing this for example to `100` will make line `1` of the input source to be marked as line `100`, line `2` as `101`, line `3` as `102`, ...
  183 +
  184 +Function predicate declaration ([#103](https://github.com/babel/babylon/pull/103)) (Panagiotis Vekris)
  185 +
  186 +Added support for function predicates which flow introduced in version 0.33.0
  187 +
  188 +```js
  189 +declare function is_number(x: mixed): boolean %checks(typeof x === "number");
  190 +```
  191 +
  192 +Allow imports in declare module ([#315](https://github.com/babel/babylon/pull/315)) (Daniel Tschinder)
  193 +
  194 +Added support for imports within module declarations which flow introduced in version 0.37.0
  195 +
  196 +```js
  197 +declare module "C" {
  198 + import type { DT } from "D";
  199 + declare export type CT = { D: DT };
  200 +}
  201 +```
  202 +
  203 +### :eyeglasses: Spec Compliancy
  204 +
  205 +Forbid semicolons after decorators in classes ([#352](https://github.com/babel/babylon/pull/352)) (Kevin Gibbons)
  206 +
  207 +This example now correctly throws an error when there is a semicolon after the decorator:
  208 +
  209 +```js
  210 +class A {
  211 +@a;
  212 +foo(){}
  213 +}
  214 +```
  215 +
  216 +Keywords are not allowed as local specifier ([#307](https://github.com/babel/babylon/pull/307)) (Daniel Tschinder)
  217 +
  218 +Using keywords in imports is not allowed anymore:
  219 +
  220 +```js
  221 +import { default } from "foo";
  222 +import { a as debugger } from "foo";
  223 +```
  224 +
  225 +Do not allow overwritting of primitive types ([#314](https://github.com/babel/babylon/pull/314)) (Daniel Tschinder)
  226 +
  227 +In flow it is now forbidden to overwrite the primitve types `"any"`, `"mixed"`, `"empty"`, `"bool"`, `"boolean"`, `"number"`, `"string"`, `"void"` and `"null"` with your own type declaration.
  228 +
  229 +Disallow import type { type a } from … ([#305](https://github.com/babel/babylon/pull/305)) (Daniel Tschinder)
  230 +
  231 +The following code now correctly throws an error
  232 +
  233 +```js
  234 +import type { type a } from "foo";
  235 +```
  236 +
  237 +Don't parse class properties without initializers when classProperties is disabled and Flow is enabled ([#300](https://github.com/babel/babylon/pull/300)) (Andrew Levine)
  238 +
  239 +Ensure that you enable the `classProperties` plugin in order to enable correct parsing of class properties. Prior to this version it was possible to parse them by enabling the `flow` plugin but this was not intended the behaviour.
  240 +
  241 +If you enable the flow plugin you can only define the type of the class properties, but not initialize them.
  242 +
  243 +Fix export default async function to be FunctionDeclaration ([#324](https://github.com/babel/babylon/pull/324)) (Daniel Tschinder)
  244 +
  245 +Parsing the following code now returns a `FunctionDeclaration` AST node instead of `FunctionExpression`.
  246 +
  247 +```js
  248 +export default async function bar() {};
  249 +```
  250 +
  251 +### :nail_care: Polish
  252 +
  253 +Improve error message on attempt to destructure named import ([#288](https://github.com/babel/babylon/pull/288)) (Brian Ng)
  254 +
  255 +### :bug: Bug Fix
  256 +
  257 +Fix negative number literal typeannotations ([#366](https://github.com/babel/babylon/pull/366)) (Daniel Tschinder)
  258 +
  259 +Ensure takeDecorators is called on exported class ([#358](https://github.com/babel/babylon/pull/358)) (Brian Ng)
  260 +
  261 +ESTree: correctly change literals in all cases ([#368](https://github.com/babel/babylon/pull/368)) (Daniel Tschinder)
  262 +
  263 +Correctly convert RestProperty to Assignable ([#339](https://github.com/babel/babylon/pull/339)) (Daniel Tschinder)
  264 +
  265 +Fix #321 by allowing question marks in type params ([#338](https://github.com/babel/babylon/pull/338)) (Daniel Tschinder)
  266 +
  267 +Fix #336 by correctly setting arrow-param ([#337](https://github.com/babel/babylon/pull/337)) (Daniel Tschinder)
  268 +
  269 +Fix parse error when destructuring `set` with default value ([#317](https://github.com/babel/babylon/pull/317)) (Brian Ng)
  270 +
  271 +Fix ObjectTypeCallProperty static ([#298](https://github.com/babel/babylon/pull/298)) (Dan Harper)
  272 +
  273 +
  274 +### :house: Internal
  275 +
  276 +Fix generator-method-with-computed-name spec ([#360](https://github.com/babel/babylon/pull/360)) (Alex Rattray)
  277 +
  278 +Fix flow type-parameter-declaration test with unintended semantic ([#361](https://github.com/babel/babylon/pull/361)) (Alex Rattray)
  279 +
  280 +Cleanup and splitup parser functions ([#295](https://github.com/babel/babylon/pull/295)) (Daniel Tschinder)
  281 +
  282 +chore(package): update flow-bin to version 0.38.0 ([#313](https://github.com/babel/babylon/pull/313)) (greenkeeper[bot])
  283 +
  284 +Call inner function instead of 1:1 copy to plugin ([#294](https://github.com/babel/babylon/pull/294)) (Daniel Tschinder)
  285 +
  286 +Update eslint-config-babel to the latest version 🚀 ([#299](https://github.com/babel/babylon/pull/299)) (greenkeeper[bot])
  287 +
  288 +Update eslint-config-babel to the latest version 🚀 ([#293](https://github.com/babel/babylon/pull/293)) (greenkeeper[bot])
  289 +
  290 +devDeps: remove eslint-plugin-babel ([#292](https://github.com/babel/babylon/pull/292)) (Kai Cataldo)
  291 +
  292 +Correct indent eslint rule config ([#276](https://github.com/babel/babylon/pull/276)) (Daniel Tschinder)
  293 +
  294 +Fail tests that have expected.json and throws-option ([#285](https://github.com/babel/babylon/pull/285)) (Daniel Tschinder)
  295 +
  296 +### :memo: Documentation
  297 +
  298 +Update contributing with more test info [skip ci] ([#355](https://github.com/babel/babylon/pull/355)) (Brian Ng)
  299 +
  300 +Update API documentation ([#330](https://github.com/babel/babylon/pull/330)) (Timothy Gu)
  301 +
  302 +Added keywords to package.json ([#323](https://github.com/babel/babylon/pull/323)) (Dmytro)
  303 +
  304 +AST spec: fix casing of `RegExpLiteral` ([#318](https://github.com/babel/babylon/pull/318)) (Mathias Bynens)
  305 +
  306 +## 6.15.0 (2017-01-10)
  307 +
  308 +### :eyeglasses: Spec Compliancy
  309 +
  310 +Add support for Flow shorthand import type ([#267](https://github.com/babel/babylon/pull/267)) (Jeff Morrison)
  311 +
  312 +This change implements flows new shorthand import syntax
  313 +and where previously you had to write this code:
  314 +
  315 +```js
  316 +import {someValue} from "blah";
  317 +import type {someType} from "blah";
  318 +import typeof {someOtherValue} from "blah";
  319 +```
  320 +
  321 +you can now write it like this:
  322 +
  323 +```js
  324 +import {
  325 + someValue,
  326 + type someType,
  327 + typeof someOtherValue,
  328 +} from "blah";
  329 +```
  330 +
  331 +For more information look at [this](https://github.com/facebook/flow/pull/2890) pull request.
  332 +
  333 +flow: allow leading pipes in all positions ([#256](https://github.com/babel/babylon/pull/256)) (Vladimir Kurchatkin)
  334 +
  335 +This change now allows a leading pipe everywhere types can be used:
  336 +```js
  337 +var f = (x): | 1 | 2 => 1;
  338 +```
  339 +
  340 +Throw error when exporting non-declaration ([#241](https://github.com/babel/babylon/pull/241)) (Kai Cataldo)
  341 +
  342 +Previously babylon parsed the following exports, although they are not valid:
  343 +```js
  344 +export typeof foo;
  345 +export new Foo();
  346 +export function() {};
  347 +export for (;;);
  348 +export while(foo);
  349 +```
  350 +
  351 +### :bug: Bug Fix
  352 +
  353 +Don't set inType flag when parsing property names ([#266](https://github.com/babel/babylon/pull/266)) (Vladimir Kurchatkin)
  354 +
  355 +This fixes parsing of this case:
  356 +
  357 +```js
  358 +const map = {
  359 + [age <= 17] : 'Too young'
  360 +};
  361 +```
  362 +
  363 +Fix source location for JSXEmptyExpression nodes (fixes #248) ([#249](https://github.com/babel/babylon/pull/249)) (James Long)
  364 +
  365 +The following case produced an invalid AST
  366 +```js
  367 +<div>{/* foo */}</div>
  368 +```
  369 +
  370 +Use fromCodePoint to convert high value unicode entities ([#243](https://github.com/babel/babylon/pull/243)) (Ryan Duffy)
  371 +
  372 +When high value unicode entities (e.g. 💩) were used in the input source code they are now correctly encoded in the resulting AST.
  373 +
  374 +Rename folder to avoid Windows-illegal characters ([#281](https://github.com/babel/babylon/pull/281)) (Ryan Plant)
  375 +
  376 +Allow this.state.clone() when parsing decorators ([#262](https://github.com/babel/babylon/pull/262)) (Alex Rattray)
  377 +
  378 +### :house: Internal
  379 +
  380 +User external-helpers ([#254](https://github.com/babel/babylon/pull/254)) (Daniel Tschinder)
  381 +
  382 +Add watch script for dev ([#234](https://github.com/babel/babylon/pull/234)) (Kai Cataldo)
  383 +
  384 +Freeze current plugins list for "*" option, and remove from README.md ([#245](https://github.com/babel/babylon/pull/245)) (Andrew Levine)
  385 +
  386 +Prepare tests for multiple fixture runners. ([#240](https://github.com/babel/babylon/pull/240)) (Daniel Tschinder)
  387 +
  388 +Add some test coverage for decorators stage-0 plugin ([#250](https://github.com/babel/babylon/pull/250)) (Andrew Levine)
  389 +
  390 +Refactor tokenizer types file ([#263](https://github.com/babel/babylon/pull/263)) (Sven SAULEAU)
  391 +
  392 +Update eslint-config-babel to the latest version 🚀 ([#273](https://github.com/babel/babylon/pull/273)) (greenkeeper[bot])
  393 +
  394 +chore(package): update rollup to version 0.41.0 ([#272](https://github.com/babel/babylon/pull/272)) (greenkeeper[bot])
  395 +
  396 +chore(package): update flow-bin to version 0.37.0 ([#255](https://github.com/babel/babylon/pull/255)) (greenkeeper[bot])
  397 +
  398 +## 6.14.1 (2016-11-17)
  399 +
  400 +### :bug: Bug Fix
  401 +
  402 +Allow `"plugins": ["*"]` ([#229](https://github.com/babel/babylon/pull/229)) (Daniel Tschinder)
  403 +
  404 +```js
  405 +{
  406 + "plugins": ["*"]
  407 +}
  408 +```
  409 +
  410 +Will include all parser plugins instead of specifying each one individually. Useful for tools like babel-eslint, jscodeshift, and ast-explorer.
  411 +
  412 +## 6.14.0 (2016-11-16)
  413 +
  414 +### :eyeglasses: Spec Compliancy
  415 +
  416 +Throw error for reserved words `enum` and `await` ([#195](https://github.com/babel/babylon/pull/195)) (Kai Cataldo)
  417 +
  418 +[11.6.2.2 Future Reserved Words](http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words)
  419 +
  420 +Babylon will throw for more reserved words such as `enum` or `await` (in strict mode).
  421 +
  422 +```
  423 +class enum {} // throws
  424 +class await {} // throws in strict mode (module)
  425 +```
  426 +
  427 +Optional names for function types and object type indexers ([#197](https://github.com/babel/babylon/pull/197)) (Gabe Levi)
  428 +
  429 +So where you used to have to write
  430 +
  431 +```js
  432 +type A = (x: string, y: boolean) => number;
  433 +type B = (z: string) => number;
  434 +type C = { [key: string]: number };
  435 +```
  436 +
  437 +you can now write (with flow 0.34.0)
  438 +
  439 +```js
  440 +type A = (string, boolean) => number;
  441 +type B = string => number;
  442 +type C = { [string]: number };
  443 +```
  444 +
  445 +Parse flow nested array type annotations like `number[][]` ([#219](https://github.com/babel/babylon/pull/219)) (Bernhard Häussner)
  446 +
  447 +Supports these form now of specifying array types:
  448 +
  449 +```js
  450 +var a: number[][][][];
  451 +var b: string[][];
  452 +```
  453 +
  454 +### :bug: Bug Fix
  455 +
  456 +Correctly eat semicolon at the end of `DelcareModuleExports` ([#223](https://github.com/babel/babylon/pull/223)) (Daniel Tschinder)
  457 +
  458 +```
  459 +declare module "foo" { declare module.exports: number }
  460 +declare module "foo" { declare module.exports: number; } // also allowed now
  461 +```
  462 +
  463 +### :house: Internal
  464 +
  465 + * Count Babel tests towards Babylon code coverage ([#182](https://github.com/babel/babylon/pull/182)) (Moti Zilberman)
  466 + * Fix strange line endings ([#214](https://github.com/babel/babylon/pull/214)) (Thomas Grainger)
  467 + * Add node 7 (Daniel Tschinder)
  468 + * chore(package): update flow-bin to version 0.34.0 ([#204](https://github.com/babel/babylon/pull/204)) (Greenkeeper)
  469 +
  470 +## v6.13.1 (2016-10-26)
  471 +
  472 +### :nail_care: Polish
  473 +
  474 +- Use rollup for bundling to speed up startup time ([#190](https://github.com/babel/babylon/pull/190)) ([@drewml](https://github.com/DrewML))
  475 +
  476 +```js
  477 +const babylon = require('babylon');
  478 +const ast = babylon.parse('var foo = "lol";');
  479 +```
  480 +
  481 +With that test case, there was a ~95ms savings by removing the need for node to build/traverse the dependency graph.
  482 +
  483 +**Without bundling**
  484 +![image](https://cloud.githubusercontent.com/assets/5233399/19420264/3133497e-93ad-11e6-9a6a-2da59c4f5c13.png)
  485 +
  486 +**With bundling**
  487 +![image](https://cloud.githubusercontent.com/assets/5233399/19420267/388f556e-93ad-11e6-813e-7c5c396be322.png)
  488 +
  489 +- add clean command [skip ci] ([#201](https://github.com/babel/babylon/pull/201)) (Henry Zhu)
  490 +- add ForAwaitStatement (async generator already added) [skip ci] ([#196](https://github.com/babel/babylon/pull/196)) (Henry Zhu)
  491 +
  492 +## v6.13.0 (2016-10-21)
  493 +
  494 +### :eyeglasses: Spec Compliancy
  495 +
  496 +Property variance type annotations for Flow plugin ([#161](https://github.com/babel/babylon/pull/161)) (Sam Goldman)
  497 +
  498 +> See https://flowtype.org/docs/variance.html for more information
  499 +
  500 +```js
  501 +type T = { +p: T };
  502 +interface T { -p: T };
  503 +declare class T { +[k:K]: V };
  504 +class T { -[k:K]: V };
  505 +class C2 { +p: T = e };
  506 +```
  507 +
  508 +Raise error on duplicate definition of __proto__ ([#183](https://github.com/babel/babylon/pull/183)) (Moti Zilberman)
  509 +
  510 +```js
  511 +({ __proto__: 1, __proto__: 2 }) // Throws an error now
  512 +```
  513 +
  514 +### :bug: Bug Fix
  515 +
  516 +Flow: Allow class properties to be named `static` ([#184](https://github.com/babel/babylon/pull/184)) (Moti Zilberman)
  517 +
  518 +```js
  519 +declare class A {
  520 + static: T;
  521 +}
  522 +```
  523 +
  524 +Allow "async" as identifier for object literal property shorthand ([#187](https://github.com/babel/babylon/pull/187)) (Andrew Levine)
  525 +
  526 +```js
  527 +var foo = { async, bar };
  528 +```
  529 +
  530 +### :nail_care: Polish
  531 +
  532 +Fix flowtype and add inType to state ([#189](https://github.com/babel/babylon/pull/189)) (Daniel Tschinder)
  533 +
  534 +> This improves the performance slightly (because of hidden classes)
  535 +
  536 +### :house: Internal
  537 +
  538 +Fix .gitattributes line ending setting ([#191](https://github.com/babel/babylon/pull/191)) (Moti Zilberman)
  539 +
  540 +Increase test coverage ([#175](https://github.com/babel/babylon/pull/175) (Moti Zilberman)
  541 +
  542 +Readd missin .eslinignore for IDEs (Daniel Tschinder)
  543 +
  544 +Error on missing expected.json fixture in CI ([#188](https://github.com/babel/babylon/pull/188)) (Moti Zilberman)
  545 +
  546 +Add .gitattributes and .editorconfig for LF line endings ([#179](https://github.com/babel/babylon/pull/179)) (Moti Zilberman)
  547 +
  548 +Fixes two tests that are failing after the merge of #172 ([#177](https://github.com/babel/babylon/pull/177)) (Moti Zilberman)
  549 +
  550 +## v6.12.0 (2016-10-14)
  551 +
  552 +### :eyeglasses: Spec Compliancy
  553 +
  554 +Implement import() syntax ([#163](https://github.com/babel/babylon/pull/163)) (Jordan Gensler)
  555 +
  556 +#### Dynamic Import
  557 +
  558 +- Proposal Repo: https://github.com/domenic/proposal-dynamic-import
  559 +- Championed by [@domenic](https://github.com/domenic)
  560 +- stage-2
  561 +- [sept-28 tc39 notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2016-09/sept-28.md#113a-import)
  562 +
  563 +> This repository contains a proposal for adding a "function-like" import() module loading syntactic form to JavaScript
  564 +
  565 +```js
  566 +import(`./section-modules/${link.dataset.entryModule}.js`)
  567 +.then(module => {
  568 + module.loadPageInto(main);
  569 +})
  570 +```
  571 +
  572 +Add EmptyTypeAnnotation ([#171](https://github.com/babel/babylon/pull/171)) (Sam Goldman)
  573 +
  574 +#### EmptyTypeAnnotation
  575 +
  576 +Just wasn't covered before.
  577 +
  578 +```js
  579 +type T = empty;
  580 +```
  581 +
  582 +### :bug: Bug Fix
  583 +
  584 +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels)
  585 +
  586 +```js
  587 +// was failing due to sparse array
  588 +export const { foo: [ ,, qux7 ] } = bar;
  589 +```
  590 +
  591 +Allow keyword in Flow object declaration property names with type parameters ([#146](https://github.com/babel/babylon/pull/146)) (Dan Harper)
  592 +
  593 +```js
  594 +declare class X {
  595 + foobar<T>(): void;
  596 + static foobar<T>(): void;
  597 +}
  598 +```
  599 +
  600 +Allow keyword in object/class property names with Flow type parameters ([#145](https://github.com/babel/babylon/pull/145)) (Dan Harper)
  601 +
  602 +```js
  603 +class Foo {
  604 + delete<T>(item: T): T {
  605 + return item;
  606 + }
  607 +}
  608 +```
  609 +
  610 +Allow typeAnnotations for yield expressions ([#174](https://github.com/babel/babylon/pull/174))) (Daniel Tschinder)
  611 +
  612 +```js
  613 +function *foo() {
  614 + const x = (yield 5: any);
  615 +}
  616 +```
  617 +
  618 +### :nail_care: Polish
  619 +
  620 +Annotate more errors with expected token ([#172](https://github.com/babel/babylon/pull/172))) (Moti Zilberman)
  621 +
  622 +```js
  623 +// Unexpected token, expected ; (1:6)
  624 +{ set 1 }
  625 +```
  626 +
  627 +### :house: Internal
  628 +
  629 +Remove kcheck ([#173](https://github.com/babel/babylon/pull/173))) (Daniel Tschinder)
  630 +
  631 +Also run flow, linting, babel tests on seperate instances (add back node 0.10)
  632 +
  633 +## v6.11.6 (2016-10-12)
  634 +
  635 +### :bug: Bug Fix/Regression
  636 +
  637 +Fix crash when exporting with destructuring and sparse array ([#170](https://github.com/babel/babylon/pull/170)) (Jeroen Engels)
  638 +
  639 +```js
  640 +// was failing with `Cannot read property 'type' of null` because of null identifiers
  641 +export const { foo: [ ,, qux7 ] } = bar;
  642 +```
  643 +
  644 +## v6.11.5 (2016-10-12)
  645 +
  646 +### :eyeglasses: Spec Compliancy
  647 +
  648 +Fix: Check for duplicate named exports in exported destructuring assignments ([#144](https://github.com/babel/babylon/pull/144)) (Kai Cataldo)
  649 +
  650 +```js
  651 +// `foo` has already been exported. Exported identifiers must be unique. (2:20)
  652 +export function foo() {};
  653 +export const { a: [{foo}] } = bar;
  654 +```
  655 +
  656 +Fix: Check for duplicate named exports in exported rest elements/properties ([#164](https://github.com/babel/babylon/pull/164)) (Kai Cataldo)
  657 +
  658 +```js
  659 +// `foo` has already been exported. Exported identifiers must be unique. (2:22)
  660 +export const foo = 1;
  661 +export const [bar, ...foo] = baz;
  662 +```
  663 +
  664 +### :bug: Bug Fix
  665 +
  666 +Fix: Allow identifier `async` for default param in arrow expression ([#165](https://github.com/babel/babylon/pull/165)) (Kai Cataldo)
  667 +
  668 +```js
  669 +// this is ok now
  670 +const test = ({async = true}) => {};
  671 +```
  672 +
  673 +### :nail_care: Polish
  674 +
  675 +Babylon will now print out the token it's expecting if there's a `SyntaxError` ([#150](https://github.com/babel/babylon/pull/150)) (Daniel Tschinder)
  676 +
  677 +```bash
  678 +# So in the case of a missing ending curly (`}`)
  679 +Module build failed: SyntaxError: Unexpected token, expected } (30:0)
  680 + 28 | }
  681 + 29 |
  682 +> 30 |
  683 + | ^
  684 +```
  685 +
  686 +## v6.11.4 (2016-10-03)
  687 +
  688 +Temporary rollback for erroring on trailing comma with spread (#154) (Henry Zhu)
  689 +
  690 +## v6.11.3 (2016-10-01)
  691 +
  692 +### :eyeglasses: Spec Compliancy
  693 +
  694 +Add static errors for object rest (#149) ([@danez](https://github.com/danez))
  695 +
  696 +> https://github.com/sebmarkbage/ecmascript-rest-spread
  697 +
  698 +Object rest copies the *rest* of properties from the right hand side `obj` starting from the left to right.
  699 +
  700 +```js
  701 +let { x, y, ...z } = { x: 1, y: 2, z: 3 };
  702 +// x = 1
  703 +// y = 2
  704 +// z = { z: 3 }
  705 +```
  706 +
  707 +#### New Syntax Errors:
  708 +
  709 +**SyntaxError**: The rest element has to be the last element when destructuring (1:10)
  710 +```bash
  711 +> 1 | let { ...x, y, z } = { x: 1, y: 2, z: 3};
  712 + | ^
  713 +# Previous behavior:
  714 +# x = { x: 1, y: 2, z: 3 }
  715 +# y = 2
  716 +# z = 3
  717 +```
  718 +
  719 +Before, this was just a more verbose way of shallow copying `obj` since it doesn't actually do what you think.
  720 +
  721 +**SyntaxError**: Cannot have multiple rest elements when destructuring (1:13)
  722 +
  723 +```bash
  724 +> 1 | let { x, ...y, ...z } = { x: 1, y: 2, z: 3};
  725 + | ^
  726 +# Previous behavior:
  727 +# x = 1
  728 +# y = { y: 2, z: 3 }
  729 +# z = { y: 2, z: 3 }
  730 +```
  731 +
  732 +Before y and z would just be the same value anyway so there is no reason to need to have both.
  733 +
  734 +**SyntaxError**: A trailing comma is not permitted after the rest element (1:16)
  735 +
  736 +```js
  737 +let { x, y, ...z, } = obj;
  738 +```
  739 +
  740 +The rationale for this is that the use case for trailing comma is that you can add something at the end without affecting the line above. Since a RestProperty always has to be the last property it doesn't make sense.
  741 +
  742 +---
  743 +
  744 +get / set are valid property names in default assignment (#142) ([@jezell](https://github.com/jezell))
  745 +
  746 +```js
  747 +// valid
  748 +function something({ set = null, get = null }) {}
  749 +```
  750 +
  751 +## v6.11.2 (2016-09-23)
  752 +
  753 +### Bug Fix
  754 +
  755 +- [#139](https://github.com/babel/babylon/issues/139) Don't do the duplicate check if not an identifier (#140) @hzoo
  756 +
  757 +```js
  758 +// regression with duplicate export check
  759 +SyntaxError: ./typography.js: `undefined` has already been exported. Exported identifiers must be unique. (22:13)
  760 + 20 |
  761 + 21 | export const { rhythm } = typography;
  762 +> 22 | export const { TypographyStyle } = typography
  763 +```
  764 +
  765 +Bail out for now, and make a change to account for destructuring in the next release.
  766 +
  767 +## 6.11.1 (2016-09-22)
  768 +
  769 +### Bug Fix
  770 +- [#137](https://github.com/babel/babylon/pull/137) - Fix a regression with duplicate exports - it was erroring on all keys in `Object.prototype`. @danez
  771 +
  772 +```javascript
  773 +export toString from './toString';
  774 +```
  775 +
  776 +```bash
  777 +`toString` has already been exported. Exported identifiers must be unique. (1:7)
  778 +> 1 | export toString from './toString';
  779 + | ^
  780 + 2 |
  781 +```
  782 +
  783 +## 6.11.0 (2016-09-22)
  784 +
  785 +### Spec Compliancy (will break CI)
  786 +
  787 +- Disallow duplicate named exports ([#107](https://github.com/babel/babylon/pull/107)) @kaicataldo
  788 +
  789 +```js
  790 +// Only one default export allowed per module. (2:9)
  791 +export default function() {};
  792 +export { foo as default };
  793 +
  794 +// Only one default export allowed per module. (2:0)
  795 +export default {};
  796 +export default function() {};
  797 +
  798 +// `Foo` has already been exported. Exported identifiers must be unique. (2:0)
  799 +export { Foo };
  800 +export class Foo {};
  801 +```
  802 +
  803 +### New Feature (Syntax)
  804 +
  805 +- Add support for computed class property names ([#121](https://github.com/babel/babylon/pull/121)) @motiz88
  806 +
  807 +```js
  808 +// AST
  809 +interface ClassProperty <: Node {
  810 + type: "ClassProperty";
  811 + key: Identifier;
  812 + value: Expression;
  813 + computed: boolean; // added
  814 +}
  815 +```
  816 +
  817 +```js
  818 +// with "plugins": ["classProperties"]
  819 +class Foo {
  820 + [x]
  821 + ['y']
  822 +}
  823 +
  824 +class Bar {
  825 + [p]
  826 + [m] () {}
  827 +}
  828 + ```
  829 +
  830 +### Bug Fix
  831 +
  832 +- Fix `static` property falling through in the declare class Flow AST ([#135](https://github.com/babel/babylon/pull/135)) @danharper
  833 +
  834 +```js
  835 +declare class X {
  836 + a: number;
  837 + static b: number; // static
  838 + c: number; // this was being marked as static in the AST as well
  839 +}
  840 +```
  841 +
  842 +### Polish
  843 +
  844 +- Rephrase "assigning/binding to rvalue" errors to include context ([#119](https://github.com/babel/babylon/pull/119)) @motiz88
  845 +
  846 +```js
  847 +// Used to error with:
  848 +// SyntaxError: Assigning to rvalue (1:0)
  849 +
  850 +// Now:
  851 +// Invalid left-hand side in assignment expression (1:0)
  852 +3 = 4
  853 +
  854 +// Invalid left-hand side in for-in statement (1:5)
  855 +for (+i in {});
  856 +```
  857 +
  858 +### Internal
  859 +
  860 +- Fix call to `this.parseMaybeAssign` with correct arguments ([#133](https://github.com/babel/babylon/pull/133)) @danez
  861 +- Add semver note to changelog ([#131](https://github.com/babel/babylon/pull/131)) @hzoo
  862 +
  863 +## 6.10.0 (2016-09-19)
  864 +
  865 +> We plan to include some spec compliancy bugs in patch versions. An example was the multiple default exports issue.
  866 +
  867 +### Spec Compliancy
  868 +
  869 +* Implement ES2016 check for simple parameter list in strict mode ([#106](https://github.com/babel/babylon/pull/106)) (Timothy Gu)
  870 +
  871 +> It is a Syntax Error if ContainsUseStrict of FunctionBody is true and IsSimpleParameterList of FormalParameters is false. https://tc39.github.io/ecma262/2016/#sec-function-definitions-static-semantics-early-errors
  872 +
  873 +More Context: [tc39-notes](https://github.com/rwaldron/tc39-notes/blob/master/es7/2015-07/july-29.md#611-the-scope-of-use-strict-with-respect-to-destructuring-in-parameter-lists)
  874 +
  875 +For example:
  876 +
  877 +```js
  878 +// this errors because it uses destructuring and default parameters
  879 +// in a function with a "use strict" directive
  880 +function a([ option1, option2 ] = []) {
  881 + "use strict";
  882 +}
  883 + ```
  884 +
  885 +The solution would be to use a top level "use strict" or to remove the destructuring or default parameters when using a function + "use strict" or to.
  886 +
  887 +### New Feature
  888 +
  889 +* Exact object type annotations for Flow plugin ([#104](https://github.com/babel/babylon/pull/104)) (Basil Hosmer)
  890 +
  891 +Added to flow in https://github.com/facebook/flow/commit/c710c40aa2a115435098d6c0dfeaadb023cd39b8
  892 +
  893 +Looks like:
  894 +
  895 +```js
  896 +var a : {| x: number, y: string |} = { x: 0, y: 'foo' };
  897 +```
  898 +
  899 +### Bug Fixes
  900 +
  901 +* Include `typeParameter` location in `ArrowFunctionExpression` ([#126](https://github.com/babel/babylon/pull/126)) (Daniel Tschinder)
  902 +* Error on invalid flow type annotation with default assignment ([#122](https://github.com/babel/babylon/pull/122)) (Dan Harper)
  903 +* Fix Flow return types on arrow functions ([#124](https://github.com/babel/babylon/pull/124)) (Dan Harper)
  904 +
  905 +### Misc
  906 +
  907 +* Add tests for export extensions ([#127](https://github.com/babel/babylon/pull/127)) (Daniel Tschinder)
  908 +* Fix Contributing guidelines [skip ci] (Daniel Tschinder)
  909 +
  910 +## 6.9.2 (2016-09-09)
  911 +
  912 +The only change is to remove the `babel-runtime` dependency by compiling with Babel's ES2015 loose mode. So using babylon standalone should be smaller.
  913 +
  914 +## 6.9.1 (2016-08-23)
  915 +
  916 +This release contains mainly small bugfixes but also updates babylons default mode to es2017. The features for `exponentiationOperator`, `asyncFunctions` and `trailingFunctionCommas` which previously needed to be activated via plugin are now enabled by default and the plugins are now no-ops.
  917 +
  918 +### Bug Fixes
  919 +
  920 +- Fix issues with default object params in async functions ([#96](https://github.com/babel/babylon/pull/96)) @danez
  921 +- Fix issues with flow-types and async function ([#95](https://github.com/babel/babylon/pull/95)) @danez
  922 +- Fix arrow functions with destructuring, types & default value ([#94](https://github.com/babel/babylon/pull/94)) @danharper
  923 +- Fix declare class with qualified type identifier ([#97](https://github.com/babel/babylon/pull/97)) @danez
  924 +- Remove exponentiationOperator, asyncFunctions, trailingFunctionCommas plugins and enable them by default ([#98](https://github.com/babel/babylon/pull/98)) @danez
  925 +
  926 +## 6.9.0 (2016-08-16)
  927 +
  928 +### New syntax support
  929 +
  930 +- Add JSX spread children ([#42](https://github.com/babel/babylon/pull/42)) @calebmer
  931 +
  932 +(Be aware that React is not going to support this syntax)
  933 +
  934 +```js
  935 +<div>
  936 + {...todos.map(todo => <Todo key={todo.id} todo={todo}/>)}
  937 +</div>
  938 +```
  939 +
  940 +- Add support for declare module.exports ([#72](https://github.com/babel/babylon/pull/72)) @danez
  941 +
  942 +```js
  943 +declare module "foo" {
  944 + declare module.exports: {}
  945 +}
  946 +```
  947 +
  948 +### New Features
  949 +
  950 +- If supplied, attach filename property to comment node loc. ([#80](https://github.com/babel/babylon/pull/80)) @divmain
  951 +- Add identifier name to node loc field ([#90](https://github.com/babel/babylon/pull/90)) @kittens
  952 +
  953 +### Bug Fixes
  954 +
  955 +- Fix exponential operator to behave according to spec ([#75](https://github.com/babel/babylon/pull/75)) @danez
  956 +- Fix lookahead to not add comments to arrays which are not cloned ([#76](https://github.com/babel/babylon/pull/76)) @danez
  957 +- Fix accidental fall-through in Flow type parsing. ([#82](https://github.com/babel/babylon/pull/82)) @xiemaisi
  958 +- Only allow declares inside declare module ([#73](https://github.com/babel/babylon/pull/73)) @danez
  959 +- Small fix for parsing type parameter declarations ([#83](https://github.com/babel/babylon/pull/83)) @gabelevi
  960 +- Fix arrow param locations with flow types ([#57](https://github.com/babel/babylon/pull/57)) @danez
  961 +- Fixes SyntaxError position with flow optional type ([#65](https://github.com/babel/babylon/pull/65)) @danez
  962 +
  963 +### Internal
  964 +
  965 +- Add codecoverage to tests @danez
  966 +- Fix tests to not save expected output if we expect the test to fail @danez
  967 +- Make a shallow clone of babel for testing @danez
  968 +- chore(package): update cross-env to version 2.0.0 ([#77](https://github.com/babel/babylon/pull/77)) @greenkeeperio-bot
  969 +- chore(package): update ava to version 0.16.0 ([#86](https://github.com/babel/babylon/pull/86)) @greenkeeperio-bot
  970 +- chore(package): update babel-plugin-istanbul to version 2.0.0 ([#89](https://github.com/babel/babylon/pull/89)) @greenkeeperio-bot
  971 +- chore(package): update nyc to version 8.0.0 ([#88](https://github.com/babel/babylon/pull/88)) @greenkeeperio-bot
  972 +
  973 +## 6.8.4 (2016-07-06)
  974 +
  975 +### Bug Fixes
  976 +
  977 +- Fix the location of params, when flow and default value used ([#68](https://github.com/babel/babylon/pull/68)) @danez
  978 +
  979 +## 6.8.3 (2016-07-02)
  980 +
  981 +### Bug Fixes
  982 +
  983 +- Fix performance regression introduced in 6.8.2 with conditionals ([#63](https://github.com/babel/babylon/pull/63)) @danez
  984 +
  985 +## 6.8.2 (2016-06-24)
  986 +
  987 +### Bug Fixes
  988 +
  989 +- Fix parse error with yielding jsx elements in generators `function* it() { yield <a></a>; }` ([#31](https://github.com/babel/babylon/pull/31)) @eldereal
  990 +- When cloning nodes do not clone its comments ([#24](https://github.com/babel/babylon/pull/24)) @danez
  991 +- Fix parse errors when using arrow functions with an spread element and return type `(...props): void => {}` ([#10](https://github.com/babel/babylon/pull/10)) @danez
  992 +- Fix leading comments added from previous node ([#23](https://github.com/babel/babylon/pull/23)) @danez
  993 +- Fix parse errors with flow's optional arguments `(arg?) => {}` ([#19](https://github.com/babel/babylon/pull/19)) @danez
  994 +- Support negative numeric type literals @kittens
  995 +- Remove line terminator restriction after await keyword @kittens
  996 +- Remove grouped type arrow restriction as it seems flow no longer has it @kittens
  997 +- Fix parse error with generic methods that have the name `get` or `set` `class foo { get() {} }` ([#55](https://github.com/babel/babylon/pull/55)) @vkurchatkin
  998 +- Fix parse error with arrow functions that have flow type parameter declarations `<T>(x: T): T => x;` ([#54](https://github.com/babel/babylon/pull/54)) @gabelevi
  999 +
  1000 +### Documentation
  1001 +
  1002 +- Document AST differences from ESTree ([#41](https://github.com/babel/babylon/pull/41)) @nene
  1003 +- Move ast spec from babel/babel ([#46](https://github.com/babel/babylon/pull/46)) @hzoo
  1004 +
  1005 +### Internal
  1006 +
  1007 +- Enable skipped tests ([#16](https://github.com/babel/babylon/pull/16)) @danez
  1008 +- Add script to test latest version of babylon with babel ([#21](https://github.com/babel/babylon/pull/21)) @danez
  1009 +- Upgrade test runner ava @kittens
  1010 +- Add missing generate-identifier-regex script @kittens
  1011 +- Rename parser context types @kittens
  1012 +- Add node v6 to travis testing @hzoo
  1013 +- Update to Unicode v9 ([#45](https://github.com/babel/babylon/pull/45)) @mathiasbynens
  1014 +
  1015 +## 6.8.1 (2016-06-06)
  1016 +
  1017 +### New Feature
  1018 +
  1019 +- Parse type parameter declarations with defaults like `type Foo<T = string> = T`
  1020 +
  1021 +### Bug Fixes
  1022 +- Type parameter declarations need 1 or more type parameters.
  1023 +- The existential type `*` is not a valid type parameter.
  1024 +- The existential type `*` is a primary type
  1025 +
  1026 +### Spec Compliancy
  1027 +- The param list for type parameter declarations now consists of `TypeParameter` nodes
  1028 +- New `TypeParameter` AST Node (replaces using the `Identifier` node before)
  1029 +
  1030 +```
  1031 +interface TypeParameter <: Node {
  1032 + bound: TypeAnnotation;
  1033 + default: TypeAnnotation;
  1034 + name: string;
  1035 + variance: "plus" | "minus";
  1036 +}
  1037 +```
  1038 +
  1039 +## 6.8.0 (2016-05-02)
  1040 +
  1041 +#### New Feature
  1042 +
  1043 +##### Parse Method Parameter Decorators ([#12](https://github.com/babel/babylon/pull/12))
  1044 +
  1045 +> [Method Parameter Decorators](https://goo.gl/8MmCMG) is now a TC39 [stage 0 proposal](https://github.com/tc39/ecma262/blob/master/stage0.md).
  1046 +
  1047 +Examples:
  1048 +
  1049 +```js
  1050 +class Foo {
  1051 + constructor(@foo() x, @bar({ a: 123 }) @baz() y) {}
  1052 +}
  1053 +
  1054 +export default function func(@foo() x, @bar({ a: 123 }) @baz() y) {}
  1055 +
  1056 +var obj = {
  1057 + method(@foo() x, @bar({ a: 123 }) @baz() y) {}
  1058 +};
  1059 +```
  1060 +
  1061 +##### Parse for-await statements (w/ `asyncGenerators` plugin) ([#17](https://github.com/babel/babylon/pull/17))
  1062 +
  1063 +There is also a new node type, `ForAwaitStatement`.
  1064 +
  1065 +> [Async generators and for-await](https://github.com/tc39/proposal-async-iteration) are now a [stage 2 proposal](https://github.com/tc39/ecma262#current-proposals).
  1066 +
  1067 +Example:
  1068 +
  1069 +```js
  1070 +async function f() {
  1071 + for await (let x of y);
  1072 +}
  1073 +```
  1 +Copyright (C) 2012-2014 by various contributors (see AUTHORS)
  2 +
  3 +Permission is hereby granted, free of charge, to any person obtaining a copy
  4 +of this software and associated documentation files (the "Software"), to deal
  5 +in the Software without restriction, including without limitation the rights
  6 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7 +copies of the Software, and to permit persons to whom the Software is
  8 +furnished to do so, subject to the following conditions:
  9 +
  10 +The above copyright notice and this permission notice shall be included in
  11 +all copies or substantial portions of the Software.
  12 +
  13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19 +THE SOFTWARE.
  1 +<p align="center">
  2 + <img alt="babylon" src="https://raw.githubusercontent.com/babel/logo/master/babylon.png" width="700">
  3 +</p>
  4 +
  5 +<p align="center">
  6 + Babylon is a JavaScript parser used in <a href="https://github.com/babel/babel">Babel</a>.
  7 +</p>
  8 +
  9 +<p align="center">
  10 + <a href="https://www.npmjs.com/package/babylon"><img alt="NPM Version" src="https://img.shields.io/npm/v/babylon.svg?style=flat"></a>
  11 + <a href="https://travis-ci.org/babel/babylon"><img alt="Travis Status" src="https://img.shields.io/travis/babel/babylon/master.svg?style=flat&label=travis"></a>
  12 + <a href="https://codecov.io/gh/babel/babylon"><img alt="Codecov Status" src="https://img.shields.io/codecov/c/github/babel/babylon/master.svg?style=flat"></a>
  13 +</p>
  14 +
  15 + - The latest ECMAScript version enabled by default (ES2017).
  16 + - Comment attachment.
  17 + - Support for JSX, Flow, Typescript.
  18 + - Support for experimental language proposals (accepting PRs for anything at least [stage-0](https://github.com/tc39/proposals/blob/master/stage-0-proposals.md)).
  19 +
  20 +## Contributing
  21 +
  22 +Check out [contributing.md](https://github.com/babel/babylon/blob/master/CONTRIBUTING.md)
  23 +
  24 +## Credits
  25 +
  26 +Heavily based on [acorn](https://github.com/marijnh/acorn) and [acorn-jsx](https://github.com/RReverser/acorn-jsx),
  27 +thanks to the awesome work of [@RReverser](https://github.com/RReverser) and [@marijnh](https://github.com/marijnh).
  28 +
  29 +## API
  30 +
  31 +### `babylon.parse(code, [options])`
  32 +
  33 +### `babylon.parseExpression(code, [options])`
  34 +
  35 +`parse()` parses the provided `code` as an entire ECMAScript program, while
  36 +`parseExpression()` tries to parse a single Expression with performance in
  37 +mind. When in doubt, use `.parse()`.
  38 +
  39 +### Options
  40 +
  41 +- **allowImportExportEverywhere**: By default, `import` and `export`
  42 + declarations can only appear at a program's top level. Setting this
  43 + option to `true` allows them anywhere where a statement is allowed.
  44 +
  45 +- **allowReturnOutsideFunction**: By default, a return statement at
  46 + the top level raises an error. Set this to `true` to accept such
  47 + code.
  48 +
  49 +- **allowSuperOutsideMethod**: TODO
  50 +
  51 +- **sourceType**: Indicate the mode the code should be parsed in. Can be
  52 + either `"script"` or `"module"`.
  53 +
  54 +- **sourceFilename**: Correlate output AST nodes with their source filename. Useful when generating code and source maps from the ASTs of multiple input files.
  55 +
  56 +- **startLine**: By default, the first line of code parsed is treated as line 1. You can provide a line number to alternatively start with. Useful for integration with other source tools.
  57 +
  58 +- **plugins**: Array containing the plugins that you want to enable.
  59 +
  60 +- **strictMode**: TODO
  61 +
  62 +- **ranges**: Adds a `ranges` property to each node: `[node.start, node.end]`
  63 +
  64 +- **tokens**: Adds all parsed tokens to a `tokens` property on the `File` node
  65 +
  66 +### Output
  67 +
  68 +Babylon generates AST according to [Babel AST format][].
  69 +It is based on [ESTree spec][] with the following deviations:
  70 +
  71 +> There is now an `estree` plugin which reverts these deviations
  72 +
  73 +- [Literal][] token is replaced with [StringLiteral][], [NumericLiteral][], [BooleanLiteral][], [NullLiteral][], [RegExpLiteral][]
  74 +- [Property][] token is replaced with [ObjectProperty][] and [ObjectMethod][]
  75 +- [MethodDefinition][] is replaced with [ClassMethod][]
  76 +- [Program][] and [BlockStatement][] contain additional `directives` field with [Directive][] and [DirectiveLiteral][]
  77 +- [ClassMethod][], [ObjectProperty][], and [ObjectMethod][] value property's properties in [FunctionExpression][] is coerced/brought into the main method node.
  78 +
  79 +AST for JSX code is based on [Facebook JSX AST][] with the addition of one node type:
  80 +
  81 +- `JSXText`
  82 +
  83 +[Babel AST format]: https://github.com/babel/babylon/blob/master/ast/spec.md
  84 +[ESTree spec]: https://github.com/estree/estree
  85 +
  86 +[Literal]: https://github.com/estree/estree/blob/master/es5.md#literal
  87 +[Property]: https://github.com/estree/estree/blob/master/es5.md#property
  88 +[MethodDefinition]: https://github.com/estree/estree/blob/master/es2015.md#methoddefinition
  89 +
  90 +[StringLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#stringliteral
  91 +[NumericLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#numericliteral
  92 +[BooleanLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#booleanliteral
  93 +[NullLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#nullliteral
  94 +[RegExpLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#regexpliteral
  95 +[ObjectProperty]: https://github.com/babel/babylon/blob/master/ast/spec.md#objectproperty
  96 +[ObjectMethod]: https://github.com/babel/babylon/blob/master/ast/spec.md#objectmethod
  97 +[ClassMethod]: https://github.com/babel/babylon/blob/master/ast/spec.md#classmethod
  98 +[Program]: https://github.com/babel/babylon/blob/master/ast/spec.md#programs
  99 +[BlockStatement]: https://github.com/babel/babylon/blob/master/ast/spec.md#blockstatement
  100 +[Directive]: https://github.com/babel/babylon/blob/master/ast/spec.md#directive
  101 +[DirectiveLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#directiveliteral
  102 +[FunctionExpression]: https://github.com/babel/babylon/blob/master/ast/spec.md#functionexpression
  103 +
  104 +[Facebook JSX AST]: https://github.com/facebook/jsx/blob/master/AST.md
  105 +
  106 +### Semver
  107 +
  108 +Babylon follows semver in most situations. The only thing to note is that some spec-compliancy bug fixes may be released under patch versions.
  109 +
  110 +For example: We push a fix to early error on something like [#107](https://github.com/babel/babylon/pull/107) - multiple default exports per file. That would be considered a bug fix even though it would cause a build to fail.
  111 +
  112 +### Example
  113 +
  114 +```javascript
  115 +require("babylon").parse("code", {
  116 + // parse in strict mode and allow module declarations
  117 + sourceType: "module",
  118 +
  119 + plugins: [
  120 + // enable jsx and flow syntax
  121 + "jsx",
  122 + "flow"
  123 + ]
  124 +});
  125 +```
  126 +
  127 +### Plugins
  128 +
  129 +| Name | Code Example |
  130 +|------|--------------|
  131 +| `estree` ([repo](https://github.com/estree/estree)) | n/a |
  132 +| `jsx` ([repo](https://facebook.github.io/jsx/)) | `<a attr="b">{s}</a>` |
  133 +| `flow` ([repo](https://github.com/facebook/flow)) | `var a: string = "";` |
  134 +| `typescript` ([repo](https://github.com/Microsoft/TypeScript)) | `var a: string = "";` |
  135 +| `doExpressions` | `var a = do { if (true) { 'hi'; } };` |
  136 +| `objectRestSpread` ([proposal](https://github.com/tc39/proposal-object-rest-spread)) | `var a = { b, ...c };` |
  137 +| `decorators` (Stage 1) and `decorators2` (Stage 2 [proposal](https://github.com/tc39/proposal-decorators)) | `@a class A {}` |
  138 +| `classProperties` ([proposal](https://github.com/tc39/proposal-class-public-fields)) | `class A { b = 1; }` |
  139 +| `classPrivateProperties` ([proposal](https://github.com/tc39/proposal-private-fields)) | `class A { #b = 1; }` |
  140 +| `exportExtensions` ([proposal 1](https://github.com/leebyron/ecmascript-export-default-from)), ([proposal 2](https://github.com/leebyron/ecmascript-export-ns-from)) | Proposal 1: `export v from "mod"` Proposal 2: `export * as ns from "mod"` |
  141 +| `asyncGenerators` ([proposal](https://github.com/tc39/proposal-async-iteration)) | `async function*() {}`, `for await (let a of b) {}` |
  142 +| `functionBind` ([proposal](https://github.com/zenparsing/es-function-bind)) | `a::b`, `::console.log` |
  143 +| `functionSent` | `function.sent` |
  144 +| `dynamicImport` ([proposal](https://github.com/tc39/proposal-dynamic-import)) | `import('./guy').then(a)` |
  145 +| `numericSeparator` ([proposal](https://github.com/samuelgoto/proposal-numeric-separator)) | `1_000_000` |
  146 +| `optionalChaining` ([proposal](https://github.com/tc39/proposal-optional-chaining)) | `a?.b` |
  147 +| `importMeta` ([proposal](https://github.com/tc39/proposal-import-meta)) | `import.meta.url` |
  148 +| `bigInt` ([proposal](https://github.com/tc39/proposal-bigint)) | `100n` |
  149 +| `optionalCatchBinding` ([proposal](https://github.com/babel/proposals/issues/7)) | `try {throw 0;} catch{do();}` |
  150 +
  151 +### FAQ
  152 +
  153 +#### Will Babylon support a plugin system?
  154 +
  155 +Previous issues: [babel/babel#1351](https://github.com/babel/babel/issues/1351), [#500](https://github.com/babel/babylon/issues/500).
  156 +
  157 +We currently aren't willing to commit to supporting the API for plugins or the resulting ecosystem (there is already enough work maintaining Babel's own plugin system). It's not clear how to make that API effective, and it would limit out ability to refactor and optimize the codebase.
  158 +
  159 +Our current recommendation for those that want to create their own custom syntax is for users to fork Babylon.
  160 +
  161 +To consume your custom parser, you can add to your `.babelrc` via its npm package name or require it if using JavaScript,
  162 +
  163 +```json
  164 +{
  165 + "parserOpts": {
  166 + "parser": "custom-fork-of-babylon-on-npm-here"
  167 + }
  168 +}
  169 +```
  1 +#!/usr/bin/env node
  2 +/* eslint no-var: 0 */
  3 +
  4 +var babylon = require("..");
  5 +var fs = require("fs");
  6 +
  7 +var filename = process.argv[2];
  8 +if (!filename) {
  9 + console.error("no filename specified");
  10 + process.exit(0);
  11 +}
  12 +
  13 +var file = fs.readFileSync(filename, "utf8");
  14 +var ast = babylon.parse(file);
  15 +
  16 +console.log(JSON.stringify(ast, null, " "));
  1 +"use strict";
  2 +
  3 +// Which Unicode version should be used?
  4 +const version = "9.0.0";
  5 +
  6 +const start = require("unicode-" +
  7 + version +
  8 + "/Binary_Property/ID_Start/code-points.js").filter(function(ch) {
  9 + return ch > 0x7f;
  10 +});
  11 +let last = -1;
  12 +const cont = [0x200c, 0x200d].concat(
  13 + require("unicode-" +
  14 + version +
  15 + "/Binary_Property/ID_Continue/code-points.js").filter(function(ch) {
  16 + return ch > 0x7f && search(start, ch, last + 1) == -1;
  17 + }),
  18 +);
  19 +
  20 +function search(arr, ch, starting) {
  21 + for (let i = starting; arr[i] <= ch && i < arr.length; last = i++)
  22 + if (arr[i] === ch) return i;
  23 + return -1;
  24 +}
  25 +
  26 +function pad(str, width) {
  27 + while (str.length < width) str = "0" + str;
  28 + return str;
  29 +}
  30 +
  31 +function esc(code) {
  32 + const hex = code.toString(16);
  33 + if (hex.length <= 2) return "\\x" + pad(hex, 2);
  34 + else return "\\u" + pad(hex, 4);
  35 +}
  36 +
  37 +function generate(chars) {
  38 + const astral = [];
  39 + let re = "";
  40 + for (let i = 0, at = 0x10000; i < chars.length; i++) {
  41 + const from = chars[i];
  42 + let to = from;
  43 + while (i < chars.length - 1 && chars[i + 1] == to + 1) {
  44 + i++;
  45 + to++;
  46 + }
  47 + if (to <= 0xffff) {
  48 + if (from == to) re += esc(from);
  49 + else if (from + 1 == to) re += esc(from) + esc(to);
  50 + else re += esc(from) + "-" + esc(to);
  51 + } else {
  52 + astral.push(from - at, to - from);
  53 + at = to;
  54 + }
  55 + }
  56 + return { nonASCII: re, astral: astral };
  57 +}
  58 +
  59 +const startData = generate(start);
  60 +const contData = generate(cont);
  61 +
  62 +console.log('let nonASCIIidentifierStartChars = "' + startData.nonASCII + '";');
  63 +console.log('let nonASCIIidentifierChars = "' + contData.nonASCII + '";');
  64 +console.log(
  65 + "const astralIdentifierStartCodes = " +
  66 + JSON.stringify(startData.astral) +
  67 + ";",
  68 +);
  69 +console.log(
  70 + "const astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";",
  71 +);
此 diff 太大无法显示。
  1 +{
  2 + "_args": [
  3 + [
  4 + {
  5 + "raw": "babylon@~7.0.0-beta.19",
  6 + "scope": null,
  7 + "escapedName": "babylon",
  8 + "name": "babylon",
  9 + "rawSpec": "~7.0.0-beta.19",
  10 + "spec": ">=7.0.0-beta.19 <7.1.0",
  11 + "type": "range"
  12 + },
  13 + "/Users/fzy/project/koa2_Sequelize_project/node_modules/jsdoc"
  14 + ]
  15 + ],
  16 + "_from": "babylon@>=7.0.0-beta.19 <7.1.0",
  17 + "_id": "babylon@7.0.0-beta.20",
  18 + "_inCache": true,
  19 + "_location": "/babylon",
  20 + "_nodeVersion": "8.1.4",
  21 + "_npmOperationalInternal": {
  22 + "host": "s3://npm-registry-packages",
  23 + "tmp": "tmp/babylon-7.0.0-beta.20.tgz_1503153450138_0.7646075191441923"
  24 + },
  25 + "_npmUser": {
  26 + "name": "hzoo",
  27 + "email": "hi@henryzoo.com"
  28 + },
  29 + "_npmVersion": "5.3.0",
  30 + "_phantomChildren": {},
  31 + "_requested": {
  32 + "raw": "babylon@~7.0.0-beta.19",
  33 + "scope": null,
  34 + "escapedName": "babylon",
  35 + "name": "babylon",
  36 + "rawSpec": "~7.0.0-beta.19",
  37 + "spec": ">=7.0.0-beta.19 <7.1.0",
  38 + "type": "range"
  39 + },
  40 + "_requiredBy": [
  41 + "/jsdoc"
  42 + ],
  43 + "_resolved": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.20.tgz",
  44 + "_shasum": "7dbc70cc88de13334066fe5200e0efaa30c0490e",
  45 + "_shrinkwrap": null,
  46 + "_spec": "babylon@~7.0.0-beta.19",
  47 + "_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/jsdoc",
  48 + "author": {
  49 + "name": "Sebastian McKenzie",
  50 + "email": "sebmck@gmail.com"
  51 + },
  52 + "ava": {
  53 + "files": [
  54 + "test/*.js"
  55 + ],
  56 + "source": [
  57 + "src/**/*.js",
  58 + "bin/**/*.js"
  59 + ]
  60 + },
  61 + "bin": {
  62 + "babylon": "./bin/babylon.js"
  63 + },
  64 + "bugs": {
  65 + "url": "https://github.com/babel/babylon/issues"
  66 + },
  67 + "changelog": {
  68 + "repo": "babel/babylon",
  69 + "labels": {
  70 + "Tag: Breaking Change": ":boom: Breaking Change",
  71 + "Tag: Bug Fix": ":bug: Bug Fix",
  72 + "Tag: Docs": ":memo: Documentation",
  73 + "Tag: Internal": ":house: Internal",
  74 + "Tag: New Feature": ":rocket: New Feature",
  75 + "Tag: Polish": ":nail_care: Polish"
  76 + }
  77 + },
  78 + "contributors": [
  79 + {
  80 + "name": "List of Acorn contributors. Updated before every release."
  81 + },
  82 + {
  83 + "name": "Adrian Rakovsky"
  84 + },
  85 + {
  86 + "name": "Alistair Braidwood"
  87 + },
  88 + {
  89 + "name": "Andres Suarez"
  90 + },
  91 + {
  92 + "name": "Aparajita Fishman"
  93 + },
  94 + {
  95 + "name": "Arian Stolwijk"
  96 + },
  97 + {
  98 + "name": "Artem Govorov"
  99 + },
  100 + {
  101 + "name": "Brandon Mills"
  102 + },
  103 + {
  104 + "name": "Charles Hughes"
  105 + },
  106 + {
  107 + "name": "Conrad Irwin"
  108 + },
  109 + {
  110 + "name": "David Bonnet"
  111 + },
  112 + {
  113 + "name": "Forbes Lindesay"
  114 + },
  115 + {
  116 + "name": "Gilad Peleg"
  117 + },
  118 + {
  119 + "name": "impinball"
  120 + },
  121 + {
  122 + "name": "Ingvar Stepanyan"
  123 + },
  124 + {
  125 + "name": "Jesse McCarthy"
  126 + },
  127 + {
  128 + "name": "Jiaxing Wang"
  129 + },
  130 + {
  131 + "name": "Joel Kemp"
  132 + },
  133 + {
  134 + "name": "Johannes Herr"
  135 + },
  136 + {
  137 + "name": "Jürg Lehni"
  138 + },
  139 + {
  140 + "name": "keeyipchan"
  141 + },
  142 + {
  143 + "name": "Kevin Kwok"
  144 + },
  145 + {
  146 + "name": "krator"
  147 + },
  148 + {
  149 + "name": "Marijn Haverbeke"
  150 + },
  151 + {
  152 + "name": "Martin Carlberg"
  153 + },
  154 + {
  155 + "name": "Mathias Bynens"
  156 + },
  157 + {
  158 + "name": "Mathieu 'p01' Henri"
  159 + },
  160 + {
  161 + "name": "Max Schaefer"
  162 + },
  163 + {
  164 + "name": "Max Zerzouri"
  165 + },
  166 + {
  167 + "name": "Mihai Bazon"
  168 + },
  169 + {
  170 + "name": "Mike Rennie"
  171 + },
  172 + {
  173 + "name": "Nick Fitzgerald"
  174 + },
  175 + {
  176 + "name": "Oskar Schöldström"
  177 + },
  178 + {
  179 + "name": "Paul Harper"
  180 + },
  181 + {
  182 + "name": "Peter Rust"
  183 + },
  184 + {
  185 + "name": "PlNG"
  186 + },
  187 + {
  188 + "name": "r-e-d"
  189 + },
  190 + {
  191 + "name": "Rich Harris"
  192 + },
  193 + {
  194 + "name": "Sebastian McKenzie"
  195 + },
  196 + {
  197 + "name": "zsjforcn"
  198 + }
  199 + ],
  200 + "dependencies": {},
  201 + "description": "A JavaScript parser",
  202 + "devDependencies": {
  203 + "ava": "^0.22.0",
  204 + "babel-core": "7.0.0-alpha.18",
  205 + "babel-eslint": "8.0.0-alpha.13",
  206 + "babel-helper-fixtures": "7.0.0-alpha.18",
  207 + "babel-plugin-external-helpers": "7.0.0-alpha.18",
  208 + "babel-plugin-istanbul": "^4.1.4",
  209 + "babel-preset-env": "2.0.0-alpha.18",
  210 + "babel-preset-flow": "7.0.0-alpha.18",
  211 + "chalk": "^2.0.0",
  212 + "cross-env": "^5.0.0",
  213 + "eslint": "^4.0.0",
  214 + "eslint-config-babel": "^7.0.1",
  215 + "eslint-plugin-flowtype": "^2.34.0",
  216 + "eslint-plugin-prettier": "^2.1.2",
  217 + "flow-bin": "^0.53.0",
  218 + "graceful-fs": "^4.1.11",
  219 + "husky": "^0.14.1",
  220 + "lint-staged": "^4.0.0",
  221 + "nyc": "^11.0.3",
  222 + "prettier": "^1.5.2",
  223 + "rimraf": "^2.5.4",
  224 + "rollup": "^0.47.0",
  225 + "rollup-plugin-babel": "^3.0.1",
  226 + "rollup-plugin-node-resolve": "^3.0.0",
  227 + "rollup-watch": "^4.0.0",
  228 + "unicode-9.0.0": "~0.7.0",
  229 + "util.promisify": "^1.0.0"
  230 + },
  231 + "directories": {},
  232 + "dist": {
  233 + "integrity": "sha512-kkMTbo/6QmDD+ggF4KaeMLNvf+RfHVtC4mZJcGDZsbQvRqUgG4yWdy6fh3FZbwwLX9BD6PGmAeKN08P5O8pGLQ==",
  234 + "shasum": "7dbc70cc88de13334066fe5200e0efaa30c0490e",
  235 + "tarball": "https://registry.npmjs.org/babylon/-/babylon-7.0.0-beta.20.tgz"
  236 + },
  237 + "engines": {
  238 + "node": ">=4.2.0"
  239 + },
  240 + "files": [
  241 + "bin",
  242 + "lib"
  243 + ],
  244 + "gitHead": "f87b81a8b173cf8b07643b3615156c2fdc5c5c2f",
  245 + "homepage": "https://babeljs.io/",
  246 + "keywords": [
  247 + "babel",
  248 + "javascript",
  249 + "parser",
  250 + "babylon"
  251 + ],
  252 + "license": "MIT",
  253 + "lint-staged": {
  254 + "*.js": [
  255 + "eslint --format=codeframe --fix",
  256 + "git add"
  257 + ]
  258 + },
  259 + "main": "lib/index.js",
  260 + "maintainers": [
  261 + {
  262 + "name": "thejameskyle",
  263 + "email": "me@thejameskyle.com"
  264 + },
  265 + {
  266 + "name": "sebmck",
  267 + "email": "sebmck@gmail.com"
  268 + },
  269 + {
  270 + "name": "danez",
  271 + "email": "daniel@tschinder.de"
  272 + },
  273 + {
  274 + "name": "hzoo",
  275 + "email": "hi@henryzoo.com"
  276 + },
  277 + {
  278 + "name": "loganfsmyth",
  279 + "email": "loganfsmyth@gmail.com"
  280 + }
  281 + ],
  282 + "name": "babylon",
  283 + "nyc": {
  284 + "include": [
  285 + "src/**/*.js",
  286 + "bin/**/*.js"
  287 + ],
  288 + "sourceMap": false,
  289 + "instrument": false
  290 + },
  291 + "optionalDependencies": {},
  292 + "readme": "<p align=\"center\">\n <img alt=\"babylon\" src=\"https://raw.githubusercontent.com/babel/logo/master/babylon.png\" width=\"700\">\n</p>\n\n<p align=\"center\">\n Babylon is a JavaScript parser used in <a href=\"https://github.com/babel/babel\">Babel</a>.\n</p>\n\n<p align=\"center\">\n <a href=\"https://www.npmjs.com/package/babylon\"><img alt=\"NPM Version\" src=\"https://img.shields.io/npm/v/babylon.svg?style=flat\"></a>\n <a href=\"https://travis-ci.org/babel/babylon\"><img alt=\"Travis Status\" src=\"https://img.shields.io/travis/babel/babylon/master.svg?style=flat&label=travis\"></a>\n <a href=\"https://codecov.io/gh/babel/babylon\"><img alt=\"Codecov Status\" src=\"https://img.shields.io/codecov/c/github/babel/babylon/master.svg?style=flat\"></a>\n</p>\n\n - The latest ECMAScript version enabled by default (ES2017).\n - Comment attachment.\n - Support for JSX, Flow, Typescript.\n - Support for experimental language proposals (accepting PRs for anything at least [stage-0](https://github.com/tc39/proposals/blob/master/stage-0-proposals.md)).\n\n## Contributing\n\nCheck out [contributing.md](https://github.com/babel/babylon/blob/master/CONTRIBUTING.md)\n\n## Credits\n\nHeavily based on [acorn](https://github.com/marijnh/acorn) and [acorn-jsx](https://github.com/RReverser/acorn-jsx),\nthanks to the awesome work of [@RReverser](https://github.com/RReverser) and [@marijnh](https://github.com/marijnh).\n\n## API\n\n### `babylon.parse(code, [options])`\n\n### `babylon.parseExpression(code, [options])`\n\n`parse()` parses the provided `code` as an entire ECMAScript program, while\n`parseExpression()` tries to parse a single Expression with performance in\nmind. When in doubt, use `.parse()`.\n\n### Options\n\n- **allowImportExportEverywhere**: By default, `import` and `export`\n declarations can only appear at a program's top level. Setting this\n option to `true` allows them anywhere where a statement is allowed.\n\n- **allowReturnOutsideFunction**: By default, a return statement at\n the top level raises an error. Set this to `true` to accept such\n code.\n\n- **allowSuperOutsideMethod**: TODO\n\n- **sourceType**: Indicate the mode the code should be parsed in. Can be\n either `\"script\"` or `\"module\"`.\n\n- **sourceFilename**: Correlate output AST nodes with their source filename. Useful when generating code and source maps from the ASTs of multiple input files.\n\n- **startLine**: By default, the first line of code parsed is treated as line 1. You can provide a line number to alternatively start with. Useful for integration with other source tools.\n\n- **plugins**: Array containing the plugins that you want to enable.\n\n- **strictMode**: TODO\n\n- **ranges**: Adds a `ranges` property to each node: `[node.start, node.end]`\n\n- **tokens**: Adds all parsed tokens to a `tokens` property on the `File` node\n\n### Output\n\nBabylon generates AST according to [Babel AST format][].\nIt is based on [ESTree spec][] with the following deviations:\n\n> There is now an `estree` plugin which reverts these deviations\n\n- [Literal][] token is replaced with [StringLiteral][], [NumericLiteral][], [BooleanLiteral][], [NullLiteral][], [RegExpLiteral][]\n- [Property][] token is replaced with [ObjectProperty][] and [ObjectMethod][]\n- [MethodDefinition][] is replaced with [ClassMethod][]\n- [Program][] and [BlockStatement][] contain additional `directives` field with [Directive][] and [DirectiveLiteral][]\n- [ClassMethod][], [ObjectProperty][], and [ObjectMethod][] value property's properties in [FunctionExpression][] is coerced/brought into the main method node.\n\nAST for JSX code is based on [Facebook JSX AST][] with the addition of one node type:\n\n- `JSXText`\n\n[Babel AST format]: https://github.com/babel/babylon/blob/master/ast/spec.md\n[ESTree spec]: https://github.com/estree/estree\n\n[Literal]: https://github.com/estree/estree/blob/master/es5.md#literal\n[Property]: https://github.com/estree/estree/blob/master/es5.md#property\n[MethodDefinition]: https://github.com/estree/estree/blob/master/es2015.md#methoddefinition\n\n[StringLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#stringliteral\n[NumericLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#numericliteral\n[BooleanLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#booleanliteral\n[NullLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#nullliteral\n[RegExpLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#regexpliteral\n[ObjectProperty]: https://github.com/babel/babylon/blob/master/ast/spec.md#objectproperty\n[ObjectMethod]: https://github.com/babel/babylon/blob/master/ast/spec.md#objectmethod\n[ClassMethod]: https://github.com/babel/babylon/blob/master/ast/spec.md#classmethod\n[Program]: https://github.com/babel/babylon/blob/master/ast/spec.md#programs\n[BlockStatement]: https://github.com/babel/babylon/blob/master/ast/spec.md#blockstatement\n[Directive]: https://github.com/babel/babylon/blob/master/ast/spec.md#directive\n[DirectiveLiteral]: https://github.com/babel/babylon/blob/master/ast/spec.md#directiveliteral\n[FunctionExpression]: https://github.com/babel/babylon/blob/master/ast/spec.md#functionexpression\n\n[Facebook JSX AST]: https://github.com/facebook/jsx/blob/master/AST.md\n\n### Semver\n\nBabylon follows semver in most situations. The only thing to note is that some spec-compliancy bug fixes may be released under patch versions.\n\nFor example: We push a fix to early error on something like [#107](https://github.com/babel/babylon/pull/107) - multiple default exports per file. That would be considered a bug fix even though it would cause a build to fail.\n\n### Example\n\n```javascript\nrequire(\"babylon\").parse(\"code\", {\n // parse in strict mode and allow module declarations\n sourceType: \"module\",\n\n plugins: [\n // enable jsx and flow syntax\n \"jsx\",\n \"flow\"\n ]\n});\n```\n\n### Plugins\n\n| Name | Code Example |\n|------|--------------|\n| `estree` ([repo](https://github.com/estree/estree)) | n/a |\n| `jsx` ([repo](https://facebook.github.io/jsx/)) | `<a attr=\"b\">{s}</a>` |\n| `flow` ([repo](https://github.com/facebook/flow)) | `var a: string = \"\";` |\n| `typescript` ([repo](https://github.com/Microsoft/TypeScript)) | `var a: string = \"\";` |\n| `doExpressions` | `var a = do { if (true) { 'hi'; } };` |\n| `objectRestSpread` ([proposal](https://github.com/tc39/proposal-object-rest-spread)) | `var a = { b, ...c };` |\n| `decorators` (Stage 1) and `decorators2` (Stage 2 [proposal](https://github.com/tc39/proposal-decorators)) | `@a class A {}` |\n| `classProperties` ([proposal](https://github.com/tc39/proposal-class-public-fields)) | `class A { b = 1; }` |\n| `classPrivateProperties` ([proposal](https://github.com/tc39/proposal-private-fields)) | `class A { #b = 1; }` |\n| `exportExtensions` ([proposal 1](https://github.com/leebyron/ecmascript-export-default-from)), ([proposal 2](https://github.com/leebyron/ecmascript-export-ns-from)) | Proposal 1: `export v from \"mod\"` Proposal 2: `export * as ns from \"mod\"` |\n| `asyncGenerators` ([proposal](https://github.com/tc39/proposal-async-iteration)) | `async function*() {}`, `for await (let a of b) {}` |\n| `functionBind` ([proposal](https://github.com/zenparsing/es-function-bind)) | `a::b`, `::console.log` |\n| `functionSent` | `function.sent` |\n| `dynamicImport` ([proposal](https://github.com/tc39/proposal-dynamic-import)) | `import('./guy').then(a)` |\n| `numericSeparator` ([proposal](https://github.com/samuelgoto/proposal-numeric-separator)) | `1_000_000` |\n| `optionalChaining` ([proposal](https://github.com/tc39/proposal-optional-chaining)) | `a?.b` |\n| `importMeta` ([proposal](https://github.com/tc39/proposal-import-meta)) | `import.meta.url` |\n| `bigInt` ([proposal](https://github.com/tc39/proposal-bigint)) | `100n` |\n| `optionalCatchBinding` ([proposal](https://github.com/babel/proposals/issues/7)) | `try {throw 0;} catch{do();}` |\n\n### FAQ\n\n#### Will Babylon support a plugin system?\n\nPrevious issues: [babel/babel#1351](https://github.com/babel/babel/issues/1351), [#500](https://github.com/babel/babylon/issues/500).\n\nWe currently aren't willing to commit to supporting the API for plugins or the resulting ecosystem (there is already enough work maintaining Babel's own plugin system). It's not clear how to make that API effective, and it would limit out ability to refactor and optimize the codebase.\n\nOur current recommendation for those that want to create their own custom syntax is for users to fork Babylon.\n\nTo consume your custom parser, you can add to your `.babelrc` via its npm package name or require it if using JavaScript,\n\n```json\n{\n \"parserOpts\": {\n \"parser\": \"custom-fork-of-babylon-on-npm-here\"\n }\n}\n```\n",
  293 + "readmeFilename": "README.md",
  294 + "repository": {
  295 + "type": "git",
  296 + "url": "git+https://github.com/babel/babylon.git"
  297 + },
  298 + "scripts": {
  299 + "build": "yarn run clean && rollup -c",
  300 + "changelog": "git log `git describe --tags --abbrev=0`..HEAD --pretty=format:' * %s (%an)' | grep -v 'Merge pull request'",
  301 + "clean": "rimraf lib",
  302 + "flow": "flow",
  303 + "lint": "eslint src bin test",
  304 + "prepublish": "cross-env BABEL_ENV=production yarn run build",
  305 + "preversion": "yarn run test && npm run changelog",
  306 + "test": "yarn run lint && yarn run flow && yarn run build -- -m && yarn run test-only",
  307 + "test-coverage": "cross-env BABEL_ENV=test yarn run build && nyc --reporter=json --reporter=text yarn run test-only",
  308 + "test-only": "ava",
  309 + "watch": "yarn run clean && rollup -c --watch"
  310 + },
  311 + "version": "7.0.0-beta.20"
  312 +}
  1 +Copyright (c) 2014 Google Inc.
  2 +Copyright (c) 2012-2014 Jeff Williams
  3 +
  4 +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  5 +associated documentation files (the "Software"), to deal in the Software without restriction,
  6 +including without limitation the rights to use, copy, modify, merge, publish, distribute,
  7 +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
  8 +furnished to do so, subject to the following conditions:
  9 +
  10 +The above copyright notice and this permission notice shall be included in all copies or substantial
  11 +portions of the Software.
  12 +
  13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
  14 +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  15 +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
  16 +OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  17 +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1 +# Catharsis #
  2 +
  3 +A JavaScript parser for
  4 +[Google Closure Compiler](https://developers.google.com/closure/compiler/docs/js-for-compiler#types)
  5 +and [JSDoc](https://github.com/jsdoc3/jsdoc) type expressions.
  6 +
  7 +Catharsis is designed to be:
  8 +
  9 ++ **Accurate**. Catharsis is based on a [PEG.js](http://pegjs.majda.cz/) grammar that's designed to
  10 +handle any valid type expression. It uses a [Mocha](http://visionmedia.github.com/mocha/) test suite
  11 +to verify the parser's accuracy.
  12 ++ **Fast**. Parse results are cached, so the parser is invoked only when necessary.
  13 ++ **Flexible**. Catharsis can convert a parse result back into a type expression, or into a
  14 +description of the type expression. In addition, Catharsis can parse
  15 +[JSDoc](https://github.com/jsdoc3/jsdoc)-style type expressions.
  16 +
  17 +
  18 +## Example ##
  19 +
  20 +```js
  21 +var catharsis = require('catharsis');
  22 +
  23 +// Google Closure Compiler parsing
  24 +var type = '!Object';
  25 +var parsedType;
  26 +try {
  27 + parsedType = catharsis.parse(type); // {"type":"NameExpression,"name":"Object","nullable":false}
  28 +} catch(e) {
  29 + console.error('unable to parse %s: %s', type, e);
  30 +}
  31 +
  32 +// JSDoc-style type expressions enabled
  33 +var jsdocType = 'string[]'; // Closure Compiler expects Array.<string>
  34 +var parsedJsdocType;
  35 +try {
  36 + parsedJsdocType = catharsis.parse(jsdocType, {jsdoc: true});
  37 +} catch (e) {
  38 + console.error('unable to parse %s: %s', jsdocType, e);
  39 +}
  40 +
  41 +// Converting parse results back to type expressions
  42 +catharsis.stringify(parsedType); // !Object
  43 +catharsis.stringify(parsedJsdocType); // string[]
  44 +catharsis.stringify(parsedJsdocType, {restringify: true}); // Array.<string>
  45 +
  46 +// Converting parse results to descriptions of the type expression
  47 +catharsis.describe(parsedType).simple; // non-null Object
  48 +catharsis.describe(parsedJsdocType).simple; // Array of string
  49 +```
  50 +
  51 +See the [test/specs directory](test/specs) for more examples of Catharsis' parse results.
  52 +
  53 +
  54 +## Methods ##
  55 +
  56 +### parse(typeExpression, options) ###
  57 +Parse a type expression, and return the parse results. Throws an error if the type expression cannot
  58 +be parsed.
  59 +
  60 +When called without options, Catharsis attempts to parse type expressions in the same way as
  61 +Closure Compiler. When the `jsdoc` option is enabled, Catharsis can also parse several kinds of
  62 +type expressions that are permitted in [JSDoc](https://github.com/jsdoc3/jsdoc):
  63 +
  64 ++ The string `function` is treated as a function type with no parameters.
  65 ++ The period may be omitted from type applications. For example, `Array.<string>` and
  66 +`Array<string>` will be parsed in the same way.
  67 ++ You may append `[]` to a name expression (for example, `string[]`) to interpret it as a type
  68 +application with the expression `Array` (for example, `Array.<string>`).
  69 ++ Name expressions may contain the characters `#`, `~`, `:`, and `/`.
  70 ++ Name expressions may contain a suffix that is similar to a function signature (for example,
  71 +`MyClass(foo, bar)`).
  72 ++ Name expressions may contain a reserved word.
  73 ++ Record types may use types other than name expressions for keys.
  74 +
  75 +#### Parameters ####
  76 ++ `type`: A string containing a Closure Compiler type expression.
  77 ++ `options`: Options for parsing the type expression.
  78 + + `options.jsdoc`: Specifies whether to enable parsing of JSDoc-style type expressions. Defaults
  79 + to `false`.
  80 + + `options.useCache`: Specifies whether to use the cache of parsed types. Defaults to `true`.
  81 +
  82 +#### Returns ####
  83 +An object containing the parse results. See the [test/specs directory](test/specs) for examples of
  84 +the parse results for different type expressions.
  85 +
  86 +The object also includes two non-enumerable properties:
  87 +
  88 ++ `jsdoc`: A boolean indicating whether the type expression was parsed with JSDoc support enabled.
  89 ++ `typeExpression`: A string containing the type expression that was parsed.
  90 +
  91 +### stringify(parsedType, options) ###
  92 +Stringify `parsedType`, and return the type expression. If validation is enabled, throws an error if
  93 +the stringified type expression cannot be parsed.
  94 +
  95 +#### Parameters ####
  96 ++ `parsedType`: An object containing a parsed Closure Compiler type expression.
  97 ++ `options`: Options for stringifying the parse results.
  98 + + `options.cssClass`: Synonym for `options.linkClass`. Deprecated in version 0.8.0; will be
  99 + removed in a future version.
  100 + + `options.htmlSafe`: Specifies whether to return an HTML-safe string that replaces left angle
  101 + brackets (`<`) with the corresponding entity (`&lt;`). **Note**: Characters in name expressions
  102 + are not escaped.
  103 + + `options.linkClass`: A CSS class to add to HTML links. Used only if `options.links` is
  104 + provided. By default, no CSS class is added.
  105 + + `options.links`: An object whose keys are name expressions and whose values are URIs. If a
  106 + name expression matches a key in `options.links`, the name expression will be wrapped in an
  107 + HTML `<a>` tag that links to the URI. If `options.linkClass` is specified, the `<a>` tag will
  108 + include a `class` attribute. **Note**: When using this option, parsed types are always
  109 + restringified, and the resulting string is not cached.
  110 + + `options.restringify`: Forces Catharsis to restringify the parsed type. If this option is not
  111 + specified, and the parsed type object includes a `typeExpression` property, Catharsis will
  112 + return the `typeExpression` property without modification when possible. Defaults to `false`.
  113 + + `options.useCache`: Specifies whether to use the cache of stringified type expressions.
  114 + Defaults to `true`.
  115 + + `options.validate`: Specifies whether to validate the stringified parse results by attempting
  116 + to parse them as a type expression. If the stringified results are not parsable by default, you
  117 + must also provide the appropriate options to pass to the `parse()` method. Defaults to `false`.
  118 +
  119 +#### Returns ####
  120 +A string containing the type expression.
  121 +
  122 +### describe(parsedType, options) ###
  123 +Convert a parsed type to a description of the type expression. This method is especially useful if
  124 +your users are not familiar with the syntax for type expressions.
  125 +
  126 +The `describe()` method returns the description in two formats:
  127 +
  128 ++ **Simple format**. A string that provides a complete description of the type expression.
  129 ++ **Extended format**. An object that separates out some of the details about the outermost type
  130 +expression, such as whether the type is optional, nullable, or repeatable.
  131 +
  132 +For example, if you call `describe('?function(new:MyObject, string)=')`, it returns the following
  133 +object:
  134 +
  135 +```js
  136 +{
  137 + simple: 'optional nullable function(constructs MyObject, string)',
  138 + extended: {
  139 + description: 'function(string)',
  140 + modifiers: {
  141 + functionNew: 'Returns MyObject when called with new.',
  142 + functionThis: '',
  143 + optional: 'Optional.',
  144 + nullable: 'May be null.',
  145 + repeatable: ''
  146 + },
  147 + returns: ''
  148 + }
  149 +}
  150 +```
  151 +
  152 +#### Parameters ####
  153 ++ `parsedType`: An object containing a parsed Closure Compiler type expression.
  154 ++ `options`: Options for creating the description.
  155 + + `options.codeClass`: A CSS class to add to the tag that is wrapped around type names. Used
  156 + only if `options.codeTag` is provided. By default, no CSS class is added.
  157 + + `options.codeTag`: The name of an HTML tag (for example, `code`) to wrap around type names.
  158 + For example, if this option is set to `code`, the type expression `Array.<string>` would have
  159 + the simple description `<code>Array</code> of <code>string</code>`.
  160 + + `options.language`: A string identifying the language in which to generate the description.
  161 + The identifier should be an
  162 + [ISO 639-1 language code](http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (for example,
  163 + `en`). It can optionally be followed by a hyphen and an
  164 + [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) (for example,
  165 + `en-US`). If you use values other than `en`, you must provide translation resources in
  166 + `options.resources`. Defaults to `en`.
  167 + + `options.linkClass`: A CSS class to add to HTML links. Used only if `options.links` is
  168 + provided. By default, no CSS class is added.
  169 + + `options.links`: An object whose keys are name expressions and whose values are URIs. If a
  170 + name expression matches a key in `options.links`, the name expression will be wrapped in an
  171 + HTML `<a>` tag that links to the URI. If `options.linkClass` is specified, the `<a>` tag will
  172 + include a `class` attribute. **Note**: When using this option, the description is not cached.
  173 + + `options.resources`: An object that specifies how to describe type expressions for a given
  174 + language. The object's property names should use the same format as `options.language`. Each
  175 + property should contain an object in the same format as the translation resources in
  176 + [res/en.json](res/en.json). If you specify a value for `options.resources.en`, it will override
  177 + the defaults in [res/en.json](res/en.json).
  178 + + `options.useCache`: Specifies whether to use the cache of descriptions. Defaults to `true`.
  179 +
  180 +### Returns ###
  181 +An object with the following properties:
  182 +
  183 ++ `simple`: A string that provides a complete description of the type expression.
  184 ++ `extended`: An object containing details about the outermost type expression.
  185 + + `extended.description`: A string that provides a basic description of the type expression,
  186 + excluding the information contained in other properties.
  187 + + `extended.modifiers`: Information about modifiers that apply to the type expression.
  188 + + `extended.modifiers.functionNew`: A string describing what a function returns when called
  189 + with `new`. Used only for function types.
  190 + + `extended.modifiers.functionThis`: A string describing what the keyword `this` refers to
  191 + within a function. Used only for function types.
  192 + + `extended.modifiers.nullable`: A string indicating whether the type is nullable or
  193 + non-nullable.
  194 + + `extended.modifiers.optional`: A string indicating whether the type is optional.
  195 + + `extended.modifiers.repeatable`: A string indicating whether the type can be provided
  196 + + `extended.returns`: A string describing the function's return value. Used only for function
  197 + types.
  198 +
  199 +
  200 +## Installation ##
  201 +
  202 +With [npm](http://npmjs.org):
  203 +
  204 + npm install catharsis
  205 +
  206 +Or by cloning the git repo:
  207 +
  208 + git clone git://github.com/hegemonic/catharsis.git
  209 + cd catharsis
  210 + npm install
  211 +
  212 +
  213 +## Roadmap and known issues ##
  214 +
  215 +Take a look at the [issue tracker](https://github.com/hegemonic/catharsis/issues) to see what's in
  216 +store for Catharsis.
  217 +
  218 +Bug reports, feature requests, and pull requests are always welcome! If you're working on a large
  219 +pull request, please contact me in advance so I can help things go smoothly.
  220 +
  221 +**Note**: The parse tree's format should not be considered final until Catharsis reaches version
  222 +1.0. I'll do my best to provide release notes for any changes.
  223 +
  224 +
  225 +## Changelog ##
  226 +
  227 ++ 0.8.9 (July 2017): Type expressions that include an `@` sign (for example,
  228 +`module:@prefix/mymodule~myCallback`) are now supported.
  229 ++ 0.8.8 (April 2016): Corrected the description of type applications other than arrays that contain
  230 +a single type (for example, `Promise.<string>`).
  231 ++ 0.8.7 (June 2015):
  232 + + Record types that use numeric literals as property names (for example, `{0: string}`) are now
  233 + parsed correctly.
  234 + + Record types with a property that contains a function, with no space after the preceding colon
  235 + (for example, `{foo:function()}`), are now parsed correctly.
  236 + + Repeatable function parameters are no longer required to be enclosed in brackets, regardless
  237 + of whether JSDoc-style type expressions are enabled. In addition, the brackets are omitted when
  238 + stringifying a parsed type expression.
  239 ++ 0.8.6 (December 2014): Improved the description of the unknown type.
  240 ++ 0.8.5 (December 2014): Added support for postfix nullable/non-nullable operators combined with the
  241 +optional operator (for example, `foo?=`).
  242 ++ 0.8.4 (December 2014): JSDoc-style nested arrays (for example, `number[][]`) are now parsed
  243 +correctly when JSDoc-style type expressions are enabled.
  244 ++ 0.8.3 (October 2014):
  245 + + Type applications are no longer required to include a period (`.`) as a separator, regardless
  246 + of whether JSDoc-style type expressions are enabled.
  247 + + Type unions that are not enclosed in parentheses can now include the repeatable (`...`)
  248 + modifier when JSDoc-style type expressions are enabled.
  249 + + Name expressions may now be enclosed in single or double quotation marks when JSDoc-style
  250 + type expressions are enabled.
  251 ++ 0.8.2 (June 2014): Fixed a compatibility issue with the JSDoc fork of Mozilla Rhino.
  252 ++ 0.8.1 (June 2014): Added support for type unions that are not enclosed in parentheses, and that
  253 +contain nullable or non-nullable modifiers (for example, `!string|!number`).
  254 ++ 0.8.0 (May 2014):
  255 + + Added a `describe()` method, which converts a parsed type to a description of the type.
  256 + + Added a `linkClass` option to the `stringify()` method, and deprecated the existing `cssClass`
  257 + option. The `cssClass` option will be removed in a future release.
  258 + + Clarified and corrected several sections in the `README`.
  259 ++ 0.7.1 (April 2014): In record types, property names that begin with a keyword (for example,
  260 +`undefinedHTML`) are now parsed correctly when JSDoc-style type expressions are enabled.
  261 ++ 0.7.0 (October 2013):
  262 + + Repeatable type expressions other than name expressions (for example, `...function()`) are now
  263 + parsed and stringified correctly.
  264 + + Type expressions that are both repeatable and either nullable or non-nullable (for example,
  265 + `...!number`) are now parsed and stringified correctly.
  266 + + Name expressions are now parsed correctly when they match a property name in an object
  267 + instance (for example, `constructor`).
  268 ++ 0.6.0 (September 2013): Added support for the type expression `function[]` when JSDoc-style type
  269 +expressions are enabled.
  270 ++ 0.5.6 (April 2013):
  271 + + For consistency with Google Closure Library, parentheses are no longer required around type
  272 + unions. (In previous versions, the parentheses could be omitted when JSDoc support was enabled.)
  273 + + For consistency with Google Closure Library, you can now use postfix notation for the `?`
  274 + (nullable) and `!` (non-nullable) modifiers. For example, `?string` and `string?` are now
  275 + treated as equivalent.
  276 + + String literals and numeric literals are now allowed as property names within name
  277 + expressions. For example, the name expression `Foo."bar"` is now parsed correctly.
  278 ++ 0.5.5 (April 2013): Corrected a parsing issue with name expressions that end with a value enclosed
  279 +in parentheses.
  280 ++ 0.5.4 (April 2013):
  281 + + Repeatable literals (for example, `...*`) are now parsed correctly.
  282 + + When JSDoc-style type expressions are enabled, a name expression can now contain a value
  283 + enclosed in parentheses at the end of the name expression (for example, `MyClass(2)`).
  284 ++ 0.5.3 (March 2013): The `parse()` method now correctly parses name expressions that contain
  285 +hyphens.
  286 ++ 0.5.2 (March 2013): The `parse()` method now correctly parses function types when JSDoc-style type
  287 +expressions are enabled.
  288 ++ 0.5.1 (March 2013): Newlines and extra spaces are now removed from type expressions before they
  289 +are parsed.
  290 ++ 0.5.0 (March 2013):
  291 + + The `parse()` method's `lenient` option has been renamed to `jsdoc`. **Note**: This change is
  292 + not backwards-compatible with previous versions.
  293 + + The `stringify()` method now accepts `cssClass` and `links` options, which you can use to
  294 + add HTML links to a type expression.
  295 ++ 0.4.3 (March 2013):
  296 + + The `stringify()` method no longer caches HTML-safe type expressions as if they were normal
  297 + type expressions.
  298 + + The `stringify()` method's options parameter may now include an `options.restringify`
  299 + property, and the behavior of the `options.useCache` property has changed.
  300 ++ 0.4.2 (March 2013):
  301 + + When lenient parsing is enabled, name expressions can now contain the characters `:` and `/`.
  302 + + When lenient parsing is enabled, a name expression followed by `[]` (for example, `string[]`)
  303 + will be interpreted as a type application with the expression `Array` (for example,
  304 + `Array.<string>`).
  305 ++ 0.4.1 (March 2013):
  306 + + The `parse()` and `stringify()` methods now honor all of the specified options.
  307 + + When lenient parsing is enabled, name expressions can now contain a reserved word.
  308 ++ 0.4.0 (March 2013):
  309 + + Catharsis now supports a lenient parsing option that can parse several kinds of malformed type
  310 + expressions. See the documentation for details.
  311 + + The objects containing parse results are now frozen.
  312 + + The objects containing parse results now have two non-enumerable properties:
  313 + + `lenient`: A boolean indicating whether the type expression was parsed in lenient mode.
  314 + + `typeExpression`: A string containing the original type expression.
  315 + + The `stringify()` method now honors the `useCache` option. If a parsed type includes a
  316 + `typeExpression` property, and `useCache` is not set to `false`, the stringified type will be
  317 + identical to the original type expression.
  318 ++ 0.3.1 (March 2013): Type expressions that begin with a reserved word, such as `integer`, are now
  319 +parsed correctly.
  320 ++ 0.3.0 (March 2013):
  321 + + The `parse()` and `stringify()` methods are now synchronous, and the `parseSync()` and
  322 + `stringifySync()` methods have been removed. **Note**: This change is not backwards-compatible
  323 + with previous versions.
  324 + + The parse results now use a significantly different format from previous versions. The new
  325 + format is more expressive and is similar, but not identical, to the format used by the
  326 + [doctrine](https://github.com/Constellation/doctrine) parser. **Note**: This change is not
  327 + backwards-compatible with previous versions.
  328 + + Name expressions that contain a reserved word now include a `reservedWord: true` property.
  329 + + Union types that are optional or nullable, or that can be passed a variable number of times,
  330 + are now parsed and stringified correctly.
  331 + + Optional function types and record types are now parsed and stringified correctly.
  332 + + Function types now longer include `new` or `this` properties unless the properties are defined
  333 + in the type expression. In addition, the `new` and `this` properties can now use any type
  334 + expression.
  335 + + In record types, the key for a field type can now use any type expression.
  336 + + Standalone single-character literals, such as ALL (`*`), are now parsed and stringified
  337 + correctly.
  338 + + `null` and `undefined` literals with additional properties, such as `repeatable`, are now
  339 + stringified correctly.
  340 ++ 0.2.0 (November 2012):
  341 + + Added `stringify()` and `stringifySync()` methods, which convert a parsed type to a type
  342 + expression.
  343 + + Simplified the parse results for function signatures. **Note**: This change is not
  344 + backwards-compatible with previous versions.
  345 + + Corrected minor errors in README.md.
  346 ++ 0.1.1 (November 2012): Added `opts` argument to `parse()` and `parseSync()` methods. **Note**: The
  347 +change to `parse()` is not backwards-compatible with previous versions.
  348 ++ 0.1.0 (November 2012): Initial release.
  349 +
  350 +## License ##
  351 +
  352 +[MIT license](https://github.com/hegemonic/catharsis/blob/master/LICENSE).
  1 +#!/usr/bin/env node
  2 +
  3 +'use strict';
  4 +
  5 +// Command-line tool that parses a type expression and dumps a JSON version of the parse tree.
  6 +var catharsis = require('../catharsis');
  7 +var path = require('path');
  8 +var util = require('util');
  9 +
  10 +var command = path.basename(process.argv[1]);
  11 +var typeExpression = process.argv[2];
  12 +var opts = {
  13 + describe: false,
  14 + jsdoc: false
  15 +};
  16 +var parsedType;
  17 +
  18 +function usage() {
  19 + console.log(util.format('Usage:\n %s typeExpression [--jsdoc] [--describe]', command));
  20 +}
  21 +
  22 +function done(err) {
  23 + /*eslint no-process-exit: 0 */
  24 + process.exit(err === undefined ? 0 : err);
  25 +}
  26 +
  27 +process.argv.slice(3).forEach(function(arg) {
  28 + var parsedArg = arg.replace(/^\-{2}/, '');
  29 + if (opts[parsedArg] !== undefined) {
  30 + opts[parsedArg] = true;
  31 + } else {
  32 + console.error('Unknown option "%s"', arg);
  33 + usage();
  34 + done(1);
  35 + }
  36 +});
  37 +
  38 +if (!typeExpression) {
  39 + usage();
  40 + done(1);
  41 +} else {
  42 + try {
  43 + parsedType = catharsis.parse(typeExpression, opts);
  44 + if (opts.describe) {
  45 + parsedType = catharsis.describe(parsedType);
  46 + }
  47 + } catch (e) {
  48 + console.error(util.format('Unable to parse "%s" (exception follows):', typeExpression));
  49 + console.error(e.stack || e.message);
  50 + done(1);
  51 + }
  52 +
  53 + console.log(JSON.stringify(parsedType, null, 2));
  54 + done();
  55 +}
  1 +/**
  2 + * Catharsis
  3 + * A parser for Google Closure Compiler type expressions, powered by PEG.js.
  4 + *
  5 + * @author Jeff Williams <jeffrey.l.williams@gmail.com>
  6 + * @license MIT License <http://opensource.org/licenses/mit-license.php/>
  7 + */
  8 +
  9 +'use strict';
  10 +
  11 +var describe = require('./lib/describe');
  12 +var parse = require('./lib/parser').parse;
  13 +var stringify = require('./lib/stringify');
  14 +
  15 +var typeExpressionCache = {
  16 + normal: {},
  17 + jsdoc: {}
  18 +};
  19 +
  20 +var parsedTypeCache = {
  21 + normal: {},
  22 + htmlSafe: {}
  23 +};
  24 +
  25 +var descriptionCache = {
  26 + normal: {}
  27 +};
  28 +
  29 +function getTypeExpressionCache(options) {
  30 + if (options.useCache === false) {
  31 + return null;
  32 + } else if (options.jsdoc === true) {
  33 + return typeExpressionCache.jsdoc;
  34 + } else {
  35 + return typeExpressionCache.normal;
  36 + }
  37 +}
  38 +
  39 +function getParsedTypeCache(options) {
  40 + if (options.useCache === false || options.links !== null || options.links !== undefined) {
  41 + return null;
  42 + } else if (options.htmlSafe === true) {
  43 + return parsedTypeCache.htmlSafe;
  44 + } else {
  45 + return parsedTypeCache.normal;
  46 + }
  47 +}
  48 +
  49 +function getDescriptionCache(options) {
  50 + if (options.useCache === false || options.links !== null || options.links !== undefined) {
  51 + return null;
  52 + } else {
  53 + return descriptionCache.normal;
  54 + }
  55 +}
  56 +
  57 +// can't return the original if any of the following are true:
  58 +// 1. restringification was requested
  59 +// 2. htmlSafe option was requested
  60 +// 3. links option was provided
  61 +// 4. typeExpression property is missing
  62 +function canReturnOriginalExpression(parsedType, options) {
  63 + return options.restringify !== true && options.htmlSafe !== true &&
  64 + (options.links === null || options.links === undefined) &&
  65 + Object.prototype.hasOwnProperty.call(parsedType, 'typeExpression');
  66 +}
  67 +
  68 +// Add non-enumerable properties to a result object, then freeze it.
  69 +function prepareFrozenObject(obj, expr, options) {
  70 + Object.defineProperty(obj, 'jsdoc', {
  71 + value: options.jsdoc === true ? true : false
  72 + });
  73 +
  74 + if (expr) {
  75 + Object.defineProperty(obj, 'typeExpression', {
  76 + value: expr
  77 + });
  78 + }
  79 +
  80 + return Object.freeze(obj);
  81 +}
  82 +
  83 +function cachedParse(expr, options) {
  84 + var cache = getTypeExpressionCache(options);
  85 + var parsedType;
  86 +
  87 + if (cache && Object.prototype.hasOwnProperty.call(cache, expr)) {
  88 + return cache[expr];
  89 + } else {
  90 + parsedType = parse(expr, options);
  91 + parsedType = prepareFrozenObject(parsedType, expr, options);
  92 +
  93 + if (cache) {
  94 + cache[expr] = parsedType;
  95 + }
  96 +
  97 + return parsedType;
  98 + }
  99 +}
  100 +
  101 +function cachedStringify(parsedType, options) {
  102 + var cache = getParsedTypeCache(options);
  103 + var json;
  104 +
  105 + if (canReturnOriginalExpression(parsedType, options)) {
  106 + return parsedType.typeExpression;
  107 + } else if (cache) {
  108 + json = JSON.stringify(parsedType);
  109 + cache[json] = cache[json] || stringify(parsedType, options);
  110 + return cache[json];
  111 + } else {
  112 + return stringify(parsedType, options);
  113 + }
  114 +}
  115 +
  116 +function cachedDescribe(parsedType, options) {
  117 + var cache = getDescriptionCache(options);
  118 + var json;
  119 + var result;
  120 +
  121 + if (cache) {
  122 + json = JSON.stringify(parsedType);
  123 + cache[json] = cache[json] || describe(parsedType, options);
  124 + return cache[json];
  125 + } else {
  126 + result = describe(parsedType, options);
  127 + result = prepareFrozenObject(result, null, options);
  128 +
  129 + return result;
  130 + }
  131 +}
  132 +
  133 +function Catharsis() {
  134 + this.Types = require('./lib/types');
  135 +}
  136 +
  137 +Catharsis.prototype.parse = function(typeExpr, options) {
  138 + options = options || {};
  139 +
  140 + typeExpr = typeExpr.replace(/[\r\n]/g, '')
  141 + .replace(/\s+/g, ' ')
  142 + .trim();
  143 +
  144 + return cachedParse(typeExpr, options);
  145 +};
  146 +
  147 +Catharsis.prototype.stringify = function(parsedType, options) {
  148 + var result;
  149 +
  150 + options = options || {};
  151 +
  152 + result = cachedStringify(parsedType, options);
  153 + if (options.validate) {
  154 + this.parse(result, options);
  155 + }
  156 +
  157 + return result;
  158 +};
  159 +
  160 +Catharsis.prototype.describe = function(parsedType, options) {
  161 + options = options || {};
  162 +
  163 + return cachedDescribe(parsedType, options);
  164 +};
  165 +
  166 +module.exports = new Catharsis();
  1 +'use strict';
  2 +
  3 +var _ = require('underscore-contrib');
  4 +var fs = require('fs');
  5 +var path = require('path');
  6 +var stringify = require('./stringify');
  7 +var Types = require('./types');
  8 +var util = require('util');
  9 +
  10 +var DEFAULT_OPTIONS = {
  11 + language: 'en',
  12 + resources: {
  13 + en: JSON.parse(fs.readFileSync(path.join(__dirname, '../res/en.json'), 'utf8'))
  14 + }
  15 +};
  16 +
  17 +// order matters for these!
  18 +var FUNCTION_DETAILS = ['new', 'this'];
  19 +var FUNCTION_DETAILS_VARIABLES = ['functionNew', 'functionThis'];
  20 +var MODIFIERS = ['optional', 'nullable', 'repeatable'];
  21 +
  22 +var TEMPLATE_VARIABLES = [
  23 + 'application',
  24 + 'codeTagClose',
  25 + 'codeTagOpen',
  26 + 'element',
  27 + 'field',
  28 + 'functionNew',
  29 + 'functionParams',
  30 + 'functionReturns',
  31 + 'functionThis',
  32 + 'keyApplication',
  33 + 'name',
  34 + 'nullable',
  35 + 'optional',
  36 + 'param',
  37 + 'prefix',
  38 + 'repeatable',
  39 + 'suffix',
  40 + 'type'
  41 +];
  42 +
  43 +var FORMATS = {
  44 + EXTENDED: 'extended',
  45 + SIMPLE: 'simple'
  46 +};
  47 +
  48 +function makeTagOpen(codeTag, codeClass) {
  49 + var tagOpen = '';
  50 + var tags = codeTag ? codeTag.split(' ') : [];
  51 +
  52 + tags.forEach(function(tag) {
  53 + var tagClass = codeClass ? util.format(' class="%s"', codeClass) : '';
  54 + tagOpen += util.format('<%s%s>', tag, tagClass);
  55 + });
  56 +
  57 + return tagOpen;
  58 +}
  59 +
  60 +function makeTagClose(codeTag) {
  61 + var tagClose = '';
  62 + var tags = codeTag ? codeTag.split(' ') : [];
  63 +
  64 + tags.reverse();
  65 + tags.forEach(function(tag) {
  66 + tagClose += util.format('</%s>', tag);
  67 + });
  68 +
  69 + return tagClose;
  70 +}
  71 +
  72 +function Result() {
  73 + this.description = '';
  74 + this.modifiers = {
  75 + functionNew: '',
  76 + functionThis: '',
  77 + optional: '',
  78 + nullable: '',
  79 + repeatable: ''
  80 + };
  81 + this.returns = '';
  82 +}
  83 +
  84 +function Context(props) {
  85 + var self = this;
  86 +
  87 + props = props || {};
  88 +
  89 + TEMPLATE_VARIABLES.forEach(function(variable) {
  90 + self[variable] = props[variable] || '';
  91 + });
  92 +}
  93 +
  94 +function Describer(opts) {
  95 + var options;
  96 +
  97 + this._useLongFormat = true;
  98 + options = this._options = _.defaults(opts || {}, DEFAULT_OPTIONS);
  99 + this._stringifyOptions = _.defaults(options, {_ignoreModifiers: true});
  100 +
  101 + // use a dictionary, not a Context object, so we can more easily merge this into Context objects
  102 + this._i18nContext = {
  103 + codeTagClose: makeTagClose(options.codeTag),
  104 + codeTagOpen: makeTagOpen(options.codeTag, options.codeClass)
  105 + };
  106 +
  107 + // templates start out as strings; we lazily replace them with template functions
  108 + this._templates = options.resources[options.language];
  109 + if (!this._templates) {
  110 + throw new Error('I18N resources are not available for the language ' + options.language);
  111 + }
  112 +}
  113 +
  114 +function modifierKind(useLongFormat) {
  115 + return useLongFormat ? FORMATS.EXTENDED : FORMATS.SIMPLE;
  116 +}
  117 +
  118 +function buildModifierStrings(describer, modifiers, type, useLongFormat) {
  119 + var result = {};
  120 +
  121 + modifiers.forEach(function(modifier) {
  122 + var key = modifierKind(useLongFormat);
  123 + var modifierStrings = describer[modifier](type[modifier]);
  124 +
  125 + result[modifier] = modifierStrings[key];
  126 + });
  127 +
  128 + return result;
  129 +}
  130 +
  131 +function addModifiers(describer, context, result, type, useLongFormat) {
  132 + var keyPrefix = 'modifiers.' + modifierKind(useLongFormat);
  133 + var modifiers = buildModifierStrings(describer, MODIFIERS, type, useLongFormat);
  134 +
  135 + MODIFIERS.forEach(function(modifier) {
  136 + var modifierText = modifiers[modifier] || '';
  137 +
  138 + result.modifiers[modifier] = modifierText;
  139 + if (!useLongFormat) {
  140 + context[modifier] = modifierText;
  141 + }
  142 + });
  143 +
  144 + context.prefix = describer._translate(keyPrefix + '.prefix', context);
  145 + context.suffix = describer._translate(keyPrefix + '.suffix', context);
  146 +}
  147 +
  148 +function addFunctionModifiers(describer, context, result, type, useLongFormat) {
  149 + var functionDetails = buildModifierStrings(describer, FUNCTION_DETAILS, type, useLongFormat);
  150 + var kind = modifierKind(useLongFormat);
  151 + var strings = [];
  152 +
  153 + FUNCTION_DETAILS.forEach(function(functionDetail, i) {
  154 + var functionExtraInfo = functionDetails[functionDetail] || '';
  155 + var functionDetailsVariable = FUNCTION_DETAILS_VARIABLES[i];
  156 +
  157 + result.modifiers[functionDetailsVariable] = functionExtraInfo;
  158 + if (!useLongFormat) {
  159 + context[functionDetailsVariable] += functionExtraInfo;
  160 + }
  161 + });
  162 +}
  163 +
  164 +// Replace 2+ whitespace characters with a single whitespace character.
  165 +function collapseSpaces(string) {
  166 + return string.replace(/(\s)+/g, '$1');
  167 +}
  168 +
  169 +Describer.prototype._stringify = function(type, typeString, useLongFormat) {
  170 + var context = new Context({
  171 + type: typeString || stringify(type, this._stringifyOptions)
  172 + });
  173 + var result = new Result();
  174 +
  175 + addModifiers(this, context, result, type, useLongFormat);
  176 + result.description = this._translate('type', context).trim();
  177 +
  178 + return result;
  179 +};
  180 +
  181 +Describer.prototype._translate = function(key, context) {
  182 + var result;
  183 + var templateFunction = _.getPath(this._templates, key);
  184 +
  185 + context = context || new Context();
  186 +
  187 + if (templateFunction === undefined) {
  188 + throw new Error(util.format('The template %s does not exist for the language %s', key,
  189 + this._options.language));
  190 + }
  191 +
  192 + // compile and cache the template function if necessary
  193 + if (typeof templateFunction === 'string') {
  194 + // force the templates to use the `context` object
  195 + templateFunction = templateFunction.replace(/\<\%\= /g, '<%= context.');
  196 + templateFunction = _.template(templateFunction, null, {variable: 'context'});
  197 + _.setPath(this._templates, templateFunction, key);
  198 + }
  199 +
  200 + result = (templateFunction(_.extend(context, this._i18nContext)) || '')
  201 + // strip leading spaces
  202 + .replace(/^\s+/, '');
  203 + result = collapseSpaces(result);
  204 +
  205 + return result;
  206 +};
  207 +
  208 +Describer.prototype._modifierHelper = function(key, modifierPrefix, context) {
  209 + modifierPrefix = modifierPrefix || '';
  210 +
  211 + return {
  212 + extended: key ?
  213 + this._translate(util.format('%s.%s.%s', modifierPrefix, FORMATS.EXTENDED, key),
  214 + context) :
  215 + '',
  216 + simple: key ?
  217 + this._translate(util.format('%s.%s.%s', modifierPrefix, FORMATS.SIMPLE, key), context) :
  218 + ''
  219 + };
  220 +};
  221 +
  222 +Describer.prototype._translateModifier = function(key, context) {
  223 + return this._modifierHelper(key, 'modifiers', context);
  224 +};
  225 +
  226 +Describer.prototype._translateFunctionModifier = function(key, context) {
  227 + return this._modifierHelper(key, 'function', context);
  228 +};
  229 +
  230 +function getApplicationKey(type, applications) {
  231 + if (applications.length === 1) {
  232 + if (/[Aa]rray/.test(type.expression.name)) {
  233 + return 'array';
  234 + } else {
  235 + return 'other';
  236 + }
  237 + } else if (/[Ss]tring/.test(applications[0].name)) {
  238 + // object with string keys
  239 + return 'object';
  240 + } else {
  241 + // object with non-string keys
  242 + return 'objectNonString';
  243 + }
  244 +}
  245 +
  246 +Describer.prototype.application = function(type, useLongFormat) {
  247 + var applications = type.applications.slice(0);
  248 + var context = new Context();
  249 + var key = 'application.' + getApplicationKey(type, applications);
  250 + var result = new Result();
  251 + var self = this;
  252 +
  253 + addModifiers(this, context, result, type, useLongFormat);
  254 +
  255 + context.type = this.type(type.expression).description;
  256 + context.application = this.type(applications.pop()).description;
  257 + context.keyApplication = applications.length ? this.type(applications.pop()).description : '';
  258 +
  259 + result.description = this._translate(key, context).trim();
  260 +
  261 + return result;
  262 +};
  263 +
  264 +function reduceMultiple(context, keyName, contextName, translate, previous, current, index, items) {
  265 + var key =
  266 + index === 0 ? '.first.many' :
  267 + index === (items.length - 1) ? '.last.many' :
  268 + '.middle.many';
  269 +
  270 + key = keyName + key;
  271 + context[contextName] = items[index];
  272 +
  273 + return previous + translate(key, context);
  274 +}
  275 +
  276 +Describer.prototype.elements = function(type, useLongFormat) {
  277 + var context = new Context();
  278 + var items = type.elements.slice(0);
  279 + var result = new Result();
  280 +
  281 + addModifiers(this, context, result, type, useLongFormat);
  282 + result.description = this._combineMultiple(items, context, 'union', 'element', useLongFormat);
  283 +
  284 + return result;
  285 +};
  286 +
  287 +Describer.prototype.new = function(funcNew) {
  288 + var context = new Context({'functionNew': this.type(funcNew).description});
  289 + var key = funcNew ? 'new' : '';
  290 +
  291 + return this._translateFunctionModifier(key, context);
  292 +};
  293 +
  294 +Describer.prototype.nullable = function(nullable) {
  295 + var key = nullable === true ? 'nullable' :
  296 + nullable === false ? 'nonNullable' :
  297 + '';
  298 +
  299 + return this._translateModifier(key);
  300 +};
  301 +
  302 +Describer.prototype.optional = function(optional) {
  303 + var key = (optional === true) ? 'optional' : '';
  304 +
  305 + return this._translateModifier(key);
  306 +};
  307 +
  308 +Describer.prototype.repeatable = function(repeatable) {
  309 + var key = (repeatable === true) ? 'repeatable' : '';
  310 +
  311 + return this._translateModifier(key);
  312 +};
  313 +
  314 +Describer.prototype._combineMultiple = function(items, context, keyName, contextName,
  315 + useLongFormat) {
  316 + var result = new Result();
  317 + var self = this;
  318 + var strings;
  319 +
  320 + strings = typeof items[0] === 'string' ?
  321 + items.slice(0) :
  322 + items.map(function(item) {
  323 + return self.type(item).description;
  324 + });
  325 +
  326 + switch(strings.length) {
  327 + case 0:
  328 + // falls through
  329 + case 1:
  330 + context[contextName] = strings[0] || '';
  331 + result.description = this._translate(keyName + '.first.one', context);
  332 + break;
  333 + case 2:
  334 + strings.forEach(function(item, idx) {
  335 + var key = keyName + (idx === 0 ? '.first' : '.last' ) + '.two';
  336 +
  337 + context[contextName] = item;
  338 + result.description += self._translate(key, context);
  339 + });
  340 + break;
  341 + default:
  342 + result.description = strings.reduce(reduceMultiple.bind(null, context, keyName,
  343 + contextName, this._translate.bind(this)), '');
  344 + }
  345 +
  346 + return result.description.trim();
  347 +};
  348 +
  349 +Describer.prototype.params = function(params, functionContext) {
  350 + var context = new Context();
  351 + var result = new Result();
  352 + var self = this;
  353 + var strings;
  354 +
  355 + // TODO: this hardcodes the order and placement of functionNew and functionThis; need to move
  356 + // this to the template (and also track whether to put a comma after the last modifier)
  357 + functionContext = functionContext || {};
  358 + params = params || [];
  359 + strings = params.map(function(param) {
  360 + return self.type(param).description;
  361 + });
  362 +
  363 + if (functionContext.functionThis) {
  364 + strings.unshift(functionContext.functionThis);
  365 + }
  366 + if (functionContext.functionNew) {
  367 + strings.unshift(functionContext.functionNew);
  368 + }
  369 + result.description = this._combineMultiple(strings, context, 'params', 'param', false);
  370 +
  371 + return result;
  372 +};
  373 +
  374 +Describer.prototype.this = function(funcThis) {
  375 + var context = new Context({'functionThis': this.type(funcThis).description});
  376 + var key = funcThis ? 'this' : '';
  377 +
  378 + return this._translateFunctionModifier(key, context);
  379 +};
  380 +
  381 +Describer.prototype.type = function(type, useLongFormat) {
  382 + var result = new Result();
  383 +
  384 + if (useLongFormat === undefined) {
  385 + useLongFormat = this._useLongFormat;
  386 + }
  387 + // ensure we don't use the long format for inner types
  388 + this._useLongFormat = false;
  389 +
  390 + if (!type) {
  391 + return result;
  392 + }
  393 +
  394 + switch(type.type) {
  395 + case Types.AllLiteral:
  396 + result = this._stringify(type, this._translate('all'), useLongFormat);
  397 + break;
  398 + case Types.FunctionType:
  399 + result = this._signature(type, useLongFormat);
  400 + break;
  401 + case Types.NameExpression:
  402 + result = this._stringify(type, null, useLongFormat);
  403 + break;
  404 + case Types.NullLiteral:
  405 + result = this._stringify(type, this._translate('null'), useLongFormat);
  406 + break;
  407 + case Types.RecordType:
  408 + result = this._record(type, useLongFormat);
  409 + break;
  410 + case Types.TypeApplication:
  411 + result = this.application(type, useLongFormat);
  412 + break;
  413 + case Types.TypeUnion:
  414 + result = this.elements(type, useLongFormat);
  415 + break;
  416 + case Types.UndefinedLiteral:
  417 + result = this._stringify(type, this._translate('undefined'), useLongFormat);
  418 + break;
  419 + case Types.UnknownLiteral:
  420 + result = this._stringify(type, this._translate('unknown'), useLongFormat);
  421 + break;
  422 + default:
  423 + throw new Error('Unknown type: ' + JSON.stringify(type));
  424 + }
  425 +
  426 + return result;
  427 +};
  428 +
  429 +Describer.prototype._record = function(type, useLongFormat) {
  430 + var context = new Context();
  431 + var items;
  432 + var result = new Result();
  433 +
  434 + items = this._recordFields(type.fields);
  435 +
  436 + addModifiers(this, context, result, type, useLongFormat);
  437 + result.description = this._combineMultiple(items, context, 'record', 'field', useLongFormat);
  438 +
  439 + return result;
  440 +};
  441 +
  442 +Describer.prototype._recordFields = function(fields) {
  443 + var context = new Context();
  444 + var result = [];
  445 + var self = this;
  446 +
  447 + if (!fields.length) {
  448 + return result;
  449 + }
  450 +
  451 + result = fields.map(function(field) {
  452 + var key = 'field.' + (field.value ? 'typed' : 'untyped');
  453 +
  454 + context.name = self.type(field.key).description;
  455 + if (field.value) {
  456 + context.type = self.type(field.value).description;
  457 + }
  458 +
  459 + return self._translate(key, context);
  460 + });
  461 +
  462 + return result;
  463 +};
  464 +
  465 +Describer.prototype._addLinks = function(nameString) {
  466 + var linkClass = '';
  467 + var options = this._options;
  468 + var result = nameString;
  469 +
  470 +
  471 + if (options.links && Object.prototype.hasOwnProperty.call(options.links, nameString)) {
  472 + if (options.linkClass) {
  473 + linkClass = util.format(' class="%s"', options.linkClass);
  474 + }
  475 +
  476 + nameString = util.format('<a href="%s"%s>%s</a>', options.links[nameString], linkClass,
  477 + nameString);
  478 + }
  479 +
  480 + return nameString;
  481 +};
  482 +
  483 +Describer.prototype.result = function(type, useLongFormat) {
  484 + var context = new Context();
  485 + var description;
  486 + var key = 'function.' + modifierKind(useLongFormat) + '.returns';
  487 + var result = new Result();
  488 +
  489 + context.type = this.type(type).description;
  490 +
  491 + addModifiers(this, context, result, type, useLongFormat);
  492 + result.description = this._translate(key, context);
  493 +
  494 + return result;
  495 +};
  496 +
  497 +Describer.prototype._signature = function(type, useLongFormat) {
  498 + var context = new Context();
  499 + var functionModifiers;
  500 + var kind = modifierKind(useLongFormat);
  501 + var result = new Result();
  502 + var returns;
  503 + var self = this;
  504 +
  505 + addModifiers(this, context, result, type, useLongFormat);
  506 + addFunctionModifiers(this, context, result, type, useLongFormat);
  507 +
  508 + context.functionParams = this.params(type.params || [], context).description;
  509 +
  510 + if (type.result) {
  511 + returns = this.result(type.result, useLongFormat);
  512 + if (useLongFormat) {
  513 + result.returns = returns.description;
  514 + } else {
  515 + context.functionReturns = returns.description;
  516 + }
  517 + }
  518 +
  519 + result.description += this._translate('function.' + kind + '.signature', context).trim();
  520 +
  521 + return result;
  522 +};
  523 +
  524 +module.exports = function(type, options) {
  525 + var simple = new Describer(options).type(type, false);
  526 + var extended = new Describer(options).type(type);
  527 +
  528 + [simple, extended].forEach(function(result) {
  529 + result.description = collapseSpaces(result.description.trim());
  530 + });
  531 +
  532 + return {
  533 + simple: simple.description,
  534 + extended: extended
  535 + };
  536 +};
此 diff 太大无法显示。
  1 +'use strict';
  2 +
  3 +var _ = require('underscore-contrib');
  4 +
  5 +// JSON schema types
  6 +var ARRAY = 'array';
  7 +var BOOLEAN = 'boolean';
  8 +var OBJECT = 'object';
  9 +var STRING = 'string';
  10 +var UNDEFINED = 'undefined';
  11 +
  12 +var TYPES = require('./types');
  13 +var TYPE_NAMES = _.values(TYPES);
  14 +
  15 +module.exports = {
  16 + id: '#parsedType',
  17 + type: [OBJECT, UNDEFINED],
  18 + additionalProperties: false,
  19 + properties: {
  20 + type: {
  21 + type: STRING,
  22 + enum: TYPE_NAMES
  23 + },
  24 +
  25 + // field type
  26 + key: { '$ref': '#parsedType' },
  27 + value: { '$ref': '#parsedType' },
  28 +
  29 + // function type
  30 + params: {
  31 + type: ARRAY,
  32 + items: { '$ref': '#parsedType' }
  33 + },
  34 + 'new': { '$ref': '#parsedType' },
  35 + 'this': { '$ref': '#parsedType' },
  36 + result: {'$ref': '#parsedType' },
  37 +
  38 + // name expression
  39 + name: STRING,
  40 +
  41 + // record type
  42 + fields: {
  43 + type: ARRAY,
  44 + items: { '$ref': '#parsedType' }
  45 + },
  46 +
  47 + // type application
  48 + expression: { '$ref': '#parsedType' },
  49 + applications: {
  50 + type: ARRAY,
  51 + minItems: 1,
  52 + maxItems: 2,
  53 + items: { '$ref': '#parsedType' }
  54 + },
  55 +
  56 + // type union
  57 + elements: {
  58 + type: ARRAY,
  59 + minItems: 1,
  60 + items: { '$ref': '#parsedType' }
  61 + },
  62 +
  63 + optional: BOOLEAN,
  64 + nullable: BOOLEAN,
  65 + repeatable: BOOLEAN,
  66 + reservedWord: BOOLEAN
  67 + },
  68 + required: [ 'type' ]
  69 +};
  1 +'use strict';
  2 +
  3 +var Types = require('./types');
  4 +
  5 +function Stringifier(options) {
  6 + this._options = options || {};
  7 + this._options.linkClass = this._options.linkClass || this._options.cssClass;
  8 +}
  9 +
  10 +Stringifier.prototype.applications = function(applications) {
  11 + var result = '';
  12 + var strings = [];
  13 +
  14 + if (!applications) {
  15 + return result;
  16 + }
  17 +
  18 + for (var i = 0, l = applications.length; i < l; i++) {
  19 + strings.push(this.type(applications[i]));
  20 + }
  21 +
  22 + if (this._options.htmlSafe) {
  23 + result = '.&lt;';
  24 + } else {
  25 + result = '.<';
  26 + }
  27 +
  28 + result += strings.join(', ') + '>';
  29 +
  30 + return result;
  31 +};
  32 +
  33 +Stringifier.prototype.elements = function(elements) {
  34 + var result = '';
  35 + var strings = [];
  36 +
  37 + if (!elements) {
  38 + return result;
  39 + }
  40 +
  41 + for (var i = 0, l = elements.length; i < l; i++) {
  42 + strings.push(this.type(elements[i]));
  43 + }
  44 +
  45 + result = '(' + strings.join('|') + ')';
  46 +
  47 + return result;
  48 +};
  49 +
  50 +Stringifier.prototype.name = function(name) {
  51 + return name || '';
  52 +};
  53 +
  54 +Stringifier.prototype.new = function(funcNew) {
  55 + return funcNew ? 'new:' + this.type(funcNew) : '';
  56 +};
  57 +
  58 +Stringifier.prototype.nullable = function(nullable) {
  59 + switch (nullable) {
  60 + case true:
  61 + return '?';
  62 + case false:
  63 + return '!';
  64 + default:
  65 + return '';
  66 + }
  67 +};
  68 +
  69 +Stringifier.prototype.optional = function(optional) {
  70 + if (optional === true) {
  71 + return '=';
  72 + } else {
  73 + return '';
  74 + }
  75 +};
  76 +
  77 +Stringifier.prototype.params = function(params) {
  78 + var result = '';
  79 + var strings = [];
  80 +
  81 + if (!params || params.length === 0) {
  82 + return result;
  83 + }
  84 +
  85 + for (var i = 0, l = params.length; i < l; i++) {
  86 + strings.push(this.type(params[i]));
  87 + }
  88 +
  89 + result = strings.join(', ');
  90 +
  91 + return result;
  92 +};
  93 +
  94 +Stringifier.prototype.result = function(result) {
  95 + return result ? ': ' + this.type(result) : '';
  96 +};
  97 +
  98 +Stringifier.prototype.this = function(funcThis) {
  99 + return funcThis ? 'this:' + this.type(funcThis) : '';
  100 +};
  101 +
  102 +Stringifier.prototype.type = function(type) {
  103 + var typeString = '';
  104 +
  105 + if (!type) {
  106 + return typeString;
  107 + }
  108 +
  109 + switch(type.type) {
  110 + case Types.AllLiteral:
  111 + typeString = this._formatNameAndType(type, '*');
  112 + break;
  113 + case Types.FunctionType:
  114 + typeString = this._signature(type);
  115 + break;
  116 + case Types.NullLiteral:
  117 + typeString = this._formatNameAndType(type, 'null');
  118 + break;
  119 + case Types.RecordType:
  120 + typeString = this._record(type);
  121 + break;
  122 + case Types.TypeApplication:
  123 + typeString = this.type(type.expression) + this.applications(type.applications);
  124 + break;
  125 + case Types.UndefinedLiteral:
  126 + typeString = this._formatNameAndType(type, 'undefined');
  127 + break;
  128 + case Types.TypeUnion:
  129 + typeString = this.elements(type.elements);
  130 + break;
  131 + case Types.UnknownLiteral:
  132 + typeString = this._formatNameAndType(type, '?');
  133 + break;
  134 + default:
  135 + typeString = this._formatNameAndType(type);
  136 + }
  137 +
  138 + // add optional/nullable/repeatable modifiers
  139 + if (!this._options._ignoreModifiers) {
  140 + typeString = this._addModifiers(type, typeString);
  141 + }
  142 +
  143 + return typeString;
  144 +};
  145 +
  146 +Stringifier.prototype.stringify = Stringifier.prototype.type;
  147 +
  148 +Stringifier.prototype.key = Stringifier.prototype.type;
  149 +
  150 +Stringifier.prototype._record = function(type) {
  151 + var fields = this._recordFields(type.fields);
  152 +
  153 + return '{' + fields.join(', ') + '}';
  154 +};
  155 +
  156 +Stringifier.prototype._recordFields = function(fields) {
  157 + var field;
  158 + var keyAndValue;
  159 +
  160 + var result = [];
  161 +
  162 + if (!fields) {
  163 + return result;
  164 + }
  165 +
  166 + for (var i = 0, l = fields.length; i < l; i++) {
  167 + field = fields[i];
  168 +
  169 + keyAndValue = this.key(field.key);
  170 + keyAndValue += field.value ? ': ' + this.type(field.value) : '';
  171 +
  172 + result.push(keyAndValue);
  173 + }
  174 +
  175 + return result;
  176 +};
  177 +
  178 +function combineNameAndType(nameString, typeString) {
  179 + var separator = (nameString && typeString) ? ':' : '';
  180 +
  181 + return nameString + separator + typeString;
  182 +}
  183 +
  184 +// Adds optional, nullable, and repeatable modifiers if necessary.
  185 +Stringifier.prototype._addModifiers = function(type, typeString) {
  186 + var combined;
  187 +
  188 + var optional = '';
  189 + var repeatable = '';
  190 +
  191 + if (type.repeatable) {
  192 + repeatable = '...';
  193 + }
  194 +
  195 + combined = this.nullable(type.nullable) + combineNameAndType('', typeString);
  196 + optional = this.optional(type.optional);
  197 +
  198 + return repeatable + combined + optional;
  199 +};
  200 +
  201 +Stringifier.prototype._addLinks = function(nameString) {
  202 + var openTag;
  203 +
  204 + var linkClass = '';
  205 + var options = this._options;
  206 +
  207 + if (options.links && Object.prototype.hasOwnProperty.call(options.links, nameString)) {
  208 + if (options.linkClass) {
  209 + linkClass = ' class="' + options.linkClass + '"';
  210 + }
  211 +
  212 + openTag = '<a href="' + options.links[nameString] + '"' + linkClass + '>';
  213 + nameString = openTag + nameString + '</a>';
  214 + }
  215 +
  216 + return nameString;
  217 +};
  218 +
  219 +Stringifier.prototype._formatNameAndType = function(type, literal) {
  220 + var nameString = type.name || literal || '';
  221 + var typeString = type.type ? this.type(type.type) : '';
  222 +
  223 + nameString = this._addLinks(nameString);
  224 +
  225 + return combineNameAndType(nameString, typeString);
  226 +};
  227 +
  228 +Stringifier.prototype._signature = function(type) {
  229 + var param;
  230 + var prop;
  231 + var signature;
  232 +
  233 + var params = [];
  234 + // these go within the signature's parens, in this order
  235 + var props = [
  236 + 'new',
  237 + 'this',
  238 + 'params'
  239 + ];
  240 +
  241 + for (var i = 0, l = props.length; i < l; i++) {
  242 + prop = props[i];
  243 + param = this[prop](type[prop]);
  244 + if (param.length > 0) {
  245 + params.push(param);
  246 + }
  247 + }
  248 +
  249 + signature = 'function(' + params.join(', ') + ')';
  250 + signature += this.result(type.result);
  251 +
  252 + return signature;
  253 +};
  254 +
  255 +
  256 +module.exports = function(type, options) {
  257 + return new Stringifier(options).stringify(type);
  258 +};
  1 +'use strict';
  2 +
  3 +module.exports = Object.freeze({
  4 + // `*`
  5 + AllLiteral: 'AllLiteral',
  6 + // like `blah` in `{blah: string}`
  7 + FieldType: 'FieldType',
  8 + // like `function(string): string`
  9 + FunctionType: 'FunctionType',
  10 + // any string literal, such as `string` or `My.Namespace`
  11 + NameExpression: 'NameExpression',
  12 + // null
  13 + NullLiteral: 'NullLiteral',
  14 + // like `{foo: string}`
  15 + RecordType: 'RecordType',
  16 + // like `Array.<string>`
  17 + TypeApplication: 'TypeApplication',
  18 + // like `(number|string)`
  19 + TypeUnion: 'TypeUnion',
  20 + // undefined
  21 + UndefinedLiteral: 'UndefinedLiteral',
  22 + // `?`
  23 + UnknownLiteral: 'UnknownLiteral'
  24 +});
  1 +{
  2 + "_args": [
  3 + [
  4 + {
  5 + "raw": "catharsis@~0.8.9",
  6 + "scope": null,
  7 + "escapedName": "catharsis",
  8 + "name": "catharsis",
  9 + "rawSpec": "~0.8.9",
  10 + "spec": ">=0.8.9 <0.9.0",
  11 + "type": "range"
  12 + },
  13 + "/Users/fzy/project/koa2_Sequelize_project/node_modules/jsdoc"
  14 + ]
  15 + ],
  16 + "_from": "catharsis@>=0.8.9 <0.9.0",
  17 + "_id": "catharsis@0.8.9",
  18 + "_inCache": true,
  19 + "_location": "/catharsis",
  20 + "_nodeVersion": "6.10.2",
  21 + "_npmOperationalInternal": {
  22 + "host": "s3://npm-registry-packages",
  23 + "tmp": "tmp/catharsis-0.8.9.tgz_1499903127213_0.83025440457277"
  24 + },
  25 + "_npmUser": {
  26 + "name": "hegemonic",
  27 + "email": "jeffrey.l.williams@gmail.com"
  28 + },
  29 + "_npmVersion": "3.10.10",
  30 + "_phantomChildren": {},
  31 + "_requested": {
  32 + "raw": "catharsis@~0.8.9",
  33 + "scope": null,
  34 + "escapedName": "catharsis",
  35 + "name": "catharsis",
  36 + "rawSpec": "~0.8.9",
  37 + "spec": ">=0.8.9 <0.9.0",
  38 + "type": "range"
  39 + },
  40 + "_requiredBy": [
  41 + "/jsdoc"
  42 + ],
  43 + "_resolved": "https://registry.npmjs.org/catharsis/-/catharsis-0.8.9.tgz",
  44 + "_shasum": "98cc890ca652dd2ef0e70b37925310ff9e90fc8b",
  45 + "_shrinkwrap": null,
  46 + "_spec": "catharsis@~0.8.9",
  47 + "_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/jsdoc",
  48 + "author": {
  49 + "name": "Jeff Williams",
  50 + "email": "jeffrey.l.williams@gmail.com"
  51 + },
  52 + "bugs": {
  53 + "url": "https://github.com/hegemonic/catharsis/issues"
  54 + },
  55 + "dependencies": {
  56 + "underscore-contrib": "~0.3.0"
  57 + },
  58 + "description": "A JavaScript parser for Google Closure Compiler and JSDoc type expressions.",
  59 + "devDependencies": {
  60 + "mocha": "~2.0.1",
  61 + "pegjs": "https://github.com/dmajda/pegjs/tarball/eaca5f0acf97b66ef141fed84aa95d4e72e33757",
  62 + "should": "~4.0.4",
  63 + "tv4": "https://github.com/geraintluff/tv4/tarball/eb7561072d44943306e5fd88b55b4a4c98cb6c75"
  64 + },
  65 + "directories": {},
  66 + "dist": {
  67 + "shasum": "98cc890ca652dd2ef0e70b37925310ff9e90fc8b",
  68 + "tarball": "https://registry.npmjs.org/catharsis/-/catharsis-0.8.9.tgz"
  69 + },
  70 + "engines": {
  71 + "node": ">= 0.10"
  72 + },
  73 + "gitHead": "e318f14f6d9b615fb2b90e8fac681b12fd98b03e",
  74 + "homepage": "https://github.com/hegemonic/catharsis#readme",
  75 + "license": "MIT",
  76 + "main": "catharsis.js",
  77 + "maintainers": [
  78 + {
  79 + "name": "hegemonic",
  80 + "email": "jeffrey.l.williams@gmail.com"
  81 + }
  82 + ],
  83 + "name": "catharsis",
  84 + "optionalDependencies": {},
  85 + "readme": "# Catharsis #\n\nA JavaScript parser for\n[Google Closure Compiler](https://developers.google.com/closure/compiler/docs/js-for-compiler#types)\nand [JSDoc](https://github.com/jsdoc3/jsdoc) type expressions.\n\nCatharsis is designed to be:\n\n+ **Accurate**. Catharsis is based on a [PEG.js](http://pegjs.majda.cz/) grammar that's designed to\nhandle any valid type expression. It uses a [Mocha](http://visionmedia.github.com/mocha/) test suite\nto verify the parser's accuracy.\n+ **Fast**. Parse results are cached, so the parser is invoked only when necessary.\n+ **Flexible**. Catharsis can convert a parse result back into a type expression, or into a\ndescription of the type expression. In addition, Catharsis can parse\n[JSDoc](https://github.com/jsdoc3/jsdoc)-style type expressions.\n\n\n## Example ##\n\n```js\nvar catharsis = require('catharsis');\n\n// Google Closure Compiler parsing\nvar type = '!Object';\nvar parsedType;\ntry {\n parsedType = catharsis.parse(type); // {\"type\":\"NameExpression,\"name\":\"Object\",\"nullable\":false}\n} catch(e) {\n console.error('unable to parse %s: %s', type, e);\n}\n\n// JSDoc-style type expressions enabled\nvar jsdocType = 'string[]'; // Closure Compiler expects Array.<string>\nvar parsedJsdocType;\ntry {\n parsedJsdocType = catharsis.parse(jsdocType, {jsdoc: true});\n} catch (e) {\n console.error('unable to parse %s: %s', jsdocType, e);\n}\n\n// Converting parse results back to type expressions\ncatharsis.stringify(parsedType); // !Object\ncatharsis.stringify(parsedJsdocType); // string[]\ncatharsis.stringify(parsedJsdocType, {restringify: true}); // Array.<string>\n\n// Converting parse results to descriptions of the type expression\ncatharsis.describe(parsedType).simple; // non-null Object\ncatharsis.describe(parsedJsdocType).simple; // Array of string\n```\n\nSee the [test/specs directory](test/specs) for more examples of Catharsis' parse results.\n\n\n## Methods ##\n\n### parse(typeExpression, options) ###\nParse a type expression, and return the parse results. Throws an error if the type expression cannot\nbe parsed.\n\nWhen called without options, Catharsis attempts to parse type expressions in the same way as\nClosure Compiler. When the `jsdoc` option is enabled, Catharsis can also parse several kinds of\ntype expressions that are permitted in [JSDoc](https://github.com/jsdoc3/jsdoc):\n\n+ The string `function` is treated as a function type with no parameters.\n+ The period may be omitted from type applications. For example, `Array.<string>` and\n`Array<string>` will be parsed in the same way.\n+ You may append `[]` to a name expression (for example, `string[]`) to interpret it as a type\napplication with the expression `Array` (for example, `Array.<string>`).\n+ Name expressions may contain the characters `#`, `~`, `:`, and `/`.\n+ Name expressions may contain a suffix that is similar to a function signature (for example,\n`MyClass(foo, bar)`).\n+ Name expressions may contain a reserved word.\n+ Record types may use types other than name expressions for keys.\n\n#### Parameters ####\n+ `type`: A string containing a Closure Compiler type expression.\n+ `options`: Options for parsing the type expression.\n + `options.jsdoc`: Specifies whether to enable parsing of JSDoc-style type expressions. Defaults\n to `false`.\n + `options.useCache`: Specifies whether to use the cache of parsed types. Defaults to `true`.\n\n#### Returns ####\nAn object containing the parse results. See the [test/specs directory](test/specs) for examples of\nthe parse results for different type expressions.\n\nThe object also includes two non-enumerable properties:\n\n+ `jsdoc`: A boolean indicating whether the type expression was parsed with JSDoc support enabled.\n+ `typeExpression`: A string containing the type expression that was parsed.\n\n### stringify(parsedType, options) ###\nStringify `parsedType`, and return the type expression. If validation is enabled, throws an error if\nthe stringified type expression cannot be parsed.\n\n#### Parameters ####\n+ `parsedType`: An object containing a parsed Closure Compiler type expression.\n+ `options`: Options for stringifying the parse results.\n + `options.cssClass`: Synonym for `options.linkClass`. Deprecated in version 0.8.0; will be\n removed in a future version.\n + `options.htmlSafe`: Specifies whether to return an HTML-safe string that replaces left angle\n brackets (`<`) with the corresponding entity (`&lt;`). **Note**: Characters in name expressions\n are not escaped.\n + `options.linkClass`: A CSS class to add to HTML links. Used only if `options.links` is\n provided. By default, no CSS class is added.\n + `options.links`: An object whose keys are name expressions and whose values are URIs. If a\n name expression matches a key in `options.links`, the name expression will be wrapped in an\n HTML `<a>` tag that links to the URI. If `options.linkClass` is specified, the `<a>` tag will\n include a `class` attribute. **Note**: When using this option, parsed types are always\n restringified, and the resulting string is not cached.\n + `options.restringify`: Forces Catharsis to restringify the parsed type. If this option is not\n specified, and the parsed type object includes a `typeExpression` property, Catharsis will\n return the `typeExpression` property without modification when possible. Defaults to `false`.\n + `options.useCache`: Specifies whether to use the cache of stringified type expressions.\n Defaults to `true`.\n + `options.validate`: Specifies whether to validate the stringified parse results by attempting\n to parse them as a type expression. If the stringified results are not parsable by default, you\n must also provide the appropriate options to pass to the `parse()` method. Defaults to `false`.\n\n#### Returns ####\nA string containing the type expression.\n\n### describe(parsedType, options) ###\nConvert a parsed type to a description of the type expression. This method is especially useful if\nyour users are not familiar with the syntax for type expressions.\n\nThe `describe()` method returns the description in two formats:\n\n+ **Simple format**. A string that provides a complete description of the type expression.\n+ **Extended format**. An object that separates out some of the details about the outermost type\nexpression, such as whether the type is optional, nullable, or repeatable.\n\nFor example, if you call `describe('?function(new:MyObject, string)=')`, it returns the following\nobject:\n\n```js\n{\n simple: 'optional nullable function(constructs MyObject, string)',\n extended: {\n description: 'function(string)',\n modifiers: {\n functionNew: 'Returns MyObject when called with new.',\n functionThis: '',\n optional: 'Optional.',\n nullable: 'May be null.',\n repeatable: ''\n },\n returns: ''\n }\n}\n```\n\n#### Parameters ####\n+ `parsedType`: An object containing a parsed Closure Compiler type expression.\n+ `options`: Options for creating the description.\n + `options.codeClass`: A CSS class to add to the tag that is wrapped around type names. Used\n only if `options.codeTag` is provided. By default, no CSS class is added.\n + `options.codeTag`: The name of an HTML tag (for example, `code`) to wrap around type names.\n For example, if this option is set to `code`, the type expression `Array.<string>` would have\n the simple description `<code>Array</code> of <code>string</code>`.\n + `options.language`: A string identifying the language in which to generate the description.\n The identifier should be an\n [ISO 639-1 language code](http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (for example,\n `en`). It can optionally be followed by a hyphen and an\n [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) (for example,\n `en-US`). If you use values other than `en`, you must provide translation resources in\n `options.resources`. Defaults to `en`.\n + `options.linkClass`: A CSS class to add to HTML links. Used only if `options.links` is\n provided. By default, no CSS class is added.\n + `options.links`: An object whose keys are name expressions and whose values are URIs. If a\n name expression matches a key in `options.links`, the name expression will be wrapped in an\n HTML `<a>` tag that links to the URI. If `options.linkClass` is specified, the `<a>` tag will\n include a `class` attribute. **Note**: When using this option, the description is not cached.\n + `options.resources`: An object that specifies how to describe type expressions for a given\n language. The object's property names should use the same format as `options.language`. Each\n property should contain an object in the same format as the translation resources in\n [res/en.json](res/en.json). If you specify a value for `options.resources.en`, it will override\n the defaults in [res/en.json](res/en.json).\n + `options.useCache`: Specifies whether to use the cache of descriptions. Defaults to `true`.\n\n### Returns ###\nAn object with the following properties:\n\n+ `simple`: A string that provides a complete description of the type expression.\n+ `extended`: An object containing details about the outermost type expression.\n + `extended.description`: A string that provides a basic description of the type expression,\n excluding the information contained in other properties.\n + `extended.modifiers`: Information about modifiers that apply to the type expression.\n + `extended.modifiers.functionNew`: A string describing what a function returns when called\n with `new`. Used only for function types.\n + `extended.modifiers.functionThis`: A string describing what the keyword `this` refers to\n within a function. Used only for function types.\n + `extended.modifiers.nullable`: A string indicating whether the type is nullable or\n non-nullable.\n + `extended.modifiers.optional`: A string indicating whether the type is optional.\n + `extended.modifiers.repeatable`: A string indicating whether the type can be provided\n + `extended.returns`: A string describing the function's return value. Used only for function\n types.\n\n\n## Installation ##\n\nWith [npm](http://npmjs.org):\n\n npm install catharsis\n\nOr by cloning the git repo:\n\n git clone git://github.com/hegemonic/catharsis.git\n cd catharsis\n npm install\n\n\n## Roadmap and known issues ##\n\nTake a look at the [issue tracker](https://github.com/hegemonic/catharsis/issues) to see what's in\nstore for Catharsis.\n\nBug reports, feature requests, and pull requests are always welcome! If you're working on a large\npull request, please contact me in advance so I can help things go smoothly.\n\n**Note**: The parse tree's format should not be considered final until Catharsis reaches version\n1.0. I'll do my best to provide release notes for any changes.\n\n\n## Changelog ##\n\n+ 0.8.9 (July 2017): Type expressions that include an `@` sign (for example,\n`module:@prefix/mymodule~myCallback`) are now supported.\n+ 0.8.8 (April 2016): Corrected the description of type applications other than arrays that contain\na single type (for example, `Promise.<string>`).\n+ 0.8.7 (June 2015):\n + Record types that use numeric literals as property names (for example, `{0: string}`) are now\n parsed correctly.\n + Record types with a property that contains a function, with no space after the preceding colon\n (for example, `{foo:function()}`), are now parsed correctly.\n + Repeatable function parameters are no longer required to be enclosed in brackets, regardless\n of whether JSDoc-style type expressions are enabled. In addition, the brackets are omitted when\n stringifying a parsed type expression.\n+ 0.8.6 (December 2014): Improved the description of the unknown type.\n+ 0.8.5 (December 2014): Added support for postfix nullable/non-nullable operators combined with the\noptional operator (for example, `foo?=`).\n+ 0.8.4 (December 2014): JSDoc-style nested arrays (for example, `number[][]`) are now parsed\ncorrectly when JSDoc-style type expressions are enabled.\n+ 0.8.3 (October 2014):\n + Type applications are no longer required to include a period (`.`) as a separator, regardless\n of whether JSDoc-style type expressions are enabled.\n + Type unions that are not enclosed in parentheses can now include the repeatable (`...`)\n modifier when JSDoc-style type expressions are enabled.\n + Name expressions may now be enclosed in single or double quotation marks when JSDoc-style\n type expressions are enabled.\n+ 0.8.2 (June 2014): Fixed a compatibility issue with the JSDoc fork of Mozilla Rhino.\n+ 0.8.1 (June 2014): Added support for type unions that are not enclosed in parentheses, and that\ncontain nullable or non-nullable modifiers (for example, `!string|!number`).\n+ 0.8.0 (May 2014):\n + Added a `describe()` method, which converts a parsed type to a description of the type.\n + Added a `linkClass` option to the `stringify()` method, and deprecated the existing `cssClass`\n option. The `cssClass` option will be removed in a future release.\n + Clarified and corrected several sections in the `README`.\n+ 0.7.1 (April 2014): In record types, property names that begin with a keyword (for example,\n`undefinedHTML`) are now parsed correctly when JSDoc-style type expressions are enabled.\n+ 0.7.0 (October 2013):\n + Repeatable type expressions other than name expressions (for example, `...function()`) are now\n parsed and stringified correctly.\n + Type expressions that are both repeatable and either nullable or non-nullable (for example,\n `...!number`) are now parsed and stringified correctly.\n + Name expressions are now parsed correctly when they match a property name in an object\n instance (for example, `constructor`).\n+ 0.6.0 (September 2013): Added support for the type expression `function[]` when JSDoc-style type\nexpressions are enabled.\n+ 0.5.6 (April 2013):\n + For consistency with Google Closure Library, parentheses are no longer required around type\n unions. (In previous versions, the parentheses could be omitted when JSDoc support was enabled.)\n + For consistency with Google Closure Library, you can now use postfix notation for the `?`\n (nullable) and `!` (non-nullable) modifiers. For example, `?string` and `string?` are now\n treated as equivalent.\n + String literals and numeric literals are now allowed as property names within name\n expressions. For example, the name expression `Foo.\"bar\"` is now parsed correctly.\n+ 0.5.5 (April 2013): Corrected a parsing issue with name expressions that end with a value enclosed\nin parentheses.\n+ 0.5.4 (April 2013):\n + Repeatable literals (for example, `...*`) are now parsed correctly.\n + When JSDoc-style type expressions are enabled, a name expression can now contain a value\n enclosed in parentheses at the end of the name expression (for example, `MyClass(2)`).\n+ 0.5.3 (March 2013): The `parse()` method now correctly parses name expressions that contain\nhyphens.\n+ 0.5.2 (March 2013): The `parse()` method now correctly parses function types when JSDoc-style type\nexpressions are enabled.\n+ 0.5.1 (March 2013): Newlines and extra spaces are now removed from type expressions before they\nare parsed.\n+ 0.5.0 (March 2013):\n + The `parse()` method's `lenient` option has been renamed to `jsdoc`. **Note**: This change is\n not backwards-compatible with previous versions.\n + The `stringify()` method now accepts `cssClass` and `links` options, which you can use to\n add HTML links to a type expression.\n+ 0.4.3 (March 2013):\n + The `stringify()` method no longer caches HTML-safe type expressions as if they were normal\n type expressions.\n + The `stringify()` method's options parameter may now include an `options.restringify`\n property, and the behavior of the `options.useCache` property has changed.\n+ 0.4.2 (March 2013):\n + When lenient parsing is enabled, name expressions can now contain the characters `:` and `/`.\n + When lenient parsing is enabled, a name expression followed by `[]` (for example, `string[]`)\n will be interpreted as a type application with the expression `Array` (for example,\n `Array.<string>`).\n+ 0.4.1 (March 2013):\n + The `parse()` and `stringify()` methods now honor all of the specified options.\n + When lenient parsing is enabled, name expressions can now contain a reserved word.\n+ 0.4.0 (March 2013):\n + Catharsis now supports a lenient parsing option that can parse several kinds of malformed type\n expressions. See the documentation for details.\n + The objects containing parse results are now frozen.\n + The objects containing parse results now have two non-enumerable properties:\n + `lenient`: A boolean indicating whether the type expression was parsed in lenient mode.\n + `typeExpression`: A string containing the original type expression.\n + The `stringify()` method now honors the `useCache` option. If a parsed type includes a\n `typeExpression` property, and `useCache` is not set to `false`, the stringified type will be\n identical to the original type expression.\n+ 0.3.1 (March 2013): Type expressions that begin with a reserved word, such as `integer`, are now\nparsed correctly.\n+ 0.3.0 (March 2013):\n + The `parse()` and `stringify()` methods are now synchronous, and the `parseSync()` and\n `stringifySync()` methods have been removed. **Note**: This change is not backwards-compatible\n with previous versions.\n + The parse results now use a significantly different format from previous versions. The new\n format is more expressive and is similar, but not identical, to the format used by the\n [doctrine](https://github.com/Constellation/doctrine) parser. **Note**: This change is not\n backwards-compatible with previous versions.\n + Name expressions that contain a reserved word now include a `reservedWord: true` property.\n + Union types that are optional or nullable, or that can be passed a variable number of times,\n are now parsed and stringified correctly.\n + Optional function types and record types are now parsed and stringified correctly.\n + Function types now longer include `new` or `this` properties unless the properties are defined\n in the type expression. In addition, the `new` and `this` properties can now use any type\n expression.\n + In record types, the key for a field type can now use any type expression.\n + Standalone single-character literals, such as ALL (`*`), are now parsed and stringified\n correctly.\n + `null` and `undefined` literals with additional properties, such as `repeatable`, are now\n stringified correctly.\n+ 0.2.0 (November 2012):\n + Added `stringify()` and `stringifySync()` methods, which convert a parsed type to a type\n expression.\n + Simplified the parse results for function signatures. **Note**: This change is not\n backwards-compatible with previous versions.\n + Corrected minor errors in README.md.\n+ 0.1.1 (November 2012): Added `opts` argument to `parse()` and `parseSync()` methods. **Note**: The\nchange to `parse()` is not backwards-compatible with previous versions.\n+ 0.1.0 (November 2012): Initial release.\n\n## License ##\n\n[MIT license](https://github.com/hegemonic/catharsis/blob/master/LICENSE).\n",
  86 + "readmeFilename": "README.md",
  87 + "repository": {
  88 + "type": "git",
  89 + "url": "git+https://github.com/hegemonic/catharsis.git"
  90 + },
  91 + "scripts": {
  92 + "prepublish": "./node_modules/pegjs/bin/pegjs ./lib/parser.pegjs",
  93 + "test": "mocha"
  94 + },
  95 + "version": "0.8.9"
  96 +}
  1 +{
  2 + "all": "any type",
  3 + "application": {
  4 + "array": "<%= prefix %> <%= codeTagOpen %>Array<%= codeTagClose %> of <%= application %> <%= suffix %>",
  5 + "object": "<%= prefix %> <%= codeTagOpen %>Object<%= codeTagClose %> with <%= application %> properties <%= suffix %>",
  6 + "objectNonString": "<%= prefix %> <%= codeTagOpen %>Object<%= codeTagClose %> with <%= keyApplication %> keys and <%= application %> properties <%= suffix %>",
  7 + "other": "<%= prefix %> <%= codeTagOpen %><%= type %> containing <%= application %> <%= suffix %>"
  8 + },
  9 + "function": {
  10 + "extended": {
  11 + "new": "Returns <%= functionNew %> when called with <%= codeTagOpen %>new<%= codeTagClose %>.",
  12 + "returns": "Returns <%= type %>.",
  13 + "signature": "function(<%= functionParams %>)",
  14 + "this": "Within the function, <%= codeTagOpen %>this<%= codeTagClose %> refers to <%= functionThis %>."
  15 + },
  16 + "simple": {
  17 + "new": "constructs <%= functionNew %>",
  18 + "returns": "returns <%= type %>",
  19 + "signature": "<%= prefix %> function(<%= functionParams %>) <%= functionReturns %>",
  20 + "this": "<%= codeTagOpen %>this<%= codeTagClose %> = <%= functionThis %>"
  21 + }
  22 + },
  23 + "modifiers": {
  24 + "extended": {
  25 + "nonNullable": "Must not be null.",
  26 + "nullable": "May be null.",
  27 + "optional": "Optional.",
  28 + "prefix": "",
  29 + "repeatable": "May be provided more than once.",
  30 + "suffix": ""
  31 + },
  32 + "simple": {
  33 + "nonNullable": "non-null",
  34 + "nullable": "nullable",
  35 + "optional": "optional",
  36 + "prefix": "<%= optional %> <%= nullable %> <%= repeatable %>",
  37 + "repeatable": "repeatable",
  38 + "suffix": ""
  39 + }
  40 + },
  41 + "name": "<%= codeTagOpen %>{{ name }}<%= codeTagClose %> <%= suffix %>",
  42 + "null": "null",
  43 + "params": {
  44 + "first": {
  45 + "one": "<%= param %>",
  46 + "two": "<%= param %>, ",
  47 + "many": "<%= param %>, "
  48 + },
  49 + "middle": {
  50 + "many": "<%= param %>, "
  51 + },
  52 + "last": {
  53 + "two": "<%= param %>",
  54 + "many": "<%= param %>"
  55 + }
  56 + },
  57 + "record": {
  58 + "first": {
  59 + "one": "<%= prefix %> {<%= field %>} <%= suffix %>",
  60 + "two": "<%= prefix %> {<%= field %>, ",
  61 + "many": "<%= prefix %> {<%= field %>, "
  62 + },
  63 + "middle": {
  64 + "many": "<%= field %>, "
  65 + },
  66 + "last": {
  67 + "two": "<%= field %>} <%= suffix %>",
  68 + "many": "<%= field %>} <%= suffix %>"
  69 + }
  70 + },
  71 + "field": {
  72 + "typed": "<%= name %>: <%= type %>",
  73 + "untyped": "<%= name %>"
  74 + },
  75 + "type": "<%= prefix %> <%= codeTagOpen %><%= type %><%= codeTagClose %> <%= suffix %>",
  76 + "undefined": "undefined",
  77 + "union": {
  78 + "first": {
  79 + "one": "<%= prefix %> <%= element %> <%= suffix %>",
  80 + "two": "<%= prefix %> (<%= element %> ",
  81 + "many": "<%= prefix %> (<%= element %>, "
  82 + },
  83 + "middle": {
  84 + "many": "<%= element %>, "
  85 + },
  86 + "last": {
  87 + "two": "or <%= element %>) <%= suffix %>",
  88 + "many": "or <%= element %>) <%= suffix %>"
  89 + }
  90 + },
  91 + "unknown": "unknown"
  92 +}
  1 +## 3.0.0 ##
  2 +
  3 +* Bug fixes
  4 +* Add null and undefined in type declarations
  5 +* Remove explicit engines requirement
  6 +
  7 +## 2.0.2 ##
  8 +
  9 +* Bug fixes
  10 +
  11 +## 2.0.1 ##
  12 +
  13 +* Remove unnecessary development dependencies from npm shrinkwrap
  14 +
  15 +## 2.0.0 ##
  16 +
  17 +* Re-write in TypeScript
  18 +* Re-write to use xmlcreate (greatly simplifies module source)
  19 +* Added support for the ECMAScript 2015 Map and Set objects
  20 +* New method of calling module:
  21 + ```javascript
  22 + var js2xmlparser = require("js2xmlparser");
  23 +
  24 + var root = "root";
  25 + var data = { hello: "world" };
  26 + var options = {};
  27 +
  28 + // old method (no longer works):
  29 + // js2xmlparser(root, data, options);
  30 +
  31 + // new method:
  32 + js2xmlparser.parse(root, data, options);
  33 + ```
  34 +* New options and changes to functionality of some existing options:
  35 + * `declaration` contains additional options
  36 + * `attributeString` has additional functionality
  37 + * `valueString` has additional functionality
  38 + * The functionality provided by `prettyPrinting` is now provided by the new
  39 + `format` option, which contains additional options
  40 + * `arrayMap` is now `wrapHandlers` to reflect the fact that wrapping is
  41 + provided for both arrays and ES2015 sets
  42 + * `convertMap` is now `typeHandlers` to match the name change to `arrayMap`
  43 + * The functionality provided by `useCDATA` is now provided by the new
  44 + `cdataInvalidChars` and `cdataKeys` options, which also provide additional
  45 + functionality
  46 + * Added support for document type definitions using the `dtd` option
  47 +
  48 +## 1.0.0 ##
  49 +
  50 +* First stable release
  51 +* Add arrayMap feature
  52 +* Switch to semantic versioning
  53 +* Switch to Apache 2.0 license
  54 +
  55 +## 0.1.9 ##
  56 +
  57 +* Fix error in example.js
  58 +
  59 +## 0.1.8 ##
  60 +
  61 +* Reconcile readme and tests with examples
  62 +
  63 +## 0.1.7 ##
  64 +
  65 +* Added .gitattributes to .gitignore file
  66 +* Minor tweaks to examples
  67 +
  68 +## 0.1.6 ##
  69 +
  70 +* Addition of alias string option
  71 +* Minor changes to examples
  72 +* Minor fixes to tests
  73 +
  74 +## 0.1.5 ##
  75 +
  76 +* Bug fixes
  77 +* Minor changes to examples
  78 +
  79 +## 0.1.4 ##
  80 +
  81 +* Removed callFunctions option (functionality already provided by convertMap option)
  82 +* Removed wrapArray option (functionality already provided by existing array functionality)
  83 +* Escape numbers when at tbe beginning of an element name
  84 +* Edits to documentation
  85 +* Added tests
  86 +* Added copyright headers to individual JS files
  87 +
  88 +## 0.1.3 ##
  89 +
  90 +* Fixed crash when undefined objects are converted to strings
  91 +* Added callFunctions option
  92 +* Added wrapArray option
  93 +* Added useCDATA option
  94 +* Added convertMap option
  95 +* Added copyright year and "and other contributors" to license
  96 +
  97 +## 0.1.2 ##
  98 +
  99 +* Fixed crash when null objects are converted to strings
  100 +
  101 +## 0.1.1 ##
  102 +
  103 +* Fixed accidental truncation of XML when pretty-printing is disabled
  104 +* Removed copyright year from license
  105 +
  106 +## 0.1.0 ##
  107 +
  108 +* Initial release
  1 +Apache License
  2 +==============
  3 +
  4 +_Version 2.0, January 2004_
  5 +_&lt;<http://www.apache.org/licenses/>&gt;_
  6 +
  7 +### Terms and Conditions for use, reproduction, and distribution
  8 +
  9 +#### 1. Definitions
  10 +
  11 +“License” shall mean the terms and conditions for use, reproduction, and
  12 +distribution as defined by Sections 1 through 9 of this document.
  13 +
  14 +“Licensor” shall mean the copyright owner or entity authorized by the copyright
  15 +owner that is granting the License.
  16 +
  17 +“Legal Entity” shall mean the union of the acting entity and all other entities
  18 +that control, are controlled by, or are under common control with that entity.
  19 +For the purposes of this definition, “control” means **(i)** the power, direct or
  20 +indirect, to cause the direction or management of such entity, whether by
  21 +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
  22 +outstanding shares, or **(iii)** beneficial ownership of such entity.
  23 +
  24 +“You” (or “Your”) shall mean an individual or Legal Entity exercising
  25 +permissions granted by this License.
  26 +
  27 +“Source” form shall mean the preferred form for making modifications, including
  28 +but not limited to software source code, documentation source, and configuration
  29 +files.
  30 +
  31 +“Object” form shall mean any form resulting from mechanical transformation or
  32 +translation of a Source form, including but not limited to compiled object code,
  33 +generated documentation, and conversions to other media types.
  34 +
  35 +“Work” shall mean the work of authorship, whether in Source or Object form, made
  36 +available under the License, as indicated by a copyright notice that is included
  37 +in or attached to the work (an example is provided in the Appendix below).
  38 +
  39 +“Derivative Works” shall mean any work, whether in Source or Object form, that
  40 +is based on (or derived from) the Work and for which the editorial revisions,
  41 +annotations, elaborations, or other modifications represent, as a whole, an
  42 +original work of authorship. For the purposes of this License, Derivative Works
  43 +shall not include works that remain separable from, or merely link (or bind by
  44 +name) to the interfaces of, the Work and Derivative Works thereof.
  45 +
  46 +“Contribution” shall mean any work of authorship, including the original version
  47 +of the Work and any modifications or additions to that Work or Derivative Works
  48 +thereof, that is intentionally submitted to Licensor for inclusion in the Work
  49 +by the copyright owner or by an individual or Legal Entity authorized to submit
  50 +on behalf of the copyright owner. For the purposes of this definition,
  51 +“submitted” means any form of electronic, verbal, or written communication sent
  52 +to the Licensor or its representatives, including but not limited to
  53 +communication on electronic mailing lists, source code control systems, and
  54 +issue tracking systems that are managed by, or on behalf of, the Licensor for
  55 +the purpose of discussing and improving the Work, but excluding communication
  56 +that is conspicuously marked or otherwise designated in writing by the copyright
  57 +owner as “Not a Contribution.”
  58 +
  59 +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
  60 +of whom a Contribution has been received by Licensor and subsequently
  61 +incorporated within the Work.
  62 +
  63 +#### 2. Grant of Copyright License
  64 +
  65 +Subject to the terms and conditions of this License, each Contributor hereby
  66 +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
  67 +irrevocable copyright license to reproduce, prepare Derivative Works of,
  68 +publicly display, publicly perform, sublicense, and distribute the Work and such
  69 +Derivative Works in Source or Object form.
  70 +
  71 +#### 3. Grant of Patent License
  72 +
  73 +Subject to the terms and conditions of this License, each Contributor hereby
  74 +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
  75 +irrevocable (except as stated in this section) patent license to make, have
  76 +made, use, offer to sell, sell, import, and otherwise transfer the Work, where
  77 +such license applies only to those patent claims licensable by such Contributor
  78 +that are necessarily infringed by their Contribution(s) alone or by combination
  79 +of their Contribution(s) with the Work to which such Contribution(s) was
  80 +submitted. If You institute patent litigation against any entity (including a
  81 +cross-claim or counterclaim in a lawsuit) alleging that the Work or a
  82 +Contribution incorporated within the Work constitutes direct or contributory
  83 +patent infringement, then any patent licenses granted to You under this License
  84 +for that Work shall terminate as of the date such litigation is filed.
  85 +
  86 +#### 4. Redistribution
  87 +
  88 +You may reproduce and distribute copies of the Work or Derivative Works thereof
  89 +in any medium, with or without modifications, and in Source or Object form,
  90 +provided that You meet the following conditions:
  91 +
  92 +* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
  93 +this License; and
  94 +* **(b)** You must cause any modified files to carry prominent notices stating that You
  95 +changed the files; and
  96 +* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
  97 +all copyright, patent, trademark, and attribution notices from the Source form
  98 +of the Work, excluding those notices that do not pertain to any part of the
  99 +Derivative Works; and
  100 +* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
  101 +Derivative Works that You distribute must include a readable copy of the
  102 +attribution notices contained within such NOTICE file, excluding those notices
  103 +that do not pertain to any part of the Derivative Works, in at least one of the
  104 +following places: within a NOTICE text file distributed as part of the
  105 +Derivative Works; within the Source form or documentation, if provided along
  106 +with the Derivative Works; or, within a display generated by the Derivative
  107 +Works, if and wherever such third-party notices normally appear. The contents of
  108 +the NOTICE file are for informational purposes only and do not modify the
  109 +License. You may add Your own attribution notices within Derivative Works that
  110 +You distribute, alongside or as an addendum to the NOTICE text from the Work,
  111 +provided that such additional attribution notices cannot be construed as
  112 +modifying the License.
  113 +
  114 +You may add Your own copyright statement to Your modifications and may provide
  115 +additional or different license terms and conditions for use, reproduction, or
  116 +distribution of Your modifications, or for any such Derivative Works as a whole,
  117 +provided Your use, reproduction, and distribution of the Work otherwise complies
  118 +with the conditions stated in this License.
  119 +
  120 +#### 5. Submission of Contributions
  121 +
  122 +Unless You explicitly state otherwise, any Contribution intentionally submitted
  123 +for inclusion in the Work by You to the Licensor shall be under the terms and
  124 +conditions of this License, without any additional terms or conditions.
  125 +Notwithstanding the above, nothing herein shall supersede or modify the terms of
  126 +any separate license agreement you may have executed with Licensor regarding
  127 +such Contributions.
  128 +
  129 +#### 6. Trademarks
  130 +
  131 +This License does not grant permission to use the trade names, trademarks,
  132 +service marks, or product names of the Licensor, except as required for
  133 +reasonable and customary use in describing the origin of the Work and
  134 +reproducing the content of the NOTICE file.
  135 +
  136 +#### 7. Disclaimer of Warranty
  137 +
  138 +Unless required by applicable law or agreed to in writing, Licensor provides the
  139 +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
  140 +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
  141 +including, without limitation, any warranties or conditions of TITLE,
  142 +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
  143 +solely responsible for determining the appropriateness of using or
  144 +redistributing the Work and assume any risks associated with Your exercise of
  145 +permissions under this License.
  146 +
  147 +#### 8. Limitation of Liability
  148 +
  149 +In no event and under no legal theory, whether in tort (including negligence),
  150 +contract, or otherwise, unless required by applicable law (such as deliberate
  151 +and grossly negligent acts) or agreed to in writing, shall any Contributor be
  152 +liable to You for damages, including any direct, indirect, special, incidental,
  153 +or consequential damages of any character arising as a result of this License or
  154 +out of the use or inability to use the Work (including but not limited to
  155 +damages for loss of goodwill, work stoppage, computer failure or malfunction, or
  156 +any and all other commercial damages or losses), even if such Contributor has
  157 +been advised of the possibility of such damages.
  158 +
  159 +#### 9. Accepting Warranty or Additional Liability
  160 +
  161 +While redistributing the Work or Derivative Works thereof, You may choose to
  162 +offer, and charge a fee for, acceptance of support, warranty, indemnity, or
  163 +other liability obligations and/or rights consistent with this License. However,
  164 +in accepting such obligations, You may act only on Your own behalf and on Your
  165 +sole responsibility, not on behalf of any other Contributor, and only if You
  166 +agree to indemnify, defend, and hold each Contributor harmless for any liability
  167 +incurred by, or claims asserted against, such Contributor by reason of your
  168 +accepting any such warranty or additional liability.
  169 +
  170 +_END OF TERMS AND CONDITIONS_
  171 +
  172 +### APPENDIX: How to apply the Apache License to your work
  173 +
  174 +To apply the Apache License to your work, attach the following boilerplate
  175 +notice, with the fields enclosed by brackets `[]` replaced with your own
  176 +identifying information. (Don't include the brackets!) The text should be
  177 +enclosed in the appropriate comment syntax for the file format. We also
  178 +recommend that a file or class name and description of purpose be included on
  179 +the same “printed page” as the copyright notice for easier identification within
  180 +third-party archives.
  181 +
  182 + Copyright [yyyy] [name of copyright owner]
  183 +
  184 + Licensed under the Apache License, Version 2.0 (the "License");
  185 + you may not use this file except in compliance with the License.
  186 + You may obtain a copy of the License at
  187 +
  188 + http://www.apache.org/licenses/LICENSE-2.0
  189 +
  190 + Unless required by applicable law or agreed to in writing, software
  191 + distributed under the License is distributed on an "AS IS" BASIS,
  192 + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  193 + See the License for the specific language governing permissions and
  194 + limitations under the License.
  1 +js2xmlparser
  2 +Copyright (C) 2016-2017 Michael Kourlas
  3 +
  4 +## Apache License, version 2.0 ##
  5 +
  6 +The following components are provided under the [Apache License, version 2.0](https://www.apache.org/licenses/LICENSE-2.0):
  7 +
  8 +xmlcreate
  9 +Copyright (C) 2016-2017 Michael Kourlas
  1 +# js2xmlparser #
  2 +
  3 +[![Build Status](https://travis-ci.org/michaelkourlas/node-js2xmlparser.svg?branch=master)](https://travis-ci.org/michaelkourlas/node-js2xmlparser)
  4 +[![npm version](https://badge.fury.io/js/js2xmlparser.svg)](https://badge.fury.io/js/js2xmlparser)
  5 +
  6 +## Overview ##
  7 +
  8 +js2xmlparser is a Node.js module that parses JavaScript objects into XML.
  9 +
  10 +## Features ##
  11 +
  12 +Since XML is a data-interchange format, js2xmlparser is designed primarily for
  13 +JSON-type objects, arrays and primitive data types, like many of the other
  14 +JavaScript to XML parsers currently available for Node.js.
  15 +
  16 +However, js2xmlparser is capable of parsing any object, including native
  17 +JavaScript objects such as `Date` and `RegExp`, by taking advantage of each
  18 +object's `toString` function or, if this function does not exist, the `String`
  19 +constructor.
  20 +
  21 +js2xmlparser also has support for the new `Map` and `Set` objects introduced in
  22 +ECMAScript 2015, treating them as JSON-type objects and arrays respectively.
  23 +Support for `Map`s is necessary to generate XML with elements in a specific
  24 +order, since JSON-type objects do not guarantee insertion order. `Map` keys are
  25 +always converted to strings using the method described above.
  26 +
  27 +js2xmlparser also supports a number of constructs unique to XML:
  28 +
  29 +* attributes (through an attribute property in objects)
  30 +* mixed content (through value properties in objects)
  31 +* multiple elements with the same name (through arrays)
  32 +
  33 +js2xmlparser can also pretty-print the XML it outputs.
  34 +
  35 +## Installation ##
  36 +
  37 +The easiest way to install js2xmlparser is using npm:
  38 +
  39 +```
  40 +npm install js2xmlparser
  41 +```
  42 +
  43 +You can also build js2xmlparser from source using gulp:
  44 +
  45 +```
  46 +git clone https://github.com/michaelkourlas/node-js2xmlparser.git
  47 +npm install
  48 +gulp
  49 +```
  50 +
  51 +You'll need to install gulp first if you don't have it:
  52 +
  53 +```
  54 +npm install -g gulp
  55 +```
  56 +
  57 +You can then copy the folder into your node_modules directory.
  58 +
  59 +The `default` target will build the production variant of js2xmlparser, run all
  60 +tests, and build the documentation.
  61 +
  62 +You can build the production variant without running tests using the target
  63 +`prod`. You can also build the development version using the target `dev`. At
  64 +the moment, the only difference between the two is that the development version
  65 +includes source maps.
  66 +
  67 +## Usage ##
  68 +
  69 +The documentation for the current version is available [here](http://www.kourlas.com/node-js2xmlparser/docs/3.0.0/).
  70 +
  71 +You can also build the documentation using gulp:
  72 +
  73 +```
  74 +gulp docs
  75 +```
  76 +
  77 +## Examples ##
  78 +
  79 +The following example illustrates the basic usage of js2xmlparser:
  80 +
  81 +```javascript
  82 +var js2xmlparser = require("js2xmlparser");
  83 +
  84 +var obj = {
  85 + "firstName": "John",
  86 + "lastName": "Smith",
  87 + "dateOfBirth": new Date(1964, 7, 26),
  88 + "address": {
  89 + "@": {
  90 + "type": "home"
  91 + },
  92 + "streetAddress": "3212 22nd St",
  93 + "city": "Chicago",
  94 + "state": "Illinois",
  95 + "zip": 10000
  96 + },
  97 + "phone": [
  98 + {
  99 + "@": {
  100 + "type": "home"
  101 + },
  102 + "#": "123-555-4567"
  103 + },
  104 + {
  105 + "@": {
  106 + "type": "cell"
  107 + },
  108 + "#": "890-555-1234"
  109 + },
  110 + {
  111 + "@": {
  112 + "type": "work"
  113 + },
  114 + "#": "567-555-8901"
  115 + }
  116 + ],
  117 + "email": "john@smith.com"
  118 +};
  119 +
  120 +console.log(js2xmlparser.parse("person", obj));
  121 +```
  122 +
  123 +This example produces the following XML:
  124 +
  125 +```xml
  126 +<?xml version='1.0'?>
  127 +<person>
  128 + <firstName>John</firstName>
  129 + <lastName>Smith</lastName>
  130 + <dateOfBirth>Wed Aug 26 1964 00:00:00 GMT-0400 (Eastern Summer Time)</dateOfBirth>
  131 + <address type='home'>
  132 + <streetAddress>3212 22nd St</streetAddress>
  133 + <city>Chicago</city>
  134 + <state>Illinois</state>
  135 + <zip>10000</zip>
  136 + </address>
  137 + <phone type='home'>123-555-4567</phone>
  138 + <phone type='cell'>890-555-1234</phone>
  139 + <phone type='work'>567-555-8901</phone>
  140 + <email>john@smith.com</email>
  141 +</person>
  142 +```
  143 +
  144 +Additional examples can be found in examples/example.js.
  145 +
  146 +## Tests ##
  147 +
  148 +js2xmlparser includes a set of tests to verify core functionality. You can run
  149 +the tests using gulp:
  150 +
  151 +```
  152 +gulp test
  153 +```
  154 +
  155 +The `test` target builds the production variant of js2xmlparser before running
  156 +the tests. The `test-prod` target does the same thing, while the `test-dev`
  157 +target builds the development variant first instead.
  158 +
  159 +## License ##
  160 +
  161 +js2xmlparser is licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
  162 +Please see the LICENSE.md file for more information.
  1 +import { IOptions } from "./options";
  2 +/**
  3 + * Returns a XML string representation of the specified object.
  4 + *
  5 + * @param root The name of the root XML element. When the object is converted
  6 + * to XML, it will be a child of this root element.
  7 + * @param object The object to convert to XML.
  8 + * @param options Options for parsing the object and formatting the resulting
  9 + * XML.
  10 + *
  11 + * @returns An XML string representation of the specified object.
  12 + */
  13 +export declare function parse(root: string, object: any, options?: IOptions): string;
  1 +"use strict";
  2 +/**
  3 + * Copyright (C) 2016-2017 Michael Kourlas
  4 + *
  5 + * Licensed under the Apache License, Version 2.0 (the "License");
  6 + * you may not use this file except in compliance with the License.
  7 + * You may obtain a copy of the License at
  8 + *
  9 + * http://www.apache.org/licenses/LICENSE-2.0
  10 + *
  11 + * Unless required by applicable law or agreed to in writing, software
  12 + * distributed under the License is distributed on an "AS IS" BASIS,
  13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14 + * See the License for the specific language governing permissions and
  15 + * limitations under the License.
  16 + */
  17 +var xmlcreate_1 = require("xmlcreate");
  18 +var options_1 = require("./options");
  19 +var utils_1 = require("./utils");
  20 +/**
  21 + * Parses a string into XML.
  22 + *
  23 + * @param str The string to parse into XML.
  24 + * @param parentElement The XML element or attribute that will contain the
  25 + * string.
  26 + * @param options Options for parsing the string into XML.
  27 + *
  28 + * @private
  29 + */
  30 +function parseString(str, parentElement, options) {
  31 + var requiresCdata = function (s) {
  32 + return (options.cdataInvalidChars && (s.indexOf("<") !== -1
  33 + || s.indexOf("&") !== -1))
  34 + || options.cdataKeys.indexOf(parentElement.name) !== -1
  35 + || options.cdataKeys.indexOf("*") !== -1;
  36 + };
  37 + if (parentElement instanceof xmlcreate_1.XmlElement) {
  38 + if (requiresCdata(str)) {
  39 + var cdataStrs = str.split("]]>");
  40 + for (var i = 0; i < cdataStrs.length; i++) {
  41 + if (requiresCdata(cdataStrs[i])) {
  42 + parentElement.cdata(cdataStrs[i]);
  43 + }
  44 + else {
  45 + parentElement.charData(cdataStrs[i]);
  46 + }
  47 + if (i < cdataStrs.length - 1) {
  48 + parentElement.charData("]]>");
  49 + }
  50 + }
  51 + }
  52 + else {
  53 + parentElement.charData(str);
  54 + }
  55 + }
  56 + else {
  57 + parentElement.text(str);
  58 + }
  59 +}
  60 +/**
  61 + * Parses an attribute into XML.
  62 + *
  63 + * @param name The name of the attribute.
  64 + * @param value The value of the attribute.
  65 + * @param parentElement The XML element that will contain the string.
  66 + * @param options Options for parsing the attribute into XML.
  67 + *
  68 + * @private
  69 + */
  70 +function parseAttribute(name, value, parentElement, options) {
  71 + var attribute = parentElement.attribute(name, "");
  72 + if (utils_1.isPrimitive(value)) {
  73 + parseString(utils_1.stringify(value), attribute, options);
  74 + }
  75 + else {
  76 + throw new Error("attribute value for name '" + name + "' should be a"
  77 + + " primitive (string, number, boolean, null, or"
  78 + + " undefined)");
  79 + }
  80 +}
  81 +/**
  82 + * Parses an object or Map entry into XML.
  83 + *
  84 + * @param key The key associated with the object or Map entry.
  85 + * @param value The object or map entry.
  86 + * @param parentElement The XML element that will contain the object or map
  87 + * entry.
  88 + * @param options Options for parsing the object or map entry into XML.
  89 + *
  90 + * @private
  91 + */
  92 +function parseObjectOrMapEntry(key, value, parentElement, options) {
  93 + // Alias key
  94 + if (key === options.aliasString) {
  95 + if (!utils_1.isString(value)) {
  96 + throw new Error("aliasString value for " + value
  97 + + " should be a string");
  98 + }
  99 + parentElement.name = value;
  100 + return;
  101 + }
  102 + // Attributes key
  103 + if (key.indexOf(options.attributeString) === 0) {
  104 + if (utils_1.isObject(value)) {
  105 + for (var _i = 0, _a = Object.keys(value); _i < _a.length; _i++) {
  106 + var subkey = _a[_i];
  107 + parseAttribute(subkey, value[subkey], parentElement, options);
  108 + }
  109 + }
  110 + else {
  111 + throw new Error("attributes object for " + key + " should be an"
  112 + + " object");
  113 + }
  114 + return;
  115 + }
  116 + // Value key
  117 + if (key.indexOf(options.valueString) === 0) {
  118 + if (utils_1.isPrimitive(value)) {
  119 + parseValue(key, value, parentElement, options);
  120 + return;
  121 + }
  122 + else {
  123 + throw new Error("value " + value + " should be a primitive"
  124 + + " (string, number, boolean, null, or undefined)");
  125 + }
  126 + }
  127 + // Standard handling (create new element for entry)
  128 + var element = parentElement;
  129 + if (!utils_1.isArray(value) && !utils_1.isSet(value)) {
  130 + element = parentElement.element(key);
  131 + }
  132 + parseValue(key, value, element, options);
  133 +}
  134 +/**
  135 + * Parses an Object or Map into XML.
  136 + *
  137 + * @param objectOrMap The object or map to parse into XML.
  138 + * @param parentElement The XML element that will contain the object.
  139 + * @param options Options for parsing the object into XML.
  140 + *
  141 + * @private
  142 + */
  143 +function parseObjectOrMap(objectOrMap, parentElement, options) {
  144 + if (utils_1.isMap(objectOrMap)) {
  145 + objectOrMap.forEach(function (value, key) {
  146 + parseObjectOrMapEntry(utils_1.stringify(key), value, parentElement, options);
  147 + });
  148 + }
  149 + else {
  150 + for (var _i = 0, _a = Object.keys(objectOrMap); _i < _a.length; _i++) {
  151 + var key = _a[_i];
  152 + parseObjectOrMapEntry(key, objectOrMap[key], parentElement, options);
  153 + }
  154 + }
  155 +}
  156 +/**
  157 + * Parses an array or Set into XML.
  158 + *
  159 + * @param key The key associated with the array or set to parse into XML.
  160 + * @param arrayOrSet The array or set to parse into XML.
  161 + * @param parentElement The XML element that will contain the function.
  162 + * @param options Options for parsing the array or set into XML.
  163 + *
  164 + * @private
  165 + */
  166 +function parseArrayOrSet(key, arrayOrSet, parentElement, options) {
  167 + var arrayNameFunc;
  168 + if (options.wrapHandlers.hasOwnProperty("*")) {
  169 + arrayNameFunc = options.wrapHandlers["*"];
  170 + }
  171 + if (options.wrapHandlers.hasOwnProperty(key)) {
  172 + arrayNameFunc = options.wrapHandlers[key];
  173 + }
  174 + var arrayKey = key;
  175 + var arrayElement = parentElement;
  176 + if (!utils_1.isUndefined(arrayNameFunc)) {
  177 + var arrayNameFuncKey = arrayNameFunc(arrayKey, arrayOrSet);
  178 + if (utils_1.isString(arrayNameFuncKey)) {
  179 + arrayKey = arrayNameFuncKey;
  180 + arrayElement = parentElement.element(key);
  181 + }
  182 + else if (!utils_1.isNull(arrayNameFuncKey)) {
  183 + throw new Error("wrapHandlers function for " + arrayKey
  184 + + " should return a string or null");
  185 + }
  186 + }
  187 + arrayOrSet.forEach(function (item) {
  188 + var element = arrayElement;
  189 + if (!utils_1.isArray(item) && !utils_1.isSet(item)) {
  190 + element = arrayElement.element(arrayKey);
  191 + }
  192 + parseValue(arrayKey, item, element, options);
  193 + });
  194 +}
  195 +/**
  196 + * Parses an arbitrary JavaScript value into XML.
  197 + *
  198 + * @param key The key associated with the value to parse into XML.
  199 + * @param value The value to parse into XML.
  200 + * @param parentElement The XML element that will contain the value.
  201 + * @param options Options for parsing the value into XML.
  202 + *
  203 + * @private
  204 + */
  205 +function parseValue(key, value, parentElement, options) {
  206 + // If a handler for a particular type is user-defined, use that handler
  207 + // instead of the defaults
  208 + var type = Object.prototype.toString.call(value);
  209 + var handler;
  210 + if (options.typeHandlers.hasOwnProperty("*")) {
  211 + handler = options.typeHandlers["*"];
  212 + }
  213 + if (options.typeHandlers.hasOwnProperty(type)) {
  214 + handler = options.typeHandlers[type];
  215 + }
  216 + if (!utils_1.isUndefined(handler)) {
  217 + value = handler(value);
  218 + }
  219 + if (utils_1.isObject(value) || utils_1.isMap(value)) {
  220 + parseObjectOrMap(value, parentElement, options);
  221 + return;
  222 + }
  223 + if (utils_1.isArray(value) || utils_1.isSet(value)) {
  224 + parseArrayOrSet(key, value, parentElement, options);
  225 + return;
  226 + }
  227 + parseString(utils_1.stringify(value), parentElement, options);
  228 +}
  229 +/**
  230 + * Returns a XML document corresponding to the specified value.
  231 + *
  232 + * @param root The name of the root XML element. When the value is converted to
  233 + * XML, it will be a child of this root element.
  234 + * @param value The value to convert to XML.
  235 + * @param options Options for parsing the value into XML.
  236 + *
  237 + * @returns An XML document corresponding to the specified value.
  238 + *
  239 + * @private
  240 + */
  241 +function parseToDocument(root, value, options) {
  242 + var document = new xmlcreate_1.XmlDocument(root);
  243 + if (options.declaration.include) {
  244 + document.decl(options.declaration);
  245 + }
  246 + if (options.dtd.include) {
  247 + document.dtd(options.dtd.name, options.dtd.sysId, options.dtd.pubId);
  248 + }
  249 + parseValue(root, value, document.root(), options);
  250 + return document;
  251 +}
  252 +/**
  253 + * Returns a XML string representation of the specified object.
  254 + *
  255 + * @param root The name of the root XML element. When the object is converted
  256 + * to XML, it will be a child of this root element.
  257 + * @param object The object to convert to XML.
  258 + * @param options Options for parsing the object and formatting the resulting
  259 + * XML.
  260 + *
  261 + * @returns An XML string representation of the specified object.
  262 + */
  263 +function parse(root, object, options) {
  264 + var opts = new options_1.Options(options);
  265 + var document = parseToDocument(root, object, opts);
  266 + return document.toString(opts.format);
  267 +}
  268 +exports.parse = parse;
  1 +/**
  2 + * The options associated with parsing an object and formatting the resulting
  3 + * XML.
  4 + */
  5 +export interface IOptions {
  6 + /**
  7 + * If an object or map contains a key that, when converted to a string,
  8 + * is equal to the value of `aliasString`, then the name of the XML element
  9 + * containing the object will be replaced with the value associated with
  10 + * said key.
  11 + *
  12 + * For example, if `aliasString` is `"="`, then the following object:
  13 + * ```javascript
  14 + * {
  15 + * "abc": {
  16 + * "=": "def"
  17 + * "__val": "ghi"
  18 + * }
  19 + * }
  20 + * ```
  21 + * will result in the following XML for a root element named `"root"`:
  22 + * ```xml
  23 + * <root>
  24 + * <def>ghi</def>
  25 + * </root>
  26 + * ```
  27 + *
  28 + * If left undefined, the default value is `"="`.
  29 + */
  30 + aliasString?: string;
  31 + /**
  32 + * If an object or map contains a key that, when converted to a string,
  33 + * begins with the value of `attributeString`, then the value mapped by
  34 + * said key will be interpreted as attributes for the XML element for that
  35 + * object.
  36 + *
  37 + * The attribute object must be an object containing keys that map to
  38 + * primitives (string, number, boolean, null, or undefined).
  39 + *
  40 + * For example, if `attributeString` is `"@"`, then the following object:
  41 + * ```javascript
  42 + * {
  43 + * "abc": {
  44 + * "@1": {
  45 + * "ghi": "jkl",
  46 + * "mno": "pqr"
  47 + * },
  48 + * "stu": "vwx",
  49 + * "@2": {
  50 + * "yza": "bcd"
  51 + * },
  52 + * }
  53 + * }
  54 + * ```
  55 + * will result in the following XML for a root element named `"root"`:
  56 + * ```xml
  57 + * <root>
  58 + * <abc ghi='jkl' mno='pqr' yza='bcd'>
  59 + * <stu>vwx</stu>
  60 + * </abc>
  61 + * </root>
  62 + * ```
  63 + *
  64 + * If left undefined, the default value is `"@"`.
  65 + */
  66 + attributeString?: string;
  67 + /**
  68 + * If `cdataInvalidChars` is `true`, then any text containing the
  69 + * characters `<` or `&` shall be enclosed in CDATA sections. Otherwise,
  70 + * those characters shall be replaced with XML escape characters.
  71 + *
  72 + * If left undefined, the default value is `false`.
  73 + */
  74 + cdataInvalidChars?: boolean;
  75 + /**
  76 + * If an object or map contains a key that, when converted to a string, is
  77 + * equal to an item in `cdataKeys`, then the value mapped by said key will
  78 + * be enclosed in a CDATA section.
  79 + *
  80 + * For example, if `cdataKeys` is:
  81 + * ```javascript
  82 + * [
  83 + * "abc"
  84 + * ]
  85 + * ```
  86 + * then the following object:
  87 + * ```javascript
  88 + * {
  89 + * "abc": "def&",
  90 + * "ghi": "jkl",
  91 + * "mno": "pqr<"
  92 + * }
  93 + * ```
  94 + * will result in the following XML for a root element named `"root"`:
  95 + * ```xml
  96 + * <root>
  97 + * <abc><![CDATA[def&]]></ghi>
  98 + * <ghi>jlk</ghi>
  99 + * <mno>pqr&lt;</mno>
  100 + * </root>
  101 + * ```
  102 + *
  103 + * If `cdataKeys` has a key named `"*"`, then that entry will match all
  104 + * keys.
  105 + *
  106 + * If left undefined, the default value is an empty array.
  107 + */
  108 + cdataKeys?: string[];
  109 + /**
  110 + * The options associated with the XML declaration.
  111 + */
  112 + declaration?: IDeclarationOptions;
  113 + /**
  114 + * The options associated with the XML document type definition.
  115 + */
  116 + dtd?: IDtdOptions;
  117 + /**
  118 + * The options associated with the formatting of the XML document.
  119 + */
  120 + format?: IFormatOptions;
  121 + /**
  122 + * If an value has a type (as defined by calling `Object.prototype.toString`
  123 + * on the value) equal to a key in `typeHandlers`, then said value will be
  124 + * replaced by the return value of the function mapped to by the key in
  125 + * `typeHandlers`. This function is called with the value as a parameter.
  126 + *
  127 + * For example, if `typeHandlers` is:
  128 + * ```javascript
  129 + * {
  130 + * "[object Date]": function(value) {
  131 + * return value.getYear();
  132 + * }
  133 + * }
  134 + * ```
  135 + * then the following object:
  136 + * ```javascript
  137 + * {
  138 + * "abc": new Date(2012, 10, 31)
  139 + * }
  140 + * ```
  141 + * will result in the following XML for a root element named `"root"`:
  142 + * ```xml
  143 + * <root>
  144 + * <abc>2012</abc>
  145 + * </root>
  146 + * ```
  147 + *
  148 + * If `typeHandlers` has a key named `"*"`, then that entry will match all
  149 + * values, unless there is a more specific entry.
  150 + *
  151 + * Note that normal parsing still occurs for the value returned by the
  152 + * function; it is not directly converted to a string.
  153 + *
  154 + * If left undefined, the default value is an empty object.
  155 + */
  156 + typeHandlers?: ITypeHandlers;
  157 + /**
  158 + * If an object or map contains a key that, when converted to a string,
  159 + * begins with the value of `valueString`, then the value mapped by said key
  160 + * will be represented as bare text within the XML element for that object.
  161 + * The value must be a primitive (string, number, boolean, null, or
  162 + * undefined).
  163 + *
  164 + * For example, if `valueString` is `"#"`, then the following object:
  165 + * ```javascript
  166 + * new Map([
  167 + * ["#1", "abc"],
  168 + * ["def", "ghi"],
  169 + * ["#2", "jkl"]
  170 + * ])
  171 + * ```
  172 + * will result in the following XML for a root element named `"root"`:
  173 + * ```xml
  174 + * <root>
  175 + * abc
  176 + * <def>ghi</def>
  177 + * jkl
  178 + * </root>
  179 + * ```
  180 + *
  181 + * If left undefined, the default value is `"#"`.
  182 + */
  183 + valueString?: string;
  184 + /**
  185 + * If an object or map contains a key that, when converted to a string, is
  186 + * equal to a key in `wrapHandlers`, and the key in said object or map maps
  187 + * to an array or set, then all items in the array or set will be wrapped
  188 + * in an XML element with the same name as the key.
  189 + *
  190 + * The key in `wrapHandlers` must map to a function that is called with the
  191 + * key name, as well as the array or set, as parameters. This function must
  192 + * return a string, which will become the name for each XML element for
  193 + * each item in the array or set. Alternatively, this function may return
  194 + * `null` to indicate that no wrapping should occur.
  195 + *
  196 + * For example, if `wrapHandlers` is:
  197 + * ```javascript
  198 + * {
  199 + * "abc": function(key, value) {
  200 + * return "def";
  201 + * }
  202 + * }
  203 + * ```
  204 + * then the following object:
  205 + * ```javascript
  206 + * {
  207 + * "ghi": "jkl",
  208 + * "mno": {
  209 + * "pqr": ["s", "t"]
  210 + * },
  211 + * "uvw": {
  212 + * "abc": ["x", "y"]
  213 + * }
  214 + * }
  215 + * ```
  216 + * will result in the following XML for a root element named `"root"`:
  217 + * ```xml
  218 + * <root>
  219 + * <ghi>jkl</ghi>
  220 + * <mno>
  221 + * <pqr>s</pqr>
  222 + * <pqr>t</pqr>
  223 + * </mno>
  224 + * <uwv>
  225 + * <abc>
  226 + * <def>x</def>
  227 + * <def>y</def>
  228 + * </abc>
  229 + * </uwv>
  230 + * </root>
  231 + * ```
  232 + *
  233 + * If `wrapHandlers` has a key named `"*"`, then that entry will
  234 + * match all arrays and sets, unless there is a more specific entry.
  235 + *
  236 + * If left undefined, the default value is an empty object.
  237 + */
  238 + wrapHandlers?: IWrapHandlers;
  239 +}
  240 +/**
  241 + * Implementation of the IOptions interface used to provide default values
  242 + * to fields.
  243 + *
  244 + * @private
  245 + */
  246 +export declare class Options implements IOptions {
  247 + aliasString: string;
  248 + attributeString: string;
  249 + cdataInvalidChars: boolean;
  250 + cdataKeys: string[];
  251 + declaration: DeclarationOptions;
  252 + dtd: DtdOptions;
  253 + format: FormatOptions;
  254 + typeHandlers: TypeHandlers;
  255 + valueString: string;
  256 + wrapHandlers: WrapHandlers;
  257 + constructor(options?: IOptions);
  258 +}
  259 +/**
  260 + * The options associated with the XML declaration. An example of an XML
  261 + * declaration is as follows:
  262 + *
  263 + * ```xml
  264 + * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  265 + * ```
  266 + */
  267 +export interface IDeclarationOptions {
  268 + /**
  269 + * If `include` is true, an XML declaration is included in the generated
  270 + * XML. If left undefined, the default value is `true`.
  271 + */
  272 + include?: boolean;
  273 + /**
  274 + * The XML encoding to be included in the declaration. If defined, this
  275 + * value must be a valid encoding. If left undefined, no encoding is
  276 + * included.
  277 + */
  278 + encoding?: string;
  279 + /**
  280 + * The XML standalone attribute to be included. If defined, this value must
  281 + * be `"yes"` or `"no"`. If left undefined, no standalone attribute is
  282 + * included.
  283 + */
  284 + standalone?: string;
  285 + /**
  286 + * The XML version to be included in the declaration. If defined, this
  287 + * value must be a valid XML version number. If left undefined, the default
  288 + * version is `"1.0"`.
  289 + */
  290 + version?: string;
  291 +}
  292 +/**
  293 + * Implementation of the IDeclarationOptions interface used to provide default
  294 + * values to fields.
  295 + *
  296 + * @private
  297 + */
  298 +export declare class DeclarationOptions implements IDeclarationOptions {
  299 + include: boolean;
  300 + encoding?: string;
  301 + standalone?: string;
  302 + version?: string;
  303 + constructor(declarationOptions?: IDeclarationOptions);
  304 +}
  305 +/**
  306 + * The options associated with the XML document type definition (DTD). An
  307 + * example of an XML document type definition is as follows:
  308 + *
  309 + * ```xml
  310 + * <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  311 + * "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  312 + * ```
  313 + */
  314 +export interface IDtdOptions {
  315 + /**
  316 + * If `include` is `true`, an XML DTD is included in the resulting XML. If
  317 + * left undefined, the default value is `true`.
  318 + */
  319 + include?: boolean;
  320 + /**
  321 + * The name of the DTD. This value cannot be left undefined if `include`
  322 + * is `true`.
  323 + */
  324 + name?: string;
  325 + /**
  326 + * The system identifier of the DTD, excluding quotation marks. If left
  327 + * undefined, no system identifier is included.
  328 + */
  329 + sysId?: string;
  330 + /**
  331 + * The public identifier of the DTD, excluding quotation marks. If `pubId`
  332 + * is defined, `sysId` must be defined as well. If left undefined, no
  333 + * public identifier is included.
  334 + */
  335 + pubId?: string;
  336 +}
  337 +/**
  338 + * Implementation of the IDtdOptions interface used to provide default values
  339 + * to fields.
  340 + *
  341 + * @private
  342 + */
  343 +export declare class DtdOptions implements IDtdOptions {
  344 + include: boolean;
  345 + name?: string;
  346 + sysId?: string;
  347 + pubId?: string;
  348 + constructor(dtdOptions?: IDtdOptions);
  349 +}
  350 +/**
  351 + * The options associated with the formatting of the XML document.
  352 + */
  353 +export interface IFormatOptions {
  354 + /**
  355 + * If `doubleQuotes` is `true`, double quotes are used in XML attributes.
  356 + * Otherwise, single quotes are used in XML attributes. If left undefined,
  357 + * the default value is `false`.
  358 + */
  359 + doubleQuotes?: boolean;
  360 + /**
  361 + * The indent string used for pretty-printing. If left undefined, the
  362 + * default value is four spaces.
  363 + */
  364 + indent?: string;
  365 + /**
  366 + * The newline string used for pretty-printing. If left undefined, the
  367 + * default value is `"\n"`.
  368 + */
  369 + newline?: string;
  370 + /**
  371 + * If `pretty` is `true`, pretty-printing is enabled. If left undefined,
  372 + * the default value is `true`.
  373 + */
  374 + pretty?: boolean;
  375 +}
  376 +/**
  377 + * Implementation of the IFormatOptions interface used to provide default values
  378 + * to fields.
  379 + *
  380 + * @private
  381 + */
  382 +export declare class FormatOptions implements IFormatOptions {
  383 + doubleQuotes?: boolean;
  384 + indent?: string;
  385 + newline?: string;
  386 + pretty?: boolean;
  387 + constructor(formatOptions?: IFormatOptions);
  388 +}
  389 +/**
  390 + * Map for the `typeHandlers` property in the {@link IOptions} interface.
  391 + */
  392 +export interface ITypeHandlers {
  393 + /**
  394 + * Mapping between the type of a value in an object to a function taking
  395 + * this value and returning a replacement value.
  396 + */
  397 + [type: string]: (value: any) => any;
  398 +}
  399 +/**
  400 + * Implementation of the ITypeHandlers interface used to provide default values
  401 + * to fields.
  402 + *
  403 + * @private
  404 + */
  405 +export declare class TypeHandlers implements ITypeHandlers {
  406 + [type: string]: (value: any) => any;
  407 + constructor(typeHandlers?: ITypeHandlers);
  408 +}
  409 +/**
  410 + * Map for the `wrapHandlers` property in the {@link IOptions} interface.
  411 + */
  412 +export interface IWrapHandlers {
  413 + /**
  414 + * Mapping between the string version of a key in an object or map with a
  415 + * value that is an array or set to a function taking the string version
  416 + * of that key, as well as that array or set.
  417 + *
  418 + * This function returns either a string that will become the name for each
  419 + * XML element for each item in the array or set, or `null` to indicate that
  420 + * wrapping should not occur.
  421 + */
  422 + [key: string]: (key: string, value: any) => string | null;
  423 +}
  424 +/**
  425 + * Implementation of the IWrapHandlers interface used to provide default values
  426 + * to fields.
  427 + *
  428 + * @private
  429 + */
  430 +export declare class WrapHandlers implements IWrapHandlers {
  431 + [key: string]: (key: string, value: any) => string | null;
  432 + constructor(wrapHandlers?: IWrapHandlers);
  433 +}
  1 +/**
  2 + * Copyright (C) 2016 Michael Kourlas
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * http://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +"use strict";
  17 +var utils_1 = require("./utils");
  18 +/**
  19 + * Implementation of the IOptions interface used to provide default values
  20 + * to fields.
  21 + *
  22 + * @private
  23 + */
  24 +var Options = (function () {
  25 + function Options(options) {
  26 + if (options === void 0) { options = {}; }
  27 + this.aliasString = "=";
  28 + this.attributeString = "@";
  29 + this.cdataInvalidChars = false;
  30 + this.cdataKeys = [];
  31 + this.valueString = "#";
  32 + if (!utils_1.isObject(options)) {
  33 + throw new TypeError("options should be an Object or undefined");
  34 + }
  35 + if (!utils_1.isString(options.aliasString)) {
  36 + if (!utils_1.isUndefined(options.aliasString)) {
  37 + throw new TypeError("options.aliasString should be a string or"
  38 + + " undefined");
  39 + }
  40 + }
  41 + else {
  42 + this.aliasString = options.aliasString;
  43 + }
  44 + if (!utils_1.isString(options.attributeString)) {
  45 + if (!utils_1.isUndefined(options.attributeString)) {
  46 + throw new TypeError("options.attributeString should be a string"
  47 + + " or undefined");
  48 + }
  49 + }
  50 + else {
  51 + this.attributeString = options.attributeString;
  52 + }
  53 + if (!utils_1.isBoolean(options.cdataInvalidChars)) {
  54 + if (!utils_1.isUndefined(options.cdataInvalidChars)) {
  55 + throw new TypeError("options.cdataInvalidChars should be a"
  56 + + " boolean or undefined");
  57 + }
  58 + }
  59 + else {
  60 + this.cdataInvalidChars = options.cdataInvalidChars;
  61 + }
  62 + if (!utils_1.isStringArray(options.cdataKeys)) {
  63 + if (!utils_1.isUndefined(options.cdataKeys)) {
  64 + throw new TypeError("options.cdataKeys should be an Array or" +
  65 + " undefined");
  66 + }
  67 + }
  68 + else {
  69 + this.cdataKeys = options.cdataKeys;
  70 + }
  71 + this.declaration = new DeclarationOptions(options.declaration);
  72 + this.dtd = new DtdOptions(options.dtd);
  73 + this.format = new FormatOptions(options.format);
  74 + this.typeHandlers = new TypeHandlers(options.typeHandlers);
  75 + if (!utils_1.isString(options.valueString)) {
  76 + if (!utils_1.isUndefined(options.valueString)) {
  77 + throw new TypeError("options.valueString should be a string"
  78 + + " or undefined");
  79 + }
  80 + }
  81 + else {
  82 + this.valueString = options.valueString;
  83 + }
  84 + this.wrapHandlers = new WrapHandlers(options.wrapHandlers);
  85 + }
  86 + return Options;
  87 +}());
  88 +exports.Options = Options;
  89 +/**
  90 + * Implementation of the IDeclarationOptions interface used to provide default
  91 + * values to fields.
  92 + *
  93 + * @private
  94 + */
  95 +var DeclarationOptions = (function () {
  96 + function DeclarationOptions(declarationOptions) {
  97 + if (declarationOptions === void 0) { declarationOptions = {}; }
  98 + this.include = true;
  99 + if (!utils_1.isObject(declarationOptions)) {
  100 + throw new TypeError("options.declaration should be an Object or"
  101 + + " undefined");
  102 + }
  103 + if (!utils_1.isBoolean(declarationOptions.include)) {
  104 + if (!utils_1.isUndefined(declarationOptions.include)) {
  105 + throw new TypeError("options.declaration.include should be a"
  106 + + " boolean or undefined");
  107 + }
  108 + }
  109 + else {
  110 + this.include = declarationOptions.include;
  111 + }
  112 + // Validation performed by xmlcreate
  113 + this.encoding = declarationOptions.encoding;
  114 + this.standalone = declarationOptions.standalone;
  115 + this.version = declarationOptions.version;
  116 + }
  117 + return DeclarationOptions;
  118 +}());
  119 +exports.DeclarationOptions = DeclarationOptions;
  120 +/**
  121 + * Implementation of the IDtdOptions interface used to provide default values
  122 + * to fields.
  123 + *
  124 + * @private
  125 + */
  126 +var DtdOptions = (function () {
  127 + function DtdOptions(dtdOptions) {
  128 + if (dtdOptions === void 0) { dtdOptions = {}; }
  129 + this.include = false;
  130 + if (!utils_1.isObject(dtdOptions)) {
  131 + throw new TypeError("options.dtd should be an Object or undefined");
  132 + }
  133 + if (!utils_1.isBoolean(dtdOptions.include)) {
  134 + if (!utils_1.isUndefined(dtdOptions.include)) {
  135 + throw new TypeError("options.dtd.include should be a boolean"
  136 + + " or undefined");
  137 + }
  138 + }
  139 + else {
  140 + this.include = dtdOptions.include;
  141 + }
  142 + // Validation performed by xmlcreate
  143 + this.name = dtdOptions.name;
  144 + this.sysId = dtdOptions.sysId;
  145 + this.pubId = dtdOptions.pubId;
  146 + }
  147 + return DtdOptions;
  148 +}());
  149 +exports.DtdOptions = DtdOptions;
  150 +/**
  151 + * Implementation of the IFormatOptions interface used to provide default values
  152 + * to fields.
  153 + *
  154 + * @private
  155 + */
  156 +var FormatOptions = (function () {
  157 + function FormatOptions(formatOptions) {
  158 + if (formatOptions === void 0) { formatOptions = {}; }
  159 + if (!utils_1.isObject(formatOptions)) {
  160 + throw new TypeError("options.format should be an Object or"
  161 + + " undefined");
  162 + }
  163 + // Validation performed by xmlcreate
  164 + this.doubleQuotes = formatOptions.doubleQuotes;
  165 + this.indent = formatOptions.indent;
  166 + this.newline = formatOptions.newline;
  167 + this.pretty = formatOptions.pretty;
  168 + }
  169 + return FormatOptions;
  170 +}());
  171 +exports.FormatOptions = FormatOptions;
  172 +/**
  173 + * Implementation of the ITypeHandlers interface used to provide default values
  174 + * to fields.
  175 + *
  176 + * @private
  177 + */
  178 +var TypeHandlers = (function () {
  179 + function TypeHandlers(typeHandlers) {
  180 + if (typeHandlers === void 0) { typeHandlers = {}; }
  181 + if (!utils_1.isObject(typeHandlers)) {
  182 + throw new TypeError("options.typeHandlers should be an Object or"
  183 + + " undefined");
  184 + }
  185 + for (var key in typeHandlers) {
  186 + if (typeHandlers.hasOwnProperty(key)) {
  187 + if (!utils_1.isFunction(typeHandlers[key])) {
  188 + throw new TypeError("options.typeHandlers['" + key + "']" +
  189 + " should be a Function");
  190 + }
  191 + else {
  192 + this[key] = typeHandlers[key];
  193 + }
  194 + }
  195 + }
  196 + }
  197 + return TypeHandlers;
  198 +}());
  199 +exports.TypeHandlers = TypeHandlers;
  200 +/**
  201 + * Implementation of the IWrapHandlers interface used to provide default values
  202 + * to fields.
  203 + *
  204 + * @private
  205 + */
  206 +var WrapHandlers = (function () {
  207 + function WrapHandlers(wrapHandlers) {
  208 + if (wrapHandlers === void 0) { wrapHandlers = {}; }
  209 + if (!utils_1.isObject(wrapHandlers)) {
  210 + throw new TypeError("options.wrapHandlers should be an Object or"
  211 + + " undefined");
  212 + }
  213 + for (var key in wrapHandlers) {
  214 + if (wrapHandlers.hasOwnProperty(key)) {
  215 + if (!utils_1.isFunction(wrapHandlers[key])) {
  216 + throw new TypeError("options.wrapHandlers['" + key + "']" +
  217 + " should be a Function");
  218 + }
  219 + else {
  220 + this[key] = wrapHandlers[key];
  221 + }
  222 + }
  223 + }
  224 + }
  225 + return WrapHandlers;
  226 +}());
  227 +exports.WrapHandlers = WrapHandlers;
  1 +/**
  2 + * Copyright (C) 2016 Michael Kourlas
  3 + *
  4 + * Licensed under the Apache License, Version 2.0 (the "License");
  5 + * you may not use this file except in compliance with the License.
  6 + * You may obtain a copy of the License at
  7 + *
  8 + * http://www.apache.org/licenses/LICENSE-2.0
  9 + *
  10 + * Unless required by applicable law or agreed to in writing, software
  11 + * distributed under the License is distributed on an "AS IS" BASIS,
  12 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13 + * See the License for the specific language governing permissions and
  14 + * limitations under the License.
  15 + */
  16 +/**
  17 + * @private
  18 + */
  19 +export declare function isString(val: any): val is string;
  20 +/**
  21 + * @private
  22 + */
  23 +export declare function isNumber(val: any): val is number;
  24 +/**
  25 + * @private
  26 + */
  27 +export declare function isBoolean(val: any): val is boolean;
  28 +/**
  29 + * @private
  30 + */
  31 +export declare function isUndefined(val: any): val is undefined;
  32 +/**
  33 + * @private
  34 + */
  35 +export declare function isNull(val: any): val is null;
  36 +/**
  37 + * @private
  38 + */
  39 +export declare function isPrimitive(val: any): val is (string | number | boolean | undefined | null);
  40 +/**
  41 + * @private
  42 + */
  43 +export declare function isObject(val: any): val is Object;
  44 +/**
  45 + * @private
  46 + */
  47 +export declare function isArray(val: any): val is any[];
  48 +/**
  49 + * @private
  50 + */
  51 +export declare function isStringArray(val: any): val is string[];
  52 +/**
  53 + * @private
  54 + */
  55 +export declare function isFunction(val: any): val is Function;
  56 +/**
  57 + * @private
  58 + */
  59 +export declare function isSet(val: any): boolean;
  60 +/**
  61 + * @private
  62 + */
  63 +export declare function isMap(val: any): boolean;
  64 +/**
  65 + * Returns a string representation of the specified value, as given by the
  66 + * value's toString() method (if it has one) or the global String() function
  67 + * (if it does not).
  68 + *
  69 + * @param value The value to convert to a string.
  70 + *
  71 + * @returns A string representation of the specified value.
  72 + *
  73 + * @private
  74 + */
  75 +export declare function stringify(value: any): string;