UNPKG

443 kBJavaScriptView Raw
1/*!
2 * JSON Schema $Ref Parser v6.0.0 (October 4th 2018)
3 *
4 * https://github.com/APIDevTools/json-schema-ref-parser
5 *
6 * @author James Messinger (https://jamesmessinger.com)
7 * @license MIT
8 */
9(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.$RefParser = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
10'use strict';
11
12var $Ref = require('./ref'),
13 Pointer = require('./pointer'),
14 url = require('./util/url');
15
16module.exports = bundle;
17
18/**
19 * Bundles all external JSON references into the main JSON schema, thus resulting in a schema that
20 * only has *internal* references, not any *external* references.
21 * This method mutates the JSON schema object, adding new references and re-mapping existing ones.
22 *
23 * @param {$RefParser} parser
24 * @param {$RefParserOptions} options
25 */
26function bundle (parser, options) {
27 // console.log('Bundling $ref pointers in %s', parser.$refs._root$Ref.path);
28
29 // Build an inventory of all $ref pointers in the JSON Schema
30 var inventory = [];
31 crawl(parser, 'schema', parser.$refs._root$Ref.path + '#', '#', 0, inventory, parser.$refs, options);
32
33 // Remap all $ref pointers
34 remap(inventory);
35}
36
37/**
38 * Recursively crawls the given value, and inventories all JSON references.
39 *
40 * @param {object} parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored.
41 * @param {string} key - The property key of `parent` to be crawled
42 * @param {string} path - The full path of the property being crawled, possibly with a JSON Pointer in the hash
43 * @param {string} pathFromRoot - The path of the property being crawled, from the schema root
44 * @param {object[]} inventory - An array of already-inventoried $ref pointers
45 * @param {$Refs} $refs
46 * @param {$RefParserOptions} options
47 */
48function crawl (parent, key, path, pathFromRoot, indirections, inventory, $refs, options) {
49 var obj = key === null ? parent : parent[key];
50
51 if (obj && typeof obj === 'object') {
52 if ($Ref.isAllowed$Ref(obj)) {
53 inventory$Ref(parent, key, path, pathFromRoot, indirections, inventory, $refs, options);
54 }
55 else {
56 // Crawl the object in a specific order that's optimized for bundling.
57 // This is important because it determines how `pathFromRoot` gets built,
58 // which later determines which keys get dereferenced and which ones get remapped
59 var keys = Object.keys(obj)
60 .sort(function (a, b) {
61 // Most people will expect references to be bundled into the the "definitions" property,
62 // so we always crawl that property first, if it exists.
63 if (a === 'definitions') {
64 return -1;
65 }
66 else if (b === 'definitions') {
67 return 1;
68 }
69 else {
70 // Otherwise, crawl the keys based on their length.
71 // This produces the shortest possible bundled references
72 return a.length - b.length;
73 }
74 });
75
76 keys.forEach(function (key) {
77 var keyPath = Pointer.join(path, key);
78 var keyPathFromRoot = Pointer.join(pathFromRoot, key);
79 var value = obj[key];
80
81 if ($Ref.isAllowed$Ref(value)) {
82 inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options);
83 }
84 else {
85 crawl(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options);
86 }
87 });
88 }
89 }
90}
91
92/**
93 * Inventories the given JSON Reference (i.e. records detailed information about it so we can
94 * optimize all $refs in the schema), and then crawls the resolved value.
95 *
96 * @param {object} $refParent - The object that contains a JSON Reference as one of its keys
97 * @param {string} $refKey - The key in `$refParent` that is a JSON Reference
98 * @param {string} path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash
99 * @param {string} pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root
100 * @param {object[]} inventory - An array of already-inventoried $ref pointers
101 * @param {$Refs} $refs
102 * @param {$RefParserOptions} options
103 */
104function inventory$Ref ($refParent, $refKey, path, pathFromRoot, indirections, inventory, $refs, options) {
105 var $ref = $refKey === null ? $refParent : $refParent[$refKey];
106 var $refPath = url.resolve(path, $ref.$ref);
107 var pointer = $refs._resolve($refPath, options);
108 var depth = Pointer.parse(pathFromRoot).length;
109 var file = url.stripHash(pointer.path);
110 var hash = url.getHash(pointer.path);
111 var external = file !== $refs._root$Ref.path;
112 var extended = $Ref.isExtended$Ref($ref);
113 indirections += pointer.indirections;
114
115 var existingEntry = findInInventory(inventory, $refParent, $refKey);
116 if (existingEntry) {
117 // This $Ref has already been inventoried, so we don't need to process it again
118 if (depth < existingEntry.depth || indirections < existingEntry.indirections) {
119 removeFromInventory(inventory, existingEntry);
120 }
121 else {
122 return;
123 }
124 }
125
126 inventory.push({
127 $ref: $ref, // The JSON Reference (e.g. {$ref: string})
128 parent: $refParent, // The object that contains this $ref pointer
129 key: $refKey, // The key in `parent` that is the $ref pointer
130 pathFromRoot: pathFromRoot, // The path to the $ref pointer, from the JSON Schema root
131 depth: depth, // How far from the JSON Schema root is this $ref pointer?
132 file: file, // The file that the $ref pointer resolves to
133 hash: hash, // The hash within `file` that the $ref pointer resolves to
134 value: pointer.value, // The resolved value of the $ref pointer
135 circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself)
136 extended: extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref")
137 external: external, // Does this $ref pointer point to a file other than the main JSON Schema file?
138 indirections: indirections, // The number of indirect references that were traversed to resolve the value
139 });
140
141 // Recursively crawl the resolved value
142 crawl(pointer.value, null, pointer.path, pathFromRoot, indirections + 1, inventory, $refs, options);
143}
144
145/**
146 * Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema.
147 * Each referenced value is dereferenced EXACTLY ONCE. All subsequent references to the same
148 * value are re-mapped to point to the first reference.
149 *
150 * @example:
151 * {
152 * first: { $ref: somefile.json#/some/part },
153 * second: { $ref: somefile.json#/another/part },
154 * third: { $ref: somefile.json },
155 * fourth: { $ref: somefile.json#/some/part/sub/part }
156 * }
157 *
158 * In this example, there are four references to the same file, but since the third reference points
159 * to the ENTIRE file, that's the only one we need to dereference. The other three can just be
160 * remapped to point inside the third one.
161 *
162 * On the other hand, if the third reference DIDN'T exist, then the first and second would both need
163 * to be dereferenced, since they point to different parts of the file. The fourth reference does NOT
164 * need to be dereferenced, because it can be remapped to point inside the first one.
165 *
166 * @param {object[]} inventory
167 */
168function remap (inventory) {
169 // Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them
170 inventory.sort(function (a, b) {
171 if (a.file !== b.file) {
172 // Group all the $refs that point to the same file
173 return a.file < b.file ? -1 : +1;
174 }
175 else if (a.hash !== b.hash) {
176 // Group all the $refs that point to the same part of the file
177 return a.hash < b.hash ? -1 : +1;
178 }
179 else if (a.circular !== b.circular) {
180 // If the $ref points to itself, then sort it higher than other $refs that point to this $ref
181 return a.circular ? -1 : +1;
182 }
183 else if (a.extended !== b.extended) {
184 // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value
185 return a.extended ? +1 : -1;
186 }
187 else if (a.indirections !== b.indirections) {
188 // Sort direct references higher than indirect references
189 return a.indirections - b.indirections;
190 }
191 else if (a.depth !== b.depth) {
192 // Sort $refs by how close they are to the JSON Schema root
193 return a.depth - b.depth;
194 }
195 else {
196 // Determine how far each $ref is from the "definitions" property.
197 // Most people will expect references to be bundled into the the "definitions" property if possible.
198 var aDefinitionsIndex = a.pathFromRoot.lastIndexOf('/definitions');
199 var bDefinitionsIndex = b.pathFromRoot.lastIndexOf('/definitions');
200
201 if (aDefinitionsIndex !== bDefinitionsIndex) {
202 // Give higher priority to the $ref that's closer to the "definitions" property
203 return bDefinitionsIndex - aDefinitionsIndex;
204 }
205 else {
206 // All else is equal, so use the shorter path, which will produce the shortest possible reference
207 return a.pathFromRoot.length - b.pathFromRoot.length;
208 }
209 }
210 });
211
212 var file, hash, pathFromRoot;
213 inventory.forEach(function (entry) {
214 // console.log('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot);
215
216 if (!entry.external) {
217 // This $ref already resolves to the main JSON Schema file
218 entry.$ref.$ref = entry.hash;
219 }
220 else if (entry.file === file && entry.hash === hash) {
221 // This $ref points to the same value as the prevous $ref, so remap it to the same path
222 entry.$ref.$ref = pathFromRoot;
223 }
224 else if (entry.file === file && entry.hash.indexOf(hash + '/') === 0) {
225 // This $ref points to the a sub-value as the prevous $ref, so remap it beneath that path
226 entry.$ref.$ref = Pointer.join(pathFromRoot, Pointer.parse(entry.hash));
227 }
228 else {
229 // We've moved to a new file or new hash
230 file = entry.file;
231 hash = entry.hash;
232 pathFromRoot = entry.pathFromRoot;
233
234 // This is the first $ref to point to this value, so dereference the value.
235 // Any other $refs that point to the same value will point to this $ref instead
236 entry.$ref = entry.parent[entry.key] = $Ref.dereference(entry.$ref, entry.value);
237
238 if (entry.circular) {
239 // This $ref points to itself
240 entry.$ref.$ref = entry.pathFromRoot;
241 }
242 }
243
244 // console.log(' new value: %s', (entry.$ref && entry.$ref.$ref) ? entry.$ref.$ref : '[object Object]');
245 });
246}
247
248/**
249 * TODO
250 */
251function findInInventory (inventory, $refParent, $refKey) {
252 for (var i = 0; i < inventory.length; i++) {
253 var existingEntry = inventory[i];
254 if (existingEntry.parent === $refParent && existingEntry.key === $refKey) {
255 return existingEntry;
256 }
257 }
258}
259
260function removeFromInventory (inventory, entry) {
261 var index = inventory.indexOf(entry);
262 inventory.splice(index, 1);
263}
264
265},{"./pointer":11,"./ref":12,"./util/url":18}],2:[function(require,module,exports){
266'use strict';
267
268var $Ref = require('./ref'),
269 Pointer = require('./pointer'),
270 ono = require('ono'),
271 url = require('./util/url');
272
273module.exports = dereference;
274
275/**
276 * Crawls the JSON schema, finds all JSON references, and dereferences them.
277 * This method mutates the JSON schema object, replacing JSON references with their resolved value.
278 *
279 * @param {$RefParser} parser
280 * @param {$RefParserOptions} options
281 */
282function dereference (parser, options) {
283 // console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path);
284 var dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, '#', [], parser.$refs, options);
285 parser.$refs.circular = dereferenced.circular;
286 parser.schema = dereferenced.value;
287}
288
289/**
290 * Recursively crawls the given value, and dereferences any JSON references.
291 *
292 * @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored.
293 * @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash
294 * @param {string} pathFromRoot - The path of `obj` from the schema root
295 * @param {object[]} parents - An array of the parent objects that have already been dereferenced
296 * @param {$Refs} $refs
297 * @param {$RefParserOptions} options
298 * @returns {{value: object, circular: boolean}}
299 */
300function crawl (obj, path, pathFromRoot, parents, $refs, options) {
301 var dereferenced;
302 var result = {
303 value: obj,
304 circular: false
305 };
306
307 if (obj && typeof obj === 'object') {
308 parents.push(obj);
309
310 if ($Ref.isAllowed$Ref(obj, options)) {
311 dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, $refs, options);
312 result.circular = dereferenced.circular;
313 result.value = dereferenced.value;
314 }
315 else {
316 Object.keys(obj).forEach(function (key) {
317 var keyPath = Pointer.join(path, key);
318 var keyPathFromRoot = Pointer.join(pathFromRoot, key);
319 var value = obj[key];
320 var circular = false;
321
322 if ($Ref.isAllowed$Ref(value, options)) {
323 dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, $refs, options);
324 circular = dereferenced.circular;
325 obj[key] = dereferenced.value;
326 }
327 else {
328 if (parents.indexOf(value) === -1) {
329 dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, $refs, options);
330 circular = dereferenced.circular;
331 obj[key] = dereferenced.value;
332 }
333 else {
334 circular = foundCircularReference(keyPath, $refs, options);
335 }
336 }
337
338 // Set the "isCircular" flag if this or any other property is circular
339 result.circular = result.circular || circular;
340 });
341 }
342
343 parents.pop();
344 }
345
346 return result;
347}
348
349/**
350 * Dereferences the given JSON Reference, and then crawls the resulting value.
351 *
352 * @param {{$ref: string}} $ref - The JSON Reference to resolve
353 * @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash
354 * @param {string} pathFromRoot - The path of `$ref` from the schema root
355 * @param {object[]} parents - An array of the parent objects that have already been dereferenced
356 * @param {$Refs} $refs
357 * @param {$RefParserOptions} options
358 * @returns {{value: object, circular: boolean}}
359 */
360function dereference$Ref ($ref, path, pathFromRoot, parents, $refs, options) {
361 // console.log('Dereferencing $ref pointer "%s" at %s', $ref.$ref, path);
362
363 var $refPath = url.resolve(path, $ref.$ref);
364 var pointer = $refs._resolve($refPath, options);
365
366 // Check for circular references
367 var directCircular = pointer.circular;
368 var circular = directCircular || parents.indexOf(pointer.value) !== -1;
369 circular && foundCircularReference(path, $refs, options);
370
371 // Dereference the JSON reference
372 var dereferencedValue = $Ref.dereference($ref, pointer.value);
373
374 // Crawl the dereferenced value (unless it's circular)
375 if (!circular) {
376 // Determine if the dereferenced value is circular
377 var dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, $refs, options);
378 circular = dereferenced.circular;
379 dereferencedValue = dereferenced.value;
380 }
381
382 if (circular && !directCircular && options.dereference.circular === 'ignore') {
383 // The user has chosen to "ignore" circular references, so don't change the value
384 dereferencedValue = $ref;
385 }
386
387 if (directCircular) {
388 // The pointer is a DIRECT circular reference (i.e. it references itself).
389 // So replace the $ref path with the absolute path from the JSON Schema root
390 dereferencedValue.$ref = pathFromRoot;
391 }
392
393 return {
394 circular: circular,
395 value: dereferencedValue
396 };
397}
398
399/**
400 * Called when a circular reference is found.
401 * It sets the {@link $Refs#circular} flag, and throws an error if options.dereference.circular is false.
402 *
403 * @param {string} keyPath - The JSON Reference path of the circular reference
404 * @param {$Refs} $refs
405 * @param {$RefParserOptions} options
406 * @returns {boolean} - always returns true, to indicate that a circular reference was found
407 */
408function foundCircularReference (keyPath, $refs, options) {
409 $refs.circular = true;
410 if (!options.dereference.circular) {
411 throw ono.reference('Circular $ref pointer found at %s', keyPath);
412 }
413 return true;
414}
415
416},{"./pointer":11,"./ref":12,"./util/url":18,"ono":63}],3:[function(require,module,exports){
417(function (Buffer){
418'use strict';
419
420var Options = require('./options'),
421 $Refs = require('./refs'),
422 parse = require('./parse'),
423 normalizeArgs = require('./normalize-args'),
424 resolveExternal = require('./resolve-external'),
425 bundle = require('./bundle'),
426 dereference = require('./dereference'),
427 url = require('./util/url'),
428 maybe = require('call-me-maybe'),
429 ono = require('ono');
430
431module.exports = $RefParser;
432module.exports.YAML = require('./util/yaml');
433
434/**
435 * This class parses a JSON schema, builds a map of its JSON references and their resolved values,
436 * and provides methods for traversing, manipulating, and dereferencing those references.
437 *
438 * @constructor
439 */
440function $RefParser () {
441 /**
442 * The parsed (and possibly dereferenced) JSON schema object
443 *
444 * @type {object}
445 * @readonly
446 */
447 this.schema = null;
448
449 /**
450 * The resolved JSON references
451 *
452 * @type {$Refs}
453 * @readonly
454 */
455 this.$refs = new $Refs();
456}
457
458/**
459 * Parses the given JSON schema.
460 * This method does not resolve any JSON references.
461 * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
462 *
463 * @param {string} [path] - The file path or URL of the JSON schema
464 * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
465 * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed
466 * @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object.
467 * @returns {Promise} - The returned promise resolves with the parsed JSON schema object.
468 */
469$RefParser.parse = function (path, schema, options, callback) {
470 var Class = this; // eslint-disable-line consistent-this
471 var instance = new Class();
472 return instance.parse.apply(instance, arguments);
473};
474
475/**
476 * Parses the given JSON schema.
477 * This method does not resolve any JSON references.
478 * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
479 *
480 * @param {string} [path] - The file path or URL of the JSON schema
481 * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
482 * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed
483 * @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object.
484 * @returns {Promise} - The returned promise resolves with the parsed JSON schema object.
485 */
486$RefParser.prototype.parse = function (path, schema, options, callback) {
487 var args = normalizeArgs(arguments);
488 var promise;
489
490 if (!args.path && !args.schema) {
491 var err = ono('Expected a file path, URL, or object. Got %s', args.path || args.schema);
492 return maybe(args.callback, Promise.reject(err));
493 }
494
495 // Reset everything
496 this.schema = null;
497 this.$refs = new $Refs();
498
499 // If the path is a filesystem path, then convert it to a URL.
500 // NOTE: According to the JSON Reference spec, these should already be URLs,
501 // but, in practice, many people use local filesystem paths instead.
502 // So we're being generous here and doing the conversion automatically.
503 // This is not intended to be a 100% bulletproof solution.
504 // If it doesn't work for your use-case, then use a URL instead.
505 var pathType = 'http';
506 if (url.isFileSystemPath(args.path)) {
507 args.path = url.fromFileSystemPath(args.path);
508 pathType = 'file';
509 }
510
511 // Resolve the absolute path of the schema
512 args.path = url.resolve(url.cwd(), args.path);
513
514 if (args.schema && typeof args.schema === 'object') {
515 // A schema object was passed-in.
516 // So immediately add a new $Ref with the schema object as its value
517 var $ref = this.$refs._add(args.path);
518 $ref.value = args.schema;
519 $ref.pathType = pathType;
520 promise = Promise.resolve(args.schema);
521 }
522 else {
523 // Parse the schema file/url
524 promise = parse(args.path, this.$refs, args.options);
525 }
526
527 var me = this;
528 return promise
529 .then(function (result) {
530 if (!result || typeof result !== 'object' || Buffer.isBuffer(result)) {
531 throw ono.syntax('"%s" is not a valid JSON Schema', me.$refs._root$Ref.path || result);
532 }
533 else {
534 me.schema = result;
535 return maybe(args.callback, Promise.resolve(me.schema));
536 }
537 })
538 .catch(function (e) {
539 return maybe(args.callback, Promise.reject(e));
540 });
541};
542
543/**
544 * Parses the given JSON schema and resolves any JSON references, including references in
545 * externally-referenced files.
546 *
547 * @param {string} [path] - The file path or URL of the JSON schema
548 * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
549 * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved
550 * @param {function} [callback]
551 * - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references
552 *
553 * @returns {Promise}
554 * The returned promise resolves with a {@link $Refs} object containing the resolved JSON references
555 */
556$RefParser.resolve = function (path, schema, options, callback) {
557 var Class = this; // eslint-disable-line consistent-this
558 var instance = new Class();
559 return instance.resolve.apply(instance, arguments);
560};
561
562/**
563 * Parses the given JSON schema and resolves any JSON references, including references in
564 * externally-referenced files.
565 *
566 * @param {string} [path] - The file path or URL of the JSON schema
567 * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
568 * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved
569 * @param {function} [callback]
570 * - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references
571 *
572 * @returns {Promise}
573 * The returned promise resolves with a {@link $Refs} object containing the resolved JSON references
574 */
575$RefParser.prototype.resolve = function (path, schema, options, callback) {
576 var me = this;
577 var args = normalizeArgs(arguments);
578
579 return this.parse(args.path, args.schema, args.options)
580 .then(function () {
581 return resolveExternal(me, args.options);
582 })
583 .then(function () {
584 return maybe(args.callback, Promise.resolve(me.$refs));
585 })
586 .catch(function (err) {
587 return maybe(args.callback, Promise.reject(err));
588 });
589};
590
591/**
592 * Parses the given JSON schema, resolves any JSON references, and bundles all external references
593 * into the main JSON schema. This produces a JSON schema that only has *internal* references,
594 * not any *external* references.
595 *
596 * @param {string} [path] - The file path or URL of the JSON schema
597 * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
598 * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
599 * @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object
600 * @returns {Promise} - The returned promise resolves with the bundled JSON schema object.
601 */
602$RefParser.bundle = function (path, schema, options, callback) {
603 var Class = this; // eslint-disable-line consistent-this
604 var instance = new Class();
605 return instance.bundle.apply(instance, arguments);
606};
607
608/**
609 * Parses the given JSON schema, resolves any JSON references, and bundles all external references
610 * into the main JSON schema. This produces a JSON schema that only has *internal* references,
611 * not any *external* references.
612 *
613 * @param {string} [path] - The file path or URL of the JSON schema
614 * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
615 * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
616 * @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object
617 * @returns {Promise} - The returned promise resolves with the bundled JSON schema object.
618 */
619$RefParser.prototype.bundle = function (path, schema, options, callback) {
620 var me = this;
621 var args = normalizeArgs(arguments);
622
623 return this.resolve(args.path, args.schema, args.options)
624 .then(function () {
625 bundle(me, args.options);
626 return maybe(args.callback, Promise.resolve(me.schema));
627 })
628 .catch(function (err) {
629 return maybe(args.callback, Promise.reject(err));
630 });
631};
632
633/**
634 * Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema.
635 * That is, all JSON references are replaced with their resolved values.
636 *
637 * @param {string} [path] - The file path or URL of the JSON schema
638 * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
639 * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
640 * @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object
641 * @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object.
642 */
643$RefParser.dereference = function (path, schema, options, callback) {
644 var Class = this; // eslint-disable-line consistent-this
645 var instance = new Class();
646 return instance.dereference.apply(instance, arguments);
647};
648
649/**
650 * Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema.
651 * That is, all JSON references are replaced with their resolved values.
652 *
653 * @param {string} [path] - The file path or URL of the JSON schema
654 * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`.
655 * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced
656 * @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object
657 * @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object.
658 */
659$RefParser.prototype.dereference = function (path, schema, options, callback) {
660 var me = this;
661 var args = normalizeArgs(arguments);
662
663 return this.resolve(args.path, args.schema, args.options)
664 .then(function () {
665 dereference(me, args.options);
666 return maybe(args.callback, Promise.resolve(me.schema));
667 })
668 .catch(function (err) {
669 return maybe(args.callback, Promise.reject(err));
670 });
671};
672
673}).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")})
674
675},{"../node_modules/is-buffer/index.js":31,"./bundle":1,"./dereference":2,"./normalize-args":4,"./options":5,"./parse":6,"./refs":13,"./resolve-external":14,"./util/url":18,"./util/yaml":19,"call-me-maybe":24,"ono":63}],4:[function(require,module,exports){
676'use strict';
677
678var Options = require('./options');
679
680module.exports = normalizeArgs;
681
682/**
683 * Normalizes the given arguments, accounting for optional args.
684 *
685 * @param {Arguments} args
686 * @returns {object}
687 */
688function normalizeArgs (args) {
689 var path, schema, options, callback;
690 args = Array.prototype.slice.call(args);
691
692 if (typeof args[args.length - 1] === 'function') {
693 // The last parameter is a callback function
694 callback = args.pop();
695 }
696
697 if (typeof args[0] === 'string') {
698 // The first parameter is the path
699 path = args[0];
700 if (typeof args[2] === 'object') {
701 // The second parameter is the schema, and the third parameter is the options
702 schema = args[1];
703 options = args[2];
704 }
705 else {
706 // The second parameter is the options
707 schema = undefined;
708 options = args[1];
709 }
710 }
711 else {
712 // The first parameter is the schema
713 path = '';
714 schema = args[0];
715 options = args[1];
716 }
717
718 if (!(options instanceof Options)) {
719 options = new Options(options);
720 }
721
722 return {
723 path: path,
724 schema: schema,
725 options: options,
726 callback: callback
727 };
728}
729
730},{"./options":5}],5:[function(require,module,exports){
731/* eslint lines-around-comment: [2, {beforeBlockComment: false}] */
732'use strict';
733
734var jsonParser = require('./parsers/json'),
735 yamlParser = require('./parsers/yaml'),
736 textParser = require('./parsers/text'),
737 binaryParser = require('./parsers/binary'),
738 fileResolver = require('./resolvers/file'),
739 httpResolver = require('./resolvers/http');
740
741module.exports = $RefParserOptions;
742
743/**
744 * Options that determine how JSON schemas are parsed, resolved, and dereferenced.
745 *
746 * @param {object|$RefParserOptions} [options] - Overridden options
747 * @constructor
748 */
749function $RefParserOptions (options) {
750 merge(this, $RefParserOptions.defaults);
751 merge(this, options);
752}
753
754$RefParserOptions.defaults = {
755 /**
756 * Determines how different types of files will be parsed.
757 *
758 * You can add additional parsers of your own, replace an existing one with
759 * your own implemenation, or disable any parser by setting it to false.
760 */
761 parse: {
762 json: jsonParser,
763 yaml: yamlParser,
764 text: textParser,
765 binary: binaryParser,
766 },
767
768 /**
769 * Determines how JSON References will be resolved.
770 *
771 * You can add additional resolvers of your own, replace an existing one with
772 * your own implemenation, or disable any resolver by setting it to false.
773 */
774 resolve: {
775 file: fileResolver,
776 http: httpResolver,
777
778 /**
779 * Determines whether external $ref pointers will be resolved.
780 * If this option is disabled, then none of above resolvers will be called.
781 * Instead, external $ref pointers will simply be ignored.
782 *
783 * @type {boolean}
784 */
785 external: true,
786 },
787
788 /**
789 * Determines the types of JSON references that are allowed.
790 */
791 dereference: {
792 /**
793 * Dereference circular (recursive) JSON references?
794 * If false, then a {@link ReferenceError} will be thrown if a circular reference is found.
795 * If "ignore", then circular references will not be dereferenced.
796 *
797 * @type {boolean|string}
798 */
799 circular: true
800 },
801};
802
803/**
804 * Merges the properties of the source object into the target object.
805 *
806 * @param {object} target - The object that we're populating
807 * @param {?object} source - The options that are being merged
808 * @returns {object}
809 */
810function merge (target, source) {
811 if (isMergeable(source)) {
812 var keys = Object.keys(source);
813 for (var i = 0; i < keys.length; i++) {
814 var key = keys[i];
815 var sourceSetting = source[key];
816 var targetSetting = target[key];
817
818 if (isMergeable(sourceSetting)) {
819 // It's a nested object, so merge it recursively
820 target[key] = merge(targetSetting || {}, sourceSetting);
821 }
822 else if (sourceSetting !== undefined) {
823 // It's a scalar value, function, or array. No merging necessary. Just overwrite the target value.
824 target[key] = sourceSetting;
825 }
826 }
827 }
828 return target;
829}
830
831/**
832 * Determines whether the given value can be merged,
833 * or if it is a scalar value that should just override the target value.
834 *
835 * @param {*} val
836 * @returns {Boolean}
837 */
838function isMergeable (val) {
839 return val &&
840 (typeof val === 'object') &&
841 !Array.isArray(val) &&
842 !(val instanceof RegExp) &&
843 !(val instanceof Date);
844}
845
846},{"./parsers/binary":7,"./parsers/json":8,"./parsers/text":9,"./parsers/yaml":10,"./resolvers/file":15,"./resolvers/http":16}],6:[function(require,module,exports){
847(function (Buffer){
848'use strict';
849
850var ono = require('ono'),
851 url = require('./util/url'),
852 plugins = require('./util/plugins');
853
854module.exports = parse;
855
856/**
857 * Reads and parses the specified file path or URL.
858 *
859 * @param {string} path - This path MUST already be resolved, since `read` doesn't know the resolution context
860 * @param {$Refs} $refs
861 * @param {$RefParserOptions} options
862 *
863 * @returns {Promise}
864 * The promise resolves with the parsed file contents, NOT the raw (Buffer) contents.
865 */
866function parse (path, $refs, options) {
867 try {
868 // Remove the URL fragment, if any
869 path = url.stripHash(path);
870
871 // Add a new $Ref for this file, even though we don't have the value yet.
872 // This ensures that we don't simultaneously read & parse the same file multiple times
873 var $ref = $refs._add(path);
874
875 // This "file object" will be passed to all resolvers and parsers.
876 var file = {
877 url: path,
878 extension: url.getExtension(path),
879 };
880
881 // Read the file and then parse the data
882 return readFile(file, options)
883 .then(function (resolver) {
884 $ref.pathType = resolver.plugin.name;
885 file.data = resolver.result;
886 return parseFile(file, options);
887 })
888 .then(function (parser) {
889 $ref.value = parser.result;
890 return parser.result;
891 });
892 }
893 catch (e) {
894 return Promise.reject(e);
895 }
896}
897
898/**
899 * Reads the given file, using the configured resolver plugins
900 *
901 * @param {object} file - An object containing information about the referenced file
902 * @param {string} file.url - The full URL of the referenced file
903 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
904 * @param {$RefParserOptions} options
905 *
906 * @returns {Promise}
907 * The promise resolves with the raw file contents and the resolver that was used.
908 */
909function readFile (file, options) {
910 return new Promise(function (resolve, reject) {
911 // console.log('Reading %s', file.url);
912
913 // Find the resolvers that can read this file
914 var resolvers = plugins.all(options.resolve);
915 resolvers = plugins.filter(resolvers, 'canRead', file);
916
917 // Run the resolvers, in order, until one of them succeeds
918 plugins.sort(resolvers);
919 plugins.run(resolvers, 'read', file)
920 .then(resolve, onError);
921
922 function onError (err) {
923 // Throw the original error, if it's one of our own (user-friendly) errors.
924 // Otherwise, throw a generic, friendly error.
925 if (err && !(err instanceof SyntaxError)) {
926 reject(err);
927 }
928 else {
929 reject(ono.syntax('Unable to resolve $ref pointer "%s"', file.url));
930 }
931 }
932 });
933}
934
935/**
936 * Parses the given file's contents, using the configured parser plugins.
937 *
938 * @param {object} file - An object containing information about the referenced file
939 * @param {string} file.url - The full URL of the referenced file
940 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
941 * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
942 * @param {$RefParserOptions} options
943 *
944 * @returns {Promise}
945 * The promise resolves with the parsed file contents and the parser that was used.
946 */
947function parseFile (file, options) {
948 return new Promise(function (resolve, reject) {
949 // console.log('Parsing %s', file.url);
950
951 // Find the parsers that can read this file type.
952 // If none of the parsers are an exact match for this file, then we'll try ALL of them.
953 // This handles situations where the file IS a supported type, just with an unknown extension.
954 var allParsers = plugins.all(options.parse);
955 var filteredParsers = plugins.filter(allParsers, 'canParse', file);
956 var parsers = filteredParsers.length > 0 ? filteredParsers : allParsers;
957
958 // Run the parsers, in order, until one of them succeeds
959 plugins.sort(parsers);
960 plugins.run(parsers, 'parse', file)
961 .then(onParsed, onError);
962
963 function onParsed (parser) {
964 if (!parser.plugin.allowEmpty && isEmpty(parser.result)) {
965 reject(ono.syntax('Error parsing "%s" as %s. \nParsed value is empty', file.url, parser.plugin.name));
966 }
967 else {
968 resolve(parser);
969 }
970 }
971
972 function onError (err) {
973 if (err) {
974 err = err instanceof Error ? err : new Error(err);
975 reject(ono.syntax(err, 'Error parsing %s', file.url));
976 }
977 else {
978 reject(ono.syntax('Unable to parse %s', file.url));
979 }
980 }
981 });
982}
983
984/**
985 * Determines whether the parsed value is "empty".
986 *
987 * @param {*} value
988 * @returns {boolean}
989 */
990function isEmpty (value) {
991 return value === undefined ||
992 (typeof value === 'object' && Object.keys(value).length === 0) ||
993 (typeof value === 'string' && value.trim().length === 0) ||
994 (Buffer.isBuffer(value) && value.length === 0);
995}
996
997}).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")})
998
999},{"../node_modules/is-buffer/index.js":31,"./util/plugins":17,"./util/url":18,"ono":63}],7:[function(require,module,exports){
1000(function (Buffer){
1001'use strict';
1002
1003var BINARY_REGEXP = /\.(jpeg|jpg|gif|png|bmp|ico)$/i;
1004
1005module.exports = {
1006 /**
1007 * The order that this parser will run, in relation to other parsers.
1008 *
1009 * @type {number}
1010 */
1011 order: 400,
1012
1013 /**
1014 * Whether to allow "empty" files (zero bytes).
1015 *
1016 * @type {boolean}
1017 */
1018 allowEmpty: true,
1019
1020 /**
1021 * Determines whether this parser can parse a given file reference.
1022 * Parsers that return true will be tried, in order, until one successfully parses the file.
1023 * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case
1024 * every parser will be tried.
1025 *
1026 * @param {object} file - An object containing information about the referenced file
1027 * @param {string} file.url - The full URL of the referenced file
1028 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
1029 * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
1030 * @returns {boolean}
1031 */
1032 canParse: function isBinary (file) {
1033 // Use this parser if the file is a Buffer, and has a known binary extension
1034 return Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url);
1035 },
1036
1037 /**
1038 * Parses the given data as a Buffer (byte array).
1039 *
1040 * @param {object} file - An object containing information about the referenced file
1041 * @param {string} file.url - The full URL of the referenced file
1042 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
1043 * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
1044 * @returns {Promise<Buffer>}
1045 */
1046 parse: function parseBinary (file) {
1047 if (Buffer.isBuffer(file.data)) {
1048 return file.data;
1049 }
1050 else {
1051 // This will reject if data is anything other than a string or typed array
1052 return new Buffer(file.data);
1053 }
1054 }
1055};
1056
1057}).call(this,require("buffer").Buffer)
1058
1059},{"buffer":22}],8:[function(require,module,exports){
1060(function (Buffer){
1061'use strict';
1062
1063module.exports = {
1064 /**
1065 * The order that this parser will run, in relation to other parsers.
1066 *
1067 * @type {number}
1068 */
1069 order: 100,
1070
1071 /**
1072 * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
1073 *
1074 * @type {boolean}
1075 */
1076 allowEmpty: true,
1077
1078 /**
1079 * Determines whether this parser can parse a given file reference.
1080 * Parsers that match will be tried, in order, until one successfully parses the file.
1081 * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
1082 * every parser will be tried.
1083 *
1084 * @type {RegExp|string[]|function}
1085 */
1086 canParse: '.json',
1087
1088 /**
1089 * Parses the given file as JSON
1090 *
1091 * @param {object} file - An object containing information about the referenced file
1092 * @param {string} file.url - The full URL of the referenced file
1093 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
1094 * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
1095 * @returns {Promise}
1096 */
1097 parse: function parseJSON (file) {
1098 return new Promise(function (resolve, reject) {
1099 var data = file.data;
1100 if (Buffer.isBuffer(data)) {
1101 data = data.toString();
1102 }
1103
1104 if (typeof data === 'string') {
1105 if (data.trim().length === 0) {
1106 resolve(undefined); // This mirrors the YAML behavior
1107 }
1108 else {
1109 resolve(JSON.parse(data));
1110 }
1111 }
1112 else {
1113 // data is already a JavaScript value (object, array, number, null, NaN, etc.)
1114 resolve(data);
1115 }
1116 });
1117 }
1118};
1119
1120}).call(this,{"isBuffer":require("../../node_modules/is-buffer/index.js")})
1121
1122},{"../../node_modules/is-buffer/index.js":31}],9:[function(require,module,exports){
1123(function (Buffer){
1124'use strict';
1125
1126var TEXT_REGEXP = /\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i;
1127
1128module.exports = {
1129 /**
1130 * The order that this parser will run, in relation to other parsers.
1131 *
1132 * @type {number}
1133 */
1134 order: 300,
1135
1136 /**
1137 * Whether to allow "empty" files (zero bytes).
1138 *
1139 * @type {boolean}
1140 */
1141 allowEmpty: true,
1142
1143 /**
1144 * The encoding that the text is expected to be in.
1145 *
1146 * @type {string}
1147 */
1148 encoding: 'utf8',
1149
1150 /**
1151 * Determines whether this parser can parse a given file reference.
1152 * Parsers that return true will be tried, in order, until one successfully parses the file.
1153 * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case
1154 * every parser will be tried.
1155 *
1156 * @param {object} file - An object containing information about the referenced file
1157 * @param {string} file.url - The full URL of the referenced file
1158 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
1159 * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
1160 * @returns {boolean}
1161 */
1162 canParse: function isText (file) {
1163 // Use this parser if the file is a string or Buffer, and has a known text-based extension
1164 return (typeof file.data === 'string' || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url);
1165 },
1166
1167 /**
1168 * Parses the given file as text
1169 *
1170 * @param {object} file - An object containing information about the referenced file
1171 * @param {string} file.url - The full URL of the referenced file
1172 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
1173 * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
1174 * @returns {Promise<string>}
1175 */
1176 parse: function parseText (file) {
1177 if (typeof file.data === 'string') {
1178 return file.data;
1179 }
1180 else if (Buffer.isBuffer(file.data)) {
1181 return file.data.toString(this.encoding);
1182 }
1183 else {
1184 throw new Error('data is not text');
1185 }
1186 }
1187};
1188
1189}).call(this,{"isBuffer":require("../../node_modules/is-buffer/index.js")})
1190
1191},{"../../node_modules/is-buffer/index.js":31}],10:[function(require,module,exports){
1192(function (Buffer){
1193'use strict';
1194
1195var YAML = require('../util/yaml');
1196
1197module.exports = {
1198 /**
1199 * The order that this parser will run, in relation to other parsers.
1200 *
1201 * @type {number}
1202 */
1203 order: 200,
1204
1205 /**
1206 * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
1207 *
1208 * @type {boolean}
1209 */
1210 allowEmpty: true,
1211
1212 /**
1213 * Determines whether this parser can parse a given file reference.
1214 * Parsers that match will be tried, in order, until one successfully parses the file.
1215 * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
1216 * every parser will be tried.
1217 *
1218 * @type {RegExp|string[]|function}
1219 */
1220 canParse: ['.yaml', '.yml', '.json'], // JSON is valid YAML
1221
1222 /**
1223 * Parses the given file as YAML
1224 *
1225 * @param {object} file - An object containing information about the referenced file
1226 * @param {string} file.url - The full URL of the referenced file
1227 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
1228 * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
1229 * @returns {Promise}
1230 */
1231 parse: function parseYAML (file) {
1232 return new Promise(function (resolve, reject) {
1233 var data = file.data;
1234 if (Buffer.isBuffer(data)) {
1235 data = data.toString();
1236 }
1237
1238 if (typeof data === 'string') {
1239 resolve(YAML.parse(data));
1240 }
1241 else {
1242 // data is already a JavaScript value (object, array, number, null, NaN, etc.)
1243 resolve(data);
1244 }
1245 });
1246 }
1247};
1248
1249}).call(this,{"isBuffer":require("../../node_modules/is-buffer/index.js")})
1250
1251},{"../../node_modules/is-buffer/index.js":31,"../util/yaml":19}],11:[function(require,module,exports){
1252'use strict';
1253
1254module.exports = Pointer;
1255
1256var $Ref = require('./ref'),
1257 url = require('./util/url'),
1258 ono = require('ono'),
1259 slashes = /\//g,
1260 tildes = /~/g,
1261 escapedSlash = /~1/g,
1262 escapedTilde = /~0/g;
1263
1264/**
1265 * This class represents a single JSON pointer and its resolved value.
1266 *
1267 * @param {$Ref} $ref
1268 * @param {string} path
1269 * @param {string} [friendlyPath] - The original user-specified path (used for error messages)
1270 * @constructor
1271 */
1272function Pointer ($ref, path, friendlyPath) {
1273 /**
1274 * The {@link $Ref} object that contains this {@link Pointer} object.
1275 * @type {$Ref}
1276 */
1277 this.$ref = $ref;
1278
1279 /**
1280 * The file path or URL, containing the JSON pointer in the hash.
1281 * This path is relative to the path of the main JSON schema file.
1282 * @type {string}
1283 */
1284 this.path = path;
1285
1286 /**
1287 * The original path or URL, used for error messages.
1288 * @type {string}
1289 */
1290 this.originalPath = friendlyPath || path;
1291
1292 /**
1293 * The value of the JSON pointer.
1294 * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).
1295 * @type {?*}
1296 */
1297 this.value = undefined;
1298
1299 /**
1300 * Indicates whether the pointer references itself.
1301 * @type {boolean}
1302 */
1303 this.circular = false;
1304
1305 /**
1306 * The number of indirect references that were traversed to resolve the value.
1307 * Resolving a single pointer may require resolving multiple $Refs.
1308 * @type {number}
1309 */
1310 this.indirections = 0;
1311}
1312
1313/**
1314 * Resolves the value of a nested property within the given object.
1315 *
1316 * @param {*} obj - The object that will be crawled
1317 * @param {$RefParserOptions} options
1318 *
1319 * @returns {Pointer}
1320 * Returns a JSON pointer whose {@link Pointer#value} is the resolved value.
1321 * If resolving this value required resolving other JSON references, then
1322 * the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path
1323 * of the resolved value.
1324 */
1325Pointer.prototype.resolve = function (obj, options) {
1326 var tokens = Pointer.parse(this.path);
1327
1328 // Crawl the object, one token at a time
1329 this.value = obj;
1330 for (var i = 0; i < tokens.length; i++) {
1331 if (resolveIf$Ref(this, options)) {
1332 // The $ref path has changed, so append the remaining tokens to the path
1333 this.path = Pointer.join(this.path, tokens.slice(i));
1334 }
1335
1336 var token = tokens[i];
1337 if (this.value[token] === undefined) {
1338 throw ono.syntax('Error resolving $ref pointer "%s". \nToken "%s" does not exist.', this.originalPath, token);
1339 }
1340 else {
1341 this.value = this.value[token];
1342 }
1343 }
1344
1345 // Resolve the final value
1346 resolveIf$Ref(this, options);
1347 return this;
1348};
1349
1350/**
1351 * Sets the value of a nested property within the given object.
1352 *
1353 * @param {*} obj - The object that will be crawled
1354 * @param {*} value - the value to assign
1355 * @param {$RefParserOptions} options
1356 *
1357 * @returns {*}
1358 * Returns the modified object, or an entirely new object if the entire object is overwritten.
1359 */
1360Pointer.prototype.set = function (obj, value, options) {
1361 var tokens = Pointer.parse(this.path);
1362 var token;
1363
1364 if (tokens.length === 0) {
1365 // There are no tokens, replace the entire object with the new value
1366 this.value = value;
1367 return value;
1368 }
1369
1370 // Crawl the object, one token at a time
1371 this.value = obj;
1372 for (var i = 0; i < tokens.length - 1; i++) {
1373 resolveIf$Ref(this, options);
1374
1375 token = tokens[i];
1376 if (this.value && this.value[token] !== undefined) {
1377 // The token exists
1378 this.value = this.value[token];
1379 }
1380 else {
1381 // The token doesn't exist, so create it
1382 this.value = setValue(this, token, {});
1383 }
1384 }
1385
1386 // Set the value of the final token
1387 resolveIf$Ref(this, options);
1388 token = tokens[tokens.length - 1];
1389 setValue(this, token, value);
1390
1391 // Return the updated object
1392 return obj;
1393};
1394
1395/**
1396 * Parses a JSON pointer (or a path containing a JSON pointer in the hash)
1397 * and returns an array of the pointer's tokens.
1398 * (e.g. "schema.json#/definitions/person/name" => ["definitions", "person", "name"])
1399 *
1400 * The pointer is parsed according to RFC 6901
1401 * {@link https://tools.ietf.org/html/rfc6901#section-3}
1402 *
1403 * @param {string} path
1404 * @returns {string[]}
1405 */
1406Pointer.parse = function (path) {
1407 // Get the JSON pointer from the path's hash
1408 var pointer = url.getHash(path).substr(1);
1409
1410 // If there's no pointer, then there are no tokens,
1411 // so return an empty array
1412 if (!pointer) {
1413 return [];
1414 }
1415
1416 // Split into an array
1417 pointer = pointer.split('/');
1418
1419 // Decode each part, according to RFC 6901
1420 for (var i = 0; i < pointer.length; i++) {
1421 pointer[i] = decodeURIComponent(pointer[i].replace(escapedSlash, '/').replace(escapedTilde, '~'));
1422 }
1423
1424 if (pointer[0] !== '') {
1425 throw ono.syntax('Invalid $ref pointer "%s". Pointers must begin with "#/"', pointer);
1426 }
1427
1428 return pointer.slice(1);
1429};
1430
1431/**
1432 * Creates a JSON pointer path, by joining one or more tokens to a base path.
1433 *
1434 * @param {string} base - The base path (e.g. "schema.json#/definitions/person")
1435 * @param {string|string[]} tokens - The token(s) to append (e.g. ["name", "first"])
1436 * @returns {string}
1437 */
1438Pointer.join = function (base, tokens) {
1439 // Ensure that the base path contains a hash
1440 if (base.indexOf('#') === -1) {
1441 base += '#';
1442 }
1443
1444 // Append each token to the base path
1445 tokens = Array.isArray(tokens) ? tokens : [tokens];
1446 for (var i = 0; i < tokens.length; i++) {
1447 var token = tokens[i];
1448 // Encode the token, according to RFC 6901
1449 base += '/' + encodeURIComponent(token.replace(tildes, '~0').replace(slashes, '~1'));
1450 }
1451
1452 return base;
1453};
1454
1455/**
1456 * If the given pointer's {@link Pointer#value} is a JSON reference,
1457 * then the reference is resolved and {@link Pointer#value} is replaced with the resolved value.
1458 * In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the
1459 * resolution path of the new value.
1460 *
1461 * @param {Pointer} pointer
1462 * @param {$RefParserOptions} options
1463 * @returns {boolean} - Returns `true` if the resolution path changed
1464 */
1465function resolveIf$Ref (pointer, options) {
1466 // Is the value a JSON reference? (and allowed?)
1467
1468 if ($Ref.isAllowed$Ref(pointer.value, options)) {
1469 var $refPath = url.resolve(pointer.path, pointer.value.$ref);
1470
1471 if ($refPath === pointer.path) {
1472 // The value is a reference to itself, so there's nothing to do.
1473 pointer.circular = true;
1474 }
1475 else {
1476 var resolved = pointer.$ref.$refs._resolve($refPath, options);
1477 pointer.indirections += resolved.indirections + 1;
1478
1479 if ($Ref.isExtended$Ref(pointer.value)) {
1480 // This JSON reference "extends" the resolved value, rather than simply pointing to it.
1481 // So the resolved path does NOT change. Just the value does.
1482 pointer.value = $Ref.dereference(pointer.value, resolved.value);
1483 return false;
1484 }
1485 else {
1486 // Resolve the reference
1487 pointer.$ref = resolved.$ref;
1488 pointer.path = resolved.path;
1489 pointer.value = resolved.value;
1490 }
1491
1492 return true;
1493 }
1494 }
1495}
1496
1497/**
1498 * Sets the specified token value of the {@link Pointer#value}.
1499 *
1500 * The token is evaluated according to RFC 6901.
1501 * {@link https://tools.ietf.org/html/rfc6901#section-4}
1502 *
1503 * @param {Pointer} pointer - The JSON Pointer whose value will be modified
1504 * @param {string} token - A JSON Pointer token that indicates how to modify `obj`
1505 * @param {*} value - The value to assign
1506 * @returns {*} - Returns the assigned value
1507 */
1508function setValue (pointer, token, value) {
1509 if (pointer.value && typeof pointer.value === 'object') {
1510 if (token === '-' && Array.isArray(pointer.value)) {
1511 pointer.value.push(value);
1512 }
1513 else {
1514 pointer.value[token] = value;
1515 }
1516 }
1517 else {
1518 throw ono.syntax('Error assigning $ref pointer "%s". \nCannot set "%s" of a non-object.', pointer.path, token);
1519 }
1520 return value;
1521}
1522
1523},{"./ref":12,"./util/url":18,"ono":63}],12:[function(require,module,exports){
1524'use strict';
1525
1526module.exports = $Ref;
1527
1528var Pointer = require('./pointer');
1529
1530/**
1531 * This class represents a single JSON reference and its resolved value.
1532 *
1533 * @constructor
1534 */
1535function $Ref () {
1536 /**
1537 * The file path or URL of the referenced file.
1538 * This path is relative to the path of the main JSON schema file.
1539 *
1540 * This path does NOT contain document fragments (JSON pointers). It always references an ENTIRE file.
1541 * Use methods such as {@link $Ref#get}, {@link $Ref#resolve}, and {@link $Ref#exists} to get
1542 * specific JSON pointers within the file.
1543 *
1544 * @type {string}
1545 */
1546 this.path = undefined;
1547
1548 /**
1549 * The resolved value of the JSON reference.
1550 * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).
1551 * @type {?*}
1552 */
1553 this.value = undefined;
1554
1555 /**
1556 * The {@link $Refs} object that contains this {@link $Ref} object.
1557 * @type {$Refs}
1558 */
1559 this.$refs = undefined;
1560
1561 /**
1562 * Indicates the type of {@link $Ref#path} (e.g. "file", "http", etc.)
1563 * @type {?string}
1564 */
1565 this.pathType = undefined;
1566}
1567
1568/**
1569 * Determines whether the given JSON reference exists within this {@link $Ref#value}.
1570 *
1571 * @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash
1572 * @param {$RefParserOptions} options
1573 * @returns {boolean}
1574 */
1575$Ref.prototype.exists = function (path, options) {
1576 try {
1577 this.resolve(path, options);
1578 return true;
1579 }
1580 catch (e) {
1581 return false;
1582 }
1583};
1584
1585/**
1586 * Resolves the given JSON reference within this {@link $Ref#value} and returns the resolved value.
1587 *
1588 * @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash
1589 * @param {$RefParserOptions} options
1590 * @returns {*} - Returns the resolved value
1591 */
1592$Ref.prototype.get = function (path, options) {
1593 return this.resolve(path, options).value;
1594};
1595
1596/**
1597 * Resolves the given JSON reference within this {@link $Ref#value}.
1598 *
1599 * @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash
1600 * @param {$RefParserOptions} options
1601 * @param {string} [friendlyPath] - The original user-specified path (used for error messages)
1602 * @returns {Pointer}
1603 */
1604$Ref.prototype.resolve = function (path, options, friendlyPath) {
1605 var pointer = new Pointer(this, path, friendlyPath);
1606 return pointer.resolve(this.value, options);
1607};
1608
1609/**
1610 * Sets the value of a nested property within this {@link $Ref#value}.
1611 * If the property, or any of its parents don't exist, they will be created.
1612 *
1613 * @param {string} path - The full path of the property to set, optionally with a JSON pointer in the hash
1614 * @param {*} value - The value to assign
1615 */
1616$Ref.prototype.set = function (path, value) {
1617 var pointer = new Pointer(this, path);
1618 this.value = pointer.set(this.value, value);
1619};
1620
1621/**
1622 * Determines whether the given value is a JSON reference.
1623 *
1624 * @param {*} value - The value to inspect
1625 * @returns {boolean}
1626 */
1627$Ref.is$Ref = function (value) {
1628 return value && typeof value === 'object' && typeof value.$ref === 'string' && value.$ref.length > 0;
1629};
1630
1631/**
1632 * Determines whether the given value is an external JSON reference.
1633 *
1634 * @param {*} value - The value to inspect
1635 * @returns {boolean}
1636 */
1637$Ref.isExternal$Ref = function (value) {
1638 return $Ref.is$Ref(value) && value.$ref[0] !== '#';
1639};
1640
1641/**
1642 * Determines whether the given value is a JSON reference, and whether it is allowed by the options.
1643 * For example, if it references an external file, then options.resolve.external must be true.
1644 *
1645 * @param {*} value - The value to inspect
1646 * @param {$RefParserOptions} options
1647 * @returns {boolean}
1648 */
1649$Ref.isAllowed$Ref = function (value, options) {
1650 if ($Ref.is$Ref(value)) {
1651 if (value.$ref.substr(0, 2) === '#/' || value.$ref === '#') {
1652 // It's a JSON Pointer reference, which is always allowed
1653 return true;
1654 }
1655 else if (value.$ref[0] !== '#' && (!options || options.resolve.external)) {
1656 // It's an external reference, which is allowed by the options
1657 return true;
1658 }
1659 }
1660};
1661
1662/**
1663 * Determines whether the given value is a JSON reference that "extends" its resolved value.
1664 * That is, it has extra properties (in addition to "$ref"), so rather than simply pointing to
1665 * an existing value, this $ref actually creates a NEW value that is a shallow copy of the resolved
1666 * value, plus the extra properties.
1667 *
1668 * @example:
1669 * {
1670 * person: {
1671 * properties: {
1672 * firstName: { type: string }
1673 * lastName: { type: string }
1674 * }
1675 * }
1676 * employee: {
1677 * properties: {
1678 * $ref: #/person/properties
1679 * salary: { type: number }
1680 * }
1681 * }
1682 * }
1683 *
1684 * In this example, "employee" is an extended $ref, since it extends "person" with an additional
1685 * property (salary). The result is a NEW value that looks like this:
1686 *
1687 * {
1688 * properties: {
1689 * firstName: { type: string }
1690 * lastName: { type: string }
1691 * salary: { type: number }
1692 * }
1693 * }
1694 *
1695 * @param {*} value - The value to inspect
1696 * @returns {boolean}
1697 */
1698$Ref.isExtended$Ref = function (value) {
1699 return $Ref.is$Ref(value) && Object.keys(value).length > 1;
1700};
1701
1702/**
1703 * Returns the resolved value of a JSON Reference.
1704 * If necessary, the resolved value is merged with the JSON Reference to create a new object
1705 *
1706 * @example:
1707 * {
1708 * person: {
1709 * properties: {
1710 * firstName: { type: string }
1711 * lastName: { type: string }
1712 * }
1713 * }
1714 * employee: {
1715 * properties: {
1716 * $ref: #/person/properties
1717 * salary: { type: number }
1718 * }
1719 * }
1720 * }
1721 *
1722 * When "person" and "employee" are merged, you end up with the following object:
1723 *
1724 * {
1725 * properties: {
1726 * firstName: { type: string }
1727 * lastName: { type: string }
1728 * salary: { type: number }
1729 * }
1730 * }
1731 *
1732 * @param {object} $ref - The JSON reference object (the one with the "$ref" property)
1733 * @param {*} resolvedValue - The resolved value, which can be any type
1734 * @returns {*} - Returns the dereferenced value
1735 */
1736$Ref.dereference = function ($ref, resolvedValue) {
1737 if (resolvedValue && typeof resolvedValue === 'object' && $Ref.isExtended$Ref($ref)) {
1738 var merged = {};
1739 Object.keys($ref).forEach(function (key) {
1740 if (key !== '$ref') {
1741 merged[key] = $ref[key];
1742 }
1743 });
1744 Object.keys(resolvedValue).forEach(function (key) {
1745 if (!(key in merged)) {
1746 merged[key] = resolvedValue[key];
1747 }
1748 });
1749 return merged;
1750 }
1751 else {
1752 // Completely replace the original reference with the resolved value
1753 return resolvedValue;
1754 }
1755};
1756
1757},{"./pointer":11}],13:[function(require,module,exports){
1758'use strict';
1759
1760var ono = require('ono'),
1761 $Ref = require('./ref'),
1762 url = require('./util/url');
1763
1764module.exports = $Refs;
1765
1766/**
1767 * This class is a map of JSON references and their resolved values.
1768 */
1769function $Refs () {
1770 /**
1771 * Indicates whether the schema contains any circular references.
1772 *
1773 * @type {boolean}
1774 */
1775 this.circular = false;
1776
1777 /**
1778 * A map of paths/urls to {@link $Ref} objects
1779 *
1780 * @type {object}
1781 * @protected
1782 */
1783 this._$refs = {};
1784
1785 /**
1786 * The {@link $Ref} object that is the root of the JSON schema.
1787 *
1788 * @type {$Ref}
1789 * @protected
1790 */
1791 this._root$Ref = null;
1792}
1793
1794/**
1795 * Returns the paths of all the files/URLs that are referenced by the JSON schema,
1796 * including the schema itself.
1797 *
1798 * @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.)
1799 * @returns {string[]}
1800 */
1801$Refs.prototype.paths = function (types) {
1802 var paths = getPaths(this._$refs, arguments);
1803 return paths.map(function (path) {
1804 return path.decoded;
1805 });
1806};
1807
1808/**
1809 * Returns the map of JSON references and their resolved values.
1810 *
1811 * @param {...string|string[]} [types] - Only return references of the given types ("file", "http", etc.)
1812 * @returns {object}
1813 */
1814$Refs.prototype.values = function (types) {
1815 var $refs = this._$refs;
1816 var paths = getPaths($refs, arguments);
1817 return paths.reduce(function (obj, path) {
1818 obj[path.decoded] = $refs[path.encoded].value;
1819 return obj;
1820 }, {});
1821};
1822
1823/**
1824 * Returns a POJO (plain old JavaScript object) for serialization as JSON.
1825 *
1826 * @returns {object}
1827 */
1828$Refs.prototype.toJSON = $Refs.prototype.values;
1829
1830/**
1831 * Determines whether the given JSON reference exists.
1832 *
1833 * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash
1834 * @param {$RefParserOptions} [options]
1835 * @returns {boolean}
1836 */
1837$Refs.prototype.exists = function (path, options) {
1838 try {
1839 this._resolve(path, options);
1840 return true;
1841 }
1842 catch (e) {
1843 return false;
1844 }
1845};
1846
1847/**
1848 * Resolves the given JSON reference and returns the resolved value.
1849 *
1850 * @param {string} path - The path being resolved, with a JSON pointer in the hash
1851 * @param {$RefParserOptions} [options]
1852 * @returns {*} - Returns the resolved value
1853 */
1854$Refs.prototype.get = function (path, options) {
1855 return this._resolve(path, options).value;
1856};
1857
1858/**
1859 * Sets the value of a nested property within this {@link $Ref#value}.
1860 * If the property, or any of its parents don't exist, they will be created.
1861 *
1862 * @param {string} path - The path of the property to set, optionally with a JSON pointer in the hash
1863 * @param {*} value - The value to assign
1864 */
1865$Refs.prototype.set = function (path, value) {
1866 var absPath = url.resolve(this._root$Ref.path, path);
1867 var withoutHash = url.stripHash(absPath);
1868 var $ref = this._$refs[withoutHash];
1869
1870 if (!$ref) {
1871 throw ono('Error resolving $ref pointer "%s". \n"%s" not found.', path, withoutHash);
1872 }
1873
1874 $ref.set(absPath, value);
1875};
1876
1877/**
1878 * Creates a new {@link $Ref} object and adds it to this {@link $Refs} object.
1879 *
1880 * @param {string} path - The file path or URL of the referenced file
1881 */
1882$Refs.prototype._add = function (path) {
1883 var withoutHash = url.stripHash(path);
1884
1885 var $ref = new $Ref();
1886 $ref.path = withoutHash;
1887 $ref.$refs = this;
1888
1889 this._$refs[withoutHash] = $ref;
1890 this._root$Ref = this._root$Ref || $ref;
1891
1892 return $ref;
1893};
1894
1895/**
1896 * Resolves the given JSON reference.
1897 *
1898 * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash
1899 * @param {$RefParserOptions} [options]
1900 * @returns {Pointer}
1901 * @protected
1902 */
1903$Refs.prototype._resolve = function (path, options) {
1904 var absPath = url.resolve(this._root$Ref.path, path);
1905 var withoutHash = url.stripHash(absPath);
1906 var $ref = this._$refs[withoutHash];
1907
1908 if (!$ref) {
1909 throw ono('Error resolving $ref pointer "%s". \n"%s" not found.', path, withoutHash);
1910 }
1911
1912 return $ref.resolve(absPath, options, path);
1913};
1914
1915/**
1916 * Returns the specified {@link $Ref} object, or undefined.
1917 *
1918 * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash
1919 * @returns {$Ref|undefined}
1920 * @protected
1921 */
1922$Refs.prototype._get$Ref = function (path) {
1923 path = url.resolve(this._root$Ref.path, path);
1924 var withoutHash = url.stripHash(path);
1925 return this._$refs[withoutHash];
1926};
1927
1928/**
1929 * Returns the encoded and decoded paths keys of the given object.
1930 *
1931 * @param {object} $refs - The object whose keys are URL-encoded paths
1932 * @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.)
1933 * @returns {object[]}
1934 */
1935function getPaths ($refs, types) {
1936 var paths = Object.keys($refs);
1937
1938 // Filter the paths by type
1939 types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types);
1940 if (types.length > 0 && types[0]) {
1941 paths = paths.filter(function (key) {
1942 return types.indexOf($refs[key].pathType) !== -1;
1943 });
1944 }
1945
1946 // Decode local filesystem paths
1947 return paths.map(function (path) {
1948 return {
1949 encoded: path,
1950 decoded: $refs[path].pathType === 'file' ? url.toFileSystemPath(path, true) : path
1951 };
1952 });
1953}
1954
1955},{"./ref":12,"./util/url":18,"ono":63}],14:[function(require,module,exports){
1956'use strict';
1957
1958var $Ref = require('./ref'),
1959 Pointer = require('./pointer'),
1960 parse = require('./parse'),
1961 url = require('./util/url');
1962
1963module.exports = resolveExternal;
1964
1965/**
1966 * Crawls the JSON schema, finds all external JSON references, and resolves their values.
1967 * This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}.
1968 *
1969 * NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing.
1970 *
1971 * @param {$RefParser} parser
1972 * @param {$RefParserOptions} options
1973 *
1974 * @returns {Promise}
1975 * The promise resolves once all JSON references in the schema have been resolved,
1976 * including nested references that are contained in externally-referenced files.
1977 */
1978function resolveExternal (parser, options) {
1979 if (!options.resolve.external) {
1980 // Nothing to resolve, so exit early
1981 return Promise.resolve();
1982 }
1983
1984 try {
1985 // console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path);
1986 var promises = crawl(parser.schema, parser.$refs._root$Ref.path + '#', parser.$refs, options);
1987 return Promise.all(promises);
1988 }
1989 catch (e) {
1990 return Promise.reject(e);
1991 }
1992}
1993
1994/**
1995 * Recursively crawls the given value, and resolves any external JSON references.
1996 *
1997 * @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored.
1998 * @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash
1999 * @param {$Refs} $refs
2000 * @param {$RefParserOptions} options
2001 *
2002 * @returns {Promise[]}
2003 * Returns an array of promises. There will be one promise for each JSON reference in `obj`.
2004 * If `obj` does not contain any JSON references, then the array will be empty.
2005 * If any of the JSON references point to files that contain additional JSON references,
2006 * then the corresponding promise will internally reference an array of promises.
2007 */
2008function crawl (obj, path, $refs, options) {
2009 var promises = [];
2010
2011 if (obj && typeof obj === 'object') {
2012 if ($Ref.isExternal$Ref(obj)) {
2013 promises.push(resolve$Ref(obj, path, $refs, options));
2014 }
2015 else {
2016 Object.keys(obj).forEach(function (key) {
2017 var keyPath = Pointer.join(path, key);
2018 var value = obj[key];
2019
2020 if ($Ref.isExternal$Ref(value)) {
2021 promises.push(resolve$Ref(value, keyPath, $refs, options));
2022 }
2023 else {
2024 promises = promises.concat(crawl(value, keyPath, $refs, options));
2025 }
2026 });
2027 }
2028 }
2029
2030 return promises;
2031}
2032
2033/**
2034 * Resolves the given JSON Reference, and then crawls the resulting value.
2035 *
2036 * @param {{$ref: string}} $ref - The JSON Reference to resolve
2037 * @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash
2038 * @param {$Refs} $refs
2039 * @param {$RefParserOptions} options
2040 *
2041 * @returns {Promise}
2042 * The promise resolves once all JSON references in the object have been resolved,
2043 * including nested references that are contained in externally-referenced files.
2044 */
2045function resolve$Ref ($ref, path, $refs, options) {
2046 // console.log('Resolving $ref pointer "%s" at %s', $ref.$ref, path);
2047
2048 var resolvedPath = url.resolve(path, $ref.$ref);
2049 var withoutHash = url.stripHash(resolvedPath);
2050
2051 // Do we already have this $ref?
2052 $ref = $refs._$refs[withoutHash];
2053 if ($ref) {
2054 // We've already parsed this $ref, so use the existing value
2055 return Promise.resolve($ref.value);
2056 }
2057
2058 // Parse the $referenced file/url
2059 return parse(resolvedPath, $refs, options)
2060 .then(function (result) {
2061 // Crawl the parsed value
2062 // console.log('Resolving $ref pointers in %s', withoutHash);
2063 var promises = crawl(result, withoutHash + '#', $refs, options);
2064 return Promise.all(promises);
2065 });
2066}
2067
2068},{"./parse":6,"./pointer":11,"./ref":12,"./util/url":18}],15:[function(require,module,exports){
2069'use strict';
2070var fs = require('fs'),
2071 ono = require('ono'),
2072 url = require('../util/url');
2073
2074module.exports = {
2075 /**
2076 * The order that this resolver will run, in relation to other resolvers.
2077 *
2078 * @type {number}
2079 */
2080 order: 100,
2081
2082 /**
2083 * Determines whether this resolver can read a given file reference.
2084 * Resolvers that return true will be tried, in order, until one successfully resolves the file.
2085 * Resolvers that return false will not be given a chance to resolve the file.
2086 *
2087 * @param {object} file - An object containing information about the referenced file
2088 * @param {string} file.url - The full URL of the referenced file
2089 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
2090 * @returns {boolean}
2091 */
2092 canRead: function isFile (file) {
2093 return url.isFileSystemPath(file.url);
2094 },
2095
2096 /**
2097 * Reads the given file and returns its raw contents as a Buffer.
2098 *
2099 * @param {object} file - An object containing information about the referenced file
2100 * @param {string} file.url - The full URL of the referenced file
2101 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
2102 * @returns {Promise<Buffer>}
2103 */
2104 read: function readFile (file) {
2105 return new Promise(function (resolve, reject) {
2106 var path;
2107 try {
2108 path = url.toFileSystemPath(file.url);
2109 }
2110 catch (err) {
2111 reject(ono.uri(err, 'Malformed URI: %s', file.url));
2112 }
2113
2114 // console.log('Opening file: %s', path);
2115
2116 try {
2117 fs.readFile(path, function (err, data) {
2118 if (err) {
2119 reject(ono(err, 'Error opening file "%s"', path));
2120 }
2121 else {
2122 resolve(data);
2123 }
2124 });
2125 }
2126 catch (err) {
2127 reject(ono(err, 'Error opening file "%s"', path));
2128 }
2129 });
2130 }
2131};
2132
2133},{"../util/url":18,"fs":21,"ono":63}],16:[function(require,module,exports){
2134(function (process,Buffer){
2135'use strict';
2136
2137var http = require('http'),
2138 https = require('https'),
2139 ono = require('ono'),
2140 url = require('../util/url');
2141
2142module.exports = {
2143 /**
2144 * The order that this resolver will run, in relation to other resolvers.
2145 *
2146 * @type {number}
2147 */
2148 order: 200,
2149
2150 /**
2151 * HTTP headers to send when downloading files.
2152 *
2153 * @example:
2154 * {
2155 * "User-Agent": "JSON Schema $Ref Parser",
2156 * Accept: "application/json"
2157 * }
2158 *
2159 * @type {object}
2160 */
2161 headers: null,
2162
2163 /**
2164 * HTTP request timeout (in milliseconds).
2165 *
2166 * @type {number}
2167 */
2168 timeout: 5000, // 5 seconds
2169
2170 /**
2171 * The maximum number of HTTP redirects to follow.
2172 * To disable automatic following of redirects, set this to zero.
2173 *
2174 * @type {number}
2175 */
2176 redirects: 5,
2177
2178 /**
2179 * The `withCredentials` option of XMLHttpRequest.
2180 * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
2181 *
2182 * @type {boolean}
2183 */
2184 withCredentials: false,
2185
2186 /**
2187 * Determines whether this resolver can read a given file reference.
2188 * Resolvers that return true will be tried in order, until one successfully resolves the file.
2189 * Resolvers that return false will not be given a chance to resolve the file.
2190 *
2191 * @param {object} file - An object containing information about the referenced file
2192 * @param {string} file.url - The full URL of the referenced file
2193 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
2194 * @returns {boolean}
2195 */
2196 canRead: function isHttp (file) {
2197 return url.isHttp(file.url);
2198 },
2199
2200 /**
2201 * Reads the given URL and returns its raw contents as a Buffer.
2202 *
2203 * @param {object} file - An object containing information about the referenced file
2204 * @param {string} file.url - The full URL of the referenced file
2205 * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
2206 * @returns {Promise<Buffer>}
2207 */
2208 read: function readHttp (file) {
2209 var u = url.parse(file.url);
2210
2211 if (process.browser && !u.protocol) {
2212 // Use the protocol of the current page
2213 u.protocol = url.parse(location.href).protocol;
2214 }
2215
2216 return download(u, this);
2217 }
2218};
2219
2220/**
2221 * Downloads the given file.
2222 *
2223 * @param {Url|string} u - The url to download (can be a parsed {@link Url} object)
2224 * @param {object} httpOptions - The `options.resolve.http` object
2225 * @param {number} [redirects] - The redirect URLs that have already been followed
2226 *
2227 * @returns {Promise<Buffer>}
2228 * The promise resolves with the raw downloaded data, or rejects if there is an HTTP error.
2229 */
2230function download (u, httpOptions, redirects) {
2231 return new Promise(function (resolve, reject) {
2232 u = url.parse(u);
2233 redirects = redirects || [];
2234 redirects.push(u.href);
2235
2236 get(u, httpOptions)
2237 .then(function (res) {
2238 if (res.statusCode >= 400) {
2239 throw ono({ status: res.statusCode }, 'HTTP ERROR %d', res.statusCode);
2240 }
2241 else if (res.statusCode >= 300) {
2242 if (redirects.length > httpOptions.redirects) {
2243 reject(ono({ status: res.statusCode }, 'Error downloading %s. \nToo many redirects: \n %s',
2244 redirects[0], redirects.join(' \n ')));
2245 }
2246 else if (!res.headers.location) {
2247 throw ono({ status: res.statusCode }, 'HTTP %d redirect with no location header', res.statusCode);
2248 }
2249 else {
2250 // console.log('HTTP %d redirect %s -> %s', res.statusCode, u.href, res.headers.location);
2251 var redirectTo = url.resolve(u, res.headers.location);
2252 download(redirectTo, httpOptions, redirects).then(resolve, reject);
2253 }
2254 }
2255 else {
2256 resolve(res.body || new Buffer(0));
2257 }
2258 })
2259 .catch(function (err) {
2260 reject(ono(err, 'Error downloading', u.href));
2261 });
2262 });
2263}
2264
2265/**
2266 * Sends an HTTP GET request.
2267 *
2268 * @param {Url} u - A parsed {@link Url} object
2269 * @param {object} httpOptions - The `options.resolve.http` object
2270 *
2271 * @returns {Promise<Response>}
2272 * The promise resolves with the HTTP Response object.
2273 */
2274function get (u, httpOptions) {
2275 return new Promise(function (resolve, reject) {
2276 // console.log('GET', u.href);
2277
2278 var protocol = u.protocol === 'https:' ? https : http;
2279 var req = protocol.get({
2280 hostname: u.hostname,
2281 port: u.port,
2282 path: u.path,
2283 auth: u.auth,
2284 protocol: u.protocol,
2285 headers: httpOptions.headers || {},
2286 withCredentials: httpOptions.withCredentials
2287 });
2288
2289 if (typeof req.setTimeout === 'function') {
2290 req.setTimeout(httpOptions.timeout);
2291 }
2292
2293 req.on('timeout', function () {
2294 req.abort();
2295 });
2296
2297 req.on('error', reject);
2298
2299 req.once('response', function (res) {
2300 res.body = new Buffer(0);
2301
2302 res.on('data', function (data) {
2303 res.body = Buffer.concat([res.body, new Buffer(data)]);
2304 });
2305
2306 res.on('error', reject);
2307
2308 res.on('end', function () {
2309 resolve(res);
2310 });
2311 });
2312 });
2313}
2314
2315}).call(this,require('_process'),require("buffer").Buffer)
2316
2317},{"../util/url":18,"_process":64,"buffer":22,"http":70,"https":28,"ono":63}],17:[function(require,module,exports){
2318'use strict';
2319
2320/**
2321 * Returns the given plugins as an array, rather than an object map.
2322 * All other methods in this module expect an array of plugins rather than an object map.
2323 *
2324 * @param {object} plugins - A map of plugin objects
2325 * @return {object[]}
2326 */
2327exports.all = function (plugins) {
2328 return Object.keys(plugins)
2329 .filter(function (key) {
2330 return typeof plugins[key] === 'object';
2331 })
2332 .map(function (key) {
2333 plugins[key].name = key;
2334 return plugins[key];
2335 });
2336};
2337
2338/**
2339 * Filters the given plugins, returning only the ones return `true` for the given method.
2340 *
2341 * @param {object[]} plugins - An array of plugin objects
2342 * @param {string} method - The name of the filter method to invoke for each plugin
2343 * @param {object} file - A file info object, which will be passed to each method
2344 * @return {object[]}
2345 */
2346exports.filter = function (plugins, method, file) {
2347 return plugins
2348 .filter(function (plugin) {
2349 return !!getResult(plugin, method, file);
2350 });
2351};
2352
2353/**
2354 * Sorts the given plugins, in place, by their `order` property.
2355 *
2356 * @param {object[]} plugins - An array of plugin objects
2357 * @returns {object[]}
2358 */
2359exports.sort = function (plugins) {
2360 plugins.forEach(function (plugin) {
2361 plugin.order = plugin.order || Number.MAX_SAFE_INTEGER;
2362 });
2363
2364 return plugins.sort(function (a, b) { return a.order - b.order; });
2365};
2366
2367/**
2368 * Runs the specified method of the given plugins, in order, until one of them returns a successful result.
2369 * Each method can return a synchronous value, a Promise, or call an error-first callback.
2370 * If the promise resolves successfully, or the callback is called without an error, then the result
2371 * is immediately returned and no further plugins are called.
2372 * If the promise rejects, or the callback is called with an error, then the next plugin is called.
2373 * If ALL plugins fail, then the last error is thrown.
2374 *
2375 * @param {object[]} plugins - An array of plugin objects
2376 * @param {string} method - The name of the method to invoke for each plugin
2377 * @param {object} file - A file info object, which will be passed to each method
2378 * @returns {Promise}
2379 */
2380exports.run = function (plugins, method, file) {
2381 var plugin, lastError, index = 0;
2382
2383 return new Promise(function (resolve, reject) {
2384 runNextPlugin();
2385
2386 function runNextPlugin () {
2387 plugin = plugins[index++];
2388 if (!plugin) {
2389 // There are no more functions, so re-throw the last error
2390 return reject(lastError);
2391 }
2392
2393 try {
2394 // console.log(' %s', plugin.name);
2395 var result = getResult(plugin, method, file, callback);
2396 if (result && typeof result.then === 'function') {
2397 // A promise was returned
2398 result.then(onSuccess, onError);
2399 }
2400 else if (result !== undefined) {
2401 // A synchronous result was returned
2402 onSuccess(result);
2403 }
2404 // else { the callback will be called }
2405 }
2406 catch (e) {
2407 onError(e);
2408 }
2409 }
2410
2411 function callback (err, result) {
2412 if (err) {
2413 onError(err);
2414 }
2415 else {
2416 onSuccess(result);
2417 }
2418 }
2419
2420 function onSuccess (result) {
2421 // console.log(' success');
2422 resolve({
2423 plugin: plugin,
2424 result: result
2425 });
2426 }
2427
2428 function onError (err) {
2429 // console.log(' %s', err.message || err);
2430 lastError = err;
2431 runNextPlugin();
2432 }
2433 });
2434};
2435
2436/**
2437 * Returns the value of the given property.
2438 * If the property is a function, then the result of the function is returned.
2439 * If the value is a RegExp, then it will be tested against the file URL.
2440 * If the value is an aray, then it will be compared against the file extension.
2441 *
2442 * @param {object} obj - The object whose property/method is called
2443 * @param {string} prop - The name of the property/method to invoke
2444 * @param {object} file - A file info object, which will be passed to the method
2445 * @param {function} [callback] - A callback function, which will be passed to the method
2446 * @returns {*}
2447 */
2448function getResult (obj, prop, file, callback) {
2449 var value = obj[prop];
2450
2451 if (typeof value === 'function') {
2452 return value.apply(obj, [file, callback]);
2453 }
2454
2455 if (!callback) {
2456 // The synchronous plugin functions (canParse and canRead)
2457 // allow a "shorthand" syntax, where the user can match
2458 // files by RegExp or by file extension.
2459 if (value instanceof RegExp) {
2460 return value.test(file.url);
2461 }
2462 else if (typeof value === 'string') {
2463 return value === file.extension;
2464 }
2465 else if (Array.isArray(value)) {
2466 return value.indexOf(file.extension) !== -1;
2467 }
2468 }
2469
2470 return value;
2471}
2472
2473},{}],18:[function(require,module,exports){
2474(function (process){
2475'use strict';
2476
2477var isWindows = /^win/.test(process.platform),
2478 forwardSlashPattern = /\//g,
2479 protocolPattern = /^(\w{2,}):\/\//i,
2480 url = module.exports;
2481
2482// RegExp patterns to URL-encode special characters in local filesystem paths
2483var urlEncodePatterns = [
2484 /\?/g, '%3F',
2485 /\#/g, '%23',
2486];
2487
2488// RegExp patterns to URL-decode special characters for local filesystem paths
2489var urlDecodePatterns = [
2490 /\%23/g, '#',
2491 /\%24/g, '$',
2492 /\%26/g, '&',
2493 /\%2C/g, ',',
2494 /\%40/g, '@'
2495];
2496
2497exports.parse = require('url').parse;
2498exports.resolve = require('url').resolve;
2499
2500/**
2501 * Returns the current working directory (in Node) or the current page URL (in browsers).
2502 *
2503 * @returns {string}
2504 */
2505exports.cwd = function cwd () {
2506 return process.browser ? location.href : process.cwd() + '/';
2507};
2508
2509/**
2510 * Returns the protocol of the given URL, or `undefined` if it has no protocol.
2511 *
2512 * @param {string} path
2513 * @returns {?string}
2514 */
2515exports.getProtocol = function getProtocol (path) {
2516 var match = protocolPattern.exec(path);
2517 if (match) {
2518 return match[1].toLowerCase();
2519 }
2520};
2521
2522/**
2523 * Returns the lowercased file extension of the given URL,
2524 * or an empty string if it has no extension.
2525 *
2526 * @param {string} path
2527 * @returns {string}
2528 */
2529exports.getExtension = function getExtension (path) {
2530 var lastDot = path.lastIndexOf('.');
2531 if (lastDot >= 0) {
2532 return path.substr(lastDot).toLowerCase();
2533 }
2534 return '';
2535};
2536
2537/**
2538 * Returns the hash (URL fragment), of the given path.
2539 * If there is no hash, then the root hash ("#") is returned.
2540 *
2541 * @param {string} path
2542 * @returns {string}
2543 */
2544exports.getHash = function getHash (path) {
2545 var hashIndex = path.indexOf('#');
2546 if (hashIndex >= 0) {
2547 return path.substr(hashIndex);
2548 }
2549 return '#';
2550};
2551
2552/**
2553 * Removes the hash (URL fragment), if any, from the given path.
2554 *
2555 * @param {string} path
2556 * @returns {string}
2557 */
2558exports.stripHash = function stripHash (path) {
2559 var hashIndex = path.indexOf('#');
2560 if (hashIndex >= 0) {
2561 path = path.substr(0, hashIndex);
2562 }
2563 return path;
2564};
2565
2566/**
2567 * Determines whether the given path is an HTTP(S) URL.
2568 *
2569 * @param {string} path
2570 * @returns {boolean}
2571 */
2572exports.isHttp = function isHttp (path) {
2573 var protocol = url.getProtocol(path);
2574 if (protocol === 'http' || protocol === 'https') {
2575 return true;
2576 }
2577 else if (protocol === undefined) {
2578 // There is no protocol. If we're running in a browser, then assume it's HTTP.
2579 return process.browser;
2580 }
2581 else {
2582 // It's some other protocol, such as "ftp://", "mongodb://", etc.
2583 return false;
2584 }
2585};
2586
2587/**
2588 * Determines whether the given path is a filesystem path.
2589 * This includes "file://" URLs.
2590 *
2591 * @param {string} path
2592 * @returns {boolean}
2593 */
2594exports.isFileSystemPath = function isFileSystemPath (path) {
2595 if (process.browser) {
2596 // We're running in a browser, so assume that all paths are URLs.
2597 // This way, even relative paths will be treated as URLs rather than as filesystem paths
2598 return false;
2599 }
2600
2601 var protocol = url.getProtocol(path);
2602 return protocol === undefined || protocol === 'file';
2603};
2604
2605/**
2606 * Converts a filesystem path to a properly-encoded URL.
2607 *
2608 * This is intended to handle situations where JSON Schema $Ref Parser is called
2609 * with a filesystem path that contains characters which are not allowed in URLs.
2610 *
2611 * @example
2612 * The following filesystem paths would be converted to the following URLs:
2613 *
2614 * <"!@#$%^&*+=?'>.json ==> %3C%22!@%23$%25%5E&*+=%3F\'%3E.json
2615 * C:\\My Documents\\File (1).json ==> C:/My%20Documents/File%20(1).json
2616 * file://Project #42/file.json ==> file://Project%20%2342/file.json
2617 *
2618 * @param {string} path
2619 * @returns {string}
2620 */
2621exports.fromFileSystemPath = function fromFileSystemPath (path) {
2622 // Step 1: On Windows, replace backslashes with forward slashes,
2623 // rather than encoding them as "%5C"
2624 if (isWindows) {
2625 path = path.replace(/\\/g, '/');
2626 }
2627
2628 // Step 2: `encodeURI` will take care of MOST characters
2629 path = encodeURI(path);
2630
2631 // Step 3: Manually encode characters that are not encoded by `encodeURI`.
2632 // This includes characters such as "#" and "?", which have special meaning in URLs,
2633 // but are just normal characters in a filesystem path.
2634 for (var i = 0; i < urlEncodePatterns.length; i += 2) {
2635 path = path.replace(urlEncodePatterns[i], urlEncodePatterns[i + 1]);
2636 }
2637
2638 return path;
2639};
2640
2641/**
2642 * Converts a URL to a local filesystem path.
2643 *
2644 * @param {string} path
2645 * @param {boolean} [keepFileProtocol] - If true, then "file://" will NOT be stripped
2646 * @returns {string}
2647 */
2648exports.toFileSystemPath = function toFileSystemPath (path, keepFileProtocol) {
2649 // Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc.
2650 path = decodeURI(path);
2651
2652 // Step 2: Manually decode characters that are not decoded by `decodeURI`.
2653 // This includes characters such as "#" and "?", which have special meaning in URLs,
2654 // but are just normal characters in a filesystem path.
2655 for (var i = 0; i < urlDecodePatterns.length; i += 2) {
2656 path = path.replace(urlDecodePatterns[i], urlDecodePatterns[i + 1]);
2657 }
2658
2659 // Step 3: If it's a "file://" URL, then format it consistently
2660 // or convert it to a local filesystem path
2661 var isFileUrl = path.substr(0, 7).toLowerCase() === 'file://';
2662 if (isFileUrl) {
2663 // Strip-off the protocol, and the initial "/", if there is one
2664 path = path[7] === '/' ? path.substr(8) : path.substr(7);
2665
2666 // insert a colon (":") after the drive letter on Windows
2667 if (isWindows && path[1] === '/') {
2668 path = path[0] + ':' + path.substr(1);
2669 }
2670
2671 if (keepFileProtocol) {
2672 // Return the consistently-formatted "file://" URL
2673 path = 'file:///' + path;
2674 }
2675 else {
2676 // Convert the "file://" URL to a local filesystem path.
2677 // On Windows, it will start with something like "C:/".
2678 // On Posix, it will start with "/"
2679 isFileUrl = false;
2680 path = isWindows ? path : '/' + path;
2681 }
2682 }
2683
2684 // Step 4: Normalize Windows paths (unless it's a "file://" URL)
2685 if (isWindows && !isFileUrl) {
2686 // Replace forward slashes with backslashes
2687 path = path.replace(forwardSlashPattern, '\\');
2688
2689 // Capitalize the drive letter
2690 if (path.substr(1, 2) === ':\\') {
2691 path = path[0].toUpperCase() + path.substr(1);
2692 }
2693 }
2694
2695 return path;
2696};
2697
2698}).call(this,require('_process'))
2699
2700},{"_process":64,"url":87}],19:[function(require,module,exports){
2701/* eslint lines-around-comment: [2, {beforeBlockComment: false}] */
2702'use strict';
2703
2704var yaml = require('js-yaml'),
2705 ono = require('ono');
2706
2707/**
2708 * Simple YAML parsing functions, similar to {@link JSON.parse} and {@link JSON.stringify}
2709 */
2710module.exports = {
2711 /**
2712 * Parses a YAML string and returns the value.
2713 *
2714 * @param {string} text - The YAML string to be parsed
2715 * @param {function} [reviver] - Not currently supported. Provided for consistency with {@link JSON.parse}
2716 * @returns {*}
2717 */
2718 parse: function yamlParse (text, reviver) {
2719 try {
2720 return yaml.safeLoad(text);
2721 }
2722 catch (e) {
2723 if (e instanceof Error) {
2724 throw e;
2725 }
2726 else {
2727 // https://github.com/nodeca/js-yaml/issues/153
2728 throw ono(e, e.message);
2729 }
2730 }
2731 },
2732
2733 /**
2734 * Converts a JavaScript value to a YAML string.
2735 *
2736 * @param {*} value - The value to convert to YAML
2737 * @param {function|array} replacer - Not currently supported. Provided for consistency with {@link JSON.stringify}
2738 * @param {string|number} space - The number of spaces to use for indentation, or a string containing the number of spaces.
2739 * @returns {string}
2740 */
2741 stringify: function yamlStringify (value, replacer, space) {
2742 try {
2743 var indent = (typeof space === 'string' ? space.length : space) || 2;
2744 return yaml.safeDump(value, { indent: indent });
2745 }
2746 catch (e) {
2747 if (e instanceof Error) {
2748 throw e;
2749 }
2750 else {
2751 // https://github.com/nodeca/js-yaml/issues/153
2752 throw ono(e, e.message);
2753 }
2754 }
2755 }
2756};
2757
2758},{"js-yaml":33,"ono":63}],20:[function(require,module,exports){
2759'use strict'
2760
2761exports.byteLength = byteLength
2762exports.toByteArray = toByteArray
2763exports.fromByteArray = fromByteArray
2764
2765var lookup = []
2766var revLookup = []
2767var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
2768
2769var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
2770for (var i = 0, len = code.length; i < len; ++i) {
2771 lookup[i] = code[i]
2772 revLookup[code.charCodeAt(i)] = i
2773}
2774
2775// Support decoding URL-safe base64 strings, as Node.js does.
2776// See: https://en.wikipedia.org/wiki/Base64#URL_applications
2777revLookup['-'.charCodeAt(0)] = 62
2778revLookup['_'.charCodeAt(0)] = 63
2779
2780function getLens (b64) {
2781 var len = b64.length
2782
2783 if (len % 4 > 0) {
2784 throw new Error('Invalid string. Length must be a multiple of 4')
2785 }
2786
2787 // Trim off extra bytes after placeholder bytes are found
2788 // See: https://github.com/beatgammit/base64-js/issues/42
2789 var validLen = b64.indexOf('=')
2790 if (validLen === -1) validLen = len
2791
2792 var placeHoldersLen = validLen === len
2793 ? 0
2794 : 4 - (validLen % 4)
2795
2796 return [validLen, placeHoldersLen]
2797}
2798
2799// base64 is 4/3 + up to two characters of the original data
2800function byteLength (b64) {
2801 var lens = getLens(b64)
2802 var validLen = lens[0]
2803 var placeHoldersLen = lens[1]
2804 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
2805}
2806
2807function _byteLength (b64, validLen, placeHoldersLen) {
2808 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
2809}
2810
2811function toByteArray (b64) {
2812 var tmp
2813 var lens = getLens(b64)
2814 var validLen = lens[0]
2815 var placeHoldersLen = lens[1]
2816
2817 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
2818
2819 var curByte = 0
2820
2821 // if there are placeholders, only get up to the last complete 4 chars
2822 var len = placeHoldersLen > 0
2823 ? validLen - 4
2824 : validLen
2825
2826 for (var i = 0; i < len; i += 4) {
2827 tmp =
2828 (revLookup[b64.charCodeAt(i)] << 18) |
2829 (revLookup[b64.charCodeAt(i + 1)] << 12) |
2830 (revLookup[b64.charCodeAt(i + 2)] << 6) |
2831 revLookup[b64.charCodeAt(i + 3)]
2832 arr[curByte++] = (tmp >> 16) & 0xFF
2833 arr[curByte++] = (tmp >> 8) & 0xFF
2834 arr[curByte++] = tmp & 0xFF
2835 }
2836
2837 if (placeHoldersLen === 2) {
2838 tmp =
2839 (revLookup[b64.charCodeAt(i)] << 2) |
2840 (revLookup[b64.charCodeAt(i + 1)] >> 4)
2841 arr[curByte++] = tmp & 0xFF
2842 }
2843
2844 if (placeHoldersLen === 1) {
2845 tmp =
2846 (revLookup[b64.charCodeAt(i)] << 10) |
2847 (revLookup[b64.charCodeAt(i + 1)] << 4) |
2848 (revLookup[b64.charCodeAt(i + 2)] >> 2)
2849 arr[curByte++] = (tmp >> 8) & 0xFF
2850 arr[curByte++] = tmp & 0xFF
2851 }
2852
2853 return arr
2854}
2855
2856function tripletToBase64 (num) {
2857 return lookup[num >> 18 & 0x3F] +
2858 lookup[num >> 12 & 0x3F] +
2859 lookup[num >> 6 & 0x3F] +
2860 lookup[num & 0x3F]
2861}
2862
2863function encodeChunk (uint8, start, end) {
2864 var tmp
2865 var output = []
2866 for (var i = start; i < end; i += 3) {
2867 tmp =
2868 ((uint8[i] << 16) & 0xFF0000) +
2869 ((uint8[i + 1] << 8) & 0xFF00) +
2870 (uint8[i + 2] & 0xFF)
2871 output.push(tripletToBase64(tmp))
2872 }
2873 return output.join('')
2874}
2875
2876function fromByteArray (uint8) {
2877 var tmp
2878 var len = uint8.length
2879 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
2880 var parts = []
2881 var maxChunkLength = 16383 // must be multiple of 3
2882
2883 // go through the array every three bytes, we'll deal with trailing stuff later
2884 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
2885 parts.push(encodeChunk(
2886 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
2887 ))
2888 }
2889
2890 // pad the end with zeros, but make sure to not forget the extra bytes
2891 if (extraBytes === 1) {
2892 tmp = uint8[len - 1]
2893 parts.push(
2894 lookup[tmp >> 2] +
2895 lookup[(tmp << 4) & 0x3F] +
2896 '=='
2897 )
2898 } else if (extraBytes === 2) {
2899 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
2900 parts.push(
2901 lookup[tmp >> 10] +
2902 lookup[(tmp >> 4) & 0x3F] +
2903 lookup[(tmp << 2) & 0x3F] +
2904 '='
2905 )
2906 }
2907
2908 return parts.join('')
2909}
2910
2911},{}],21:[function(require,module,exports){
2912
2913},{}],22:[function(require,module,exports){
2914/*!
2915 * The buffer module from node.js, for the browser.
2916 *
2917 * @author Feross Aboukhadijeh <https://feross.org>
2918 * @license MIT
2919 */
2920/* eslint-disable no-proto */
2921
2922'use strict'
2923
2924var base64 = require('base64-js')
2925var ieee754 = require('ieee754')
2926
2927exports.Buffer = Buffer
2928exports.SlowBuffer = SlowBuffer
2929exports.INSPECT_MAX_BYTES = 50
2930
2931var K_MAX_LENGTH = 0x7fffffff
2932exports.kMaxLength = K_MAX_LENGTH
2933
2934/**
2935 * If `Buffer.TYPED_ARRAY_SUPPORT`:
2936 * === true Use Uint8Array implementation (fastest)
2937 * === false Print warning and recommend using `buffer` v4.x which has an Object
2938 * implementation (most compatible, even IE6)
2939 *
2940 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
2941 * Opera 11.6+, iOS 4.2+.
2942 *
2943 * We report that the browser does not support typed arrays if the are not subclassable
2944 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
2945 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
2946 * for __proto__ and has a buggy typed array implementation.
2947 */
2948Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
2949
2950if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
2951 typeof console.error === 'function') {
2952 console.error(
2953 'This browser lacks typed array (Uint8Array) support which is required by ' +
2954 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
2955 )
2956}
2957
2958function typedArraySupport () {
2959 // Can typed array instances can be augmented?
2960 try {
2961 var arr = new Uint8Array(1)
2962 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
2963 return arr.foo() === 42
2964 } catch (e) {
2965 return false
2966 }
2967}
2968
2969Object.defineProperty(Buffer.prototype, 'parent', {
2970 enumerable: true,
2971 get: function () {
2972 if (!Buffer.isBuffer(this)) return undefined
2973 return this.buffer
2974 }
2975})
2976
2977Object.defineProperty(Buffer.prototype, 'offset', {
2978 enumerable: true,
2979 get: function () {
2980 if (!Buffer.isBuffer(this)) return undefined
2981 return this.byteOffset
2982 }
2983})
2984
2985function createBuffer (length) {
2986 if (length > K_MAX_LENGTH) {
2987 throw new RangeError('The value "' + length + '" is invalid for option "size"')
2988 }
2989 // Return an augmented `Uint8Array` instance
2990 var buf = new Uint8Array(length)
2991 buf.__proto__ = Buffer.prototype
2992 return buf
2993}
2994
2995/**
2996 * The Buffer constructor returns instances of `Uint8Array` that have their
2997 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
2998 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
2999 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
3000 * returns a single octet.
3001 *
3002 * The `Uint8Array` prototype remains unmodified.
3003 */
3004
3005function Buffer (arg, encodingOrOffset, length) {
3006 // Common case.
3007 if (typeof arg === 'number') {
3008 if (typeof encodingOrOffset === 'string') {
3009 throw new TypeError(
3010 'The "string" argument must be of type string. Received type number'
3011 )
3012 }
3013 return allocUnsafe(arg)
3014 }
3015 return from(arg, encodingOrOffset, length)
3016}
3017
3018// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
3019if (typeof Symbol !== 'undefined' && Symbol.species != null &&
3020 Buffer[Symbol.species] === Buffer) {
3021 Object.defineProperty(Buffer, Symbol.species, {
3022 value: null,
3023 configurable: true,
3024 enumerable: false,
3025 writable: false
3026 })
3027}
3028
3029Buffer.poolSize = 8192 // not used by this implementation
3030
3031function from (value, encodingOrOffset, length) {
3032 if (typeof value === 'string') {
3033 return fromString(value, encodingOrOffset)
3034 }
3035
3036 if (ArrayBuffer.isView(value)) {
3037 return fromArrayLike(value)
3038 }
3039
3040 if (value == null) {
3041 throw TypeError(
3042 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
3043 'or Array-like Object. Received type ' + (typeof value)
3044 )
3045 }
3046
3047 if (isInstance(value, ArrayBuffer) ||
3048 (value && isInstance(value.buffer, ArrayBuffer))) {
3049 return fromArrayBuffer(value, encodingOrOffset, length)
3050 }
3051
3052 if (typeof value === 'number') {
3053 throw new TypeError(
3054 'The "value" argument must not be of type number. Received type number'
3055 )
3056 }
3057
3058 var valueOf = value.valueOf && value.valueOf()
3059 if (valueOf != null && valueOf !== value) {
3060 return Buffer.from(valueOf, encodingOrOffset, length)
3061 }
3062
3063 var b = fromObject(value)
3064 if (b) return b
3065
3066 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
3067 typeof value[Symbol.toPrimitive] === 'function') {
3068 return Buffer.from(
3069 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
3070 )
3071 }
3072
3073 throw new TypeError(
3074 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
3075 'or Array-like Object. Received type ' + (typeof value)
3076 )
3077}
3078
3079/**
3080 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
3081 * if value is a number.
3082 * Buffer.from(str[, encoding])
3083 * Buffer.from(array)
3084 * Buffer.from(buffer)
3085 * Buffer.from(arrayBuffer[, byteOffset[, length]])
3086 **/
3087Buffer.from = function (value, encodingOrOffset, length) {
3088 return from(value, encodingOrOffset, length)
3089}
3090
3091// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
3092// https://github.com/feross/buffer/pull/148
3093Buffer.prototype.__proto__ = Uint8Array.prototype
3094Buffer.__proto__ = Uint8Array
3095
3096function assertSize (size) {
3097 if (typeof size !== 'number') {
3098 throw new TypeError('"size" argument must be of type number')
3099 } else if (size < 0) {
3100 throw new RangeError('The value "' + size + '" is invalid for option "size"')
3101 }
3102}
3103
3104function alloc (size, fill, encoding) {
3105 assertSize(size)
3106 if (size <= 0) {
3107 return createBuffer(size)
3108 }
3109 if (fill !== undefined) {
3110 // Only pay attention to encoding if it's a string. This
3111 // prevents accidentally sending in a number that would
3112 // be interpretted as a start offset.
3113 return typeof encoding === 'string'
3114 ? createBuffer(size).fill(fill, encoding)
3115 : createBuffer(size).fill(fill)
3116 }
3117 return createBuffer(size)
3118}
3119
3120/**
3121 * Creates a new filled Buffer instance.
3122 * alloc(size[, fill[, encoding]])
3123 **/
3124Buffer.alloc = function (size, fill, encoding) {
3125 return alloc(size, fill, encoding)
3126}
3127
3128function allocUnsafe (size) {
3129 assertSize(size)
3130 return createBuffer(size < 0 ? 0 : checked(size) | 0)
3131}
3132
3133/**
3134 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
3135 * */
3136Buffer.allocUnsafe = function (size) {
3137 return allocUnsafe(size)
3138}
3139/**
3140 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
3141 */
3142Buffer.allocUnsafeSlow = function (size) {
3143 return allocUnsafe(size)
3144}
3145
3146function fromString (string, encoding) {
3147 if (typeof encoding !== 'string' || encoding === '') {
3148 encoding = 'utf8'
3149 }
3150
3151 if (!Buffer.isEncoding(encoding)) {
3152 throw new TypeError('Unknown encoding: ' + encoding)
3153 }
3154
3155 var length = byteLength(string, encoding) | 0
3156 var buf = createBuffer(length)
3157
3158 var actual = buf.write(string, encoding)
3159
3160 if (actual !== length) {
3161 // Writing a hex string, for example, that contains invalid characters will
3162 // cause everything after the first invalid character to be ignored. (e.g.
3163 // 'abxxcd' will be treated as 'ab')
3164 buf = buf.slice(0, actual)
3165 }
3166
3167 return buf
3168}
3169
3170function fromArrayLike (array) {
3171 var length = array.length < 0 ? 0 : checked(array.length) | 0
3172 var buf = createBuffer(length)
3173 for (var i = 0; i < length; i += 1) {
3174 buf[i] = array[i] & 255
3175 }
3176 return buf
3177}
3178
3179function fromArrayBuffer (array, byteOffset, length) {
3180 if (byteOffset < 0 || array.byteLength < byteOffset) {
3181 throw new RangeError('"offset" is outside of buffer bounds')
3182 }
3183
3184 if (array.byteLength < byteOffset + (length || 0)) {
3185 throw new RangeError('"length" is outside of buffer bounds')
3186 }
3187
3188 var buf
3189 if (byteOffset === undefined && length === undefined) {
3190 buf = new Uint8Array(array)
3191 } else if (length === undefined) {
3192 buf = new Uint8Array(array, byteOffset)
3193 } else {
3194 buf = new Uint8Array(array, byteOffset, length)
3195 }
3196
3197 // Return an augmented `Uint8Array` instance
3198 buf.__proto__ = Buffer.prototype
3199 return buf
3200}
3201
3202function fromObject (obj) {
3203 if (Buffer.isBuffer(obj)) {
3204 var len = checked(obj.length) | 0
3205 var buf = createBuffer(len)
3206
3207 if (buf.length === 0) {
3208 return buf
3209 }
3210
3211 obj.copy(buf, 0, 0, len)
3212 return buf
3213 }
3214
3215 if (obj.length !== undefined) {
3216 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
3217 return createBuffer(0)
3218 }
3219 return fromArrayLike(obj)
3220 }
3221
3222 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
3223 return fromArrayLike(obj.data)
3224 }
3225}
3226
3227function checked (length) {
3228 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
3229 // length is NaN (which is otherwise coerced to zero.)
3230 if (length >= K_MAX_LENGTH) {
3231 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
3232 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
3233 }
3234 return length | 0
3235}
3236
3237function SlowBuffer (length) {
3238 if (+length != length) { // eslint-disable-line eqeqeq
3239 length = 0
3240 }
3241 return Buffer.alloc(+length)
3242}
3243
3244Buffer.isBuffer = function isBuffer (b) {
3245 return b != null && b._isBuffer === true &&
3246 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
3247}
3248
3249Buffer.compare = function compare (a, b) {
3250 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
3251 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
3252 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
3253 throw new TypeError(
3254 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
3255 )
3256 }
3257
3258 if (a === b) return 0
3259
3260 var x = a.length
3261 var y = b.length
3262
3263 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
3264 if (a[i] !== b[i]) {
3265 x = a[i]
3266 y = b[i]
3267 break
3268 }
3269 }
3270
3271 if (x < y) return -1
3272 if (y < x) return 1
3273 return 0
3274}
3275
3276Buffer.isEncoding = function isEncoding (encoding) {
3277 switch (String(encoding).toLowerCase()) {
3278 case 'hex':
3279 case 'utf8':
3280 case 'utf-8':
3281 case 'ascii':
3282 case 'latin1':
3283 case 'binary':
3284 case 'base64':
3285 case 'ucs2':
3286 case 'ucs-2':
3287 case 'utf16le':
3288 case 'utf-16le':
3289 return true
3290 default:
3291 return false
3292 }
3293}
3294
3295Buffer.concat = function concat (list, length) {
3296 if (!Array.isArray(list)) {
3297 throw new TypeError('"list" argument must be an Array of Buffers')
3298 }
3299
3300 if (list.length === 0) {
3301 return Buffer.alloc(0)
3302 }
3303
3304 var i
3305 if (length === undefined) {
3306 length = 0
3307 for (i = 0; i < list.length; ++i) {
3308 length += list[i].length
3309 }
3310 }
3311
3312 var buffer = Buffer.allocUnsafe(length)
3313 var pos = 0
3314 for (i = 0; i < list.length; ++i) {
3315 var buf = list[i]
3316 if (isInstance(buf, Uint8Array)) {
3317 buf = Buffer.from(buf)
3318 }
3319 if (!Buffer.isBuffer(buf)) {
3320 throw new TypeError('"list" argument must be an Array of Buffers')
3321 }
3322 buf.copy(buffer, pos)
3323 pos += buf.length
3324 }
3325 return buffer
3326}
3327
3328function byteLength (string, encoding) {
3329 if (Buffer.isBuffer(string)) {
3330 return string.length
3331 }
3332 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
3333 return string.byteLength
3334 }
3335 if (typeof string !== 'string') {
3336 throw new TypeError(
3337 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
3338 'Received type ' + typeof string
3339 )
3340 }
3341
3342 var len = string.length
3343 var mustMatch = (arguments.length > 2 && arguments[2] === true)
3344 if (!mustMatch && len === 0) return 0
3345
3346 // Use a for loop to avoid recursion
3347 var loweredCase = false
3348 for (;;) {
3349 switch (encoding) {
3350 case 'ascii':
3351 case 'latin1':
3352 case 'binary':
3353 return len
3354 case 'utf8':
3355 case 'utf-8':
3356 return utf8ToBytes(string).length
3357 case 'ucs2':
3358 case 'ucs-2':
3359 case 'utf16le':
3360 case 'utf-16le':
3361 return len * 2
3362 case 'hex':
3363 return len >>> 1
3364 case 'base64':
3365 return base64ToBytes(string).length
3366 default:
3367 if (loweredCase) {
3368 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
3369 }
3370 encoding = ('' + encoding).toLowerCase()
3371 loweredCase = true
3372 }
3373 }
3374}
3375Buffer.byteLength = byteLength
3376
3377function slowToString (encoding, start, end) {
3378 var loweredCase = false
3379
3380 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
3381 // property of a typed array.
3382
3383 // This behaves neither like String nor Uint8Array in that we set start/end
3384 // to their upper/lower bounds if the value passed is out of range.
3385 // undefined is handled specially as per ECMA-262 6th Edition,
3386 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
3387 if (start === undefined || start < 0) {
3388 start = 0
3389 }
3390 // Return early if start > this.length. Done here to prevent potential uint32
3391 // coercion fail below.
3392 if (start > this.length) {
3393 return ''
3394 }
3395
3396 if (end === undefined || end > this.length) {
3397 end = this.length
3398 }
3399
3400 if (end <= 0) {
3401 return ''
3402 }
3403
3404 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
3405 end >>>= 0
3406 start >>>= 0
3407
3408 if (end <= start) {
3409 return ''
3410 }
3411
3412 if (!encoding) encoding = 'utf8'
3413
3414 while (true) {
3415 switch (encoding) {
3416 case 'hex':
3417 return hexSlice(this, start, end)
3418
3419 case 'utf8':
3420 case 'utf-8':
3421 return utf8Slice(this, start, end)
3422
3423 case 'ascii':
3424 return asciiSlice(this, start, end)
3425
3426 case 'latin1':
3427 case 'binary':
3428 return latin1Slice(this, start, end)
3429
3430 case 'base64':
3431 return base64Slice(this, start, end)
3432
3433 case 'ucs2':
3434 case 'ucs-2':
3435 case 'utf16le':
3436 case 'utf-16le':
3437 return utf16leSlice(this, start, end)
3438
3439 default:
3440 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
3441 encoding = (encoding + '').toLowerCase()
3442 loweredCase = true
3443 }
3444 }
3445}
3446
3447// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
3448// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
3449// reliably in a browserify context because there could be multiple different
3450// copies of the 'buffer' package in use. This method works even for Buffer
3451// instances that were created from another copy of the `buffer` package.
3452// See: https://github.com/feross/buffer/issues/154
3453Buffer.prototype._isBuffer = true
3454
3455function swap (b, n, m) {
3456 var i = b[n]
3457 b[n] = b[m]
3458 b[m] = i
3459}
3460
3461Buffer.prototype.swap16 = function swap16 () {
3462 var len = this.length
3463 if (len % 2 !== 0) {
3464 throw new RangeError('Buffer size must be a multiple of 16-bits')
3465 }
3466 for (var i = 0; i < len; i += 2) {
3467 swap(this, i, i + 1)
3468 }
3469 return this
3470}
3471
3472Buffer.prototype.swap32 = function swap32 () {
3473 var len = this.length
3474 if (len % 4 !== 0) {
3475 throw new RangeError('Buffer size must be a multiple of 32-bits')
3476 }
3477 for (var i = 0; i < len; i += 4) {
3478 swap(this, i, i + 3)
3479 swap(this, i + 1, i + 2)
3480 }
3481 return this
3482}
3483
3484Buffer.prototype.swap64 = function swap64 () {
3485 var len = this.length
3486 if (len % 8 !== 0) {
3487 throw new RangeError('Buffer size must be a multiple of 64-bits')
3488 }
3489 for (var i = 0; i < len; i += 8) {
3490 swap(this, i, i + 7)
3491 swap(this, i + 1, i + 6)
3492 swap(this, i + 2, i + 5)
3493 swap(this, i + 3, i + 4)
3494 }
3495 return this
3496}
3497
3498Buffer.prototype.toString = function toString () {
3499 var length = this.length
3500 if (length === 0) return ''
3501 if (arguments.length === 0) return utf8Slice(this, 0, length)
3502 return slowToString.apply(this, arguments)
3503}
3504
3505Buffer.prototype.toLocaleString = Buffer.prototype.toString
3506
3507Buffer.prototype.equals = function equals (b) {
3508 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
3509 if (this === b) return true
3510 return Buffer.compare(this, b) === 0
3511}
3512
3513Buffer.prototype.inspect = function inspect () {
3514 var str = ''
3515 var max = exports.INSPECT_MAX_BYTES
3516 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
3517 if (this.length > max) str += ' ... '
3518 return '<Buffer ' + str + '>'
3519}
3520
3521Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
3522 if (isInstance(target, Uint8Array)) {
3523 target = Buffer.from(target, target.offset, target.byteLength)
3524 }
3525 if (!Buffer.isBuffer(target)) {
3526 throw new TypeError(
3527 'The "target" argument must be one of type Buffer or Uint8Array. ' +
3528 'Received type ' + (typeof target)
3529 )
3530 }
3531
3532 if (start === undefined) {
3533 start = 0
3534 }
3535 if (end === undefined) {
3536 end = target ? target.length : 0
3537 }
3538 if (thisStart === undefined) {
3539 thisStart = 0
3540 }
3541 if (thisEnd === undefined) {
3542 thisEnd = this.length
3543 }
3544
3545 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
3546 throw new RangeError('out of range index')
3547 }
3548
3549 if (thisStart >= thisEnd && start >= end) {
3550 return 0
3551 }
3552 if (thisStart >= thisEnd) {
3553 return -1
3554 }
3555 if (start >= end) {
3556 return 1
3557 }
3558
3559 start >>>= 0
3560 end >>>= 0
3561 thisStart >>>= 0
3562 thisEnd >>>= 0
3563
3564 if (this === target) return 0
3565
3566 var x = thisEnd - thisStart
3567 var y = end - start
3568 var len = Math.min(x, y)
3569
3570 var thisCopy = this.slice(thisStart, thisEnd)
3571 var targetCopy = target.slice(start, end)
3572
3573 for (var i = 0; i < len; ++i) {
3574 if (thisCopy[i] !== targetCopy[i]) {
3575 x = thisCopy[i]
3576 y = targetCopy[i]
3577 break
3578 }
3579 }
3580
3581 if (x < y) return -1
3582 if (y < x) return 1
3583 return 0
3584}
3585
3586// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
3587// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
3588//
3589// Arguments:
3590// - buffer - a Buffer to search
3591// - val - a string, Buffer, or number
3592// - byteOffset - an index into `buffer`; will be clamped to an int32
3593// - encoding - an optional encoding, relevant is val is a string
3594// - dir - true for indexOf, false for lastIndexOf
3595function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
3596 // Empty buffer means no match
3597 if (buffer.length === 0) return -1
3598
3599 // Normalize byteOffset
3600 if (typeof byteOffset === 'string') {
3601 encoding = byteOffset
3602 byteOffset = 0
3603 } else if (byteOffset > 0x7fffffff) {
3604 byteOffset = 0x7fffffff
3605 } else if (byteOffset < -0x80000000) {
3606 byteOffset = -0x80000000
3607 }
3608 byteOffset = +byteOffset // Coerce to Number.
3609 if (numberIsNaN(byteOffset)) {
3610 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
3611 byteOffset = dir ? 0 : (buffer.length - 1)
3612 }
3613
3614 // Normalize byteOffset: negative offsets start from the end of the buffer
3615 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
3616 if (byteOffset >= buffer.length) {
3617 if (dir) return -1
3618 else byteOffset = buffer.length - 1
3619 } else if (byteOffset < 0) {
3620 if (dir) byteOffset = 0
3621 else return -1
3622 }
3623
3624 // Normalize val
3625 if (typeof val === 'string') {
3626 val = Buffer.from(val, encoding)
3627 }
3628
3629 // Finally, search either indexOf (if dir is true) or lastIndexOf
3630 if (Buffer.isBuffer(val)) {
3631 // Special case: looking for empty string/buffer always fails
3632 if (val.length === 0) {
3633 return -1
3634 }
3635 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
3636 } else if (typeof val === 'number') {
3637 val = val & 0xFF // Search for a byte value [0-255]
3638 if (typeof Uint8Array.prototype.indexOf === 'function') {
3639 if (dir) {
3640 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
3641 } else {
3642 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
3643 }
3644 }
3645 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
3646 }
3647
3648 throw new TypeError('val must be string, number or Buffer')
3649}
3650
3651function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
3652 var indexSize = 1
3653 var arrLength = arr.length
3654 var valLength = val.length
3655
3656 if (encoding !== undefined) {
3657 encoding = String(encoding).toLowerCase()
3658 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
3659 encoding === 'utf16le' || encoding === 'utf-16le') {
3660 if (arr.length < 2 || val.length < 2) {
3661 return -1
3662 }
3663 indexSize = 2
3664 arrLength /= 2
3665 valLength /= 2
3666 byteOffset /= 2
3667 }
3668 }
3669
3670 function read (buf, i) {
3671 if (indexSize === 1) {
3672 return buf[i]
3673 } else {
3674 return buf.readUInt16BE(i * indexSize)
3675 }
3676 }
3677
3678 var i
3679 if (dir) {
3680 var foundIndex = -1
3681 for (i = byteOffset; i < arrLength; i++) {
3682 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
3683 if (foundIndex === -1) foundIndex = i
3684 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
3685 } else {
3686 if (foundIndex !== -1) i -= i - foundIndex
3687 foundIndex = -1
3688 }
3689 }
3690 } else {
3691 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
3692 for (i = byteOffset; i >= 0; i--) {
3693 var found = true
3694 for (var j = 0; j < valLength; j++) {
3695 if (read(arr, i + j) !== read(val, j)) {
3696 found = false
3697 break
3698 }
3699 }
3700 if (found) return i
3701 }
3702 }
3703
3704 return -1
3705}
3706
3707Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
3708 return this.indexOf(val, byteOffset, encoding) !== -1
3709}
3710
3711Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
3712 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
3713}
3714
3715Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
3716 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
3717}
3718
3719function hexWrite (buf, string, offset, length) {
3720 offset = Number(offset) || 0
3721 var remaining = buf.length - offset
3722 if (!length) {
3723 length = remaining
3724 } else {
3725 length = Number(length)
3726 if (length > remaining) {
3727 length = remaining
3728 }
3729 }
3730
3731 var strLen = string.length
3732
3733 if (length > strLen / 2) {
3734 length = strLen / 2
3735 }
3736 for (var i = 0; i < length; ++i) {
3737 var parsed = parseInt(string.substr(i * 2, 2), 16)
3738 if (numberIsNaN(parsed)) return i
3739 buf[offset + i] = parsed
3740 }
3741 return i
3742}
3743
3744function utf8Write (buf, string, offset, length) {
3745 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
3746}
3747
3748function asciiWrite (buf, string, offset, length) {
3749 return blitBuffer(asciiToBytes(string), buf, offset, length)
3750}
3751
3752function latin1Write (buf, string, offset, length) {
3753 return asciiWrite(buf, string, offset, length)
3754}
3755
3756function base64Write (buf, string, offset, length) {
3757 return blitBuffer(base64ToBytes(string), buf, offset, length)
3758}
3759
3760function ucs2Write (buf, string, offset, length) {
3761 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
3762}
3763
3764Buffer.prototype.write = function write (string, offset, length, encoding) {
3765 // Buffer#write(string)
3766 if (offset === undefined) {
3767 encoding = 'utf8'
3768 length = this.length
3769 offset = 0
3770 // Buffer#write(string, encoding)
3771 } else if (length === undefined && typeof offset === 'string') {
3772 encoding = offset
3773 length = this.length
3774 offset = 0
3775 // Buffer#write(string, offset[, length][, encoding])
3776 } else if (isFinite(offset)) {
3777 offset = offset >>> 0
3778 if (isFinite(length)) {
3779 length = length >>> 0
3780 if (encoding === undefined) encoding = 'utf8'
3781 } else {
3782 encoding = length
3783 length = undefined
3784 }
3785 } else {
3786 throw new Error(
3787 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
3788 )
3789 }
3790
3791 var remaining = this.length - offset
3792 if (length === undefined || length > remaining) length = remaining
3793
3794 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
3795 throw new RangeError('Attempt to write outside buffer bounds')
3796 }
3797
3798 if (!encoding) encoding = 'utf8'
3799
3800 var loweredCase = false
3801 for (;;) {
3802 switch (encoding) {
3803 case 'hex':
3804 return hexWrite(this, string, offset, length)
3805
3806 case 'utf8':
3807 case 'utf-8':
3808 return utf8Write(this, string, offset, length)
3809
3810 case 'ascii':
3811 return asciiWrite(this, string, offset, length)
3812
3813 case 'latin1':
3814 case 'binary':
3815 return latin1Write(this, string, offset, length)
3816
3817 case 'base64':
3818 // Warning: maxLength not taken into account in base64Write
3819 return base64Write(this, string, offset, length)
3820
3821 case 'ucs2':
3822 case 'ucs-2':
3823 case 'utf16le':
3824 case 'utf-16le':
3825 return ucs2Write(this, string, offset, length)
3826
3827 default:
3828 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
3829 encoding = ('' + encoding).toLowerCase()
3830 loweredCase = true
3831 }
3832 }
3833}
3834
3835Buffer.prototype.toJSON = function toJSON () {
3836 return {
3837 type: 'Buffer',
3838 data: Array.prototype.slice.call(this._arr || this, 0)
3839 }
3840}
3841
3842function base64Slice (buf, start, end) {
3843 if (start === 0 && end === buf.length) {
3844 return base64.fromByteArray(buf)
3845 } else {
3846 return base64.fromByteArray(buf.slice(start, end))
3847 }
3848}
3849
3850function utf8Slice (buf, start, end) {
3851 end = Math.min(buf.length, end)
3852 var res = []
3853
3854 var i = start
3855 while (i < end) {
3856 var firstByte = buf[i]
3857 var codePoint = null
3858 var bytesPerSequence = (firstByte > 0xEF) ? 4
3859 : (firstByte > 0xDF) ? 3
3860 : (firstByte > 0xBF) ? 2
3861 : 1
3862
3863 if (i + bytesPerSequence <= end) {
3864 var secondByte, thirdByte, fourthByte, tempCodePoint
3865
3866 switch (bytesPerSequence) {
3867 case 1:
3868 if (firstByte < 0x80) {
3869 codePoint = firstByte
3870 }
3871 break
3872 case 2:
3873 secondByte = buf[i + 1]
3874 if ((secondByte & 0xC0) === 0x80) {
3875 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
3876 if (tempCodePoint > 0x7F) {
3877 codePoint = tempCodePoint
3878 }
3879 }
3880 break
3881 case 3:
3882 secondByte = buf[i + 1]
3883 thirdByte = buf[i + 2]
3884 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
3885 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
3886 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
3887 codePoint = tempCodePoint
3888 }
3889 }
3890 break
3891 case 4:
3892 secondByte = buf[i + 1]
3893 thirdByte = buf[i + 2]
3894 fourthByte = buf[i + 3]
3895 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
3896 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
3897 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
3898 codePoint = tempCodePoint
3899 }
3900 }
3901 }
3902 }
3903
3904 if (codePoint === null) {
3905 // we did not generate a valid codePoint so insert a
3906 // replacement char (U+FFFD) and advance only 1 byte
3907 codePoint = 0xFFFD
3908 bytesPerSequence = 1
3909 } else if (codePoint > 0xFFFF) {
3910 // encode to utf16 (surrogate pair dance)
3911 codePoint -= 0x10000
3912 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
3913 codePoint = 0xDC00 | codePoint & 0x3FF
3914 }
3915
3916 res.push(codePoint)
3917 i += bytesPerSequence
3918 }
3919
3920 return decodeCodePointsArray(res)
3921}
3922
3923// Based on http://stackoverflow.com/a/22747272/680742, the browser with
3924// the lowest limit is Chrome, with 0x10000 args.
3925// We go 1 magnitude less, for safety
3926var MAX_ARGUMENTS_LENGTH = 0x1000
3927
3928function decodeCodePointsArray (codePoints) {
3929 var len = codePoints.length
3930 if (len <= MAX_ARGUMENTS_LENGTH) {
3931 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
3932 }
3933
3934 // Decode in chunks to avoid "call stack size exceeded".
3935 var res = ''
3936 var i = 0
3937 while (i < len) {
3938 res += String.fromCharCode.apply(
3939 String,
3940 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
3941 )
3942 }
3943 return res
3944}
3945
3946function asciiSlice (buf, start, end) {
3947 var ret = ''
3948 end = Math.min(buf.length, end)
3949
3950 for (var i = start; i < end; ++i) {
3951 ret += String.fromCharCode(buf[i] & 0x7F)
3952 }
3953 return ret
3954}
3955
3956function latin1Slice (buf, start, end) {
3957 var ret = ''
3958 end = Math.min(buf.length, end)
3959
3960 for (var i = start; i < end; ++i) {
3961 ret += String.fromCharCode(buf[i])
3962 }
3963 return ret
3964}
3965
3966function hexSlice (buf, start, end) {
3967 var len = buf.length
3968
3969 if (!start || start < 0) start = 0
3970 if (!end || end < 0 || end > len) end = len
3971
3972 var out = ''
3973 for (var i = start; i < end; ++i) {
3974 out += toHex(buf[i])
3975 }
3976 return out
3977}
3978
3979function utf16leSlice (buf, start, end) {
3980 var bytes = buf.slice(start, end)
3981 var res = ''
3982 for (var i = 0; i < bytes.length; i += 2) {
3983 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
3984 }
3985 return res
3986}
3987
3988Buffer.prototype.slice = function slice (start, end) {
3989 var len = this.length
3990 start = ~~start
3991 end = end === undefined ? len : ~~end
3992
3993 if (start < 0) {
3994 start += len
3995 if (start < 0) start = 0
3996 } else if (start > len) {
3997 start = len
3998 }
3999
4000 if (end < 0) {
4001 end += len
4002 if (end < 0) end = 0
4003 } else if (end > len) {
4004 end = len
4005 }
4006
4007 if (end < start) end = start
4008
4009 var newBuf = this.subarray(start, end)
4010 // Return an augmented `Uint8Array` instance
4011 newBuf.__proto__ = Buffer.prototype
4012 return newBuf
4013}
4014
4015/*
4016 * Need to make sure that buffer isn't trying to write out of bounds.
4017 */
4018function checkOffset (offset, ext, length) {
4019 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
4020 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
4021}
4022
4023Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
4024 offset = offset >>> 0
4025 byteLength = byteLength >>> 0
4026 if (!noAssert) checkOffset(offset, byteLength, this.length)
4027
4028 var val = this[offset]
4029 var mul = 1
4030 var i = 0
4031 while (++i < byteLength && (mul *= 0x100)) {
4032 val += this[offset + i] * mul
4033 }
4034
4035 return val
4036}
4037
4038Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
4039 offset = offset >>> 0
4040 byteLength = byteLength >>> 0
4041 if (!noAssert) {
4042 checkOffset(offset, byteLength, this.length)
4043 }
4044
4045 var val = this[offset + --byteLength]
4046 var mul = 1
4047 while (byteLength > 0 && (mul *= 0x100)) {
4048 val += this[offset + --byteLength] * mul
4049 }
4050
4051 return val
4052}
4053
4054Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
4055 offset = offset >>> 0
4056 if (!noAssert) checkOffset(offset, 1, this.length)
4057 return this[offset]
4058}
4059
4060Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
4061 offset = offset >>> 0
4062 if (!noAssert) checkOffset(offset, 2, this.length)
4063 return this[offset] | (this[offset + 1] << 8)
4064}
4065
4066Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
4067 offset = offset >>> 0
4068 if (!noAssert) checkOffset(offset, 2, this.length)
4069 return (this[offset] << 8) | this[offset + 1]
4070}
4071
4072Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
4073 offset = offset >>> 0
4074 if (!noAssert) checkOffset(offset, 4, this.length)
4075
4076 return ((this[offset]) |
4077 (this[offset + 1] << 8) |
4078 (this[offset + 2] << 16)) +
4079 (this[offset + 3] * 0x1000000)
4080}
4081
4082Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
4083 offset = offset >>> 0
4084 if (!noAssert) checkOffset(offset, 4, this.length)
4085
4086 return (this[offset] * 0x1000000) +
4087 ((this[offset + 1] << 16) |
4088 (this[offset + 2] << 8) |
4089 this[offset + 3])
4090}
4091
4092Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
4093 offset = offset >>> 0
4094 byteLength = byteLength >>> 0
4095 if (!noAssert) checkOffset(offset, byteLength, this.length)
4096
4097 var val = this[offset]
4098 var mul = 1
4099 var i = 0
4100 while (++i < byteLength && (mul *= 0x100)) {
4101 val += this[offset + i] * mul
4102 }
4103 mul *= 0x80
4104
4105 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
4106
4107 return val
4108}
4109
4110Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
4111 offset = offset >>> 0
4112 byteLength = byteLength >>> 0
4113 if (!noAssert) checkOffset(offset, byteLength, this.length)
4114
4115 var i = byteLength
4116 var mul = 1
4117 var val = this[offset + --i]
4118 while (i > 0 && (mul *= 0x100)) {
4119 val += this[offset + --i] * mul
4120 }
4121 mul *= 0x80
4122
4123 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
4124
4125 return val
4126}
4127
4128Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
4129 offset = offset >>> 0
4130 if (!noAssert) checkOffset(offset, 1, this.length)
4131 if (!(this[offset] & 0x80)) return (this[offset])
4132 return ((0xff - this[offset] + 1) * -1)
4133}
4134
4135Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
4136 offset = offset >>> 0
4137 if (!noAssert) checkOffset(offset, 2, this.length)
4138 var val = this[offset] | (this[offset + 1] << 8)
4139 return (val & 0x8000) ? val | 0xFFFF0000 : val
4140}
4141
4142Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
4143 offset = offset >>> 0
4144 if (!noAssert) checkOffset(offset, 2, this.length)
4145 var val = this[offset + 1] | (this[offset] << 8)
4146 return (val & 0x8000) ? val | 0xFFFF0000 : val
4147}
4148
4149Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
4150 offset = offset >>> 0
4151 if (!noAssert) checkOffset(offset, 4, this.length)
4152
4153 return (this[offset]) |
4154 (this[offset + 1] << 8) |
4155 (this[offset + 2] << 16) |
4156 (this[offset + 3] << 24)
4157}
4158
4159Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
4160 offset = offset >>> 0
4161 if (!noAssert) checkOffset(offset, 4, this.length)
4162
4163 return (this[offset] << 24) |
4164 (this[offset + 1] << 16) |
4165 (this[offset + 2] << 8) |
4166 (this[offset + 3])
4167}
4168
4169Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
4170 offset = offset >>> 0
4171 if (!noAssert) checkOffset(offset, 4, this.length)
4172 return ieee754.read(this, offset, true, 23, 4)
4173}
4174
4175Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
4176 offset = offset >>> 0
4177 if (!noAssert) checkOffset(offset, 4, this.length)
4178 return ieee754.read(this, offset, false, 23, 4)
4179}
4180
4181Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
4182 offset = offset >>> 0
4183 if (!noAssert) checkOffset(offset, 8, this.length)
4184 return ieee754.read(this, offset, true, 52, 8)
4185}
4186
4187Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
4188 offset = offset >>> 0
4189 if (!noAssert) checkOffset(offset, 8, this.length)
4190 return ieee754.read(this, offset, false, 52, 8)
4191}
4192
4193function checkInt (buf, value, offset, ext, max, min) {
4194 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
4195 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
4196 if (offset + ext > buf.length) throw new RangeError('Index out of range')
4197}
4198
4199Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
4200 value = +value
4201 offset = offset >>> 0
4202 byteLength = byteLength >>> 0
4203 if (!noAssert) {
4204 var maxBytes = Math.pow(2, 8 * byteLength) - 1
4205 checkInt(this, value, offset, byteLength, maxBytes, 0)
4206 }
4207
4208 var mul = 1
4209 var i = 0
4210 this[offset] = value & 0xFF
4211 while (++i < byteLength && (mul *= 0x100)) {
4212 this[offset + i] = (value / mul) & 0xFF
4213 }
4214
4215 return offset + byteLength
4216}
4217
4218Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
4219 value = +value
4220 offset = offset >>> 0
4221 byteLength = byteLength >>> 0
4222 if (!noAssert) {
4223 var maxBytes = Math.pow(2, 8 * byteLength) - 1
4224 checkInt(this, value, offset, byteLength, maxBytes, 0)
4225 }
4226
4227 var i = byteLength - 1
4228 var mul = 1
4229 this[offset + i] = value & 0xFF
4230 while (--i >= 0 && (mul *= 0x100)) {
4231 this[offset + i] = (value / mul) & 0xFF
4232 }
4233
4234 return offset + byteLength
4235}
4236
4237Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
4238 value = +value
4239 offset = offset >>> 0
4240 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
4241 this[offset] = (value & 0xff)
4242 return offset + 1
4243}
4244
4245Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
4246 value = +value
4247 offset = offset >>> 0
4248 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
4249 this[offset] = (value & 0xff)
4250 this[offset + 1] = (value >>> 8)
4251 return offset + 2
4252}
4253
4254Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
4255 value = +value
4256 offset = offset >>> 0
4257 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
4258 this[offset] = (value >>> 8)
4259 this[offset + 1] = (value & 0xff)
4260 return offset + 2
4261}
4262
4263Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
4264 value = +value
4265 offset = offset >>> 0
4266 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
4267 this[offset + 3] = (value >>> 24)
4268 this[offset + 2] = (value >>> 16)
4269 this[offset + 1] = (value >>> 8)
4270 this[offset] = (value & 0xff)
4271 return offset + 4
4272}
4273
4274Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
4275 value = +value
4276 offset = offset >>> 0
4277 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
4278 this[offset] = (value >>> 24)
4279 this[offset + 1] = (value >>> 16)
4280 this[offset + 2] = (value >>> 8)
4281 this[offset + 3] = (value & 0xff)
4282 return offset + 4
4283}
4284
4285Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
4286 value = +value
4287 offset = offset >>> 0
4288 if (!noAssert) {
4289 var limit = Math.pow(2, (8 * byteLength) - 1)
4290
4291 checkInt(this, value, offset, byteLength, limit - 1, -limit)
4292 }
4293
4294 var i = 0
4295 var mul = 1
4296 var sub = 0
4297 this[offset] = value & 0xFF
4298 while (++i < byteLength && (mul *= 0x100)) {
4299 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
4300 sub = 1
4301 }
4302 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
4303 }
4304
4305 return offset + byteLength
4306}
4307
4308Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
4309 value = +value
4310 offset = offset >>> 0
4311 if (!noAssert) {
4312 var limit = Math.pow(2, (8 * byteLength) - 1)
4313
4314 checkInt(this, value, offset, byteLength, limit - 1, -limit)
4315 }
4316
4317 var i = byteLength - 1
4318 var mul = 1
4319 var sub = 0
4320 this[offset + i] = value & 0xFF
4321 while (--i >= 0 && (mul *= 0x100)) {
4322 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
4323 sub = 1
4324 }
4325 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
4326 }
4327
4328 return offset + byteLength
4329}
4330
4331Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
4332 value = +value
4333 offset = offset >>> 0
4334 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
4335 if (value < 0) value = 0xff + value + 1
4336 this[offset] = (value & 0xff)
4337 return offset + 1
4338}
4339
4340Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
4341 value = +value
4342 offset = offset >>> 0
4343 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
4344 this[offset] = (value & 0xff)
4345 this[offset + 1] = (value >>> 8)
4346 return offset + 2
4347}
4348
4349Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
4350 value = +value
4351 offset = offset >>> 0
4352 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
4353 this[offset] = (value >>> 8)
4354 this[offset + 1] = (value & 0xff)
4355 return offset + 2
4356}
4357
4358Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
4359 value = +value
4360 offset = offset >>> 0
4361 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
4362 this[offset] = (value & 0xff)
4363 this[offset + 1] = (value >>> 8)
4364 this[offset + 2] = (value >>> 16)
4365 this[offset + 3] = (value >>> 24)
4366 return offset + 4
4367}
4368
4369Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
4370 value = +value
4371 offset = offset >>> 0
4372 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
4373 if (value < 0) value = 0xffffffff + value + 1
4374 this[offset] = (value >>> 24)
4375 this[offset + 1] = (value >>> 16)
4376 this[offset + 2] = (value >>> 8)
4377 this[offset + 3] = (value & 0xff)
4378 return offset + 4
4379}
4380
4381function checkIEEE754 (buf, value, offset, ext, max, min) {
4382 if (offset + ext > buf.length) throw new RangeError('Index out of range')
4383 if (offset < 0) throw new RangeError('Index out of range')
4384}
4385
4386function writeFloat (buf, value, offset, littleEndian, noAssert) {
4387 value = +value
4388 offset = offset >>> 0
4389 if (!noAssert) {
4390 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
4391 }
4392 ieee754.write(buf, value, offset, littleEndian, 23, 4)
4393 return offset + 4
4394}
4395
4396Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
4397 return writeFloat(this, value, offset, true, noAssert)
4398}
4399
4400Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
4401 return writeFloat(this, value, offset, false, noAssert)
4402}
4403
4404function writeDouble (buf, value, offset, littleEndian, noAssert) {
4405 value = +value
4406 offset = offset >>> 0
4407 if (!noAssert) {
4408 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
4409 }
4410 ieee754.write(buf, value, offset, littleEndian, 52, 8)
4411 return offset + 8
4412}
4413
4414Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
4415 return writeDouble(this, value, offset, true, noAssert)
4416}
4417
4418Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
4419 return writeDouble(this, value, offset, false, noAssert)
4420}
4421
4422// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
4423Buffer.prototype.copy = function copy (target, targetStart, start, end) {
4424 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
4425 if (!start) start = 0
4426 if (!end && end !== 0) end = this.length
4427 if (targetStart >= target.length) targetStart = target.length
4428 if (!targetStart) targetStart = 0
4429 if (end > 0 && end < start) end = start
4430
4431 // Copy 0 bytes; we're done
4432 if (end === start) return 0
4433 if (target.length === 0 || this.length === 0) return 0
4434
4435 // Fatal error conditions
4436 if (targetStart < 0) {
4437 throw new RangeError('targetStart out of bounds')
4438 }
4439 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
4440 if (end < 0) throw new RangeError('sourceEnd out of bounds')
4441
4442 // Are we oob?
4443 if (end > this.length) end = this.length
4444 if (target.length - targetStart < end - start) {
4445 end = target.length - targetStart + start
4446 }
4447
4448 var len = end - start
4449
4450 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
4451 // Use built-in when available, missing from IE11
4452 this.copyWithin(targetStart, start, end)
4453 } else if (this === target && start < targetStart && targetStart < end) {
4454 // descending copy from end
4455 for (var i = len - 1; i >= 0; --i) {
4456 target[i + targetStart] = this[i + start]
4457 }
4458 } else {
4459 Uint8Array.prototype.set.call(
4460 target,
4461 this.subarray(start, end),
4462 targetStart
4463 )
4464 }
4465
4466 return len
4467}
4468
4469// Usage:
4470// buffer.fill(number[, offset[, end]])
4471// buffer.fill(buffer[, offset[, end]])
4472// buffer.fill(string[, offset[, end]][, encoding])
4473Buffer.prototype.fill = function fill (val, start, end, encoding) {
4474 // Handle string cases:
4475 if (typeof val === 'string') {
4476 if (typeof start === 'string') {
4477 encoding = start
4478 start = 0
4479 end = this.length
4480 } else if (typeof end === 'string') {
4481 encoding = end
4482 end = this.length
4483 }
4484 if (encoding !== undefined && typeof encoding !== 'string') {
4485 throw new TypeError('encoding must be a string')
4486 }
4487 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
4488 throw new TypeError('Unknown encoding: ' + encoding)
4489 }
4490 if (val.length === 1) {
4491 var code = val.charCodeAt(0)
4492 if ((encoding === 'utf8' && code < 128) ||
4493 encoding === 'latin1') {
4494 // Fast path: If `val` fits into a single byte, use that numeric value.
4495 val = code
4496 }
4497 }
4498 } else if (typeof val === 'number') {
4499 val = val & 255
4500 }
4501
4502 // Invalid ranges are not set to a default, so can range check early.
4503 if (start < 0 || this.length < start || this.length < end) {
4504 throw new RangeError('Out of range index')
4505 }
4506
4507 if (end <= start) {
4508 return this
4509 }
4510
4511 start = start >>> 0
4512 end = end === undefined ? this.length : end >>> 0
4513
4514 if (!val) val = 0
4515
4516 var i
4517 if (typeof val === 'number') {
4518 for (i = start; i < end; ++i) {
4519 this[i] = val
4520 }
4521 } else {
4522 var bytes = Buffer.isBuffer(val)
4523 ? val
4524 : Buffer.from(val, encoding)
4525 var len = bytes.length
4526 if (len === 0) {
4527 throw new TypeError('The value "' + val +
4528 '" is invalid for argument "value"')
4529 }
4530 for (i = 0; i < end - start; ++i) {
4531 this[i + start] = bytes[i % len]
4532 }
4533 }
4534
4535 return this
4536}
4537
4538// HELPER FUNCTIONS
4539// ================
4540
4541var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
4542
4543function base64clean (str) {
4544 // Node takes equal signs as end of the Base64 encoding
4545 str = str.split('=')[0]
4546 // Node strips out invalid characters like \n and \t from the string, base64-js does not
4547 str = str.trim().replace(INVALID_BASE64_RE, '')
4548 // Node converts strings with length < 2 to ''
4549 if (str.length < 2) return ''
4550 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
4551 while (str.length % 4 !== 0) {
4552 str = str + '='
4553 }
4554 return str
4555}
4556
4557function toHex (n) {
4558 if (n < 16) return '0' + n.toString(16)
4559 return n.toString(16)
4560}
4561
4562function utf8ToBytes (string, units) {
4563 units = units || Infinity
4564 var codePoint
4565 var length = string.length
4566 var leadSurrogate = null
4567 var bytes = []
4568
4569 for (var i = 0; i < length; ++i) {
4570 codePoint = string.charCodeAt(i)
4571
4572 // is surrogate component
4573 if (codePoint > 0xD7FF && codePoint < 0xE000) {
4574 // last char was a lead
4575 if (!leadSurrogate) {
4576 // no lead yet
4577 if (codePoint > 0xDBFF) {
4578 // unexpected trail
4579 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
4580 continue
4581 } else if (i + 1 === length) {
4582 // unpaired lead
4583 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
4584 continue
4585 }
4586
4587 // valid lead
4588 leadSurrogate = codePoint
4589
4590 continue
4591 }
4592
4593 // 2 leads in a row
4594 if (codePoint < 0xDC00) {
4595 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
4596 leadSurrogate = codePoint
4597 continue
4598 }
4599
4600 // valid surrogate pair
4601 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
4602 } else if (leadSurrogate) {
4603 // valid bmp char, but last char was a lead
4604 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
4605 }
4606
4607 leadSurrogate = null
4608
4609 // encode utf8
4610 if (codePoint < 0x80) {
4611 if ((units -= 1) < 0) break
4612 bytes.push(codePoint)
4613 } else if (codePoint < 0x800) {
4614 if ((units -= 2) < 0) break
4615 bytes.push(
4616 codePoint >> 0x6 | 0xC0,
4617 codePoint & 0x3F | 0x80
4618 )
4619 } else if (codePoint < 0x10000) {
4620 if ((units -= 3) < 0) break
4621 bytes.push(
4622 codePoint >> 0xC | 0xE0,
4623 codePoint >> 0x6 & 0x3F | 0x80,
4624 codePoint & 0x3F | 0x80
4625 )
4626 } else if (codePoint < 0x110000) {
4627 if ((units -= 4) < 0) break
4628 bytes.push(
4629 codePoint >> 0x12 | 0xF0,
4630 codePoint >> 0xC & 0x3F | 0x80,
4631 codePoint >> 0x6 & 0x3F | 0x80,
4632 codePoint & 0x3F | 0x80
4633 )
4634 } else {
4635 throw new Error('Invalid code point')
4636 }
4637 }
4638
4639 return bytes
4640}
4641
4642function asciiToBytes (str) {
4643 var byteArray = []
4644 for (var i = 0; i < str.length; ++i) {
4645 // Node's code seems to be doing this and not & 0x7F..
4646 byteArray.push(str.charCodeAt(i) & 0xFF)
4647 }
4648 return byteArray
4649}
4650
4651function utf16leToBytes (str, units) {
4652 var c, hi, lo
4653 var byteArray = []
4654 for (var i = 0; i < str.length; ++i) {
4655 if ((units -= 2) < 0) break
4656
4657 c = str.charCodeAt(i)
4658 hi = c >> 8
4659 lo = c % 256
4660 byteArray.push(lo)
4661 byteArray.push(hi)
4662 }
4663
4664 return byteArray
4665}
4666
4667function base64ToBytes (str) {
4668 return base64.toByteArray(base64clean(str))
4669}
4670
4671function blitBuffer (src, dst, offset, length) {
4672 for (var i = 0; i < length; ++i) {
4673 if ((i + offset >= dst.length) || (i >= src.length)) break
4674 dst[i + offset] = src[i]
4675 }
4676 return i
4677}
4678
4679// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
4680// the `instanceof` check but they should be treated as of that type.
4681// See: https://github.com/feross/buffer/issues/166
4682function isInstance (obj, type) {
4683 return obj instanceof type ||
4684 (obj != null && obj.constructor != null && obj.constructor.name != null &&
4685 obj.constructor.name === type.name)
4686}
4687function numberIsNaN (obj) {
4688 // For IE11 support
4689 return obj !== obj // eslint-disable-line no-self-compare
4690}
4691
4692},{"base64-js":20,"ieee754":29}],23:[function(require,module,exports){
4693module.exports = {
4694 "100": "Continue",
4695 "101": "Switching Protocols",
4696 "102": "Processing",
4697 "200": "OK",
4698 "201": "Created",
4699 "202": "Accepted",
4700 "203": "Non-Authoritative Information",
4701 "204": "No Content",
4702 "205": "Reset Content",
4703 "206": "Partial Content",
4704 "207": "Multi-Status",
4705 "208": "Already Reported",
4706 "226": "IM Used",
4707 "300": "Multiple Choices",
4708 "301": "Moved Permanently",
4709 "302": "Found",
4710 "303": "See Other",
4711 "304": "Not Modified",
4712 "305": "Use Proxy",
4713 "307": "Temporary Redirect",
4714 "308": "Permanent Redirect",
4715 "400": "Bad Request",
4716 "401": "Unauthorized",
4717 "402": "Payment Required",
4718 "403": "Forbidden",
4719 "404": "Not Found",
4720 "405": "Method Not Allowed",
4721 "406": "Not Acceptable",
4722 "407": "Proxy Authentication Required",
4723 "408": "Request Timeout",
4724 "409": "Conflict",
4725 "410": "Gone",
4726 "411": "Length Required",
4727 "412": "Precondition Failed",
4728 "413": "Payload Too Large",
4729 "414": "URI Too Long",
4730 "415": "Unsupported Media Type",
4731 "416": "Range Not Satisfiable",
4732 "417": "Expectation Failed",
4733 "418": "I'm a teapot",
4734 "421": "Misdirected Request",
4735 "422": "Unprocessable Entity",
4736 "423": "Locked",
4737 "424": "Failed Dependency",
4738 "425": "Unordered Collection",
4739 "426": "Upgrade Required",
4740 "428": "Precondition Required",
4741 "429": "Too Many Requests",
4742 "431": "Request Header Fields Too Large",
4743 "451": "Unavailable For Legal Reasons",
4744 "500": "Internal Server Error",
4745 "501": "Not Implemented",
4746 "502": "Bad Gateway",
4747 "503": "Service Unavailable",
4748 "504": "Gateway Timeout",
4749 "505": "HTTP Version Not Supported",
4750 "506": "Variant Also Negotiates",
4751 "507": "Insufficient Storage",
4752 "508": "Loop Detected",
4753 "509": "Bandwidth Limit Exceeded",
4754 "510": "Not Extended",
4755 "511": "Network Authentication Required"
4756}
4757
4758},{}],24:[function(require,module,exports){
4759(function (process,global){
4760"use strict"
4761
4762var next = (global.process && process.nextTick) || global.setImmediate || function (f) {
4763 setTimeout(f, 0)
4764}
4765
4766module.exports = function maybe (cb, promise) {
4767 if (cb) {
4768 promise
4769 .then(function (result) {
4770 next(function () { cb(null, result) })
4771 }, function (err) {
4772 next(function () { cb(err) })
4773 })
4774 return undefined
4775 }
4776 else {
4777 return promise
4778 }
4779}
4780
4781}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4782
4783},{"_process":64}],25:[function(require,module,exports){
4784(function (Buffer){
4785// Copyright Joyent, Inc. and other Node contributors.
4786//
4787// Permission is hereby granted, free of charge, to any person obtaining a
4788// copy of this software and associated documentation files (the
4789// "Software"), to deal in the Software without restriction, including
4790// without limitation the rights to use, copy, modify, merge, publish,
4791// distribute, sublicense, and/or sell copies of the Software, and to permit
4792// persons to whom the Software is furnished to do so, subject to the
4793// following conditions:
4794//
4795// The above copyright notice and this permission notice shall be included
4796// in all copies or substantial portions of the Software.
4797//
4798// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4799// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4800// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4801// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4802// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4803// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4804// USE OR OTHER DEALINGS IN THE SOFTWARE.
4805
4806// NOTE: These type checking functions intentionally don't use `instanceof`
4807// because it is fragile and can be easily faked with `Object.create()`.
4808
4809function isArray(arg) {
4810 if (Array.isArray) {
4811 return Array.isArray(arg);
4812 }
4813 return objectToString(arg) === '[object Array]';
4814}
4815exports.isArray = isArray;
4816
4817function isBoolean(arg) {
4818 return typeof arg === 'boolean';
4819}
4820exports.isBoolean = isBoolean;
4821
4822function isNull(arg) {
4823 return arg === null;
4824}
4825exports.isNull = isNull;
4826
4827function isNullOrUndefined(arg) {
4828 return arg == null;
4829}
4830exports.isNullOrUndefined = isNullOrUndefined;
4831
4832function isNumber(arg) {
4833 return typeof arg === 'number';
4834}
4835exports.isNumber = isNumber;
4836
4837function isString(arg) {
4838 return typeof arg === 'string';
4839}
4840exports.isString = isString;
4841
4842function isSymbol(arg) {
4843 return typeof arg === 'symbol';
4844}
4845exports.isSymbol = isSymbol;
4846
4847function isUndefined(arg) {
4848 return arg === void 0;
4849}
4850exports.isUndefined = isUndefined;
4851
4852function isRegExp(re) {
4853 return objectToString(re) === '[object RegExp]';
4854}
4855exports.isRegExp = isRegExp;
4856
4857function isObject(arg) {
4858 return typeof arg === 'object' && arg !== null;
4859}
4860exports.isObject = isObject;
4861
4862function isDate(d) {
4863 return objectToString(d) === '[object Date]';
4864}
4865exports.isDate = isDate;
4866
4867function isError(e) {
4868 return (objectToString(e) === '[object Error]' || e instanceof Error);
4869}
4870exports.isError = isError;
4871
4872function isFunction(arg) {
4873 return typeof arg === 'function';
4874}
4875exports.isFunction = isFunction;
4876
4877function isPrimitive(arg) {
4878 return arg === null ||
4879 typeof arg === 'boolean' ||
4880 typeof arg === 'number' ||
4881 typeof arg === 'string' ||
4882 typeof arg === 'symbol' || // ES6 symbol
4883 typeof arg === 'undefined';
4884}
4885exports.isPrimitive = isPrimitive;
4886
4887exports.isBuffer = Buffer.isBuffer;
4888
4889function objectToString(o) {
4890 return Object.prototype.toString.call(o);
4891}
4892
4893}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
4894
4895},{"../../is-buffer/index.js":31}],26:[function(require,module,exports){
4896// Copyright Joyent, Inc. and other Node contributors.
4897//
4898// Permission is hereby granted, free of charge, to any person obtaining a
4899// copy of this software and associated documentation files (the
4900// "Software"), to deal in the Software without restriction, including
4901// without limitation the rights to use, copy, modify, merge, publish,
4902// distribute, sublicense, and/or sell copies of the Software, and to permit
4903// persons to whom the Software is furnished to do so, subject to the
4904// following conditions:
4905//
4906// The above copyright notice and this permission notice shall be included
4907// in all copies or substantial portions of the Software.
4908//
4909// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4910// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4911// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4912// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4913// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4914// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4915// USE OR OTHER DEALINGS IN THE SOFTWARE.
4916
4917var objectCreate = Object.create || objectCreatePolyfill
4918var objectKeys = Object.keys || objectKeysPolyfill
4919var bind = Function.prototype.bind || functionBindPolyfill
4920
4921function EventEmitter() {
4922 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
4923 this._events = objectCreate(null);
4924 this._eventsCount = 0;
4925 }
4926
4927 this._maxListeners = this._maxListeners || undefined;
4928}
4929module.exports = EventEmitter;
4930
4931// Backwards-compat with node 0.10.x
4932EventEmitter.EventEmitter = EventEmitter;
4933
4934EventEmitter.prototype._events = undefined;
4935EventEmitter.prototype._maxListeners = undefined;
4936
4937// By default EventEmitters will print a warning if more than 10 listeners are
4938// added to it. This is a useful default which helps finding memory leaks.
4939var defaultMaxListeners = 10;
4940
4941var hasDefineProperty;
4942try {
4943 var o = {};
4944 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
4945 hasDefineProperty = o.x === 0;
4946} catch (err) { hasDefineProperty = false }
4947if (hasDefineProperty) {
4948 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
4949 enumerable: true,
4950 get: function() {
4951 return defaultMaxListeners;
4952 },
4953 set: function(arg) {
4954 // check whether the input is a positive number (whose value is zero or
4955 // greater and not a NaN).
4956 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
4957 throw new TypeError('"defaultMaxListeners" must be a positive number');
4958 defaultMaxListeners = arg;
4959 }
4960 });
4961} else {
4962 EventEmitter.defaultMaxListeners = defaultMaxListeners;
4963}
4964
4965// Obviously not all Emitters should be limited to 10. This function allows
4966// that to be increased. Set to zero for unlimited.
4967EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
4968 if (typeof n !== 'number' || n < 0 || isNaN(n))
4969 throw new TypeError('"n" argument must be a positive number');
4970 this._maxListeners = n;
4971 return this;
4972};
4973
4974function $getMaxListeners(that) {
4975 if (that._maxListeners === undefined)
4976 return EventEmitter.defaultMaxListeners;
4977 return that._maxListeners;
4978}
4979
4980EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
4981 return $getMaxListeners(this);
4982};
4983
4984// These standalone emit* functions are used to optimize calling of event
4985// handlers for fast cases because emit() itself often has a variable number of
4986// arguments and can be deoptimized because of that. These functions always have
4987// the same number of arguments and thus do not get deoptimized, so the code
4988// inside them can execute faster.
4989function emitNone(handler, isFn, self) {
4990 if (isFn)
4991 handler.call(self);
4992 else {
4993 var len = handler.length;
4994 var listeners = arrayClone(handler, len);
4995 for (var i = 0; i < len; ++i)
4996 listeners[i].call(self);
4997 }
4998}
4999function emitOne(handler, isFn, self, arg1) {
5000 if (isFn)
5001 handler.call(self, arg1);
5002 else {
5003 var len = handler.length;
5004 var listeners = arrayClone(handler, len);
5005 for (var i = 0; i < len; ++i)
5006 listeners[i].call(self, arg1);
5007 }
5008}
5009function emitTwo(handler, isFn, self, arg1, arg2) {
5010 if (isFn)
5011 handler.call(self, arg1, arg2);
5012 else {
5013 var len = handler.length;
5014 var listeners = arrayClone(handler, len);
5015 for (var i = 0; i < len; ++i)
5016 listeners[i].call(self, arg1, arg2);
5017 }
5018}
5019function emitThree(handler, isFn, self, arg1, arg2, arg3) {
5020 if (isFn)
5021 handler.call(self, arg1, arg2, arg3);
5022 else {
5023 var len = handler.length;
5024 var listeners = arrayClone(handler, len);
5025 for (var i = 0; i < len; ++i)
5026 listeners[i].call(self, arg1, arg2, arg3);
5027 }
5028}
5029
5030function emitMany(handler, isFn, self, args) {
5031 if (isFn)
5032 handler.apply(self, args);
5033 else {
5034 var len = handler.length;
5035 var listeners = arrayClone(handler, len);
5036 for (var i = 0; i < len; ++i)
5037 listeners[i].apply(self, args);
5038 }
5039}
5040
5041EventEmitter.prototype.emit = function emit(type) {
5042 var er, handler, len, args, i, events;
5043 var doError = (type === 'error');
5044
5045 events = this._events;
5046 if (events)
5047 doError = (doError && events.error == null);
5048 else if (!doError)
5049 return false;
5050
5051 // If there is no 'error' event listener then throw.
5052 if (doError) {
5053 if (arguments.length > 1)
5054 er = arguments[1];
5055 if (er instanceof Error) {
5056 throw er; // Unhandled 'error' event
5057 } else {
5058 // At least give some kind of context to the user
5059 var err = new Error('Unhandled "error" event. (' + er + ')');
5060 err.context = er;
5061 throw err;
5062 }
5063 return false;
5064 }
5065
5066 handler = events[type];
5067
5068 if (!handler)
5069 return false;
5070
5071 var isFn = typeof handler === 'function';
5072 len = arguments.length;
5073 switch (len) {
5074 // fast cases
5075 case 1:
5076 emitNone(handler, isFn, this);
5077 break;
5078 case 2:
5079 emitOne(handler, isFn, this, arguments[1]);
5080 break;
5081 case 3:
5082 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
5083 break;
5084 case 4:
5085 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
5086 break;
5087 // slower
5088 default:
5089 args = new Array(len - 1);
5090 for (i = 1; i < len; i++)
5091 args[i - 1] = arguments[i];
5092 emitMany(handler, isFn, this, args);
5093 }
5094
5095 return true;
5096};
5097
5098function _addListener(target, type, listener, prepend) {
5099 var m;
5100 var events;
5101 var existing;
5102
5103 if (typeof listener !== 'function')
5104 throw new TypeError('"listener" argument must be a function');
5105
5106 events = target._events;
5107 if (!events) {
5108 events = target._events = objectCreate(null);
5109 target._eventsCount = 0;
5110 } else {
5111 // To avoid recursion in the case that type === "newListener"! Before
5112 // adding it to the listeners, first emit "newListener".
5113 if (events.newListener) {
5114 target.emit('newListener', type,
5115 listener.listener ? listener.listener : listener);
5116
5117 // Re-assign `events` because a newListener handler could have caused the
5118 // this._events to be assigned to a new object
5119 events = target._events;
5120 }
5121 existing = events[type];
5122 }
5123
5124 if (!existing) {
5125 // Optimize the case of one listener. Don't need the extra array object.
5126 existing = events[type] = listener;
5127 ++target._eventsCount;
5128 } else {
5129 if (typeof existing === 'function') {
5130 // Adding the second element, need to change to array.
5131 existing = events[type] =
5132 prepend ? [listener, existing] : [existing, listener];
5133 } else {
5134 // If we've already got an array, just append.
5135 if (prepend) {
5136 existing.unshift(listener);
5137 } else {
5138 existing.push(listener);
5139 }
5140 }
5141
5142 // Check for listener leak
5143 if (!existing.warned) {
5144 m = $getMaxListeners(target);
5145 if (m && m > 0 && existing.length > m) {
5146 existing.warned = true;
5147 var w = new Error('Possible EventEmitter memory leak detected. ' +
5148 existing.length + ' "' + String(type) + '" listeners ' +
5149 'added. Use emitter.setMaxListeners() to ' +
5150 'increase limit.');
5151 w.name = 'MaxListenersExceededWarning';
5152 w.emitter = target;
5153 w.type = type;
5154 w.count = existing.length;
5155 if (typeof console === 'object' && console.warn) {
5156 console.warn('%s: %s', w.name, w.message);
5157 }
5158 }
5159 }
5160 }
5161
5162 return target;
5163}
5164
5165EventEmitter.prototype.addListener = function addListener(type, listener) {
5166 return _addListener(this, type, listener, false);
5167};
5168
5169EventEmitter.prototype.on = EventEmitter.prototype.addListener;
5170
5171EventEmitter.prototype.prependListener =
5172 function prependListener(type, listener) {
5173 return _addListener(this, type, listener, true);
5174 };
5175
5176function onceWrapper() {
5177 if (!this.fired) {
5178 this.target.removeListener(this.type, this.wrapFn);
5179 this.fired = true;
5180 switch (arguments.length) {
5181 case 0:
5182 return this.listener.call(this.target);
5183 case 1:
5184 return this.listener.call(this.target, arguments[0]);
5185 case 2:
5186 return this.listener.call(this.target, arguments[0], arguments[1]);
5187 case 3:
5188 return this.listener.call(this.target, arguments[0], arguments[1],
5189 arguments[2]);
5190 default:
5191 var args = new Array(arguments.length);
5192 for (var i = 0; i < args.length; ++i)
5193 args[i] = arguments[i];
5194 this.listener.apply(this.target, args);
5195 }
5196 }
5197}
5198
5199function _onceWrap(target, type, listener) {
5200 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
5201 var wrapped = bind.call(onceWrapper, state);
5202 wrapped.listener = listener;
5203 state.wrapFn = wrapped;
5204 return wrapped;
5205}
5206
5207EventEmitter.prototype.once = function once(type, listener) {
5208 if (typeof listener !== 'function')
5209 throw new TypeError('"listener" argument must be a function');
5210 this.on(type, _onceWrap(this, type, listener));
5211 return this;
5212};
5213
5214EventEmitter.prototype.prependOnceListener =
5215 function prependOnceListener(type, listener) {
5216 if (typeof listener !== 'function')
5217 throw new TypeError('"listener" argument must be a function');
5218 this.prependListener(type, _onceWrap(this, type, listener));
5219 return this;
5220 };
5221
5222// Emits a 'removeListener' event if and only if the listener was removed.
5223EventEmitter.prototype.removeListener =
5224 function removeListener(type, listener) {
5225 var list, events, position, i, originalListener;
5226
5227 if (typeof listener !== 'function')
5228 throw new TypeError('"listener" argument must be a function');
5229
5230 events = this._events;
5231 if (!events)
5232 return this;
5233
5234 list = events[type];
5235 if (!list)
5236 return this;
5237
5238 if (list === listener || list.listener === listener) {
5239 if (--this._eventsCount === 0)
5240 this._events = objectCreate(null);
5241 else {
5242 delete events[type];
5243 if (events.removeListener)
5244 this.emit('removeListener', type, list.listener || listener);
5245 }
5246 } else if (typeof list !== 'function') {
5247 position = -1;
5248
5249 for (i = list.length - 1; i >= 0; i--) {
5250 if (list[i] === listener || list[i].listener === listener) {
5251 originalListener = list[i].listener;
5252 position = i;
5253 break;
5254 }
5255 }
5256
5257 if (position < 0)
5258 return this;
5259
5260 if (position === 0)
5261 list.shift();
5262 else
5263 spliceOne(list, position);
5264
5265 if (list.length === 1)
5266 events[type] = list[0];
5267
5268 if (events.removeListener)
5269 this.emit('removeListener', type, originalListener || listener);
5270 }
5271
5272 return this;
5273 };
5274
5275EventEmitter.prototype.removeAllListeners =
5276 function removeAllListeners(type) {
5277 var listeners, events, i;
5278
5279 events = this._events;
5280 if (!events)
5281 return this;
5282
5283 // not listening for removeListener, no need to emit
5284 if (!events.removeListener) {
5285 if (arguments.length === 0) {
5286 this._events = objectCreate(null);
5287 this._eventsCount = 0;
5288 } else if (events[type]) {
5289 if (--this._eventsCount === 0)
5290 this._events = objectCreate(null);
5291 else
5292 delete events[type];
5293 }
5294 return this;
5295 }
5296
5297 // emit removeListener for all listeners on all events
5298 if (arguments.length === 0) {
5299 var keys = objectKeys(events);
5300 var key;
5301 for (i = 0; i < keys.length; ++i) {
5302 key = keys[i];
5303 if (key === 'removeListener') continue;
5304 this.removeAllListeners(key);
5305 }
5306 this.removeAllListeners('removeListener');
5307 this._events = objectCreate(null);
5308 this._eventsCount = 0;
5309 return this;
5310 }
5311
5312 listeners = events[type];
5313
5314 if (typeof listeners === 'function') {
5315 this.removeListener(type, listeners);
5316 } else if (listeners) {
5317 // LIFO order
5318 for (i = listeners.length - 1; i >= 0; i--) {
5319 this.removeListener(type, listeners[i]);
5320 }
5321 }
5322
5323 return this;
5324 };
5325
5326function _listeners(target, type, unwrap) {
5327 var events = target._events;
5328
5329 if (!events)
5330 return [];
5331
5332 var evlistener = events[type];
5333 if (!evlistener)
5334 return [];
5335
5336 if (typeof evlistener === 'function')
5337 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
5338
5339 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
5340}
5341
5342EventEmitter.prototype.listeners = function listeners(type) {
5343 return _listeners(this, type, true);
5344};
5345
5346EventEmitter.prototype.rawListeners = function rawListeners(type) {
5347 return _listeners(this, type, false);
5348};
5349
5350EventEmitter.listenerCount = function(emitter, type) {
5351 if (typeof emitter.listenerCount === 'function') {
5352 return emitter.listenerCount(type);
5353 } else {
5354 return listenerCount.call(emitter, type);
5355 }
5356};
5357
5358EventEmitter.prototype.listenerCount = listenerCount;
5359function listenerCount(type) {
5360 var events = this._events;
5361
5362 if (events) {
5363 var evlistener = events[type];
5364
5365 if (typeof evlistener === 'function') {
5366 return 1;
5367 } else if (evlistener) {
5368 return evlistener.length;
5369 }
5370 }
5371
5372 return 0;
5373}
5374
5375EventEmitter.prototype.eventNames = function eventNames() {
5376 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
5377};
5378
5379// About 1.5x faster than the two-arg version of Array#splice().
5380function spliceOne(list, index) {
5381 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
5382 list[i] = list[k];
5383 list.pop();
5384}
5385
5386function arrayClone(arr, n) {
5387 var copy = new Array(n);
5388 for (var i = 0; i < n; ++i)
5389 copy[i] = arr[i];
5390 return copy;
5391}
5392
5393function unwrapListeners(arr) {
5394 var ret = new Array(arr.length);
5395 for (var i = 0; i < ret.length; ++i) {
5396 ret[i] = arr[i].listener || arr[i];
5397 }
5398 return ret;
5399}
5400
5401function objectCreatePolyfill(proto) {
5402 var F = function() {};
5403 F.prototype = proto;
5404 return new F;
5405}
5406function objectKeysPolyfill(obj) {
5407 var keys = [];
5408 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
5409 keys.push(k);
5410 }
5411 return k;
5412}
5413function functionBindPolyfill(context) {
5414 var fn = this;
5415 return function () {
5416 return fn.apply(context, arguments);
5417 };
5418}
5419
5420},{}],27:[function(require,module,exports){
5421function format(fmt) {
5422 var re = /(%?)(%([jds]))/g
5423 , args = Array.prototype.slice.call(arguments, 1);
5424 if(args.length) {
5425 fmt = fmt.replace(re, function(match, escaped, ptn, flag) {
5426 var arg = args.shift();
5427 switch(flag) {
5428 case 's':
5429 arg = '' + arg;
5430 break;
5431 case 'd':
5432 arg = Number(arg);
5433 break;
5434 case 'j':
5435 arg = JSON.stringify(arg);
5436 break;
5437 }
5438 if(!escaped) {
5439 return arg;
5440 }
5441 args.unshift(arg);
5442 return match;
5443 })
5444 }
5445
5446 // arguments remain after formatting
5447 if(args.length) {
5448 fmt += ' ' + args.join(' ');
5449 }
5450
5451 // update escaped %% values
5452 fmt = fmt.replace(/%{2,2}/g, '%');
5453
5454 return '' + fmt;
5455}
5456
5457module.exports = format;
5458
5459},{}],28:[function(require,module,exports){
5460var http = require('http')
5461var url = require('url')
5462
5463var https = module.exports
5464
5465for (var key in http) {
5466 if (http.hasOwnProperty(key)) https[key] = http[key]
5467}
5468
5469https.request = function (params, cb) {
5470 params = validateParams(params)
5471 return http.request.call(this, params, cb)
5472}
5473
5474https.get = function (params, cb) {
5475 params = validateParams(params)
5476 return http.get.call(this, params, cb)
5477}
5478
5479function validateParams (params) {
5480 if (typeof params === 'string') {
5481 params = url.parse(params)
5482 }
5483 if (!params.protocol) {
5484 params.protocol = 'https:'
5485 }
5486 if (params.protocol !== 'https:') {
5487 throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
5488 }
5489 return params
5490}
5491
5492},{"http":70,"url":87}],29:[function(require,module,exports){
5493exports.read = function (buffer, offset, isLE, mLen, nBytes) {
5494 var e, m
5495 var eLen = (nBytes * 8) - mLen - 1
5496 var eMax = (1 << eLen) - 1
5497 var eBias = eMax >> 1
5498 var nBits = -7
5499 var i = isLE ? (nBytes - 1) : 0
5500 var d = isLE ? -1 : 1
5501 var s = buffer[offset + i]
5502
5503 i += d
5504
5505 e = s & ((1 << (-nBits)) - 1)
5506 s >>= (-nBits)
5507 nBits += eLen
5508 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5509
5510 m = e & ((1 << (-nBits)) - 1)
5511 e >>= (-nBits)
5512 nBits += mLen
5513 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
5514
5515 if (e === 0) {
5516 e = 1 - eBias
5517 } else if (e === eMax) {
5518 return m ? NaN : ((s ? -1 : 1) * Infinity)
5519 } else {
5520 m = m + Math.pow(2, mLen)
5521 e = e - eBias
5522 }
5523 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
5524}
5525
5526exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
5527 var e, m, c
5528 var eLen = (nBytes * 8) - mLen - 1
5529 var eMax = (1 << eLen) - 1
5530 var eBias = eMax >> 1
5531 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
5532 var i = isLE ? 0 : (nBytes - 1)
5533 var d = isLE ? 1 : -1
5534 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
5535
5536 value = Math.abs(value)
5537
5538 if (isNaN(value) || value === Infinity) {
5539 m = isNaN(value) ? 1 : 0
5540 e = eMax
5541 } else {
5542 e = Math.floor(Math.log(value) / Math.LN2)
5543 if (value * (c = Math.pow(2, -e)) < 1) {
5544 e--
5545 c *= 2
5546 }
5547 if (e + eBias >= 1) {
5548 value += rt / c
5549 } else {
5550 value += rt * Math.pow(2, 1 - eBias)
5551 }
5552 if (value * c >= 2) {
5553 e++
5554 c /= 2
5555 }
5556
5557 if (e + eBias >= eMax) {
5558 m = 0
5559 e = eMax
5560 } else if (e + eBias >= 1) {
5561 m = ((value * c) - 1) * Math.pow(2, mLen)
5562 e = e + eBias
5563 } else {
5564 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
5565 e = 0
5566 }
5567 }
5568
5569 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
5570
5571 e = (e << mLen) | m
5572 eLen += mLen
5573 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
5574
5575 buffer[offset + i - d] |= s * 128
5576}
5577
5578},{}],30:[function(require,module,exports){
5579if (typeof Object.create === 'function') {
5580 // implementation from standard node.js 'util' module
5581 module.exports = function inherits(ctor, superCtor) {
5582 ctor.super_ = superCtor
5583 ctor.prototype = Object.create(superCtor.prototype, {
5584 constructor: {
5585 value: ctor,
5586 enumerable: false,
5587 writable: true,
5588 configurable: true
5589 }
5590 });
5591 };
5592} else {
5593 // old school shim for old browsers
5594 module.exports = function inherits(ctor, superCtor) {
5595 ctor.super_ = superCtor
5596 var TempCtor = function () {}
5597 TempCtor.prototype = superCtor.prototype
5598 ctor.prototype = new TempCtor()
5599 ctor.prototype.constructor = ctor
5600 }
5601}
5602
5603},{}],31:[function(require,module,exports){
5604/*!
5605 * Determine if an object is a Buffer
5606 *
5607 * @author Feross Aboukhadijeh <https://feross.org>
5608 * @license MIT
5609 */
5610
5611// The _isBuffer check is for Safari 5-7 support, because it's missing
5612// Object.prototype.constructor. Remove this eventually
5613module.exports = function (obj) {
5614 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
5615}
5616
5617function isBuffer (obj) {
5618 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
5619}
5620
5621// For Node v0.10 support. Remove this eventually.
5622function isSlowBuffer (obj) {
5623 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
5624}
5625
5626},{}],32:[function(require,module,exports){
5627var toString = {}.toString;
5628
5629module.exports = Array.isArray || function (arr) {
5630 return toString.call(arr) == '[object Array]';
5631};
5632
5633},{}],33:[function(require,module,exports){
5634'use strict';
5635
5636
5637var yaml = require('./lib/js-yaml.js');
5638
5639
5640module.exports = yaml;
5641
5642},{"./lib/js-yaml.js":34}],34:[function(require,module,exports){
5643'use strict';
5644
5645
5646var loader = require('./js-yaml/loader');
5647var dumper = require('./js-yaml/dumper');
5648
5649
5650function deprecated(name) {
5651 return function () {
5652 throw new Error('Function ' + name + ' is deprecated and cannot be used.');
5653 };
5654}
5655
5656
5657module.exports.Type = require('./js-yaml/type');
5658module.exports.Schema = require('./js-yaml/schema');
5659module.exports.FAILSAFE_SCHEMA = require('./js-yaml/schema/failsafe');
5660module.exports.JSON_SCHEMA = require('./js-yaml/schema/json');
5661module.exports.CORE_SCHEMA = require('./js-yaml/schema/core');
5662module.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
5663module.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full');
5664module.exports.load = loader.load;
5665module.exports.loadAll = loader.loadAll;
5666module.exports.safeLoad = loader.safeLoad;
5667module.exports.safeLoadAll = loader.safeLoadAll;
5668module.exports.dump = dumper.dump;
5669module.exports.safeDump = dumper.safeDump;
5670module.exports.YAMLException = require('./js-yaml/exception');
5671
5672// Deprecated schema names from JS-YAML 2.0.x
5673module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');
5674module.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
5675module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');
5676
5677// Deprecated functions from JS-YAML 1.x.x
5678module.exports.scan = deprecated('scan');
5679module.exports.parse = deprecated('parse');
5680module.exports.compose = deprecated('compose');
5681module.exports.addConstructor = deprecated('addConstructor');
5682
5683},{"./js-yaml/dumper":36,"./js-yaml/exception":37,"./js-yaml/loader":38,"./js-yaml/schema":40,"./js-yaml/schema/core":41,"./js-yaml/schema/default_full":42,"./js-yaml/schema/default_safe":43,"./js-yaml/schema/failsafe":44,"./js-yaml/schema/json":45,"./js-yaml/type":46}],35:[function(require,module,exports){
5684'use strict';
5685
5686
5687function isNothing(subject) {
5688 return (typeof subject === 'undefined') || (subject === null);
5689}
5690
5691
5692function isObject(subject) {
5693 return (typeof subject === 'object') && (subject !== null);
5694}
5695
5696
5697function toArray(sequence) {
5698 if (Array.isArray(sequence)) return sequence;
5699 else if (isNothing(sequence)) return [];
5700
5701 return [ sequence ];
5702}
5703
5704
5705function extend(target, source) {
5706 var index, length, key, sourceKeys;
5707
5708 if (source) {
5709 sourceKeys = Object.keys(source);
5710
5711 for (index = 0, length = sourceKeys.length; index < length; index += 1) {
5712 key = sourceKeys[index];
5713 target[key] = source[key];
5714 }
5715 }
5716
5717 return target;
5718}
5719
5720
5721function repeat(string, count) {
5722 var result = '', cycle;
5723
5724 for (cycle = 0; cycle < count; cycle += 1) {
5725 result += string;
5726 }
5727
5728 return result;
5729}
5730
5731
5732function isNegativeZero(number) {
5733 return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
5734}
5735
5736
5737module.exports.isNothing = isNothing;
5738module.exports.isObject = isObject;
5739module.exports.toArray = toArray;
5740module.exports.repeat = repeat;
5741module.exports.isNegativeZero = isNegativeZero;
5742module.exports.extend = extend;
5743
5744},{}],36:[function(require,module,exports){
5745'use strict';
5746
5747/*eslint-disable no-use-before-define*/
5748
5749var common = require('./common');
5750var YAMLException = require('./exception');
5751var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
5752var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
5753
5754var _toString = Object.prototype.toString;
5755var _hasOwnProperty = Object.prototype.hasOwnProperty;
5756
5757var CHAR_TAB = 0x09; /* Tab */
5758var CHAR_LINE_FEED = 0x0A; /* LF */
5759var CHAR_SPACE = 0x20; /* Space */
5760var CHAR_EXCLAMATION = 0x21; /* ! */
5761var CHAR_DOUBLE_QUOTE = 0x22; /* " */
5762var CHAR_SHARP = 0x23; /* # */
5763var CHAR_PERCENT = 0x25; /* % */
5764var CHAR_AMPERSAND = 0x26; /* & */
5765var CHAR_SINGLE_QUOTE = 0x27; /* ' */
5766var CHAR_ASTERISK = 0x2A; /* * */
5767var CHAR_COMMA = 0x2C; /* , */
5768var CHAR_MINUS = 0x2D; /* - */
5769var CHAR_COLON = 0x3A; /* : */
5770var CHAR_GREATER_THAN = 0x3E; /* > */
5771var CHAR_QUESTION = 0x3F; /* ? */
5772var CHAR_COMMERCIAL_AT = 0x40; /* @ */
5773var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
5774var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
5775var CHAR_GRAVE_ACCENT = 0x60; /* ` */
5776var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
5777var CHAR_VERTICAL_LINE = 0x7C; /* | */
5778var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
5779
5780var ESCAPE_SEQUENCES = {};
5781
5782ESCAPE_SEQUENCES[0x00] = '\\0';
5783ESCAPE_SEQUENCES[0x07] = '\\a';
5784ESCAPE_SEQUENCES[0x08] = '\\b';
5785ESCAPE_SEQUENCES[0x09] = '\\t';
5786ESCAPE_SEQUENCES[0x0A] = '\\n';
5787ESCAPE_SEQUENCES[0x0B] = '\\v';
5788ESCAPE_SEQUENCES[0x0C] = '\\f';
5789ESCAPE_SEQUENCES[0x0D] = '\\r';
5790ESCAPE_SEQUENCES[0x1B] = '\\e';
5791ESCAPE_SEQUENCES[0x22] = '\\"';
5792ESCAPE_SEQUENCES[0x5C] = '\\\\';
5793ESCAPE_SEQUENCES[0x85] = '\\N';
5794ESCAPE_SEQUENCES[0xA0] = '\\_';
5795ESCAPE_SEQUENCES[0x2028] = '\\L';
5796ESCAPE_SEQUENCES[0x2029] = '\\P';
5797
5798var DEPRECATED_BOOLEANS_SYNTAX = [
5799 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
5800 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
5801];
5802
5803function compileStyleMap(schema, map) {
5804 var result, keys, index, length, tag, style, type;
5805
5806 if (map === null) return {};
5807
5808 result = {};
5809 keys = Object.keys(map);
5810
5811 for (index = 0, length = keys.length; index < length; index += 1) {
5812 tag = keys[index];
5813 style = String(map[tag]);
5814
5815 if (tag.slice(0, 2) === '!!') {
5816 tag = 'tag:yaml.org,2002:' + tag.slice(2);
5817 }
5818 type = schema.compiledTypeMap['fallback'][tag];
5819
5820 if (type && _hasOwnProperty.call(type.styleAliases, style)) {
5821 style = type.styleAliases[style];
5822 }
5823
5824 result[tag] = style;
5825 }
5826
5827 return result;
5828}
5829
5830function encodeHex(character) {
5831 var string, handle, length;
5832
5833 string = character.toString(16).toUpperCase();
5834
5835 if (character <= 0xFF) {
5836 handle = 'x';
5837 length = 2;
5838 } else if (character <= 0xFFFF) {
5839 handle = 'u';
5840 length = 4;
5841 } else if (character <= 0xFFFFFFFF) {
5842 handle = 'U';
5843 length = 8;
5844 } else {
5845 throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
5846 }
5847
5848 return '\\' + handle + common.repeat('0', length - string.length) + string;
5849}
5850
5851function State(options) {
5852 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
5853 this.indent = Math.max(1, (options['indent'] || 2));
5854 this.skipInvalid = options['skipInvalid'] || false;
5855 this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
5856 this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
5857 this.sortKeys = options['sortKeys'] || false;
5858 this.lineWidth = options['lineWidth'] || 80;
5859 this.noRefs = options['noRefs'] || false;
5860 this.noCompatMode = options['noCompatMode'] || false;
5861 this.condenseFlow = options['condenseFlow'] || false;
5862
5863 this.implicitTypes = this.schema.compiledImplicit;
5864 this.explicitTypes = this.schema.compiledExplicit;
5865
5866 this.tag = null;
5867 this.result = '';
5868
5869 this.duplicates = [];
5870 this.usedDuplicates = null;
5871}
5872
5873// Indents every line in a string. Empty lines (\n only) are not indented.
5874function indentString(string, spaces) {
5875 var ind = common.repeat(' ', spaces),
5876 position = 0,
5877 next = -1,
5878 result = '',
5879 line,
5880 length = string.length;
5881
5882 while (position < length) {
5883 next = string.indexOf('\n', position);
5884 if (next === -1) {
5885 line = string.slice(position);
5886 position = length;
5887 } else {
5888 line = string.slice(position, next + 1);
5889 position = next + 1;
5890 }
5891
5892 if (line.length && line !== '\n') result += ind;
5893
5894 result += line;
5895 }
5896
5897 return result;
5898}
5899
5900function generateNextLine(state, level) {
5901 return '\n' + common.repeat(' ', state.indent * level);
5902}
5903
5904function testImplicitResolving(state, str) {
5905 var index, length, type;
5906
5907 for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
5908 type = state.implicitTypes[index];
5909
5910 if (type.resolve(str)) {
5911 return true;
5912 }
5913 }
5914
5915 return false;
5916}
5917
5918// [33] s-white ::= s-space | s-tab
5919function isWhitespace(c) {
5920 return c === CHAR_SPACE || c === CHAR_TAB;
5921}
5922
5923// Returns true if the character can be printed without escaping.
5924// From YAML 1.2: "any allowed characters known to be non-printable
5925// should also be escaped. [However,] This isn’t mandatory"
5926// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
5927function isPrintable(c) {
5928 return (0x00020 <= c && c <= 0x00007E)
5929 || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
5930 || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)
5931 || (0x10000 <= c && c <= 0x10FFFF);
5932}
5933
5934// Simplified test for values allowed after the first character in plain style.
5935function isPlainSafe(c) {
5936 // Uses a subset of nb-char - c-flow-indicator - ":" - "#"
5937 // where nb-char ::= c-printable - b-char - c-byte-order-mark.
5938 return isPrintable(c) && c !== 0xFEFF
5939 // - c-flow-indicator
5940 && c !== CHAR_COMMA
5941 && c !== CHAR_LEFT_SQUARE_BRACKET
5942 && c !== CHAR_RIGHT_SQUARE_BRACKET
5943 && c !== CHAR_LEFT_CURLY_BRACKET
5944 && c !== CHAR_RIGHT_CURLY_BRACKET
5945 // - ":" - "#"
5946 && c !== CHAR_COLON
5947 && c !== CHAR_SHARP;
5948}
5949
5950// Simplified test for values allowed as the first character in plain style.
5951function isPlainSafeFirst(c) {
5952 // Uses a subset of ns-char - c-indicator
5953 // where ns-char = nb-char - s-white.
5954 return isPrintable(c) && c !== 0xFEFF
5955 && !isWhitespace(c) // - s-white
5956 // - (c-indicator ::=
5957 // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
5958 && c !== CHAR_MINUS
5959 && c !== CHAR_QUESTION
5960 && c !== CHAR_COLON
5961 && c !== CHAR_COMMA
5962 && c !== CHAR_LEFT_SQUARE_BRACKET
5963 && c !== CHAR_RIGHT_SQUARE_BRACKET
5964 && c !== CHAR_LEFT_CURLY_BRACKET
5965 && c !== CHAR_RIGHT_CURLY_BRACKET
5966 // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"”
5967 && c !== CHAR_SHARP
5968 && c !== CHAR_AMPERSAND
5969 && c !== CHAR_ASTERISK
5970 && c !== CHAR_EXCLAMATION
5971 && c !== CHAR_VERTICAL_LINE
5972 && c !== CHAR_GREATER_THAN
5973 && c !== CHAR_SINGLE_QUOTE
5974 && c !== CHAR_DOUBLE_QUOTE
5975 // | “%” | “@” | “`”)
5976 && c !== CHAR_PERCENT
5977 && c !== CHAR_COMMERCIAL_AT
5978 && c !== CHAR_GRAVE_ACCENT;
5979}
5980
5981// Determines whether block indentation indicator is required.
5982function needIndentIndicator(string) {
5983 var leadingSpaceRe = /^\n* /;
5984 return leadingSpaceRe.test(string);
5985}
5986
5987var STYLE_PLAIN = 1,
5988 STYLE_SINGLE = 2,
5989 STYLE_LITERAL = 3,
5990 STYLE_FOLDED = 4,
5991 STYLE_DOUBLE = 5;
5992
5993// Determines which scalar styles are possible and returns the preferred style.
5994// lineWidth = -1 => no limit.
5995// Pre-conditions: str.length > 0.
5996// Post-conditions:
5997// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
5998// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
5999// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
6000function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
6001 var i;
6002 var char;
6003 var hasLineBreak = false;
6004 var hasFoldableLine = false; // only checked if shouldTrackWidth
6005 var shouldTrackWidth = lineWidth !== -1;
6006 var previousLineBreak = -1; // count the first line correctly
6007 var plain = isPlainSafeFirst(string.charCodeAt(0))
6008 && !isWhitespace(string.charCodeAt(string.length - 1));
6009
6010 if (singleLineOnly) {
6011 // Case: no block styles.
6012 // Check for disallowed characters to rule out plain and single.
6013 for (i = 0; i < string.length; i++) {
6014 char = string.charCodeAt(i);
6015 if (!isPrintable(char)) {
6016 return STYLE_DOUBLE;
6017 }
6018 plain = plain && isPlainSafe(char);
6019 }
6020 } else {
6021 // Case: block styles permitted.
6022 for (i = 0; i < string.length; i++) {
6023 char = string.charCodeAt(i);
6024 if (char === CHAR_LINE_FEED) {
6025 hasLineBreak = true;
6026 // Check if any line can be folded.
6027 if (shouldTrackWidth) {
6028 hasFoldableLine = hasFoldableLine ||
6029 // Foldable line = too long, and not more-indented.
6030 (i - previousLineBreak - 1 > lineWidth &&
6031 string[previousLineBreak + 1] !== ' ');
6032 previousLineBreak = i;
6033 }
6034 } else if (!isPrintable(char)) {
6035 return STYLE_DOUBLE;
6036 }
6037 plain = plain && isPlainSafe(char);
6038 }
6039 // in case the end is missing a \n
6040 hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
6041 (i - previousLineBreak - 1 > lineWidth &&
6042 string[previousLineBreak + 1] !== ' '));
6043 }
6044 // Although every style can represent \n without escaping, prefer block styles
6045 // for multiline, since they're more readable and they don't add empty lines.
6046 // Also prefer folding a super-long line.
6047 if (!hasLineBreak && !hasFoldableLine) {
6048 // Strings interpretable as another type have to be quoted;
6049 // e.g. the string 'true' vs. the boolean true.
6050 return plain && !testAmbiguousType(string)
6051 ? STYLE_PLAIN : STYLE_SINGLE;
6052 }
6053 // Edge case: block indentation indicator can only have one digit.
6054 if (indentPerLevel > 9 && needIndentIndicator(string)) {
6055 return STYLE_DOUBLE;
6056 }
6057 // At this point we know block styles are valid.
6058 // Prefer literal style unless we want to fold.
6059 return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
6060}
6061
6062// Note: line breaking/folding is implemented for only the folded style.
6063// NB. We drop the last trailing newline (if any) of a returned block scalar
6064// since the dumper adds its own newline. This always works:
6065// • No ending newline => unaffected; already using strip "-" chomping.
6066// • Ending newline => removed then restored.
6067// Importantly, this keeps the "+" chomp indicator from gaining an extra line.
6068function writeScalar(state, string, level, iskey) {
6069 state.dump = (function () {
6070 if (string.length === 0) {
6071 return "''";
6072 }
6073 if (!state.noCompatMode &&
6074 DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
6075 return "'" + string + "'";
6076 }
6077
6078 var indent = state.indent * Math.max(1, level); // no 0-indent scalars
6079 // As indentation gets deeper, let the width decrease monotonically
6080 // to the lower bound min(state.lineWidth, 40).
6081 // Note that this implies
6082 // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
6083 // state.lineWidth > 40 + state.indent: width decreases until the lower bound.
6084 // This behaves better than a constant minimum width which disallows narrower options,
6085 // or an indent threshold which causes the width to suddenly increase.
6086 var lineWidth = state.lineWidth === -1
6087 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
6088
6089 // Without knowing if keys are implicit/explicit, assume implicit for safety.
6090 var singleLineOnly = iskey
6091 // No block styles in flow mode.
6092 || (state.flowLevel > -1 && level >= state.flowLevel);
6093 function testAmbiguity(string) {
6094 return testImplicitResolving(state, string);
6095 }
6096
6097 switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
6098 case STYLE_PLAIN:
6099 return string;
6100 case STYLE_SINGLE:
6101 return "'" + string.replace(/'/g, "''") + "'";
6102 case STYLE_LITERAL:
6103 return '|' + blockHeader(string, state.indent)
6104 + dropEndingNewline(indentString(string, indent));
6105 case STYLE_FOLDED:
6106 return '>' + blockHeader(string, state.indent)
6107 + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
6108 case STYLE_DOUBLE:
6109 return '"' + escapeString(string, lineWidth) + '"';
6110 default:
6111 throw new YAMLException('impossible error: invalid scalar style');
6112 }
6113 }());
6114}
6115
6116// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
6117function blockHeader(string, indentPerLevel) {
6118 var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';
6119
6120 // note the special case: the string '\n' counts as a "trailing" empty line.
6121 var clip = string[string.length - 1] === '\n';
6122 var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
6123 var chomp = keep ? '+' : (clip ? '' : '-');
6124
6125 return indentIndicator + chomp + '\n';
6126}
6127
6128// (See the note for writeScalar.)
6129function dropEndingNewline(string) {
6130 return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
6131}
6132
6133// Note: a long line without a suitable break point will exceed the width limit.
6134// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
6135function foldString(string, width) {
6136 // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
6137 // unless they're before or after a more-indented line, or at the very
6138 // beginning or end, in which case $k$ maps to $k$.
6139 // Therefore, parse each chunk as newline(s) followed by a content line.
6140 var lineRe = /(\n+)([^\n]*)/g;
6141
6142 // first line (possibly an empty line)
6143 var result = (function () {
6144 var nextLF = string.indexOf('\n');
6145 nextLF = nextLF !== -1 ? nextLF : string.length;
6146 lineRe.lastIndex = nextLF;
6147 return foldLine(string.slice(0, nextLF), width);
6148 }());
6149 // If we haven't reached the first content line yet, don't add an extra \n.
6150 var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
6151 var moreIndented;
6152
6153 // rest of the lines
6154 var match;
6155 while ((match = lineRe.exec(string))) {
6156 var prefix = match[1], line = match[2];
6157 moreIndented = (line[0] === ' ');
6158 result += prefix
6159 + (!prevMoreIndented && !moreIndented && line !== ''
6160 ? '\n' : '')
6161 + foldLine(line, width);
6162 prevMoreIndented = moreIndented;
6163 }
6164
6165 return result;
6166}
6167
6168// Greedy line breaking.
6169// Picks the longest line under the limit each time,
6170// otherwise settles for the shortest line over the limit.
6171// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
6172function foldLine(line, width) {
6173 if (line === '' || line[0] === ' ') return line;
6174
6175 // Since a more-indented line adds a \n, breaks can't be followed by a space.
6176 var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
6177 var match;
6178 // start is an inclusive index. end, curr, and next are exclusive.
6179 var start = 0, end, curr = 0, next = 0;
6180 var result = '';
6181
6182 // Invariants: 0 <= start <= length-1.
6183 // 0 <= curr <= next <= max(0, length-2). curr - start <= width.
6184 // Inside the loop:
6185 // A match implies length >= 2, so curr and next are <= length-2.
6186 while ((match = breakRe.exec(line))) {
6187 next = match.index;
6188 // maintain invariant: curr - start <= width
6189 if (next - start > width) {
6190 end = (curr > start) ? curr : next; // derive end <= length-2
6191 result += '\n' + line.slice(start, end);
6192 // skip the space that was output as \n
6193 start = end + 1; // derive start <= length-1
6194 }
6195 curr = next;
6196 }
6197
6198 // By the invariants, start <= length-1, so there is something left over.
6199 // It is either the whole string or a part starting from non-whitespace.
6200 result += '\n';
6201 // Insert a break if the remainder is too long and there is a break available.
6202 if (line.length - start > width && curr > start) {
6203 result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
6204 } else {
6205 result += line.slice(start);
6206 }
6207
6208 return result.slice(1); // drop extra \n joiner
6209}
6210
6211// Escapes a double-quoted string.
6212function escapeString(string) {
6213 var result = '';
6214 var char, nextChar;
6215 var escapeSeq;
6216
6217 for (var i = 0; i < string.length; i++) {
6218 char = string.charCodeAt(i);
6219 // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").
6220 if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {
6221 nextChar = string.charCodeAt(i + 1);
6222 if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {
6223 // Combine the surrogate pair and store it escaped.
6224 result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);
6225 // Advance index one extra since we already used that char here.
6226 i++; continue;
6227 }
6228 }
6229 escapeSeq = ESCAPE_SEQUENCES[char];
6230 result += !escapeSeq && isPrintable(char)
6231 ? string[i]
6232 : escapeSeq || encodeHex(char);
6233 }
6234
6235 return result;
6236}
6237
6238function writeFlowSequence(state, level, object) {
6239 var _result = '',
6240 _tag = state.tag,
6241 index,
6242 length;
6243
6244 for (index = 0, length = object.length; index < length; index += 1) {
6245 // Write only valid elements.
6246 if (writeNode(state, level, object[index], false, false)) {
6247 if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');
6248 _result += state.dump;
6249 }
6250 }
6251
6252 state.tag = _tag;
6253 state.dump = '[' + _result + ']';
6254}
6255
6256function writeBlockSequence(state, level, object, compact) {
6257 var _result = '',
6258 _tag = state.tag,
6259 index,
6260 length;
6261
6262 for (index = 0, length = object.length; index < length; index += 1) {
6263 // Write only valid elements.
6264 if (writeNode(state, level + 1, object[index], true, true)) {
6265 if (!compact || index !== 0) {
6266 _result += generateNextLine(state, level);
6267 }
6268
6269 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
6270 _result += '-';
6271 } else {
6272 _result += '- ';
6273 }
6274
6275 _result += state.dump;
6276 }
6277 }
6278
6279 state.tag = _tag;
6280 state.dump = _result || '[]'; // Empty sequence if no valid values.
6281}
6282
6283function writeFlowMapping(state, level, object) {
6284 var _result = '',
6285 _tag = state.tag,
6286 objectKeyList = Object.keys(object),
6287 index,
6288 length,
6289 objectKey,
6290 objectValue,
6291 pairBuffer;
6292
6293 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
6294 pairBuffer = state.condenseFlow ? '"' : '';
6295
6296 if (index !== 0) pairBuffer += ', ';
6297
6298 objectKey = objectKeyList[index];
6299 objectValue = object[objectKey];
6300
6301 if (!writeNode(state, level, objectKey, false, false)) {
6302 continue; // Skip this pair because of invalid key;
6303 }
6304
6305 if (state.dump.length > 1024) pairBuffer += '? ';
6306
6307 pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');
6308
6309 if (!writeNode(state, level, objectValue, false, false)) {
6310 continue; // Skip this pair because of invalid value.
6311 }
6312
6313 pairBuffer += state.dump;
6314
6315 // Both key and value are valid.
6316 _result += pairBuffer;
6317 }
6318
6319 state.tag = _tag;
6320 state.dump = '{' + _result + '}';
6321}
6322
6323function writeBlockMapping(state, level, object, compact) {
6324 var _result = '',
6325 _tag = state.tag,
6326 objectKeyList = Object.keys(object),
6327 index,
6328 length,
6329 objectKey,
6330 objectValue,
6331 explicitPair,
6332 pairBuffer;
6333
6334 // Allow sorting keys so that the output file is deterministic
6335 if (state.sortKeys === true) {
6336 // Default sorting
6337 objectKeyList.sort();
6338 } else if (typeof state.sortKeys === 'function') {
6339 // Custom sort function
6340 objectKeyList.sort(state.sortKeys);
6341 } else if (state.sortKeys) {
6342 // Something is wrong
6343 throw new YAMLException('sortKeys must be a boolean or a function');
6344 }
6345
6346 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
6347 pairBuffer = '';
6348
6349 if (!compact || index !== 0) {
6350 pairBuffer += generateNextLine(state, level);
6351 }
6352
6353 objectKey = objectKeyList[index];
6354 objectValue = object[objectKey];
6355
6356 if (!writeNode(state, level + 1, objectKey, true, true, true)) {
6357 continue; // Skip this pair because of invalid key.
6358 }
6359
6360 explicitPair = (state.tag !== null && state.tag !== '?') ||
6361 (state.dump && state.dump.length > 1024);
6362
6363 if (explicitPair) {
6364 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
6365 pairBuffer += '?';
6366 } else {
6367 pairBuffer += '? ';
6368 }
6369 }
6370
6371 pairBuffer += state.dump;
6372
6373 if (explicitPair) {
6374 pairBuffer += generateNextLine(state, level);
6375 }
6376
6377 if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
6378 continue; // Skip this pair because of invalid value.
6379 }
6380
6381 if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
6382 pairBuffer += ':';
6383 } else {
6384 pairBuffer += ': ';
6385 }
6386
6387 pairBuffer += state.dump;
6388
6389 // Both key and value are valid.
6390 _result += pairBuffer;
6391 }
6392
6393 state.tag = _tag;
6394 state.dump = _result || '{}'; // Empty mapping if no valid pairs.
6395}
6396
6397function detectType(state, object, explicit) {
6398 var _result, typeList, index, length, type, style;
6399
6400 typeList = explicit ? state.explicitTypes : state.implicitTypes;
6401
6402 for (index = 0, length = typeList.length; index < length; index += 1) {
6403 type = typeList[index];
6404
6405 if ((type.instanceOf || type.predicate) &&
6406 (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
6407 (!type.predicate || type.predicate(object))) {
6408
6409 state.tag = explicit ? type.tag : '?';
6410
6411 if (type.represent) {
6412 style = state.styleMap[type.tag] || type.defaultStyle;
6413
6414 if (_toString.call(type.represent) === '[object Function]') {
6415 _result = type.represent(object, style);
6416 } else if (_hasOwnProperty.call(type.represent, style)) {
6417 _result = type.represent[style](object, style);
6418 } else {
6419 throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
6420 }
6421
6422 state.dump = _result;
6423 }
6424
6425 return true;
6426 }
6427 }
6428
6429 return false;
6430}
6431
6432// Serializes `object` and writes it to global `result`.
6433// Returns true on success, or false on invalid object.
6434//
6435function writeNode(state, level, object, block, compact, iskey) {
6436 state.tag = null;
6437 state.dump = object;
6438
6439 if (!detectType(state, object, false)) {
6440 detectType(state, object, true);
6441 }
6442
6443 var type = _toString.call(state.dump);
6444
6445 if (block) {
6446 block = (state.flowLevel < 0 || state.flowLevel > level);
6447 }
6448
6449 var objectOrArray = type === '[object Object]' || type === '[object Array]',
6450 duplicateIndex,
6451 duplicate;
6452
6453 if (objectOrArray) {
6454 duplicateIndex = state.duplicates.indexOf(object);
6455 duplicate = duplicateIndex !== -1;
6456 }
6457
6458 if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
6459 compact = false;
6460 }
6461
6462 if (duplicate && state.usedDuplicates[duplicateIndex]) {
6463 state.dump = '*ref_' + duplicateIndex;
6464 } else {
6465 if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
6466 state.usedDuplicates[duplicateIndex] = true;
6467 }
6468 if (type === '[object Object]') {
6469 if (block && (Object.keys(state.dump).length !== 0)) {
6470 writeBlockMapping(state, level, state.dump, compact);
6471 if (duplicate) {
6472 state.dump = '&ref_' + duplicateIndex + state.dump;
6473 }
6474 } else {
6475 writeFlowMapping(state, level, state.dump);
6476 if (duplicate) {
6477 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
6478 }
6479 }
6480 } else if (type === '[object Array]') {
6481 if (block && (state.dump.length !== 0)) {
6482 writeBlockSequence(state, level, state.dump, compact);
6483 if (duplicate) {
6484 state.dump = '&ref_' + duplicateIndex + state.dump;
6485 }
6486 } else {
6487 writeFlowSequence(state, level, state.dump);
6488 if (duplicate) {
6489 state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
6490 }
6491 }
6492 } else if (type === '[object String]') {
6493 if (state.tag !== '?') {
6494 writeScalar(state, state.dump, level, iskey);
6495 }
6496 } else {
6497 if (state.skipInvalid) return false;
6498 throw new YAMLException('unacceptable kind of an object to dump ' + type);
6499 }
6500
6501 if (state.tag !== null && state.tag !== '?') {
6502 state.dump = '!<' + state.tag + '> ' + state.dump;
6503 }
6504 }
6505
6506 return true;
6507}
6508
6509function getDuplicateReferences(object, state) {
6510 var objects = [],
6511 duplicatesIndexes = [],
6512 index,
6513 length;
6514
6515 inspectNode(object, objects, duplicatesIndexes);
6516
6517 for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
6518 state.duplicates.push(objects[duplicatesIndexes[index]]);
6519 }
6520 state.usedDuplicates = new Array(length);
6521}
6522
6523function inspectNode(object, objects, duplicatesIndexes) {
6524 var objectKeyList,
6525 index,
6526 length;
6527
6528 if (object !== null && typeof object === 'object') {
6529 index = objects.indexOf(object);
6530 if (index !== -1) {
6531 if (duplicatesIndexes.indexOf(index) === -1) {
6532 duplicatesIndexes.push(index);
6533 }
6534 } else {
6535 objects.push(object);
6536
6537 if (Array.isArray(object)) {
6538 for (index = 0, length = object.length; index < length; index += 1) {
6539 inspectNode(object[index], objects, duplicatesIndexes);
6540 }
6541 } else {
6542 objectKeyList = Object.keys(object);
6543
6544 for (index = 0, length = objectKeyList.length; index < length; index += 1) {
6545 inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
6546 }
6547 }
6548 }
6549 }
6550}
6551
6552function dump(input, options) {
6553 options = options || {};
6554
6555 var state = new State(options);
6556
6557 if (!state.noRefs) getDuplicateReferences(input, state);
6558
6559 if (writeNode(state, 0, input, true, true)) return state.dump + '\n';
6560
6561 return '';
6562}
6563
6564function safeDump(input, options) {
6565 return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
6566}
6567
6568module.exports.dump = dump;
6569module.exports.safeDump = safeDump;
6570
6571},{"./common":35,"./exception":37,"./schema/default_full":42,"./schema/default_safe":43}],37:[function(require,module,exports){
6572// YAML error class. http://stackoverflow.com/questions/8458984
6573//
6574'use strict';
6575
6576function YAMLException(reason, mark) {
6577 // Super constructor
6578 Error.call(this);
6579
6580 this.name = 'YAMLException';
6581 this.reason = reason;
6582 this.mark = mark;
6583 this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');
6584
6585 // Include stack trace in error object
6586 if (Error.captureStackTrace) {
6587 // Chrome and NodeJS
6588 Error.captureStackTrace(this, this.constructor);
6589 } else {
6590 // FF, IE 10+ and Safari 6+. Fallback for others
6591 this.stack = (new Error()).stack || '';
6592 }
6593}
6594
6595
6596// Inherit from Error
6597YAMLException.prototype = Object.create(Error.prototype);
6598YAMLException.prototype.constructor = YAMLException;
6599
6600
6601YAMLException.prototype.toString = function toString(compact) {
6602 var result = this.name + ': ';
6603
6604 result += this.reason || '(unknown reason)';
6605
6606 if (!compact && this.mark) {
6607 result += ' ' + this.mark.toString();
6608 }
6609
6610 return result;
6611};
6612
6613
6614module.exports = YAMLException;
6615
6616},{}],38:[function(require,module,exports){
6617'use strict';
6618
6619/*eslint-disable max-len,no-use-before-define*/
6620
6621var common = require('./common');
6622var YAMLException = require('./exception');
6623var Mark = require('./mark');
6624var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
6625var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
6626
6627
6628var _hasOwnProperty = Object.prototype.hasOwnProperty;
6629
6630
6631var CONTEXT_FLOW_IN = 1;
6632var CONTEXT_FLOW_OUT = 2;
6633var CONTEXT_BLOCK_IN = 3;
6634var CONTEXT_BLOCK_OUT = 4;
6635
6636
6637var CHOMPING_CLIP = 1;
6638var CHOMPING_STRIP = 2;
6639var CHOMPING_KEEP = 3;
6640
6641
6642var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
6643var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
6644var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
6645var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
6646var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
6647
6648
6649function is_EOL(c) {
6650 return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
6651}
6652
6653function is_WHITE_SPACE(c) {
6654 return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
6655}
6656
6657function is_WS_OR_EOL(c) {
6658 return (c === 0x09/* Tab */) ||
6659 (c === 0x20/* Space */) ||
6660 (c === 0x0A/* LF */) ||
6661 (c === 0x0D/* CR */);
6662}
6663
6664function is_FLOW_INDICATOR(c) {
6665 return c === 0x2C/* , */ ||
6666 c === 0x5B/* [ */ ||
6667 c === 0x5D/* ] */ ||
6668 c === 0x7B/* { */ ||
6669 c === 0x7D/* } */;
6670}
6671
6672function fromHexCode(c) {
6673 var lc;
6674
6675 if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
6676 return c - 0x30;
6677 }
6678
6679 /*eslint-disable no-bitwise*/
6680 lc = c | 0x20;
6681
6682 if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
6683 return lc - 0x61 + 10;
6684 }
6685
6686 return -1;
6687}
6688
6689function escapedHexLen(c) {
6690 if (c === 0x78/* x */) { return 2; }
6691 if (c === 0x75/* u */) { return 4; }
6692 if (c === 0x55/* U */) { return 8; }
6693 return 0;
6694}
6695
6696function fromDecimalCode(c) {
6697 if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
6698 return c - 0x30;
6699 }
6700
6701 return -1;
6702}
6703
6704function simpleEscapeSequence(c) {
6705 /* eslint-disable indent */
6706 return (c === 0x30/* 0 */) ? '\x00' :
6707 (c === 0x61/* a */) ? '\x07' :
6708 (c === 0x62/* b */) ? '\x08' :
6709 (c === 0x74/* t */) ? '\x09' :
6710 (c === 0x09/* Tab */) ? '\x09' :
6711 (c === 0x6E/* n */) ? '\x0A' :
6712 (c === 0x76/* v */) ? '\x0B' :
6713 (c === 0x66/* f */) ? '\x0C' :
6714 (c === 0x72/* r */) ? '\x0D' :
6715 (c === 0x65/* e */) ? '\x1B' :
6716 (c === 0x20/* Space */) ? ' ' :
6717 (c === 0x22/* " */) ? '\x22' :
6718 (c === 0x2F/* / */) ? '/' :
6719 (c === 0x5C/* \ */) ? '\x5C' :
6720 (c === 0x4E/* N */) ? '\x85' :
6721 (c === 0x5F/* _ */) ? '\xA0' :
6722 (c === 0x4C/* L */) ? '\u2028' :
6723 (c === 0x50/* P */) ? '\u2029' : '';
6724}
6725
6726function charFromCodepoint(c) {
6727 if (c <= 0xFFFF) {
6728 return String.fromCharCode(c);
6729 }
6730 // Encode UTF-16 surrogate pair
6731 // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
6732 return String.fromCharCode(
6733 ((c - 0x010000) >> 10) + 0xD800,
6734 ((c - 0x010000) & 0x03FF) + 0xDC00
6735 );
6736}
6737
6738var simpleEscapeCheck = new Array(256); // integer, for fast access
6739var simpleEscapeMap = new Array(256);
6740for (var i = 0; i < 256; i++) {
6741 simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
6742 simpleEscapeMap[i] = simpleEscapeSequence(i);
6743}
6744
6745
6746function State(input, options) {
6747 this.input = input;
6748
6749 this.filename = options['filename'] || null;
6750 this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
6751 this.onWarning = options['onWarning'] || null;
6752 this.legacy = options['legacy'] || false;
6753 this.json = options['json'] || false;
6754 this.listener = options['listener'] || null;
6755
6756 this.implicitTypes = this.schema.compiledImplicit;
6757 this.typeMap = this.schema.compiledTypeMap;
6758
6759 this.length = input.length;
6760 this.position = 0;
6761 this.line = 0;
6762 this.lineStart = 0;
6763 this.lineIndent = 0;
6764
6765 this.documents = [];
6766
6767 /*
6768 this.version;
6769 this.checkLineBreaks;
6770 this.tagMap;
6771 this.anchorMap;
6772 this.tag;
6773 this.anchor;
6774 this.kind;
6775 this.result;*/
6776
6777}
6778
6779
6780function generateError(state, message) {
6781 return new YAMLException(
6782 message,
6783 new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));
6784}
6785
6786function throwError(state, message) {
6787 throw generateError(state, message);
6788}
6789
6790function throwWarning(state, message) {
6791 if (state.onWarning) {
6792 state.onWarning.call(null, generateError(state, message));
6793 }
6794}
6795
6796
6797var directiveHandlers = {
6798
6799 YAML: function handleYamlDirective(state, name, args) {
6800
6801 var match, major, minor;
6802
6803 if (state.version !== null) {
6804 throwError(state, 'duplication of %YAML directive');
6805 }
6806
6807 if (args.length !== 1) {
6808 throwError(state, 'YAML directive accepts exactly one argument');
6809 }
6810
6811 match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
6812
6813 if (match === null) {
6814 throwError(state, 'ill-formed argument of the YAML directive');
6815 }
6816
6817 major = parseInt(match[1], 10);
6818 minor = parseInt(match[2], 10);
6819
6820 if (major !== 1) {
6821 throwError(state, 'unacceptable YAML version of the document');
6822 }
6823
6824 state.version = args[0];
6825 state.checkLineBreaks = (minor < 2);
6826
6827 if (minor !== 1 && minor !== 2) {
6828 throwWarning(state, 'unsupported YAML version of the document');
6829 }
6830 },
6831
6832 TAG: function handleTagDirective(state, name, args) {
6833
6834 var handle, prefix;
6835
6836 if (args.length !== 2) {
6837 throwError(state, 'TAG directive accepts exactly two arguments');
6838 }
6839
6840 handle = args[0];
6841 prefix = args[1];
6842
6843 if (!PATTERN_TAG_HANDLE.test(handle)) {
6844 throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
6845 }
6846
6847 if (_hasOwnProperty.call(state.tagMap, handle)) {
6848 throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
6849 }
6850
6851 if (!PATTERN_TAG_URI.test(prefix)) {
6852 throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
6853 }
6854
6855 state.tagMap[handle] = prefix;
6856 }
6857};
6858
6859
6860function captureSegment(state, start, end, checkJson) {
6861 var _position, _length, _character, _result;
6862
6863 if (start < end) {
6864 _result = state.input.slice(start, end);
6865
6866 if (checkJson) {
6867 for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
6868 _character = _result.charCodeAt(_position);
6869 if (!(_character === 0x09 ||
6870 (0x20 <= _character && _character <= 0x10FFFF))) {
6871 throwError(state, 'expected valid JSON character');
6872 }
6873 }
6874 } else if (PATTERN_NON_PRINTABLE.test(_result)) {
6875 throwError(state, 'the stream contains non-printable characters');
6876 }
6877
6878 state.result += _result;
6879 }
6880}
6881
6882function mergeMappings(state, destination, source, overridableKeys) {
6883 var sourceKeys, key, index, quantity;
6884
6885 if (!common.isObject(source)) {
6886 throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
6887 }
6888
6889 sourceKeys = Object.keys(source);
6890
6891 for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
6892 key = sourceKeys[index];
6893
6894 if (!_hasOwnProperty.call(destination, key)) {
6895 destination[key] = source[key];
6896 overridableKeys[key] = true;
6897 }
6898 }
6899}
6900
6901function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
6902 var index, quantity;
6903
6904 keyNode = String(keyNode);
6905
6906 if (_result === null) {
6907 _result = {};
6908 }
6909
6910 if (keyTag === 'tag:yaml.org,2002:merge') {
6911 if (Array.isArray(valueNode)) {
6912 for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
6913 mergeMappings(state, _result, valueNode[index], overridableKeys);
6914 }
6915 } else {
6916 mergeMappings(state, _result, valueNode, overridableKeys);
6917 }
6918 } else {
6919 if (!state.json &&
6920 !_hasOwnProperty.call(overridableKeys, keyNode) &&
6921 _hasOwnProperty.call(_result, keyNode)) {
6922 state.line = startLine || state.line;
6923 state.position = startPos || state.position;
6924 throwError(state, 'duplicated mapping key');
6925 }
6926 _result[keyNode] = valueNode;
6927 delete overridableKeys[keyNode];
6928 }
6929
6930 return _result;
6931}
6932
6933function readLineBreak(state) {
6934 var ch;
6935
6936 ch = state.input.charCodeAt(state.position);
6937
6938 if (ch === 0x0A/* LF */) {
6939 state.position++;
6940 } else if (ch === 0x0D/* CR */) {
6941 state.position++;
6942 if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
6943 state.position++;
6944 }
6945 } else {
6946 throwError(state, 'a line break is expected');
6947 }
6948
6949 state.line += 1;
6950 state.lineStart = state.position;
6951}
6952
6953function skipSeparationSpace(state, allowComments, checkIndent) {
6954 var lineBreaks = 0,
6955 ch = state.input.charCodeAt(state.position);
6956
6957 while (ch !== 0) {
6958 while (is_WHITE_SPACE(ch)) {
6959 ch = state.input.charCodeAt(++state.position);
6960 }
6961
6962 if (allowComments && ch === 0x23/* # */) {
6963 do {
6964 ch = state.input.charCodeAt(++state.position);
6965 } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
6966 }
6967
6968 if (is_EOL(ch)) {
6969 readLineBreak(state);
6970
6971 ch = state.input.charCodeAt(state.position);
6972 lineBreaks++;
6973 state.lineIndent = 0;
6974
6975 while (ch === 0x20/* Space */) {
6976 state.lineIndent++;
6977 ch = state.input.charCodeAt(++state.position);
6978 }
6979 } else {
6980 break;
6981 }
6982 }
6983
6984 if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
6985 throwWarning(state, 'deficient indentation');
6986 }
6987
6988 return lineBreaks;
6989}
6990
6991function testDocumentSeparator(state) {
6992 var _position = state.position,
6993 ch;
6994
6995 ch = state.input.charCodeAt(_position);
6996
6997 // Condition state.position === state.lineStart is tested
6998 // in parent on each call, for efficiency. No needs to test here again.
6999 if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
7000 ch === state.input.charCodeAt(_position + 1) &&
7001 ch === state.input.charCodeAt(_position + 2)) {
7002
7003 _position += 3;
7004
7005 ch = state.input.charCodeAt(_position);
7006
7007 if (ch === 0 || is_WS_OR_EOL(ch)) {
7008 return true;
7009 }
7010 }
7011
7012 return false;
7013}
7014
7015function writeFoldedLines(state, count) {
7016 if (count === 1) {
7017 state.result += ' ';
7018 } else if (count > 1) {
7019 state.result += common.repeat('\n', count - 1);
7020 }
7021}
7022
7023
7024function readPlainScalar(state, nodeIndent, withinFlowCollection) {
7025 var preceding,
7026 following,
7027 captureStart,
7028 captureEnd,
7029 hasPendingContent,
7030 _line,
7031 _lineStart,
7032 _lineIndent,
7033 _kind = state.kind,
7034 _result = state.result,
7035 ch;
7036
7037 ch = state.input.charCodeAt(state.position);
7038
7039 if (is_WS_OR_EOL(ch) ||
7040 is_FLOW_INDICATOR(ch) ||
7041 ch === 0x23/* # */ ||
7042 ch === 0x26/* & */ ||
7043 ch === 0x2A/* * */ ||
7044 ch === 0x21/* ! */ ||
7045 ch === 0x7C/* | */ ||
7046 ch === 0x3E/* > */ ||
7047 ch === 0x27/* ' */ ||
7048 ch === 0x22/* " */ ||
7049 ch === 0x25/* % */ ||
7050 ch === 0x40/* @ */ ||
7051 ch === 0x60/* ` */) {
7052 return false;
7053 }
7054
7055 if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
7056 following = state.input.charCodeAt(state.position + 1);
7057
7058 if (is_WS_OR_EOL(following) ||
7059 withinFlowCollection && is_FLOW_INDICATOR(following)) {
7060 return false;
7061 }
7062 }
7063
7064 state.kind = 'scalar';
7065 state.result = '';
7066 captureStart = captureEnd = state.position;
7067 hasPendingContent = false;
7068
7069 while (ch !== 0) {
7070 if (ch === 0x3A/* : */) {
7071 following = state.input.charCodeAt(state.position + 1);
7072
7073 if (is_WS_OR_EOL(following) ||
7074 withinFlowCollection && is_FLOW_INDICATOR(following)) {
7075 break;
7076 }
7077
7078 } else if (ch === 0x23/* # */) {
7079 preceding = state.input.charCodeAt(state.position - 1);
7080
7081 if (is_WS_OR_EOL(preceding)) {
7082 break;
7083 }
7084
7085 } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
7086 withinFlowCollection && is_FLOW_INDICATOR(ch)) {
7087 break;
7088
7089 } else if (is_EOL(ch)) {
7090 _line = state.line;
7091 _lineStart = state.lineStart;
7092 _lineIndent = state.lineIndent;
7093 skipSeparationSpace(state, false, -1);
7094
7095 if (state.lineIndent >= nodeIndent) {
7096 hasPendingContent = true;
7097 ch = state.input.charCodeAt(state.position);
7098 continue;
7099 } else {
7100 state.position = captureEnd;
7101 state.line = _line;
7102 state.lineStart = _lineStart;
7103 state.lineIndent = _lineIndent;
7104 break;
7105 }
7106 }
7107
7108 if (hasPendingContent) {
7109 captureSegment(state, captureStart, captureEnd, false);
7110 writeFoldedLines(state, state.line - _line);
7111 captureStart = captureEnd = state.position;
7112 hasPendingContent = false;
7113 }
7114
7115 if (!is_WHITE_SPACE(ch)) {
7116 captureEnd = state.position + 1;
7117 }
7118
7119 ch = state.input.charCodeAt(++state.position);
7120 }
7121
7122 captureSegment(state, captureStart, captureEnd, false);
7123
7124 if (state.result) {
7125 return true;
7126 }
7127
7128 state.kind = _kind;
7129 state.result = _result;
7130 return false;
7131}
7132
7133function readSingleQuotedScalar(state, nodeIndent) {
7134 var ch,
7135 captureStart, captureEnd;
7136
7137 ch = state.input.charCodeAt(state.position);
7138
7139 if (ch !== 0x27/* ' */) {
7140 return false;
7141 }
7142
7143 state.kind = 'scalar';
7144 state.result = '';
7145 state.position++;
7146 captureStart = captureEnd = state.position;
7147
7148 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
7149 if (ch === 0x27/* ' */) {
7150 captureSegment(state, captureStart, state.position, true);
7151 ch = state.input.charCodeAt(++state.position);
7152
7153 if (ch === 0x27/* ' */) {
7154 captureStart = state.position;
7155 state.position++;
7156 captureEnd = state.position;
7157 } else {
7158 return true;
7159 }
7160
7161 } else if (is_EOL(ch)) {
7162 captureSegment(state, captureStart, captureEnd, true);
7163 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
7164 captureStart = captureEnd = state.position;
7165
7166 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
7167 throwError(state, 'unexpected end of the document within a single quoted scalar');
7168
7169 } else {
7170 state.position++;
7171 captureEnd = state.position;
7172 }
7173 }
7174
7175 throwError(state, 'unexpected end of the stream within a single quoted scalar');
7176}
7177
7178function readDoubleQuotedScalar(state, nodeIndent) {
7179 var captureStart,
7180 captureEnd,
7181 hexLength,
7182 hexResult,
7183 tmp,
7184 ch;
7185
7186 ch = state.input.charCodeAt(state.position);
7187
7188 if (ch !== 0x22/* " */) {
7189 return false;
7190 }
7191
7192 state.kind = 'scalar';
7193 state.result = '';
7194 state.position++;
7195 captureStart = captureEnd = state.position;
7196
7197 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
7198 if (ch === 0x22/* " */) {
7199 captureSegment(state, captureStart, state.position, true);
7200 state.position++;
7201 return true;
7202
7203 } else if (ch === 0x5C/* \ */) {
7204 captureSegment(state, captureStart, state.position, true);
7205 ch = state.input.charCodeAt(++state.position);
7206
7207 if (is_EOL(ch)) {
7208 skipSeparationSpace(state, false, nodeIndent);
7209
7210 // TODO: rework to inline fn with no type cast?
7211 } else if (ch < 256 && simpleEscapeCheck[ch]) {
7212 state.result += simpleEscapeMap[ch];
7213 state.position++;
7214
7215 } else if ((tmp = escapedHexLen(ch)) > 0) {
7216 hexLength = tmp;
7217 hexResult = 0;
7218
7219 for (; hexLength > 0; hexLength--) {
7220 ch = state.input.charCodeAt(++state.position);
7221
7222 if ((tmp = fromHexCode(ch)) >= 0) {
7223 hexResult = (hexResult << 4) + tmp;
7224
7225 } else {
7226 throwError(state, 'expected hexadecimal character');
7227 }
7228 }
7229
7230 state.result += charFromCodepoint(hexResult);
7231
7232 state.position++;
7233
7234 } else {
7235 throwError(state, 'unknown escape sequence');
7236 }
7237
7238 captureStart = captureEnd = state.position;
7239
7240 } else if (is_EOL(ch)) {
7241 captureSegment(state, captureStart, captureEnd, true);
7242 writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
7243 captureStart = captureEnd = state.position;
7244
7245 } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
7246 throwError(state, 'unexpected end of the document within a double quoted scalar');
7247
7248 } else {
7249 state.position++;
7250 captureEnd = state.position;
7251 }
7252 }
7253
7254 throwError(state, 'unexpected end of the stream within a double quoted scalar');
7255}
7256
7257function readFlowCollection(state, nodeIndent) {
7258 var readNext = true,
7259 _line,
7260 _tag = state.tag,
7261 _result,
7262 _anchor = state.anchor,
7263 following,
7264 terminator,
7265 isPair,
7266 isExplicitPair,
7267 isMapping,
7268 overridableKeys = {},
7269 keyNode,
7270 keyTag,
7271 valueNode,
7272 ch;
7273
7274 ch = state.input.charCodeAt(state.position);
7275
7276 if (ch === 0x5B/* [ */) {
7277 terminator = 0x5D;/* ] */
7278 isMapping = false;
7279 _result = [];
7280 } else if (ch === 0x7B/* { */) {
7281 terminator = 0x7D;/* } */
7282 isMapping = true;
7283 _result = {};
7284 } else {
7285 return false;
7286 }
7287
7288 if (state.anchor !== null) {
7289 state.anchorMap[state.anchor] = _result;
7290 }
7291
7292 ch = state.input.charCodeAt(++state.position);
7293
7294 while (ch !== 0) {
7295 skipSeparationSpace(state, true, nodeIndent);
7296
7297 ch = state.input.charCodeAt(state.position);
7298
7299 if (ch === terminator) {
7300 state.position++;
7301 state.tag = _tag;
7302 state.anchor = _anchor;
7303 state.kind = isMapping ? 'mapping' : 'sequence';
7304 state.result = _result;
7305 return true;
7306 } else if (!readNext) {
7307 throwError(state, 'missed comma between flow collection entries');
7308 }
7309
7310 keyTag = keyNode = valueNode = null;
7311 isPair = isExplicitPair = false;
7312
7313 if (ch === 0x3F/* ? */) {
7314 following = state.input.charCodeAt(state.position + 1);
7315
7316 if (is_WS_OR_EOL(following)) {
7317 isPair = isExplicitPair = true;
7318 state.position++;
7319 skipSeparationSpace(state, true, nodeIndent);
7320 }
7321 }
7322
7323 _line = state.line;
7324 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
7325 keyTag = state.tag;
7326 keyNode = state.result;
7327 skipSeparationSpace(state, true, nodeIndent);
7328
7329 ch = state.input.charCodeAt(state.position);
7330
7331 if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
7332 isPair = true;
7333 ch = state.input.charCodeAt(++state.position);
7334 skipSeparationSpace(state, true, nodeIndent);
7335 composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
7336 valueNode = state.result;
7337 }
7338
7339 if (isMapping) {
7340 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
7341 } else if (isPair) {
7342 _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
7343 } else {
7344 _result.push(keyNode);
7345 }
7346
7347 skipSeparationSpace(state, true, nodeIndent);
7348
7349 ch = state.input.charCodeAt(state.position);
7350
7351 if (ch === 0x2C/* , */) {
7352 readNext = true;
7353 ch = state.input.charCodeAt(++state.position);
7354 } else {
7355 readNext = false;
7356 }
7357 }
7358
7359 throwError(state, 'unexpected end of the stream within a flow collection');
7360}
7361
7362function readBlockScalar(state, nodeIndent) {
7363 var captureStart,
7364 folding,
7365 chomping = CHOMPING_CLIP,
7366 didReadContent = false,
7367 detectedIndent = false,
7368 textIndent = nodeIndent,
7369 emptyLines = 0,
7370 atMoreIndented = false,
7371 tmp,
7372 ch;
7373
7374 ch = state.input.charCodeAt(state.position);
7375
7376 if (ch === 0x7C/* | */) {
7377 folding = false;
7378 } else if (ch === 0x3E/* > */) {
7379 folding = true;
7380 } else {
7381 return false;
7382 }
7383
7384 state.kind = 'scalar';
7385 state.result = '';
7386
7387 while (ch !== 0) {
7388 ch = state.input.charCodeAt(++state.position);
7389
7390 if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
7391 if (CHOMPING_CLIP === chomping) {
7392 chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
7393 } else {
7394 throwError(state, 'repeat of a chomping mode identifier');
7395 }
7396
7397 } else if ((tmp = fromDecimalCode(ch)) >= 0) {
7398 if (tmp === 0) {
7399 throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
7400 } else if (!detectedIndent) {
7401 textIndent = nodeIndent + tmp - 1;
7402 detectedIndent = true;
7403 } else {
7404 throwError(state, 'repeat of an indentation width identifier');
7405 }
7406
7407 } else {
7408 break;
7409 }
7410 }
7411
7412 if (is_WHITE_SPACE(ch)) {
7413 do { ch = state.input.charCodeAt(++state.position); }
7414 while (is_WHITE_SPACE(ch));
7415
7416 if (ch === 0x23/* # */) {
7417 do { ch = state.input.charCodeAt(++state.position); }
7418 while (!is_EOL(ch) && (ch !== 0));
7419 }
7420 }
7421
7422 while (ch !== 0) {
7423 readLineBreak(state);
7424 state.lineIndent = 0;
7425
7426 ch = state.input.charCodeAt(state.position);
7427
7428 while ((!detectedIndent || state.lineIndent < textIndent) &&
7429 (ch === 0x20/* Space */)) {
7430 state.lineIndent++;
7431 ch = state.input.charCodeAt(++state.position);
7432 }
7433
7434 if (!detectedIndent && state.lineIndent > textIndent) {
7435 textIndent = state.lineIndent;
7436 }
7437
7438 if (is_EOL(ch)) {
7439 emptyLines++;
7440 continue;
7441 }
7442
7443 // End of the scalar.
7444 if (state.lineIndent < textIndent) {
7445
7446 // Perform the chomping.
7447 if (chomping === CHOMPING_KEEP) {
7448 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
7449 } else if (chomping === CHOMPING_CLIP) {
7450 if (didReadContent) { // i.e. only if the scalar is not empty.
7451 state.result += '\n';
7452 }
7453 }
7454
7455 // Break this `while` cycle and go to the funciton's epilogue.
7456 break;
7457 }
7458
7459 // Folded style: use fancy rules to handle line breaks.
7460 if (folding) {
7461
7462 // Lines starting with white space characters (more-indented lines) are not folded.
7463 if (is_WHITE_SPACE(ch)) {
7464 atMoreIndented = true;
7465 // except for the first content line (cf. Example 8.1)
7466 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
7467
7468 // End of more-indented block.
7469 } else if (atMoreIndented) {
7470 atMoreIndented = false;
7471 state.result += common.repeat('\n', emptyLines + 1);
7472
7473 // Just one line break - perceive as the same line.
7474 } else if (emptyLines === 0) {
7475 if (didReadContent) { // i.e. only if we have already read some scalar content.
7476 state.result += ' ';
7477 }
7478
7479 // Several line breaks - perceive as different lines.
7480 } else {
7481 state.result += common.repeat('\n', emptyLines);
7482 }
7483
7484 // Literal style: just add exact number of line breaks between content lines.
7485 } else {
7486 // Keep all line breaks except the header line break.
7487 state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
7488 }
7489
7490 didReadContent = true;
7491 detectedIndent = true;
7492 emptyLines = 0;
7493 captureStart = state.position;
7494
7495 while (!is_EOL(ch) && (ch !== 0)) {
7496 ch = state.input.charCodeAt(++state.position);
7497 }
7498
7499 captureSegment(state, captureStart, state.position, false);
7500 }
7501
7502 return true;
7503}
7504
7505function readBlockSequence(state, nodeIndent) {
7506 var _line,
7507 _tag = state.tag,
7508 _anchor = state.anchor,
7509 _result = [],
7510 following,
7511 detected = false,
7512 ch;
7513
7514 if (state.anchor !== null) {
7515 state.anchorMap[state.anchor] = _result;
7516 }
7517
7518 ch = state.input.charCodeAt(state.position);
7519
7520 while (ch !== 0) {
7521
7522 if (ch !== 0x2D/* - */) {
7523 break;
7524 }
7525
7526 following = state.input.charCodeAt(state.position + 1);
7527
7528 if (!is_WS_OR_EOL(following)) {
7529 break;
7530 }
7531
7532 detected = true;
7533 state.position++;
7534
7535 if (skipSeparationSpace(state, true, -1)) {
7536 if (state.lineIndent <= nodeIndent) {
7537 _result.push(null);
7538 ch = state.input.charCodeAt(state.position);
7539 continue;
7540 }
7541 }
7542
7543 _line = state.line;
7544 composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
7545 _result.push(state.result);
7546 skipSeparationSpace(state, true, -1);
7547
7548 ch = state.input.charCodeAt(state.position);
7549
7550 if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
7551 throwError(state, 'bad indentation of a sequence entry');
7552 } else if (state.lineIndent < nodeIndent) {
7553 break;
7554 }
7555 }
7556
7557 if (detected) {
7558 state.tag = _tag;
7559 state.anchor = _anchor;
7560 state.kind = 'sequence';
7561 state.result = _result;
7562 return true;
7563 }
7564 return false;
7565}
7566
7567function readBlockMapping(state, nodeIndent, flowIndent) {
7568 var following,
7569 allowCompact,
7570 _line,
7571 _pos,
7572 _tag = state.tag,
7573 _anchor = state.anchor,
7574 _result = {},
7575 overridableKeys = {},
7576 keyTag = null,
7577 keyNode = null,
7578 valueNode = null,
7579 atExplicitKey = false,
7580 detected = false,
7581 ch;
7582
7583 if (state.anchor !== null) {
7584 state.anchorMap[state.anchor] = _result;
7585 }
7586
7587 ch = state.input.charCodeAt(state.position);
7588
7589 while (ch !== 0) {
7590 following = state.input.charCodeAt(state.position + 1);
7591 _line = state.line; // Save the current line.
7592 _pos = state.position;
7593
7594 //
7595 // Explicit notation case. There are two separate blocks:
7596 // first for the key (denoted by "?") and second for the value (denoted by ":")
7597 //
7598 if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {
7599
7600 if (ch === 0x3F/* ? */) {
7601 if (atExplicitKey) {
7602 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
7603 keyTag = keyNode = valueNode = null;
7604 }
7605
7606 detected = true;
7607 atExplicitKey = true;
7608 allowCompact = true;
7609
7610 } else if (atExplicitKey) {
7611 // i.e. 0x3A/* : */ === character after the explicit key.
7612 atExplicitKey = false;
7613 allowCompact = true;
7614
7615 } else {
7616 throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
7617 }
7618
7619 state.position += 1;
7620 ch = following;
7621
7622 //
7623 // Implicit notation case. Flow-style node as the key first, then ":", and the value.
7624 //
7625 } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
7626
7627 if (state.line === _line) {
7628 ch = state.input.charCodeAt(state.position);
7629
7630 while (is_WHITE_SPACE(ch)) {
7631 ch = state.input.charCodeAt(++state.position);
7632 }
7633
7634 if (ch === 0x3A/* : */) {
7635 ch = state.input.charCodeAt(++state.position);
7636
7637 if (!is_WS_OR_EOL(ch)) {
7638 throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
7639 }
7640
7641 if (atExplicitKey) {
7642 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
7643 keyTag = keyNode = valueNode = null;
7644 }
7645
7646 detected = true;
7647 atExplicitKey = false;
7648 allowCompact = false;
7649 keyTag = state.tag;
7650 keyNode = state.result;
7651
7652 } else if (detected) {
7653 throwError(state, 'can not read an implicit mapping pair; a colon is missed');
7654
7655 } else {
7656 state.tag = _tag;
7657 state.anchor = _anchor;
7658 return true; // Keep the result of `composeNode`.
7659 }
7660
7661 } else if (detected) {
7662 throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
7663
7664 } else {
7665 state.tag = _tag;
7666 state.anchor = _anchor;
7667 return true; // Keep the result of `composeNode`.
7668 }
7669
7670 } else {
7671 break; // Reading is done. Go to the epilogue.
7672 }
7673
7674 //
7675 // Common reading code for both explicit and implicit notations.
7676 //
7677 if (state.line === _line || state.lineIndent > nodeIndent) {
7678 if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
7679 if (atExplicitKey) {
7680 keyNode = state.result;
7681 } else {
7682 valueNode = state.result;
7683 }
7684 }
7685
7686 if (!atExplicitKey) {
7687 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
7688 keyTag = keyNode = valueNode = null;
7689 }
7690
7691 skipSeparationSpace(state, true, -1);
7692 ch = state.input.charCodeAt(state.position);
7693 }
7694
7695 if (state.lineIndent > nodeIndent && (ch !== 0)) {
7696 throwError(state, 'bad indentation of a mapping entry');
7697 } else if (state.lineIndent < nodeIndent) {
7698 break;
7699 }
7700 }
7701
7702 //
7703 // Epilogue.
7704 //
7705
7706 // Special case: last mapping's node contains only the key in explicit notation.
7707 if (atExplicitKey) {
7708 storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
7709 }
7710
7711 // Expose the resulting mapping.
7712 if (detected) {
7713 state.tag = _tag;
7714 state.anchor = _anchor;
7715 state.kind = 'mapping';
7716 state.result = _result;
7717 }
7718
7719 return detected;
7720}
7721
7722function readTagProperty(state) {
7723 var _position,
7724 isVerbatim = false,
7725 isNamed = false,
7726 tagHandle,
7727 tagName,
7728 ch;
7729
7730 ch = state.input.charCodeAt(state.position);
7731
7732 if (ch !== 0x21/* ! */) return false;
7733
7734 if (state.tag !== null) {
7735 throwError(state, 'duplication of a tag property');
7736 }
7737
7738 ch = state.input.charCodeAt(++state.position);
7739
7740 if (ch === 0x3C/* < */) {
7741 isVerbatim = true;
7742 ch = state.input.charCodeAt(++state.position);
7743
7744 } else if (ch === 0x21/* ! */) {
7745 isNamed = true;
7746 tagHandle = '!!';
7747 ch = state.input.charCodeAt(++state.position);
7748
7749 } else {
7750 tagHandle = '!';
7751 }
7752
7753 _position = state.position;
7754
7755 if (isVerbatim) {
7756 do { ch = state.input.charCodeAt(++state.position); }
7757 while (ch !== 0 && ch !== 0x3E/* > */);
7758
7759 if (state.position < state.length) {
7760 tagName = state.input.slice(_position, state.position);
7761 ch = state.input.charCodeAt(++state.position);
7762 } else {
7763 throwError(state, 'unexpected end of the stream within a verbatim tag');
7764 }
7765 } else {
7766 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
7767
7768 if (ch === 0x21/* ! */) {
7769 if (!isNamed) {
7770 tagHandle = state.input.slice(_position - 1, state.position + 1);
7771
7772 if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
7773 throwError(state, 'named tag handle cannot contain such characters');
7774 }
7775
7776 isNamed = true;
7777 _position = state.position + 1;
7778 } else {
7779 throwError(state, 'tag suffix cannot contain exclamation marks');
7780 }
7781 }
7782
7783 ch = state.input.charCodeAt(++state.position);
7784 }
7785
7786 tagName = state.input.slice(_position, state.position);
7787
7788 if (PATTERN_FLOW_INDICATORS.test(tagName)) {
7789 throwError(state, 'tag suffix cannot contain flow indicator characters');
7790 }
7791 }
7792
7793 if (tagName && !PATTERN_TAG_URI.test(tagName)) {
7794 throwError(state, 'tag name cannot contain such characters: ' + tagName);
7795 }
7796
7797 if (isVerbatim) {
7798 state.tag = tagName;
7799
7800 } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
7801 state.tag = state.tagMap[tagHandle] + tagName;
7802
7803 } else if (tagHandle === '!') {
7804 state.tag = '!' + tagName;
7805
7806 } else if (tagHandle === '!!') {
7807 state.tag = 'tag:yaml.org,2002:' + tagName;
7808
7809 } else {
7810 throwError(state, 'undeclared tag handle "' + tagHandle + '"');
7811 }
7812
7813 return true;
7814}
7815
7816function readAnchorProperty(state) {
7817 var _position,
7818 ch;
7819
7820 ch = state.input.charCodeAt(state.position);
7821
7822 if (ch !== 0x26/* & */) return false;
7823
7824 if (state.anchor !== null) {
7825 throwError(state, 'duplication of an anchor property');
7826 }
7827
7828 ch = state.input.charCodeAt(++state.position);
7829 _position = state.position;
7830
7831 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
7832 ch = state.input.charCodeAt(++state.position);
7833 }
7834
7835 if (state.position === _position) {
7836 throwError(state, 'name of an anchor node must contain at least one character');
7837 }
7838
7839 state.anchor = state.input.slice(_position, state.position);
7840 return true;
7841}
7842
7843function readAlias(state) {
7844 var _position, alias,
7845 ch;
7846
7847 ch = state.input.charCodeAt(state.position);
7848
7849 if (ch !== 0x2A/* * */) return false;
7850
7851 ch = state.input.charCodeAt(++state.position);
7852 _position = state.position;
7853
7854 while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
7855 ch = state.input.charCodeAt(++state.position);
7856 }
7857
7858 if (state.position === _position) {
7859 throwError(state, 'name of an alias node must contain at least one character');
7860 }
7861
7862 alias = state.input.slice(_position, state.position);
7863
7864 if (!state.anchorMap.hasOwnProperty(alias)) {
7865 throwError(state, 'unidentified alias "' + alias + '"');
7866 }
7867
7868 state.result = state.anchorMap[alias];
7869 skipSeparationSpace(state, true, -1);
7870 return true;
7871}
7872
7873function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
7874 var allowBlockStyles,
7875 allowBlockScalars,
7876 allowBlockCollections,
7877 indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
7878 atNewLine = false,
7879 hasContent = false,
7880 typeIndex,
7881 typeQuantity,
7882 type,
7883 flowIndent,
7884 blockIndent;
7885
7886 if (state.listener !== null) {
7887 state.listener('open', state);
7888 }
7889
7890 state.tag = null;
7891 state.anchor = null;
7892 state.kind = null;
7893 state.result = null;
7894
7895 allowBlockStyles = allowBlockScalars = allowBlockCollections =
7896 CONTEXT_BLOCK_OUT === nodeContext ||
7897 CONTEXT_BLOCK_IN === nodeContext;
7898
7899 if (allowToSeek) {
7900 if (skipSeparationSpace(state, true, -1)) {
7901 atNewLine = true;
7902
7903 if (state.lineIndent > parentIndent) {
7904 indentStatus = 1;
7905 } else if (state.lineIndent === parentIndent) {
7906 indentStatus = 0;
7907 } else if (state.lineIndent < parentIndent) {
7908 indentStatus = -1;
7909 }
7910 }
7911 }
7912
7913 if (indentStatus === 1) {
7914 while (readTagProperty(state) || readAnchorProperty(state)) {
7915 if (skipSeparationSpace(state, true, -1)) {
7916 atNewLine = true;
7917 allowBlockCollections = allowBlockStyles;
7918
7919 if (state.lineIndent > parentIndent) {
7920 indentStatus = 1;
7921 } else if (state.lineIndent === parentIndent) {
7922 indentStatus = 0;
7923 } else if (state.lineIndent < parentIndent) {
7924 indentStatus = -1;
7925 }
7926 } else {
7927 allowBlockCollections = false;
7928 }
7929 }
7930 }
7931
7932 if (allowBlockCollections) {
7933 allowBlockCollections = atNewLine || allowCompact;
7934 }
7935
7936 if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
7937 if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
7938 flowIndent = parentIndent;
7939 } else {
7940 flowIndent = parentIndent + 1;
7941 }
7942
7943 blockIndent = state.position - state.lineStart;
7944
7945 if (indentStatus === 1) {
7946 if (allowBlockCollections &&
7947 (readBlockSequence(state, blockIndent) ||
7948 readBlockMapping(state, blockIndent, flowIndent)) ||
7949 readFlowCollection(state, flowIndent)) {
7950 hasContent = true;
7951 } else {
7952 if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
7953 readSingleQuotedScalar(state, flowIndent) ||
7954 readDoubleQuotedScalar(state, flowIndent)) {
7955 hasContent = true;
7956
7957 } else if (readAlias(state)) {
7958 hasContent = true;
7959
7960 if (state.tag !== null || state.anchor !== null) {
7961 throwError(state, 'alias node should not have any properties');
7962 }
7963
7964 } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
7965 hasContent = true;
7966
7967 if (state.tag === null) {
7968 state.tag = '?';
7969 }
7970 }
7971
7972 if (state.anchor !== null) {
7973 state.anchorMap[state.anchor] = state.result;
7974 }
7975 }
7976 } else if (indentStatus === 0) {
7977 // Special case: block sequences are allowed to have same indentation level as the parent.
7978 // http://www.yaml.org/spec/1.2/spec.html#id2799784
7979 hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
7980 }
7981 }
7982
7983 if (state.tag !== null && state.tag !== '!') {
7984 if (state.tag === '?') {
7985 for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
7986 type = state.implicitTypes[typeIndex];
7987
7988 // Implicit resolving is not allowed for non-scalar types, and '?'
7989 // non-specific tag is only assigned to plain scalars. So, it isn't
7990 // needed to check for 'kind' conformity.
7991
7992 if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
7993 state.result = type.construct(state.result);
7994 state.tag = type.tag;
7995 if (state.anchor !== null) {
7996 state.anchorMap[state.anchor] = state.result;
7997 }
7998 break;
7999 }
8000 }
8001 } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
8002 type = state.typeMap[state.kind || 'fallback'][state.tag];
8003
8004 if (state.result !== null && type.kind !== state.kind) {
8005 throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
8006 }
8007
8008 if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched
8009 throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
8010 } else {
8011 state.result = type.construct(state.result);
8012 if (state.anchor !== null) {
8013 state.anchorMap[state.anchor] = state.result;
8014 }
8015 }
8016 } else {
8017 throwError(state, 'unknown tag !<' + state.tag + '>');
8018 }
8019 }
8020
8021 if (state.listener !== null) {
8022 state.listener('close', state);
8023 }
8024 return state.tag !== null || state.anchor !== null || hasContent;
8025}
8026
8027function readDocument(state) {
8028 var documentStart = state.position,
8029 _position,
8030 directiveName,
8031 directiveArgs,
8032 hasDirectives = false,
8033 ch;
8034
8035 state.version = null;
8036 state.checkLineBreaks = state.legacy;
8037 state.tagMap = {};
8038 state.anchorMap = {};
8039
8040 while ((ch = state.input.charCodeAt(state.position)) !== 0) {
8041 skipSeparationSpace(state, true, -1);
8042
8043 ch = state.input.charCodeAt(state.position);
8044
8045 if (state.lineIndent > 0 || ch !== 0x25/* % */) {
8046 break;
8047 }
8048
8049 hasDirectives = true;
8050 ch = state.input.charCodeAt(++state.position);
8051 _position = state.position;
8052
8053 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
8054 ch = state.input.charCodeAt(++state.position);
8055 }
8056
8057 directiveName = state.input.slice(_position, state.position);
8058 directiveArgs = [];
8059
8060 if (directiveName.length < 1) {
8061 throwError(state, 'directive name must not be less than one character in length');
8062 }
8063
8064 while (ch !== 0) {
8065 while (is_WHITE_SPACE(ch)) {
8066 ch = state.input.charCodeAt(++state.position);
8067 }
8068
8069 if (ch === 0x23/* # */) {
8070 do { ch = state.input.charCodeAt(++state.position); }
8071 while (ch !== 0 && !is_EOL(ch));
8072 break;
8073 }
8074
8075 if (is_EOL(ch)) break;
8076
8077 _position = state.position;
8078
8079 while (ch !== 0 && !is_WS_OR_EOL(ch)) {
8080 ch = state.input.charCodeAt(++state.position);
8081 }
8082
8083 directiveArgs.push(state.input.slice(_position, state.position));
8084 }
8085
8086 if (ch !== 0) readLineBreak(state);
8087
8088 if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
8089 directiveHandlers[directiveName](state, directiveName, directiveArgs);
8090 } else {
8091 throwWarning(state, 'unknown document directive "' + directiveName + '"');
8092 }
8093 }
8094
8095 skipSeparationSpace(state, true, -1);
8096
8097 if (state.lineIndent === 0 &&
8098 state.input.charCodeAt(state.position) === 0x2D/* - */ &&
8099 state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
8100 state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
8101 state.position += 3;
8102 skipSeparationSpace(state, true, -1);
8103
8104 } else if (hasDirectives) {
8105 throwError(state, 'directives end mark is expected');
8106 }
8107
8108 composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
8109 skipSeparationSpace(state, true, -1);
8110
8111 if (state.checkLineBreaks &&
8112 PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
8113 throwWarning(state, 'non-ASCII line breaks are interpreted as content');
8114 }
8115
8116 state.documents.push(state.result);
8117
8118 if (state.position === state.lineStart && testDocumentSeparator(state)) {
8119
8120 if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
8121 state.position += 3;
8122 skipSeparationSpace(state, true, -1);
8123 }
8124 return;
8125 }
8126
8127 if (state.position < (state.length - 1)) {
8128 throwError(state, 'end of the stream or a document separator is expected');
8129 } else {
8130 return;
8131 }
8132}
8133
8134
8135function loadDocuments(input, options) {
8136 input = String(input);
8137 options = options || {};
8138
8139 if (input.length !== 0) {
8140
8141 // Add tailing `\n` if not exists
8142 if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
8143 input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
8144 input += '\n';
8145 }
8146
8147 // Strip BOM
8148 if (input.charCodeAt(0) === 0xFEFF) {
8149 input = input.slice(1);
8150 }
8151 }
8152
8153 var state = new State(input, options);
8154
8155 // Use 0 as string terminator. That significantly simplifies bounds check.
8156 state.input += '\0';
8157
8158 while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
8159 state.lineIndent += 1;
8160 state.position += 1;
8161 }
8162
8163 while (state.position < (state.length - 1)) {
8164 readDocument(state);
8165 }
8166
8167 return state.documents;
8168}
8169
8170
8171function loadAll(input, iterator, options) {
8172 var documents = loadDocuments(input, options), index, length;
8173
8174 if (typeof iterator !== 'function') {
8175 return documents;
8176 }
8177
8178 for (index = 0, length = documents.length; index < length; index += 1) {
8179 iterator(documents[index]);
8180 }
8181}
8182
8183
8184function load(input, options) {
8185 var documents = loadDocuments(input, options);
8186
8187 if (documents.length === 0) {
8188 /*eslint-disable no-undefined*/
8189 return undefined;
8190 } else if (documents.length === 1) {
8191 return documents[0];
8192 }
8193 throw new YAMLException('expected a single document in the stream, but found more');
8194}
8195
8196
8197function safeLoadAll(input, output, options) {
8198 if (typeof output === 'function') {
8199 loadAll(input, output, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
8200 } else {
8201 return loadAll(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
8202 }
8203}
8204
8205
8206function safeLoad(input, options) {
8207 return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
8208}
8209
8210
8211module.exports.loadAll = loadAll;
8212module.exports.load = load;
8213module.exports.safeLoadAll = safeLoadAll;
8214module.exports.safeLoad = safeLoad;
8215
8216},{"./common":35,"./exception":37,"./mark":39,"./schema/default_full":42,"./schema/default_safe":43}],39:[function(require,module,exports){
8217'use strict';
8218
8219
8220var common = require('./common');
8221
8222
8223function Mark(name, buffer, position, line, column) {
8224 this.name = name;
8225 this.buffer = buffer;
8226 this.position = position;
8227 this.line = line;
8228 this.column = column;
8229}
8230
8231
8232Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
8233 var head, start, tail, end, snippet;
8234
8235 if (!this.buffer) return null;
8236
8237 indent = indent || 4;
8238 maxLength = maxLength || 75;
8239
8240 head = '';
8241 start = this.position;
8242
8243 while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {
8244 start -= 1;
8245 if (this.position - start > (maxLength / 2 - 1)) {
8246 head = ' ... ';
8247 start += 5;
8248 break;
8249 }
8250 }
8251
8252 tail = '';
8253 end = this.position;
8254
8255 while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {
8256 end += 1;
8257 if (end - this.position > (maxLength / 2 - 1)) {
8258 tail = ' ... ';
8259 end -= 5;
8260 break;
8261 }
8262 }
8263
8264 snippet = this.buffer.slice(start, end);
8265
8266 return common.repeat(' ', indent) + head + snippet + tail + '\n' +
8267 common.repeat(' ', indent + this.position - start + head.length) + '^';
8268};
8269
8270
8271Mark.prototype.toString = function toString(compact) {
8272 var snippet, where = '';
8273
8274 if (this.name) {
8275 where += 'in "' + this.name + '" ';
8276 }
8277
8278 where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
8279
8280 if (!compact) {
8281 snippet = this.getSnippet();
8282
8283 if (snippet) {
8284 where += ':\n' + snippet;
8285 }
8286 }
8287
8288 return where;
8289};
8290
8291
8292module.exports = Mark;
8293
8294},{"./common":35}],40:[function(require,module,exports){
8295'use strict';
8296
8297/*eslint-disable max-len*/
8298
8299var common = require('./common');
8300var YAMLException = require('./exception');
8301var Type = require('./type');
8302
8303
8304function compileList(schema, name, result) {
8305 var exclude = [];
8306
8307 schema.include.forEach(function (includedSchema) {
8308 result = compileList(includedSchema, name, result);
8309 });
8310
8311 schema[name].forEach(function (currentType) {
8312 result.forEach(function (previousType, previousIndex) {
8313 if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
8314 exclude.push(previousIndex);
8315 }
8316 });
8317
8318 result.push(currentType);
8319 });
8320
8321 return result.filter(function (type, index) {
8322 return exclude.indexOf(index) === -1;
8323 });
8324}
8325
8326
8327function compileMap(/* lists... */) {
8328 var result = {
8329 scalar: {},
8330 sequence: {},
8331 mapping: {},
8332 fallback: {}
8333 }, index, length;
8334
8335 function collectType(type) {
8336 result[type.kind][type.tag] = result['fallback'][type.tag] = type;
8337 }
8338
8339 for (index = 0, length = arguments.length; index < length; index += 1) {
8340 arguments[index].forEach(collectType);
8341 }
8342 return result;
8343}
8344
8345
8346function Schema(definition) {
8347 this.include = definition.include || [];
8348 this.implicit = definition.implicit || [];
8349 this.explicit = definition.explicit || [];
8350
8351 this.implicit.forEach(function (type) {
8352 if (type.loadKind && type.loadKind !== 'scalar') {
8353 throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
8354 }
8355 });
8356
8357 this.compiledImplicit = compileList(this, 'implicit', []);
8358 this.compiledExplicit = compileList(this, 'explicit', []);
8359 this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
8360}
8361
8362
8363Schema.DEFAULT = null;
8364
8365
8366Schema.create = function createSchema() {
8367 var schemas, types;
8368
8369 switch (arguments.length) {
8370 case 1:
8371 schemas = Schema.DEFAULT;
8372 types = arguments[0];
8373 break;
8374
8375 case 2:
8376 schemas = arguments[0];
8377 types = arguments[1];
8378 break;
8379
8380 default:
8381 throw new YAMLException('Wrong number of arguments for Schema.create function');
8382 }
8383
8384 schemas = common.toArray(schemas);
8385 types = common.toArray(types);
8386
8387 if (!schemas.every(function (schema) { return schema instanceof Schema; })) {
8388 throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
8389 }
8390
8391 if (!types.every(function (type) { return type instanceof Type; })) {
8392 throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
8393 }
8394
8395 return new Schema({
8396 include: schemas,
8397 explicit: types
8398 });
8399};
8400
8401
8402module.exports = Schema;
8403
8404},{"./common":35,"./exception":37,"./type":46}],41:[function(require,module,exports){
8405// Standard YAML's Core schema.
8406// http://www.yaml.org/spec/1.2/spec.html#id2804923
8407//
8408// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
8409// So, Core schema has no distinctions from JSON schema is JS-YAML.
8410
8411
8412'use strict';
8413
8414
8415var Schema = require('../schema');
8416
8417
8418module.exports = new Schema({
8419 include: [
8420 require('./json')
8421 ]
8422});
8423
8424},{"../schema":40,"./json":45}],42:[function(require,module,exports){
8425// JS-YAML's default schema for `load` function.
8426// It is not described in the YAML specification.
8427//
8428// This schema is based on JS-YAML's default safe schema and includes
8429// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.
8430//
8431// Also this schema is used as default base schema at `Schema.create` function.
8432
8433
8434'use strict';
8435
8436
8437var Schema = require('../schema');
8438
8439
8440module.exports = Schema.DEFAULT = new Schema({
8441 include: [
8442 require('./default_safe')
8443 ],
8444 explicit: [
8445 require('../type/js/undefined'),
8446 require('../type/js/regexp'),
8447 require('../type/js/function')
8448 ]
8449});
8450
8451},{"../schema":40,"../type/js/function":51,"../type/js/regexp":52,"../type/js/undefined":53,"./default_safe":43}],43:[function(require,module,exports){
8452// JS-YAML's default schema for `safeLoad` function.
8453// It is not described in the YAML specification.
8454//
8455// This schema is based on standard YAML's Core schema and includes most of
8456// extra types described at YAML tag repository. (http://yaml.org/type/)
8457
8458
8459'use strict';
8460
8461
8462var Schema = require('../schema');
8463
8464
8465module.exports = new Schema({
8466 include: [
8467 require('./core')
8468 ],
8469 implicit: [
8470 require('../type/timestamp'),
8471 require('../type/merge')
8472 ],
8473 explicit: [
8474 require('../type/binary'),
8475 require('../type/omap'),
8476 require('../type/pairs'),
8477 require('../type/set')
8478 ]
8479});
8480
8481},{"../schema":40,"../type/binary":47,"../type/merge":55,"../type/omap":57,"../type/pairs":58,"../type/set":60,"../type/timestamp":62,"./core":41}],44:[function(require,module,exports){
8482// Standard YAML's Failsafe schema.
8483// http://www.yaml.org/spec/1.2/spec.html#id2802346
8484
8485
8486'use strict';
8487
8488
8489var Schema = require('../schema');
8490
8491
8492module.exports = new Schema({
8493 explicit: [
8494 require('../type/str'),
8495 require('../type/seq'),
8496 require('../type/map')
8497 ]
8498});
8499
8500},{"../schema":40,"../type/map":54,"../type/seq":59,"../type/str":61}],45:[function(require,module,exports){
8501// Standard YAML's JSON schema.
8502// http://www.yaml.org/spec/1.2/spec.html#id2803231
8503//
8504// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
8505// So, this schema is not such strict as defined in the YAML specification.
8506// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.
8507
8508
8509'use strict';
8510
8511
8512var Schema = require('../schema');
8513
8514
8515module.exports = new Schema({
8516 include: [
8517 require('./failsafe')
8518 ],
8519 implicit: [
8520 require('../type/null'),
8521 require('../type/bool'),
8522 require('../type/int'),
8523 require('../type/float')
8524 ]
8525});
8526
8527},{"../schema":40,"../type/bool":48,"../type/float":49,"../type/int":50,"../type/null":56,"./failsafe":44}],46:[function(require,module,exports){
8528'use strict';
8529
8530var YAMLException = require('./exception');
8531
8532var TYPE_CONSTRUCTOR_OPTIONS = [
8533 'kind',
8534 'resolve',
8535 'construct',
8536 'instanceOf',
8537 'predicate',
8538 'represent',
8539 'defaultStyle',
8540 'styleAliases'
8541];
8542
8543var YAML_NODE_KINDS = [
8544 'scalar',
8545 'sequence',
8546 'mapping'
8547];
8548
8549function compileStyleAliases(map) {
8550 var result = {};
8551
8552 if (map !== null) {
8553 Object.keys(map).forEach(function (style) {
8554 map[style].forEach(function (alias) {
8555 result[String(alias)] = style;
8556 });
8557 });
8558 }
8559
8560 return result;
8561}
8562
8563function Type(tag, options) {
8564 options = options || {};
8565
8566 Object.keys(options).forEach(function (name) {
8567 if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
8568 throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
8569 }
8570 });
8571
8572 // TODO: Add tag format check.
8573 this.tag = tag;
8574 this.kind = options['kind'] || null;
8575 this.resolve = options['resolve'] || function () { return true; };
8576 this.construct = options['construct'] || function (data) { return data; };
8577 this.instanceOf = options['instanceOf'] || null;
8578 this.predicate = options['predicate'] || null;
8579 this.represent = options['represent'] || null;
8580 this.defaultStyle = options['defaultStyle'] || null;
8581 this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
8582
8583 if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
8584 throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
8585 }
8586}
8587
8588module.exports = Type;
8589
8590},{"./exception":37}],47:[function(require,module,exports){
8591'use strict';
8592
8593/*eslint-disable no-bitwise*/
8594
8595var NodeBuffer;
8596
8597try {
8598 // A trick for browserified version, to not include `Buffer` shim
8599 var _require = require;
8600 NodeBuffer = _require('buffer').Buffer;
8601} catch (__) {}
8602
8603var Type = require('../type');
8604
8605
8606// [ 64, 65, 66 ] -> [ padding, CR, LF ]
8607var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
8608
8609
8610function resolveYamlBinary(data) {
8611 if (data === null) return false;
8612
8613 var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;
8614
8615 // Convert one by one.
8616 for (idx = 0; idx < max; idx++) {
8617 code = map.indexOf(data.charAt(idx));
8618
8619 // Skip CR/LF
8620 if (code > 64) continue;
8621
8622 // Fail on illegal characters
8623 if (code < 0) return false;
8624
8625 bitlen += 6;
8626 }
8627
8628 // If there are any bits left, source was corrupted
8629 return (bitlen % 8) === 0;
8630}
8631
8632function constructYamlBinary(data) {
8633 var idx, tailbits,
8634 input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
8635 max = input.length,
8636 map = BASE64_MAP,
8637 bits = 0,
8638 result = [];
8639
8640 // Collect by 6*4 bits (3 bytes)
8641
8642 for (idx = 0; idx < max; idx++) {
8643 if ((idx % 4 === 0) && idx) {
8644 result.push((bits >> 16) & 0xFF);
8645 result.push((bits >> 8) & 0xFF);
8646 result.push(bits & 0xFF);
8647 }
8648
8649 bits = (bits << 6) | map.indexOf(input.charAt(idx));
8650 }
8651
8652 // Dump tail
8653
8654 tailbits = (max % 4) * 6;
8655
8656 if (tailbits === 0) {
8657 result.push((bits >> 16) & 0xFF);
8658 result.push((bits >> 8) & 0xFF);
8659 result.push(bits & 0xFF);
8660 } else if (tailbits === 18) {
8661 result.push((bits >> 10) & 0xFF);
8662 result.push((bits >> 2) & 0xFF);
8663 } else if (tailbits === 12) {
8664 result.push((bits >> 4) & 0xFF);
8665 }
8666
8667 // Wrap into Buffer for NodeJS and leave Array for browser
8668 if (NodeBuffer) {
8669 // Support node 6.+ Buffer API when available
8670 return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
8671 }
8672
8673 return result;
8674}
8675
8676function representYamlBinary(object /*, style*/) {
8677 var result = '', bits = 0, idx, tail,
8678 max = object.length,
8679 map = BASE64_MAP;
8680
8681 // Convert every three bytes to 4 ASCII characters.
8682
8683 for (idx = 0; idx < max; idx++) {
8684 if ((idx % 3 === 0) && idx) {
8685 result += map[(bits >> 18) & 0x3F];
8686 result += map[(bits >> 12) & 0x3F];
8687 result += map[(bits >> 6) & 0x3F];
8688 result += map[bits & 0x3F];
8689 }
8690
8691 bits = (bits << 8) + object[idx];
8692 }
8693
8694 // Dump tail
8695
8696 tail = max % 3;
8697
8698 if (tail === 0) {
8699 result += map[(bits >> 18) & 0x3F];
8700 result += map[(bits >> 12) & 0x3F];
8701 result += map[(bits >> 6) & 0x3F];
8702 result += map[bits & 0x3F];
8703 } else if (tail === 2) {
8704 result += map[(bits >> 10) & 0x3F];
8705 result += map[(bits >> 4) & 0x3F];
8706 result += map[(bits << 2) & 0x3F];
8707 result += map[64];
8708 } else if (tail === 1) {
8709 result += map[(bits >> 2) & 0x3F];
8710 result += map[(bits << 4) & 0x3F];
8711 result += map[64];
8712 result += map[64];
8713 }
8714
8715 return result;
8716}
8717
8718function isBinary(object) {
8719 return NodeBuffer && NodeBuffer.isBuffer(object);
8720}
8721
8722module.exports = new Type('tag:yaml.org,2002:binary', {
8723 kind: 'scalar',
8724 resolve: resolveYamlBinary,
8725 construct: constructYamlBinary,
8726 predicate: isBinary,
8727 represent: representYamlBinary
8728});
8729
8730},{"../type":46}],48:[function(require,module,exports){
8731'use strict';
8732
8733var Type = require('../type');
8734
8735function resolveYamlBoolean(data) {
8736 if (data === null) return false;
8737
8738 var max = data.length;
8739
8740 return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
8741 (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
8742}
8743
8744function constructYamlBoolean(data) {
8745 return data === 'true' ||
8746 data === 'True' ||
8747 data === 'TRUE';
8748}
8749
8750function isBoolean(object) {
8751 return Object.prototype.toString.call(object) === '[object Boolean]';
8752}
8753
8754module.exports = new Type('tag:yaml.org,2002:bool', {
8755 kind: 'scalar',
8756 resolve: resolveYamlBoolean,
8757 construct: constructYamlBoolean,
8758 predicate: isBoolean,
8759 represent: {
8760 lowercase: function (object) { return object ? 'true' : 'false'; },
8761 uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
8762 camelcase: function (object) { return object ? 'True' : 'False'; }
8763 },
8764 defaultStyle: 'lowercase'
8765});
8766
8767},{"../type":46}],49:[function(require,module,exports){
8768'use strict';
8769
8770var common = require('../common');
8771var Type = require('../type');
8772
8773var YAML_FLOAT_PATTERN = new RegExp(
8774 // 2.5e4, 2.5 and integers
8775 '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
8776 // .2e4, .2
8777 // special case, seems not from spec
8778 '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
8779 // 20:59
8780 '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
8781 // .inf
8782 '|[-+]?\\.(?:inf|Inf|INF)' +
8783 // .nan
8784 '|\\.(?:nan|NaN|NAN))$');
8785
8786function resolveYamlFloat(data) {
8787 if (data === null) return false;
8788
8789 if (!YAML_FLOAT_PATTERN.test(data) ||
8790 // Quick hack to not allow integers end with `_`
8791 // Probably should update regexp & check speed
8792 data[data.length - 1] === '_') {
8793 return false;
8794 }
8795
8796 return true;
8797}
8798
8799function constructYamlFloat(data) {
8800 var value, sign, base, digits;
8801
8802 value = data.replace(/_/g, '').toLowerCase();
8803 sign = value[0] === '-' ? -1 : 1;
8804 digits = [];
8805
8806 if ('+-'.indexOf(value[0]) >= 0) {
8807 value = value.slice(1);
8808 }
8809
8810 if (value === '.inf') {
8811 return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
8812
8813 } else if (value === '.nan') {
8814 return NaN;
8815
8816 } else if (value.indexOf(':') >= 0) {
8817 value.split(':').forEach(function (v) {
8818 digits.unshift(parseFloat(v, 10));
8819 });
8820
8821 value = 0.0;
8822 base = 1;
8823
8824 digits.forEach(function (d) {
8825 value += d * base;
8826 base *= 60;
8827 });
8828
8829 return sign * value;
8830
8831 }
8832 return sign * parseFloat(value, 10);
8833}
8834
8835
8836var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
8837
8838function representYamlFloat(object, style) {
8839 var res;
8840
8841 if (isNaN(object)) {
8842 switch (style) {
8843 case 'lowercase': return '.nan';
8844 case 'uppercase': return '.NAN';
8845 case 'camelcase': return '.NaN';
8846 }
8847 } else if (Number.POSITIVE_INFINITY === object) {
8848 switch (style) {
8849 case 'lowercase': return '.inf';
8850 case 'uppercase': return '.INF';
8851 case 'camelcase': return '.Inf';
8852 }
8853 } else if (Number.NEGATIVE_INFINITY === object) {
8854 switch (style) {
8855 case 'lowercase': return '-.inf';
8856 case 'uppercase': return '-.INF';
8857 case 'camelcase': return '-.Inf';
8858 }
8859 } else if (common.isNegativeZero(object)) {
8860 return '-0.0';
8861 }
8862
8863 res = object.toString(10);
8864
8865 // JS stringifier can build scientific format without dots: 5e-100,
8866 // while YAML requres dot: 5.e-100. Fix it with simple hack
8867
8868 return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
8869}
8870
8871function isFloat(object) {
8872 return (Object.prototype.toString.call(object) === '[object Number]') &&
8873 (object % 1 !== 0 || common.isNegativeZero(object));
8874}
8875
8876module.exports = new Type('tag:yaml.org,2002:float', {
8877 kind: 'scalar',
8878 resolve: resolveYamlFloat,
8879 construct: constructYamlFloat,
8880 predicate: isFloat,
8881 represent: representYamlFloat,
8882 defaultStyle: 'lowercase'
8883});
8884
8885},{"../common":35,"../type":46}],50:[function(require,module,exports){
8886'use strict';
8887
8888var common = require('../common');
8889var Type = require('../type');
8890
8891function isHexCode(c) {
8892 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
8893 ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
8894 ((0x61/* a */ <= c) && (c <= 0x66/* f */));
8895}
8896
8897function isOctCode(c) {
8898 return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
8899}
8900
8901function isDecCode(c) {
8902 return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
8903}
8904
8905function resolveYamlInteger(data) {
8906 if (data === null) return false;
8907
8908 var max = data.length,
8909 index = 0,
8910 hasDigits = false,
8911 ch;
8912
8913 if (!max) return false;
8914
8915 ch = data[index];
8916
8917 // sign
8918 if (ch === '-' || ch === '+') {
8919 ch = data[++index];
8920 }
8921
8922 if (ch === '0') {
8923 // 0
8924 if (index + 1 === max) return true;
8925 ch = data[++index];
8926
8927 // base 2, base 8, base 16
8928
8929 if (ch === 'b') {
8930 // base 2
8931 index++;
8932
8933 for (; index < max; index++) {
8934 ch = data[index];
8935 if (ch === '_') continue;
8936 if (ch !== '0' && ch !== '1') return false;
8937 hasDigits = true;
8938 }
8939 return hasDigits && ch !== '_';
8940 }
8941
8942
8943 if (ch === 'x') {
8944 // base 16
8945 index++;
8946
8947 for (; index < max; index++) {
8948 ch = data[index];
8949 if (ch === '_') continue;
8950 if (!isHexCode(data.charCodeAt(index))) return false;
8951 hasDigits = true;
8952 }
8953 return hasDigits && ch !== '_';
8954 }
8955
8956 // base 8
8957 for (; index < max; index++) {
8958 ch = data[index];
8959 if (ch === '_') continue;
8960 if (!isOctCode(data.charCodeAt(index))) return false;
8961 hasDigits = true;
8962 }
8963 return hasDigits && ch !== '_';
8964 }
8965
8966 // base 10 (except 0) or base 60
8967
8968 // value should not start with `_`;
8969 if (ch === '_') return false;
8970
8971 for (; index < max; index++) {
8972 ch = data[index];
8973 if (ch === '_') continue;
8974 if (ch === ':') break;
8975 if (!isDecCode(data.charCodeAt(index))) {
8976 return false;
8977 }
8978 hasDigits = true;
8979 }
8980
8981 // Should have digits and should not end with `_`
8982 if (!hasDigits || ch === '_') return false;
8983
8984 // if !base60 - done;
8985 if (ch !== ':') return true;
8986
8987 // base60 almost not used, no needs to optimize
8988 return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
8989}
8990
8991function constructYamlInteger(data) {
8992 var value = data, sign = 1, ch, base, digits = [];
8993
8994 if (value.indexOf('_') !== -1) {
8995 value = value.replace(/_/g, '');
8996 }
8997
8998 ch = value[0];
8999
9000 if (ch === '-' || ch === '+') {
9001 if (ch === '-') sign = -1;
9002 value = value.slice(1);
9003 ch = value[0];
9004 }
9005
9006 if (value === '0') return 0;
9007
9008 if (ch === '0') {
9009 if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
9010 if (value[1] === 'x') return sign * parseInt(value, 16);
9011 return sign * parseInt(value, 8);
9012 }
9013
9014 if (value.indexOf(':') !== -1) {
9015 value.split(':').forEach(function (v) {
9016 digits.unshift(parseInt(v, 10));
9017 });
9018
9019 value = 0;
9020 base = 1;
9021
9022 digits.forEach(function (d) {
9023 value += (d * base);
9024 base *= 60;
9025 });
9026
9027 return sign * value;
9028
9029 }
9030
9031 return sign * parseInt(value, 10);
9032}
9033
9034function isInteger(object) {
9035 return (Object.prototype.toString.call(object)) === '[object Number]' &&
9036 (object % 1 === 0 && !common.isNegativeZero(object));
9037}
9038
9039module.exports = new Type('tag:yaml.org,2002:int', {
9040 kind: 'scalar',
9041 resolve: resolveYamlInteger,
9042 construct: constructYamlInteger,
9043 predicate: isInteger,
9044 represent: {
9045 binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
9046 octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },
9047 decimal: function (obj) { return obj.toString(10); },
9048 /* eslint-disable max-len */
9049 hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }
9050 },
9051 defaultStyle: 'decimal',
9052 styleAliases: {
9053 binary: [ 2, 'bin' ],
9054 octal: [ 8, 'oct' ],
9055 decimal: [ 10, 'dec' ],
9056 hexadecimal: [ 16, 'hex' ]
9057 }
9058});
9059
9060},{"../common":35,"../type":46}],51:[function(require,module,exports){
9061'use strict';
9062
9063var esprima;
9064
9065// Browserified version does not have esprima
9066//
9067// 1. For node.js just require module as deps
9068// 2. For browser try to require mudule via external AMD system.
9069// If not found - try to fallback to window.esprima. If not
9070// found too - then fail to parse.
9071//
9072try {
9073 // workaround to exclude package from browserify list.
9074 var _require = require;
9075 esprima = _require('esprima');
9076} catch (_) {
9077 /*global window */
9078 if (typeof window !== 'undefined') esprima = window.esprima;
9079}
9080
9081var Type = require('../../type');
9082
9083function resolveJavascriptFunction(data) {
9084 if (data === null) return false;
9085
9086 try {
9087 var source = '(' + data + ')',
9088 ast = esprima.parse(source, { range: true });
9089
9090 if (ast.type !== 'Program' ||
9091 ast.body.length !== 1 ||
9092 ast.body[0].type !== 'ExpressionStatement' ||
9093 (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
9094 ast.body[0].expression.type !== 'FunctionExpression')) {
9095 return false;
9096 }
9097
9098 return true;
9099 } catch (err) {
9100 return false;
9101 }
9102}
9103
9104function constructJavascriptFunction(data) {
9105 /*jslint evil:true*/
9106
9107 var source = '(' + data + ')',
9108 ast = esprima.parse(source, { range: true }),
9109 params = [],
9110 body;
9111
9112 if (ast.type !== 'Program' ||
9113 ast.body.length !== 1 ||
9114 ast.body[0].type !== 'ExpressionStatement' ||
9115 (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&
9116 ast.body[0].expression.type !== 'FunctionExpression')) {
9117 throw new Error('Failed to resolve function');
9118 }
9119
9120 ast.body[0].expression.params.forEach(function (param) {
9121 params.push(param.name);
9122 });
9123
9124 body = ast.body[0].expression.body.range;
9125
9126 // Esprima's ranges include the first '{' and the last '}' characters on
9127 // function expressions. So cut them out.
9128 if (ast.body[0].expression.body.type === 'BlockStatement') {
9129 /*eslint-disable no-new-func*/
9130 return new Function(params, source.slice(body[0] + 1, body[1] - 1));
9131 }
9132 // ES6 arrow functions can omit the BlockStatement. In that case, just return
9133 // the body.
9134 /*eslint-disable no-new-func*/
9135 return new Function(params, 'return ' + source.slice(body[0], body[1]));
9136}
9137
9138function representJavascriptFunction(object /*, style*/) {
9139 return object.toString();
9140}
9141
9142function isFunction(object) {
9143 return Object.prototype.toString.call(object) === '[object Function]';
9144}
9145
9146module.exports = new Type('tag:yaml.org,2002:js/function', {
9147 kind: 'scalar',
9148 resolve: resolveJavascriptFunction,
9149 construct: constructJavascriptFunction,
9150 predicate: isFunction,
9151 represent: representJavascriptFunction
9152});
9153
9154},{"../../type":46}],52:[function(require,module,exports){
9155'use strict';
9156
9157var Type = require('../../type');
9158
9159function resolveJavascriptRegExp(data) {
9160 if (data === null) return false;
9161 if (data.length === 0) return false;
9162
9163 var regexp = data,
9164 tail = /\/([gim]*)$/.exec(data),
9165 modifiers = '';
9166
9167 // if regexp starts with '/' it can have modifiers and must be properly closed
9168 // `/foo/gim` - modifiers tail can be maximum 3 chars
9169 if (regexp[0] === '/') {
9170 if (tail) modifiers = tail[1];
9171
9172 if (modifiers.length > 3) return false;
9173 // if expression starts with /, is should be properly terminated
9174 if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;
9175 }
9176
9177 return true;
9178}
9179
9180function constructJavascriptRegExp(data) {
9181 var regexp = data,
9182 tail = /\/([gim]*)$/.exec(data),
9183 modifiers = '';
9184
9185 // `/foo/gim` - tail can be maximum 4 chars
9186 if (regexp[0] === '/') {
9187 if (tail) modifiers = tail[1];
9188 regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
9189 }
9190
9191 return new RegExp(regexp, modifiers);
9192}
9193
9194function representJavascriptRegExp(object /*, style*/) {
9195 var result = '/' + object.source + '/';
9196
9197 if (object.global) result += 'g';
9198 if (object.multiline) result += 'm';
9199 if (object.ignoreCase) result += 'i';
9200
9201 return result;
9202}
9203
9204function isRegExp(object) {
9205 return Object.prototype.toString.call(object) === '[object RegExp]';
9206}
9207
9208module.exports = new Type('tag:yaml.org,2002:js/regexp', {
9209 kind: 'scalar',
9210 resolve: resolveJavascriptRegExp,
9211 construct: constructJavascriptRegExp,
9212 predicate: isRegExp,
9213 represent: representJavascriptRegExp
9214});
9215
9216},{"../../type":46}],53:[function(require,module,exports){
9217'use strict';
9218
9219var Type = require('../../type');
9220
9221function resolveJavascriptUndefined() {
9222 return true;
9223}
9224
9225function constructJavascriptUndefined() {
9226 /*eslint-disable no-undefined*/
9227 return undefined;
9228}
9229
9230function representJavascriptUndefined() {
9231 return '';
9232}
9233
9234function isUndefined(object) {
9235 return typeof object === 'undefined';
9236}
9237
9238module.exports = new Type('tag:yaml.org,2002:js/undefined', {
9239 kind: 'scalar',
9240 resolve: resolveJavascriptUndefined,
9241 construct: constructJavascriptUndefined,
9242 predicate: isUndefined,
9243 represent: representJavascriptUndefined
9244});
9245
9246},{"../../type":46}],54:[function(require,module,exports){
9247'use strict';
9248
9249var Type = require('../type');
9250
9251module.exports = new Type('tag:yaml.org,2002:map', {
9252 kind: 'mapping',
9253 construct: function (data) { return data !== null ? data : {}; }
9254});
9255
9256},{"../type":46}],55:[function(require,module,exports){
9257'use strict';
9258
9259var Type = require('../type');
9260
9261function resolveYamlMerge(data) {
9262 return data === '<<' || data === null;
9263}
9264
9265module.exports = new Type('tag:yaml.org,2002:merge', {
9266 kind: 'scalar',
9267 resolve: resolveYamlMerge
9268});
9269
9270},{"../type":46}],56:[function(require,module,exports){
9271'use strict';
9272
9273var Type = require('../type');
9274
9275function resolveYamlNull(data) {
9276 if (data === null) return true;
9277
9278 var max = data.length;
9279
9280 return (max === 1 && data === '~') ||
9281 (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
9282}
9283
9284function constructYamlNull() {
9285 return null;
9286}
9287
9288function isNull(object) {
9289 return object === null;
9290}
9291
9292module.exports = new Type('tag:yaml.org,2002:null', {
9293 kind: 'scalar',
9294 resolve: resolveYamlNull,
9295 construct: constructYamlNull,
9296 predicate: isNull,
9297 represent: {
9298 canonical: function () { return '~'; },
9299 lowercase: function () { return 'null'; },
9300 uppercase: function () { return 'NULL'; },
9301 camelcase: function () { return 'Null'; }
9302 },
9303 defaultStyle: 'lowercase'
9304});
9305
9306},{"../type":46}],57:[function(require,module,exports){
9307'use strict';
9308
9309var Type = require('../type');
9310
9311var _hasOwnProperty = Object.prototype.hasOwnProperty;
9312var _toString = Object.prototype.toString;
9313
9314function resolveYamlOmap(data) {
9315 if (data === null) return true;
9316
9317 var objectKeys = [], index, length, pair, pairKey, pairHasKey,
9318 object = data;
9319
9320 for (index = 0, length = object.length; index < length; index += 1) {
9321 pair = object[index];
9322 pairHasKey = false;
9323
9324 if (_toString.call(pair) !== '[object Object]') return false;
9325
9326 for (pairKey in pair) {
9327 if (_hasOwnProperty.call(pair, pairKey)) {
9328 if (!pairHasKey) pairHasKey = true;
9329 else return false;
9330 }
9331 }
9332
9333 if (!pairHasKey) return false;
9334
9335 if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
9336 else return false;
9337 }
9338
9339 return true;
9340}
9341
9342function constructYamlOmap(data) {
9343 return data !== null ? data : [];
9344}
9345
9346module.exports = new Type('tag:yaml.org,2002:omap', {
9347 kind: 'sequence',
9348 resolve: resolveYamlOmap,
9349 construct: constructYamlOmap
9350});
9351
9352},{"../type":46}],58:[function(require,module,exports){
9353'use strict';
9354
9355var Type = require('../type');
9356
9357var _toString = Object.prototype.toString;
9358
9359function resolveYamlPairs(data) {
9360 if (data === null) return true;
9361
9362 var index, length, pair, keys, result,
9363 object = data;
9364
9365 result = new Array(object.length);
9366
9367 for (index = 0, length = object.length; index < length; index += 1) {
9368 pair = object[index];
9369
9370 if (_toString.call(pair) !== '[object Object]') return false;
9371
9372 keys = Object.keys(pair);
9373
9374 if (keys.length !== 1) return false;
9375
9376 result[index] = [ keys[0], pair[keys[0]] ];
9377 }
9378
9379 return true;
9380}
9381
9382function constructYamlPairs(data) {
9383 if (data === null) return [];
9384
9385 var index, length, pair, keys, result,
9386 object = data;
9387
9388 result = new Array(object.length);
9389
9390 for (index = 0, length = object.length; index < length; index += 1) {
9391 pair = object[index];
9392
9393 keys = Object.keys(pair);
9394
9395 result[index] = [ keys[0], pair[keys[0]] ];
9396 }
9397
9398 return result;
9399}
9400
9401module.exports = new Type('tag:yaml.org,2002:pairs', {
9402 kind: 'sequence',
9403 resolve: resolveYamlPairs,
9404 construct: constructYamlPairs
9405});
9406
9407},{"../type":46}],59:[function(require,module,exports){
9408'use strict';
9409
9410var Type = require('../type');
9411
9412module.exports = new Type('tag:yaml.org,2002:seq', {
9413 kind: 'sequence',
9414 construct: function (data) { return data !== null ? data : []; }
9415});
9416
9417},{"../type":46}],60:[function(require,module,exports){
9418'use strict';
9419
9420var Type = require('../type');
9421
9422var _hasOwnProperty = Object.prototype.hasOwnProperty;
9423
9424function resolveYamlSet(data) {
9425 if (data === null) return true;
9426
9427 var key, object = data;
9428
9429 for (key in object) {
9430 if (_hasOwnProperty.call(object, key)) {
9431 if (object[key] !== null) return false;
9432 }
9433 }
9434
9435 return true;
9436}
9437
9438function constructYamlSet(data) {
9439 return data !== null ? data : {};
9440}
9441
9442module.exports = new Type('tag:yaml.org,2002:set', {
9443 kind: 'mapping',
9444 resolve: resolveYamlSet,
9445 construct: constructYamlSet
9446});
9447
9448},{"../type":46}],61:[function(require,module,exports){
9449'use strict';
9450
9451var Type = require('../type');
9452
9453module.exports = new Type('tag:yaml.org,2002:str', {
9454 kind: 'scalar',
9455 construct: function (data) { return data !== null ? data : ''; }
9456});
9457
9458},{"../type":46}],62:[function(require,module,exports){
9459'use strict';
9460
9461var Type = require('../type');
9462
9463var YAML_DATE_REGEXP = new RegExp(
9464 '^([0-9][0-9][0-9][0-9])' + // [1] year
9465 '-([0-9][0-9])' + // [2] month
9466 '-([0-9][0-9])$'); // [3] day
9467
9468var YAML_TIMESTAMP_REGEXP = new RegExp(
9469 '^([0-9][0-9][0-9][0-9])' + // [1] year
9470 '-([0-9][0-9]?)' + // [2] month
9471 '-([0-9][0-9]?)' + // [3] day
9472 '(?:[Tt]|[ \\t]+)' + // ...
9473 '([0-9][0-9]?)' + // [4] hour
9474 ':([0-9][0-9])' + // [5] minute
9475 ':([0-9][0-9])' + // [6] second
9476 '(?:\\.([0-9]*))?' + // [7] fraction
9477 '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
9478 '(?::([0-9][0-9]))?))?$'); // [11] tz_minute
9479
9480function resolveYamlTimestamp(data) {
9481 if (data === null) return false;
9482 if (YAML_DATE_REGEXP.exec(data) !== null) return true;
9483 if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
9484 return false;
9485}
9486
9487function constructYamlTimestamp(data) {
9488 var match, year, month, day, hour, minute, second, fraction = 0,
9489 delta = null, tz_hour, tz_minute, date;
9490
9491 match = YAML_DATE_REGEXP.exec(data);
9492 if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
9493
9494 if (match === null) throw new Error('Date resolve error');
9495
9496 // match: [1] year [2] month [3] day
9497
9498 year = +(match[1]);
9499 month = +(match[2]) - 1; // JS month starts with 0
9500 day = +(match[3]);
9501
9502 if (!match[4]) { // no hour
9503 return new Date(Date.UTC(year, month, day));
9504 }
9505
9506 // match: [4] hour [5] minute [6] second [7] fraction
9507
9508 hour = +(match[4]);
9509 minute = +(match[5]);
9510 second = +(match[6]);
9511
9512 if (match[7]) {
9513 fraction = match[7].slice(0, 3);
9514 while (fraction.length < 3) { // milli-seconds
9515 fraction += '0';
9516 }
9517 fraction = +fraction;
9518 }
9519
9520 // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
9521
9522 if (match[9]) {
9523 tz_hour = +(match[10]);
9524 tz_minute = +(match[11] || 0);
9525 delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
9526 if (match[9] === '-') delta = -delta;
9527 }
9528
9529 date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
9530
9531 if (delta) date.setTime(date.getTime() - delta);
9532
9533 return date;
9534}
9535
9536function representYamlTimestamp(object /*, style*/) {
9537 return object.toISOString();
9538}
9539
9540module.exports = new Type('tag:yaml.org,2002:timestamp', {
9541 kind: 'scalar',
9542 resolve: resolveYamlTimestamp,
9543 construct: constructYamlTimestamp,
9544 instanceOf: Date,
9545 represent: representYamlTimestamp
9546});
9547
9548},{"../type":46}],63:[function(require,module,exports){
9549'use strict';
9550
9551var format = require('format-util');
9552var slice = Array.prototype.slice;
9553var protectedProperties = ['name', 'message', 'stack'];
9554var errorPrototypeProperties = [
9555 'name', 'message', 'description', 'number', 'code', 'fileName', 'lineNumber', 'columnNumber',
9556 'sourceURL', 'line', 'column', 'stack'
9557];
9558
9559module.exports = create(Error);
9560module.exports.error = create(Error);
9561module.exports.eval = create(EvalError);
9562module.exports.range = create(RangeError);
9563module.exports.reference = create(ReferenceError);
9564module.exports.syntax = create(SyntaxError);
9565module.exports.type = create(TypeError);
9566module.exports.uri = create(URIError);
9567module.exports.formatter = format;
9568
9569/**
9570 * Creates a new {@link ono} function that creates the given Error class.
9571 *
9572 * @param {Class} Klass - The Error subclass to create
9573 * @returns {ono}
9574 */
9575function create (Klass) {
9576 /**
9577 * @param {Error} [err] - The original error, if any
9578 * @param {object} [props] - An object whose properties will be added to the error object
9579 * @param {string} [message] - The error message. May contain {@link util#format} placeholders
9580 * @param {...*} [params] - Parameters that map to the `message` placeholders
9581 * @returns {Error}
9582 */
9583 return function onoFactory (err, props, message, params) { // eslint-disable-line no-unused-vars
9584 var formatArgs = [];
9585 var formattedMessage = '';
9586
9587 // Determine which arguments were actually specified
9588 if (typeof err === 'string') {
9589 formatArgs = slice.call(arguments);
9590 err = props = undefined;
9591 }
9592 else if (typeof props === 'string') {
9593 formatArgs = slice.call(arguments, 1);
9594 props = undefined;
9595 }
9596 else if (typeof message === 'string') {
9597 formatArgs = slice.call(arguments, 2);
9598 }
9599
9600 // If there are any format arguments, then format the error message
9601 if (formatArgs.length > 0) {
9602 formattedMessage = module.exports.formatter.apply(null, formatArgs);
9603 }
9604
9605 if (err && err.message) {
9606 // The inner-error's message will be added to the new message
9607 formattedMessage += (formattedMessage ? ' \n' : '') + err.message;
9608 }
9609
9610 // Create the new error
9611 // NOTE: DON'T move this to a separate function! We don't want to pollute the stack trace
9612 var newError = new Klass(formattedMessage);
9613
9614 // Extend the new error with the additional properties
9615 extendError(newError, err); // Copy properties of the original error
9616 extendToJSON(newError); // Replace the original toJSON method
9617 extend(newError, props); // Copy custom properties, possibly including a custom toJSON method
9618
9619 return newError;
9620 };
9621}
9622
9623/**
9624 * Extends the targetError with the properties of the source error.
9625 *
9626 * @param {Error} targetError - The error object to extend
9627 * @param {?Error} sourceError - The source error object, if any
9628 */
9629function extendError (targetError, sourceError) {
9630 extendStack(targetError, sourceError);
9631 extend(targetError, sourceError);
9632}
9633
9634/**
9635 * JavaScript engines differ in how errors are serialized to JSON - especially when it comes
9636 * to custom error properties and stack traces. So we add our own toJSON method that ALWAYS
9637 * outputs every property of the error.
9638 */
9639function extendToJSON (error) {
9640 error.toJSON = errorToJSON;
9641
9642 // Also add an inspect() method, for compatibility with Node.js' `util.inspect()` method
9643 error.inspect = errorToString;
9644}
9645
9646/**
9647 * Extends the target object with the properties of the source object.
9648 *
9649 * @param {object} target - The object to extend
9650 * @param {?source} source - The object whose properties are copied
9651 */
9652function extend (target, source) {
9653 if (source && typeof source === 'object') {
9654 var keys = Object.keys(source);
9655 for (var i = 0; i < keys.length; i++) {
9656 var key = keys[i];
9657
9658 // Don't copy "protected" properties, since they have special meaning/behavior
9659 // and are set by the onoFactory function
9660 if (protectedProperties.indexOf(key) >= 0) {
9661 continue;
9662 }
9663
9664 try {
9665 target[key] = source[key];
9666 }
9667 catch (e) {
9668 // This property is read-only, so it can't be copied
9669 }
9670 }
9671 }
9672}
9673
9674/**
9675 * Custom JSON serializer for Error objects.
9676 * Returns all built-in error properties, as well as extended properties.
9677 *
9678 * @returns {object}
9679 */
9680function errorToJSON () {
9681 var json = {};
9682
9683 // Get all the properties of this error
9684 var keys = Object.keys(this);
9685
9686 // Also include properties from the Error prototype
9687 keys = keys.concat(errorPrototypeProperties);
9688
9689 for (var i = 0; i < keys.length; i++) {
9690 var key = keys[i];
9691 var value = this[key];
9692 var type = typeof value;
9693 if (type !== 'undefined' && type !== 'function') {
9694 json[key] = value;
9695 }
9696 }
9697
9698 return json;
9699}
9700
9701/**
9702 * Serializes Error objects as human-readable JSON strings for debugging/logging purposes.
9703 *
9704 * @returns {string}
9705 */
9706function errorToString () {
9707 return JSON.stringify(this, null, 2).replace(/\\n/g, '\n');
9708}
9709
9710/**
9711 * Extend the error stack to include its cause
9712 *
9713 * @param {Error} targetError
9714 * @param {Error} sourceError
9715 */
9716function extendStack (targetError, sourceError) {
9717 if (hasLazyStack(targetError)) {
9718 if (sourceError) {
9719 lazyJoinStacks(targetError, sourceError);
9720 }
9721 else {
9722 lazyPopStack(targetError);
9723 }
9724 }
9725 else {
9726 if (sourceError) {
9727 targetError.stack = joinStacks(targetError.stack, sourceError.stack);
9728 }
9729 else {
9730 targetError.stack = popStack(targetError.stack);
9731 }
9732 }
9733}
9734
9735/**
9736 * Appends the original {@link Error#stack} property to the new Error's stack.
9737 *
9738 * @param {string} newStack
9739 * @param {string} originalStack
9740 * @returns {string}
9741 */
9742function joinStacks (newStack, originalStack) {
9743 newStack = popStack(newStack);
9744
9745 if (newStack && originalStack) {
9746 return newStack + '\n\n' + originalStack;
9747 }
9748 else {
9749 return newStack || originalStack;
9750 }
9751}
9752
9753/**
9754 * Removes Ono from the stack, so that the stack starts at the original error location
9755 *
9756 * @param {string} stack
9757 * @returns {string}
9758 */
9759function popStack (stack) {
9760 if (stack) {
9761 var lines = stack.split('\n');
9762
9763 if (lines.length < 2) {
9764 // The stack only has one line, so there's nothing we can remove
9765 return stack;
9766 }
9767
9768 // Find the `onoFactory` call in the stack, and remove it
9769 for (var i = 0; i < lines.length; i++) {
9770 var line = lines[i];
9771 if (line.indexOf('onoFactory') >= 0) {
9772 lines.splice(i, 1);
9773 return lines.join('\n');
9774 }
9775 }
9776
9777 // If we get here, then the stack doesn't contain a call to `onoFactory`.
9778 // This may be due to minification or some optimization of the JS engine.
9779 // So just return the stack as-is.
9780 return stack;
9781 }
9782}
9783
9784/**
9785 * Does a one-time determination of whether this JavaScript engine
9786 * supports lazy `Error.stack` properties.
9787 */
9788var supportsLazyStack = (function () {
9789 return !!(
9790 // ES5 property descriptors must be supported
9791 Object.getOwnPropertyDescriptor && Object.defineProperty &&
9792
9793 // Chrome on Android doesn't support lazy stacks :(
9794 (typeof navigator === 'undefined' || !/Android/.test(navigator.userAgent))
9795 );
9796}());
9797
9798/**
9799 * Does this error have a lazy stack property?
9800 *
9801 * @param {Error} err
9802 * @returns {boolean}
9803 */
9804function hasLazyStack (err) {
9805 if (!supportsLazyStack) {
9806 return false;
9807 }
9808
9809 var descriptor = Object.getOwnPropertyDescriptor(err, 'stack');
9810 if (!descriptor) {
9811 return false;
9812 }
9813 return typeof descriptor.get === 'function';
9814}
9815
9816/**
9817 * Calls {@link joinStacks} lazily, when the {@link Error#stack} property is accessed.
9818 *
9819 * @param {Error} targetError
9820 * @param {Error} sourceError
9821 */
9822function lazyJoinStacks (targetError, sourceError) {
9823 var targetStack = Object.getOwnPropertyDescriptor(targetError, 'stack');
9824
9825 Object.defineProperty(targetError, 'stack', {
9826 get: function () {
9827 return joinStacks(targetStack.get.apply(targetError), sourceError.stack);
9828 },
9829 enumerable: false,
9830 configurable: true
9831 });
9832}
9833
9834/**
9835 * Calls {@link popStack} lazily, when the {@link Error#stack} property is accessed.
9836 *
9837 * @param {Error} error
9838 */
9839function lazyPopStack (error) {
9840 var targetStack = Object.getOwnPropertyDescriptor(error, 'stack');
9841
9842 Object.defineProperty(error, 'stack', {
9843 get: function () {
9844 return popStack(targetStack.get.apply(error));
9845 },
9846 enumerable: false,
9847 configurable: true
9848 });
9849}
9850
9851},{"format-util":27}],64:[function(require,module,exports){
9852// shim for using process in browser
9853var process = module.exports = {};
9854
9855// cached from whatever global is present so that test runners that stub it
9856// don't break things. But we need to wrap it in a try catch in case it is
9857// wrapped in strict mode code which doesn't define any globals. It's inside a
9858// function because try/catches deoptimize in certain engines.
9859
9860var cachedSetTimeout;
9861var cachedClearTimeout;
9862
9863function defaultSetTimout() {
9864 throw new Error('setTimeout has not been defined');
9865}
9866function defaultClearTimeout () {
9867 throw new Error('clearTimeout has not been defined');
9868}
9869(function () {
9870 try {
9871 if (typeof setTimeout === 'function') {
9872 cachedSetTimeout = setTimeout;
9873 } else {
9874 cachedSetTimeout = defaultSetTimout;
9875 }
9876 } catch (e) {
9877 cachedSetTimeout = defaultSetTimout;
9878 }
9879 try {
9880 if (typeof clearTimeout === 'function') {
9881 cachedClearTimeout = clearTimeout;
9882 } else {
9883 cachedClearTimeout = defaultClearTimeout;
9884 }
9885 } catch (e) {
9886 cachedClearTimeout = defaultClearTimeout;
9887 }
9888} ())
9889function runTimeout(fun) {
9890 if (cachedSetTimeout === setTimeout) {
9891 //normal enviroments in sane situations
9892 return setTimeout(fun, 0);
9893 }
9894 // if setTimeout wasn't available but was latter defined
9895 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
9896 cachedSetTimeout = setTimeout;
9897 return setTimeout(fun, 0);
9898 }
9899 try {
9900 // when when somebody has screwed with setTimeout but no I.E. maddness
9901 return cachedSetTimeout(fun, 0);
9902 } catch(e){
9903 try {
9904 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
9905 return cachedSetTimeout.call(null, fun, 0);
9906 } catch(e){
9907 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
9908 return cachedSetTimeout.call(this, fun, 0);
9909 }
9910 }
9911
9912
9913}
9914function runClearTimeout(marker) {
9915 if (cachedClearTimeout === clearTimeout) {
9916 //normal enviroments in sane situations
9917 return clearTimeout(marker);
9918 }
9919 // if clearTimeout wasn't available but was latter defined
9920 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
9921 cachedClearTimeout = clearTimeout;
9922 return clearTimeout(marker);
9923 }
9924 try {
9925 // when when somebody has screwed with setTimeout but no I.E. maddness
9926 return cachedClearTimeout(marker);
9927 } catch (e){
9928 try {
9929 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
9930 return cachedClearTimeout.call(null, marker);
9931 } catch (e){
9932 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
9933 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
9934 return cachedClearTimeout.call(this, marker);
9935 }
9936 }
9937
9938
9939
9940}
9941var queue = [];
9942var draining = false;
9943var currentQueue;
9944var queueIndex = -1;
9945
9946function cleanUpNextTick() {
9947 if (!draining || !currentQueue) {
9948 return;
9949 }
9950 draining = false;
9951 if (currentQueue.length) {
9952 queue = currentQueue.concat(queue);
9953 } else {
9954 queueIndex = -1;
9955 }
9956 if (queue.length) {
9957 drainQueue();
9958 }
9959}
9960
9961function drainQueue() {
9962 if (draining) {
9963 return;
9964 }
9965 var timeout = runTimeout(cleanUpNextTick);
9966 draining = true;
9967
9968 var len = queue.length;
9969 while(len) {
9970 currentQueue = queue;
9971 queue = [];
9972 while (++queueIndex < len) {
9973 if (currentQueue) {
9974 currentQueue[queueIndex].run();
9975 }
9976 }
9977 queueIndex = -1;
9978 len = queue.length;
9979 }
9980 currentQueue = null;
9981 draining = false;
9982 runClearTimeout(timeout);
9983}
9984
9985process.nextTick = function (fun) {
9986 var args = new Array(arguments.length - 1);
9987 if (arguments.length > 1) {
9988 for (var i = 1; i < arguments.length; i++) {
9989 args[i - 1] = arguments[i];
9990 }
9991 }
9992 queue.push(new Item(fun, args));
9993 if (queue.length === 1 && !draining) {
9994 runTimeout(drainQueue);
9995 }
9996};
9997
9998// v8 likes predictible objects
9999function Item(fun, array) {
10000 this.fun = fun;
10001 this.array = array;
10002}
10003Item.prototype.run = function () {
10004 this.fun.apply(null, this.array);
10005};
10006process.title = 'browser';
10007process.browser = true;
10008process.env = {};
10009process.argv = [];
10010process.version = ''; // empty string to avoid regexp issues
10011process.versions = {};
10012
10013function noop() {}
10014
10015process.on = noop;
10016process.addListener = noop;
10017process.once = noop;
10018process.off = noop;
10019process.removeListener = noop;
10020process.removeAllListeners = noop;
10021process.emit = noop;
10022process.prependListener = noop;
10023process.prependOnceListener = noop;
10024
10025process.listeners = function (name) { return [] }
10026
10027process.binding = function (name) {
10028 throw new Error('process.binding is not supported');
10029};
10030
10031process.cwd = function () { return '/' };
10032process.chdir = function (dir) {
10033 throw new Error('process.chdir is not supported');
10034};
10035process.umask = function() { return 0; };
10036
10037},{}],65:[function(require,module,exports){
10038(function (global){
10039/*! https://mths.be/punycode v1.4.1 by @mathias */
10040;(function(root) {
10041
10042 /** Detect free variables */
10043 var freeExports = typeof exports == 'object' && exports &&
10044 !exports.nodeType && exports;
10045 var freeModule = typeof module == 'object' && module &&
10046 !module.nodeType && module;
10047 var freeGlobal = typeof global == 'object' && global;
10048 if (
10049 freeGlobal.global === freeGlobal ||
10050 freeGlobal.window === freeGlobal ||
10051 freeGlobal.self === freeGlobal
10052 ) {
10053 root = freeGlobal;
10054 }
10055
10056 /**
10057 * The `punycode` object.
10058 * @name punycode
10059 * @type Object
10060 */
10061 var punycode,
10062
10063 /** Highest positive signed 32-bit float value */
10064 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
10065
10066 /** Bootstring parameters */
10067 base = 36,
10068 tMin = 1,
10069 tMax = 26,
10070 skew = 38,
10071 damp = 700,
10072 initialBias = 72,
10073 initialN = 128, // 0x80
10074 delimiter = '-', // '\x2D'
10075
10076 /** Regular expressions */
10077 regexPunycode = /^xn--/,
10078 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
10079 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
10080
10081 /** Error messages */
10082 errors = {
10083 'overflow': 'Overflow: input needs wider integers to process',
10084 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
10085 'invalid-input': 'Invalid input'
10086 },
10087
10088 /** Convenience shortcuts */
10089 baseMinusTMin = base - tMin,
10090 floor = Math.floor,
10091 stringFromCharCode = String.fromCharCode,
10092
10093 /** Temporary variable */
10094 key;
10095
10096 /*--------------------------------------------------------------------------*/
10097
10098 /**
10099 * A generic error utility function.
10100 * @private
10101 * @param {String} type The error type.
10102 * @returns {Error} Throws a `RangeError` with the applicable error message.
10103 */
10104 function error(type) {
10105 throw new RangeError(errors[type]);
10106 }
10107
10108 /**
10109 * A generic `Array#map` utility function.
10110 * @private
10111 * @param {Array} array The array to iterate over.
10112 * @param {Function} callback The function that gets called for every array
10113 * item.
10114 * @returns {Array} A new array of values returned by the callback function.
10115 */
10116 function map(array, fn) {
10117 var length = array.length;
10118 var result = [];
10119 while (length--) {
10120 result[length] = fn(array[length]);
10121 }
10122 return result;
10123 }
10124
10125 /**
10126 * A simple `Array#map`-like wrapper to work with domain name strings or email
10127 * addresses.
10128 * @private
10129 * @param {String} domain The domain name or email address.
10130 * @param {Function} callback The function that gets called for every
10131 * character.
10132 * @returns {Array} A new string of characters returned by the callback
10133 * function.
10134 */
10135 function mapDomain(string, fn) {
10136 var parts = string.split('@');
10137 var result = '';
10138 if (parts.length > 1) {
10139 // In email addresses, only the domain name should be punycoded. Leave
10140 // the local part (i.e. everything up to `@`) intact.
10141 result = parts[0] + '@';
10142 string = parts[1];
10143 }
10144 // Avoid `split(regex)` for IE8 compatibility. See #17.
10145 string = string.replace(regexSeparators, '\x2E');
10146 var labels = string.split('.');
10147 var encoded = map(labels, fn).join('.');
10148 return result + encoded;
10149 }
10150
10151 /**
10152 * Creates an array containing the numeric code points of each Unicode
10153 * character in the string. While JavaScript uses UCS-2 internally,
10154 * this function will convert a pair of surrogate halves (each of which
10155 * UCS-2 exposes as separate characters) into a single code point,
10156 * matching UTF-16.
10157 * @see `punycode.ucs2.encode`
10158 * @see <https://mathiasbynens.be/notes/javascript-encoding>
10159 * @memberOf punycode.ucs2
10160 * @name decode
10161 * @param {String} string The Unicode input string (UCS-2).
10162 * @returns {Array} The new array of code points.
10163 */
10164 function ucs2decode(string) {
10165 var output = [],
10166 counter = 0,
10167 length = string.length,
10168 value,
10169 extra;
10170 while (counter < length) {
10171 value = string.charCodeAt(counter++);
10172 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
10173 // high surrogate, and there is a next character
10174 extra = string.charCodeAt(counter++);
10175 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
10176 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
10177 } else {
10178 // unmatched surrogate; only append this code unit, in case the next
10179 // code unit is the high surrogate of a surrogate pair
10180 output.push(value);
10181 counter--;
10182 }
10183 } else {
10184 output.push(value);
10185 }
10186 }
10187 return output;
10188 }
10189
10190 /**
10191 * Creates a string based on an array of numeric code points.
10192 * @see `punycode.ucs2.decode`
10193 * @memberOf punycode.ucs2
10194 * @name encode
10195 * @param {Array} codePoints The array of numeric code points.
10196 * @returns {String} The new Unicode string (UCS-2).
10197 */
10198 function ucs2encode(array) {
10199 return map(array, function(value) {
10200 var output = '';
10201 if (value > 0xFFFF) {
10202 value -= 0x10000;
10203 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
10204 value = 0xDC00 | value & 0x3FF;
10205 }
10206 output += stringFromCharCode(value);
10207 return output;
10208 }).join('');
10209 }
10210
10211 /**
10212 * Converts a basic code point into a digit/integer.
10213 * @see `digitToBasic()`
10214 * @private
10215 * @param {Number} codePoint The basic numeric code point value.
10216 * @returns {Number} The numeric value of a basic code point (for use in
10217 * representing integers) in the range `0` to `base - 1`, or `base` if
10218 * the code point does not represent a value.
10219 */
10220 function basicToDigit(codePoint) {
10221 if (codePoint - 48 < 10) {
10222 return codePoint - 22;
10223 }
10224 if (codePoint - 65 < 26) {
10225 return codePoint - 65;
10226 }
10227 if (codePoint - 97 < 26) {
10228 return codePoint - 97;
10229 }
10230 return base;
10231 }
10232
10233 /**
10234 * Converts a digit/integer into a basic code point.
10235 * @see `basicToDigit()`
10236 * @private
10237 * @param {Number} digit The numeric value of a basic code point.
10238 * @returns {Number} The basic code point whose value (when used for
10239 * representing integers) is `digit`, which needs to be in the range
10240 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
10241 * used; else, the lowercase form is used. The behavior is undefined
10242 * if `flag` is non-zero and `digit` has no uppercase form.
10243 */
10244 function digitToBasic(digit, flag) {
10245 // 0..25 map to ASCII a..z or A..Z
10246 // 26..35 map to ASCII 0..9
10247 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
10248 }
10249
10250 /**
10251 * Bias adaptation function as per section 3.4 of RFC 3492.
10252 * https://tools.ietf.org/html/rfc3492#section-3.4
10253 * @private
10254 */
10255 function adapt(delta, numPoints, firstTime) {
10256 var k = 0;
10257 delta = firstTime ? floor(delta / damp) : delta >> 1;
10258 delta += floor(delta / numPoints);
10259 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
10260 delta = floor(delta / baseMinusTMin);
10261 }
10262 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
10263 }
10264
10265 /**
10266 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
10267 * symbols.
10268 * @memberOf punycode
10269 * @param {String} input The Punycode string of ASCII-only symbols.
10270 * @returns {String} The resulting string of Unicode symbols.
10271 */
10272 function decode(input) {
10273 // Don't use UCS-2
10274 var output = [],
10275 inputLength = input.length,
10276 out,
10277 i = 0,
10278 n = initialN,
10279 bias = initialBias,
10280 basic,
10281 j,
10282 index,
10283 oldi,
10284 w,
10285 k,
10286 digit,
10287 t,
10288 /** Cached calculation results */
10289 baseMinusT;
10290
10291 // Handle the basic code points: let `basic` be the number of input code
10292 // points before the last delimiter, or `0` if there is none, then copy
10293 // the first basic code points to the output.
10294
10295 basic = input.lastIndexOf(delimiter);
10296 if (basic < 0) {
10297 basic = 0;
10298 }
10299
10300 for (j = 0; j < basic; ++j) {
10301 // if it's not a basic code point
10302 if (input.charCodeAt(j) >= 0x80) {
10303 error('not-basic');
10304 }
10305 output.push(input.charCodeAt(j));
10306 }
10307
10308 // Main decoding loop: start just after the last delimiter if any basic code
10309 // points were copied; start at the beginning otherwise.
10310
10311 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
10312
10313 // `index` is the index of the next character to be consumed.
10314 // Decode a generalized variable-length integer into `delta`,
10315 // which gets added to `i`. The overflow checking is easier
10316 // if we increase `i` as we go, then subtract off its starting
10317 // value at the end to obtain `delta`.
10318 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
10319
10320 if (index >= inputLength) {
10321 error('invalid-input');
10322 }
10323
10324 digit = basicToDigit(input.charCodeAt(index++));
10325
10326 if (digit >= base || digit > floor((maxInt - i) / w)) {
10327 error('overflow');
10328 }
10329
10330 i += digit * w;
10331 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
10332
10333 if (digit < t) {
10334 break;
10335 }
10336
10337 baseMinusT = base - t;
10338 if (w > floor(maxInt / baseMinusT)) {
10339 error('overflow');
10340 }
10341
10342 w *= baseMinusT;
10343
10344 }
10345
10346 out = output.length + 1;
10347 bias = adapt(i - oldi, out, oldi == 0);
10348
10349 // `i` was supposed to wrap around from `out` to `0`,
10350 // incrementing `n` each time, so we'll fix that now:
10351 if (floor(i / out) > maxInt - n) {
10352 error('overflow');
10353 }
10354
10355 n += floor(i / out);
10356 i %= out;
10357
10358 // Insert `n` at position `i` of the output
10359 output.splice(i++, 0, n);
10360
10361 }
10362
10363 return ucs2encode(output);
10364 }
10365
10366 /**
10367 * Converts a string of Unicode symbols (e.g. a domain name label) to a
10368 * Punycode string of ASCII-only symbols.
10369 * @memberOf punycode
10370 * @param {String} input The string of Unicode symbols.
10371 * @returns {String} The resulting Punycode string of ASCII-only symbols.
10372 */
10373 function encode(input) {
10374 var n,
10375 delta,
10376 handledCPCount,
10377 basicLength,
10378 bias,
10379 j,
10380 m,
10381 q,
10382 k,
10383 t,
10384 currentValue,
10385 output = [],
10386 /** `inputLength` will hold the number of code points in `input`. */
10387 inputLength,
10388 /** Cached calculation results */
10389 handledCPCountPlusOne,
10390 baseMinusT,
10391 qMinusT;
10392
10393 // Convert the input in UCS-2 to Unicode
10394 input = ucs2decode(input);
10395
10396 // Cache the length
10397 inputLength = input.length;
10398
10399 // Initialize the state
10400 n = initialN;
10401 delta = 0;
10402 bias = initialBias;
10403
10404 // Handle the basic code points
10405 for (j = 0; j < inputLength; ++j) {
10406 currentValue = input[j];
10407 if (currentValue < 0x80) {
10408 output.push(stringFromCharCode(currentValue));
10409 }
10410 }
10411
10412 handledCPCount = basicLength = output.length;
10413
10414 // `handledCPCount` is the number of code points that have been handled;
10415 // `basicLength` is the number of basic code points.
10416
10417 // Finish the basic string - if it is not empty - with a delimiter
10418 if (basicLength) {
10419 output.push(delimiter);
10420 }
10421
10422 // Main encoding loop:
10423 while (handledCPCount < inputLength) {
10424
10425 // All non-basic code points < n have been handled already. Find the next
10426 // larger one:
10427 for (m = maxInt, j = 0; j < inputLength; ++j) {
10428 currentValue = input[j];
10429 if (currentValue >= n && currentValue < m) {
10430 m = currentValue;
10431 }
10432 }
10433
10434 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
10435 // but guard against overflow
10436 handledCPCountPlusOne = handledCPCount + 1;
10437 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
10438 error('overflow');
10439 }
10440
10441 delta += (m - n) * handledCPCountPlusOne;
10442 n = m;
10443
10444 for (j = 0; j < inputLength; ++j) {
10445 currentValue = input[j];
10446
10447 if (currentValue < n && ++delta > maxInt) {
10448 error('overflow');
10449 }
10450
10451 if (currentValue == n) {
10452 // Represent delta as a generalized variable-length integer
10453 for (q = delta, k = base; /* no condition */; k += base) {
10454 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
10455 if (q < t) {
10456 break;
10457 }
10458 qMinusT = q - t;
10459 baseMinusT = base - t;
10460 output.push(
10461 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
10462 );
10463 q = floor(qMinusT / baseMinusT);
10464 }
10465
10466 output.push(stringFromCharCode(digitToBasic(q, 0)));
10467 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
10468 delta = 0;
10469 ++handledCPCount;
10470 }
10471 }
10472
10473 ++delta;
10474 ++n;
10475
10476 }
10477 return output.join('');
10478 }
10479
10480 /**
10481 * Converts a Punycode string representing a domain name or an email address
10482 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
10483 * it doesn't matter if you call it on a string that has already been
10484 * converted to Unicode.
10485 * @memberOf punycode
10486 * @param {String} input The Punycoded domain name or email address to
10487 * convert to Unicode.
10488 * @returns {String} The Unicode representation of the given Punycode
10489 * string.
10490 */
10491 function toUnicode(input) {
10492 return mapDomain(input, function(string) {
10493 return regexPunycode.test(string)
10494 ? decode(string.slice(4).toLowerCase())
10495 : string;
10496 });
10497 }
10498
10499 /**
10500 * Converts a Unicode string representing a domain name or an email address to
10501 * Punycode. Only the non-ASCII parts of the domain name will be converted,
10502 * i.e. it doesn't matter if you call it with a domain that's already in
10503 * ASCII.
10504 * @memberOf punycode
10505 * @param {String} input The domain name or email address to convert, as a
10506 * Unicode string.
10507 * @returns {String} The Punycode representation of the given domain name or
10508 * email address.
10509 */
10510 function toASCII(input) {
10511 return mapDomain(input, function(string) {
10512 return regexNonASCII.test(string)
10513 ? 'xn--' + encode(string)
10514 : string;
10515 });
10516 }
10517
10518 /*--------------------------------------------------------------------------*/
10519
10520 /** Define the public API */
10521 punycode = {
10522 /**
10523 * A string representing the current Punycode.js version number.
10524 * @memberOf punycode
10525 * @type String
10526 */
10527 'version': '1.4.1',
10528 /**
10529 * An object of methods to convert from JavaScript's internal character
10530 * representation (UCS-2) to Unicode code points, and back.
10531 * @see <https://mathiasbynens.be/notes/javascript-encoding>
10532 * @memberOf punycode
10533 * @type Object
10534 */
10535 'ucs2': {
10536 'decode': ucs2decode,
10537 'encode': ucs2encode
10538 },
10539 'decode': decode,
10540 'encode': encode,
10541 'toASCII': toASCII,
10542 'toUnicode': toUnicode
10543 };
10544
10545 /** Expose `punycode` */
10546 // Some AMD build optimizers, like r.js, check for specific condition patterns
10547 // like the following:
10548 if (
10549 typeof define == 'function' &&
10550 typeof define.amd == 'object' &&
10551 define.amd
10552 ) {
10553 define('punycode', function() {
10554 return punycode;
10555 });
10556 } else if (freeExports && freeModule) {
10557 if (module.exports == freeExports) {
10558 // in Node.js, io.js, or RingoJS v0.8.0+
10559 freeModule.exports = punycode;
10560 } else {
10561 // in Narwhal or RingoJS v0.7.0-
10562 for (key in punycode) {
10563 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
10564 }
10565 }
10566 } else {
10567 // in Rhino or a web browser
10568 root.punycode = punycode;
10569 }
10570
10571}(this));
10572
10573}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10574
10575},{}],66:[function(require,module,exports){
10576// Copyright Joyent, Inc. and other Node contributors.
10577//
10578// Permission is hereby granted, free of charge, to any person obtaining a
10579// copy of this software and associated documentation files (the
10580// "Software"), to deal in the Software without restriction, including
10581// without limitation the rights to use, copy, modify, merge, publish,
10582// distribute, sublicense, and/or sell copies of the Software, and to permit
10583// persons to whom the Software is furnished to do so, subject to the
10584// following conditions:
10585//
10586// The above copyright notice and this permission notice shall be included
10587// in all copies or substantial portions of the Software.
10588//
10589// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10590// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10591// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10592// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10593// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10594// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10595// USE OR OTHER DEALINGS IN THE SOFTWARE.
10596
10597'use strict';
10598
10599// If obj.hasOwnProperty has been overridden, then calling
10600// obj.hasOwnProperty(prop) will break.
10601// See: https://github.com/joyent/node/issues/1707
10602function hasOwnProperty(obj, prop) {
10603 return Object.prototype.hasOwnProperty.call(obj, prop);
10604}
10605
10606module.exports = function(qs, sep, eq, options) {
10607 sep = sep || '&';
10608 eq = eq || '=';
10609 var obj = {};
10610
10611 if (typeof qs !== 'string' || qs.length === 0) {
10612 return obj;
10613 }
10614
10615 var regexp = /\+/g;
10616 qs = qs.split(sep);
10617
10618 var maxKeys = 1000;
10619 if (options && typeof options.maxKeys === 'number') {
10620 maxKeys = options.maxKeys;
10621 }
10622
10623 var len = qs.length;
10624 // maxKeys <= 0 means that we should not limit keys count
10625 if (maxKeys > 0 && len > maxKeys) {
10626 len = maxKeys;
10627 }
10628
10629 for (var i = 0; i < len; ++i) {
10630 var x = qs[i].replace(regexp, '%20'),
10631 idx = x.indexOf(eq),
10632 kstr, vstr, k, v;
10633
10634 if (idx >= 0) {
10635 kstr = x.substr(0, idx);
10636 vstr = x.substr(idx + 1);
10637 } else {
10638 kstr = x;
10639 vstr = '';
10640 }
10641
10642 k = decodeURIComponent(kstr);
10643 v = decodeURIComponent(vstr);
10644
10645 if (!hasOwnProperty(obj, k)) {
10646 obj[k] = v;
10647 } else if (isArray(obj[k])) {
10648 obj[k].push(v);
10649 } else {
10650 obj[k] = [obj[k], v];
10651 }
10652 }
10653
10654 return obj;
10655};
10656
10657var isArray = Array.isArray || function (xs) {
10658 return Object.prototype.toString.call(xs) === '[object Array]';
10659};
10660
10661},{}],67:[function(require,module,exports){
10662// Copyright Joyent, Inc. and other Node contributors.
10663//
10664// Permission is hereby granted, free of charge, to any person obtaining a
10665// copy of this software and associated documentation files (the
10666// "Software"), to deal in the Software without restriction, including
10667// without limitation the rights to use, copy, modify, merge, publish,
10668// distribute, sublicense, and/or sell copies of the Software, and to permit
10669// persons to whom the Software is furnished to do so, subject to the
10670// following conditions:
10671//
10672// The above copyright notice and this permission notice shall be included
10673// in all copies or substantial portions of the Software.
10674//
10675// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10676// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10677// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10678// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10679// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10680// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10681// USE OR OTHER DEALINGS IN THE SOFTWARE.
10682
10683'use strict';
10684
10685var stringifyPrimitive = function(v) {
10686 switch (typeof v) {
10687 case 'string':
10688 return v;
10689
10690 case 'boolean':
10691 return v ? 'true' : 'false';
10692
10693 case 'number':
10694 return isFinite(v) ? v : '';
10695
10696 default:
10697 return '';
10698 }
10699};
10700
10701module.exports = function(obj, sep, eq, name) {
10702 sep = sep || '&';
10703 eq = eq || '=';
10704 if (obj === null) {
10705 obj = undefined;
10706 }
10707
10708 if (typeof obj === 'object') {
10709 return map(objectKeys(obj), function(k) {
10710 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
10711 if (isArray(obj[k])) {
10712 return map(obj[k], function(v) {
10713 return ks + encodeURIComponent(stringifyPrimitive(v));
10714 }).join(sep);
10715 } else {
10716 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
10717 }
10718 }).join(sep);
10719
10720 }
10721
10722 if (!name) return '';
10723 return encodeURIComponent(stringifyPrimitive(name)) + eq +
10724 encodeURIComponent(stringifyPrimitive(obj));
10725};
10726
10727var isArray = Array.isArray || function (xs) {
10728 return Object.prototype.toString.call(xs) === '[object Array]';
10729};
10730
10731function map (xs, f) {
10732 if (xs.map) return xs.map(f);
10733 var res = [];
10734 for (var i = 0; i < xs.length; i++) {
10735 res.push(f(xs[i], i));
10736 }
10737 return res;
10738}
10739
10740var objectKeys = Object.keys || function (obj) {
10741 var res = [];
10742 for (var key in obj) {
10743 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
10744 }
10745 return res;
10746};
10747
10748},{}],68:[function(require,module,exports){
10749'use strict';
10750
10751exports.decode = exports.parse = require('./decode');
10752exports.encode = exports.stringify = require('./encode');
10753
10754},{"./decode":66,"./encode":67}],69:[function(require,module,exports){
10755/* eslint-disable node/no-deprecated-api */
10756var buffer = require('buffer')
10757var Buffer = buffer.Buffer
10758
10759// alternative to using Object.keys for old browsers
10760function copyProps (src, dst) {
10761 for (var key in src) {
10762 dst[key] = src[key]
10763 }
10764}
10765if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
10766 module.exports = buffer
10767} else {
10768 // Copy properties from require('buffer')
10769 copyProps(buffer, exports)
10770 exports.Buffer = SafeBuffer
10771}
10772
10773function SafeBuffer (arg, encodingOrOffset, length) {
10774 return Buffer(arg, encodingOrOffset, length)
10775}
10776
10777// Copy static methods from Buffer
10778copyProps(Buffer, SafeBuffer)
10779
10780SafeBuffer.from = function (arg, encodingOrOffset, length) {
10781 if (typeof arg === 'number') {
10782 throw new TypeError('Argument must not be a number')
10783 }
10784 return Buffer(arg, encodingOrOffset, length)
10785}
10786
10787SafeBuffer.alloc = function (size, fill, encoding) {
10788 if (typeof size !== 'number') {
10789 throw new TypeError('Argument must be a number')
10790 }
10791 var buf = Buffer(size)
10792 if (fill !== undefined) {
10793 if (typeof encoding === 'string') {
10794 buf.fill(fill, encoding)
10795 } else {
10796 buf.fill(fill)
10797 }
10798 } else {
10799 buf.fill(0)
10800 }
10801 return buf
10802}
10803
10804SafeBuffer.allocUnsafe = function (size) {
10805 if (typeof size !== 'number') {
10806 throw new TypeError('Argument must be a number')
10807 }
10808 return Buffer(size)
10809}
10810
10811SafeBuffer.allocUnsafeSlow = function (size) {
10812 if (typeof size !== 'number') {
10813 throw new TypeError('Argument must be a number')
10814 }
10815 return buffer.SlowBuffer(size)
10816}
10817
10818},{"buffer":22}],70:[function(require,module,exports){
10819(function (global){
10820var ClientRequest = require('./lib/request')
10821var response = require('./lib/response')
10822var extend = require('xtend')
10823var statusCodes = require('builtin-status-codes')
10824var url = require('url')
10825
10826var http = exports
10827
10828http.request = function (opts, cb) {
10829 if (typeof opts === 'string')
10830 opts = url.parse(opts)
10831 else
10832 opts = extend(opts)
10833
10834 // Normally, the page is loaded from http or https, so not specifying a protocol
10835 // will result in a (valid) protocol-relative url. However, this won't work if
10836 // the protocol is something else, like 'file:'
10837 var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
10838
10839 var protocol = opts.protocol || defaultProtocol
10840 var host = opts.hostname || opts.host
10841 var port = opts.port
10842 var path = opts.path || '/'
10843
10844 // Necessary for IPv6 addresses
10845 if (host && host.indexOf(':') !== -1)
10846 host = '[' + host + ']'
10847
10848 // This may be a relative url. The browser should always be able to interpret it correctly.
10849 opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
10850 opts.method = (opts.method || 'GET').toUpperCase()
10851 opts.headers = opts.headers || {}
10852
10853 // Also valid opts.auth, opts.mode
10854
10855 var req = new ClientRequest(opts)
10856 if (cb)
10857 req.on('response', cb)
10858 return req
10859}
10860
10861http.get = function get (opts, cb) {
10862 var req = http.request(opts, cb)
10863 req.end()
10864 return req
10865}
10866
10867http.ClientRequest = ClientRequest
10868http.IncomingMessage = response.IncomingMessage
10869
10870http.Agent = function () {}
10871http.Agent.defaultMaxSockets = 4
10872
10873http.globalAgent = new http.Agent()
10874
10875http.STATUS_CODES = statusCodes
10876
10877http.METHODS = [
10878 'CHECKOUT',
10879 'CONNECT',
10880 'COPY',
10881 'DELETE',
10882 'GET',
10883 'HEAD',
10884 'LOCK',
10885 'M-SEARCH',
10886 'MERGE',
10887 'MKACTIVITY',
10888 'MKCOL',
10889 'MOVE',
10890 'NOTIFY',
10891 'OPTIONS',
10892 'PATCH',
10893 'POST',
10894 'PROPFIND',
10895 'PROPPATCH',
10896 'PURGE',
10897 'PUT',
10898 'REPORT',
10899 'SEARCH',
10900 'SUBSCRIBE',
10901 'TRACE',
10902 'UNLOCK',
10903 'UNSUBSCRIBE'
10904]
10905}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10906
10907},{"./lib/request":72,"./lib/response":73,"builtin-status-codes":23,"url":87,"xtend":90}],71:[function(require,module,exports){
10908(function (global){
10909exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
10910
10911exports.writableStream = isFunction(global.WritableStream)
10912
10913exports.abortController = isFunction(global.AbortController)
10914
10915exports.blobConstructor = false
10916try {
10917 new Blob([new ArrayBuffer(1)])
10918 exports.blobConstructor = true
10919} catch (e) {}
10920
10921// The xhr request to example.com may violate some restrictive CSP configurations,
10922// so if we're running in a browser that supports `fetch`, avoid calling getXHR()
10923// and assume support for certain features below.
10924var xhr
10925function getXHR () {
10926 // Cache the xhr value
10927 if (xhr !== undefined) return xhr
10928
10929 if (global.XMLHttpRequest) {
10930 xhr = new global.XMLHttpRequest()
10931 // If XDomainRequest is available (ie only, where xhr might not work
10932 // cross domain), use the page location. Otherwise use example.com
10933 // Note: this doesn't actually make an http request.
10934 try {
10935 xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
10936 } catch(e) {
10937 xhr = null
10938 }
10939 } else {
10940 // Service workers don't have XHR
10941 xhr = null
10942 }
10943 return xhr
10944}
10945
10946function checkTypeSupport (type) {
10947 var xhr = getXHR()
10948 if (!xhr) return false
10949 try {
10950 xhr.responseType = type
10951 return xhr.responseType === type
10952 } catch (e) {}
10953 return false
10954}
10955
10956// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
10957// Safari 7.1 appears to have fixed this bug.
10958var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined'
10959var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice)
10960
10961// If fetch is supported, then arraybuffer will be supported too. Skip calling
10962// checkTypeSupport(), since that calls getXHR().
10963exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer'))
10964
10965// These next two tests unavoidably show warnings in Chrome. Since fetch will always
10966// be used if it's available, just return false for these to avoid the warnings.
10967exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream')
10968exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer &&
10969 checkTypeSupport('moz-chunked-arraybuffer')
10970
10971// If fetch is supported, then overrideMimeType will be supported too. Skip calling
10972// getXHR().
10973exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
10974
10975exports.vbArray = isFunction(global.VBArray)
10976
10977function isFunction (value) {
10978 return typeof value === 'function'
10979}
10980
10981xhr = null // Help gc
10982
10983}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10984
10985},{}],72:[function(require,module,exports){
10986(function (process,global,Buffer){
10987var capability = require('./capability')
10988var inherits = require('inherits')
10989var response = require('./response')
10990var stream = require('readable-stream')
10991var toArrayBuffer = require('to-arraybuffer')
10992
10993var IncomingMessage = response.IncomingMessage
10994var rStates = response.readyStates
10995
10996function decideMode (preferBinary, useFetch) {
10997 if (capability.fetch && useFetch) {
10998 return 'fetch'
10999 } else if (capability.mozchunkedarraybuffer) {
11000 return 'moz-chunked-arraybuffer'
11001 } else if (capability.msstream) {
11002 return 'ms-stream'
11003 } else if (capability.arraybuffer && preferBinary) {
11004 return 'arraybuffer'
11005 } else if (capability.vbArray && preferBinary) {
11006 return 'text:vbarray'
11007 } else {
11008 return 'text'
11009 }
11010}
11011
11012var ClientRequest = module.exports = function (opts) {
11013 var self = this
11014 stream.Writable.call(self)
11015
11016 self._opts = opts
11017 self._body = []
11018 self._headers = {}
11019 if (opts.auth)
11020 self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
11021 Object.keys(opts.headers).forEach(function (name) {
11022 self.setHeader(name, opts.headers[name])
11023 })
11024
11025 var preferBinary
11026 var useFetch = true
11027 if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
11028 // If the use of XHR should be preferred. Not typically needed.
11029 useFetch = false
11030 preferBinary = true
11031 } else if (opts.mode === 'prefer-streaming') {
11032 // If streaming is a high priority but binary compatibility and
11033 // the accuracy of the 'content-type' header aren't
11034 preferBinary = false
11035 } else if (opts.mode === 'allow-wrong-content-type') {
11036 // If streaming is more important than preserving the 'content-type' header
11037 preferBinary = !capability.overrideMimeType
11038 } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
11039 // Use binary if text streaming may corrupt data or the content-type header, or for speed
11040 preferBinary = true
11041 } else {
11042 throw new Error('Invalid value for opts.mode')
11043 }
11044 self._mode = decideMode(preferBinary, useFetch)
11045 self._fetchTimer = null
11046
11047 self.on('finish', function () {
11048 self._onFinish()
11049 })
11050}
11051
11052inherits(ClientRequest, stream.Writable)
11053
11054ClientRequest.prototype.setHeader = function (name, value) {
11055 var self = this
11056 var lowerName = name.toLowerCase()
11057 // This check is not necessary, but it prevents warnings from browsers about setting unsafe
11058 // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
11059 // http-browserify did it, so I will too.
11060 if (unsafeHeaders.indexOf(lowerName) !== -1)
11061 return
11062
11063 self._headers[lowerName] = {
11064 name: name,
11065 value: value
11066 }
11067}
11068
11069ClientRequest.prototype.getHeader = function (name) {
11070 var header = this._headers[name.toLowerCase()]
11071 if (header)
11072 return header.value
11073 return null
11074}
11075
11076ClientRequest.prototype.removeHeader = function (name) {
11077 var self = this
11078 delete self._headers[name.toLowerCase()]
11079}
11080
11081ClientRequest.prototype._onFinish = function () {
11082 var self = this
11083
11084 if (self._destroyed)
11085 return
11086 var opts = self._opts
11087
11088 var headersObj = self._headers
11089 var body = null
11090 if (opts.method !== 'GET' && opts.method !== 'HEAD') {
11091 if (capability.arraybuffer) {
11092 body = toArrayBuffer(Buffer.concat(self._body))
11093 } else if (capability.blobConstructor) {
11094 body = new global.Blob(self._body.map(function (buffer) {
11095 return toArrayBuffer(buffer)
11096 }), {
11097 type: (headersObj['content-type'] || {}).value || ''
11098 })
11099 } else {
11100 // get utf8 string
11101 body = Buffer.concat(self._body).toString()
11102 }
11103 }
11104
11105 // create flattened list of headers
11106 var headersList = []
11107 Object.keys(headersObj).forEach(function (keyName) {
11108 var name = headersObj[keyName].name
11109 var value = headersObj[keyName].value
11110 if (Array.isArray(value)) {
11111 value.forEach(function (v) {
11112 headersList.push([name, v])
11113 })
11114 } else {
11115 headersList.push([name, value])
11116 }
11117 })
11118
11119 if (self._mode === 'fetch') {
11120 var signal = null
11121 var fetchTimer = null
11122 if (capability.abortController) {
11123 var controller = new AbortController()
11124 signal = controller.signal
11125 self._fetchAbortController = controller
11126
11127 if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
11128 self._fetchTimer = global.setTimeout(function () {
11129 self.emit('requestTimeout')
11130 if (self._fetchAbortController)
11131 self._fetchAbortController.abort()
11132 }, opts.requestTimeout)
11133 }
11134 }
11135
11136 global.fetch(self._opts.url, {
11137 method: self._opts.method,
11138 headers: headersList,
11139 body: body || undefined,
11140 mode: 'cors',
11141 credentials: opts.withCredentials ? 'include' : 'same-origin',
11142 signal: signal
11143 }).then(function (response) {
11144 self._fetchResponse = response
11145 self._connect()
11146 }, function (reason) {
11147 global.clearTimeout(self._fetchTimer)
11148 if (!self._destroyed)
11149 self.emit('error', reason)
11150 })
11151 } else {
11152 var xhr = self._xhr = new global.XMLHttpRequest()
11153 try {
11154 xhr.open(self._opts.method, self._opts.url, true)
11155 } catch (err) {
11156 process.nextTick(function () {
11157 self.emit('error', err)
11158 })
11159 return
11160 }
11161
11162 // Can't set responseType on really old browsers
11163 if ('responseType' in xhr)
11164 xhr.responseType = self._mode.split(':')[0]
11165
11166 if ('withCredentials' in xhr)
11167 xhr.withCredentials = !!opts.withCredentials
11168
11169 if (self._mode === 'text' && 'overrideMimeType' in xhr)
11170 xhr.overrideMimeType('text/plain; charset=x-user-defined')
11171
11172 if ('requestTimeout' in opts) {
11173 xhr.timeout = opts.requestTimeout
11174 xhr.ontimeout = function () {
11175 self.emit('requestTimeout')
11176 }
11177 }
11178
11179 headersList.forEach(function (header) {
11180 xhr.setRequestHeader(header[0], header[1])
11181 })
11182
11183 self._response = null
11184 xhr.onreadystatechange = function () {
11185 switch (xhr.readyState) {
11186 case rStates.LOADING:
11187 case rStates.DONE:
11188 self._onXHRProgress()
11189 break
11190 }
11191 }
11192 // Necessary for streaming in Firefox, since xhr.response is ONLY defined
11193 // in onprogress, not in onreadystatechange with xhr.readyState = 3
11194 if (self._mode === 'moz-chunked-arraybuffer') {
11195 xhr.onprogress = function () {
11196 self._onXHRProgress()
11197 }
11198 }
11199
11200 xhr.onerror = function () {
11201 if (self._destroyed)
11202 return
11203 self.emit('error', new Error('XHR error'))
11204 }
11205
11206 try {
11207 xhr.send(body)
11208 } catch (err) {
11209 process.nextTick(function () {
11210 self.emit('error', err)
11211 })
11212 return
11213 }
11214 }
11215}
11216
11217/**
11218 * Checks if xhr.status is readable and non-zero, indicating no error.
11219 * Even though the spec says it should be available in readyState 3,
11220 * accessing it throws an exception in IE8
11221 */
11222function statusValid (xhr) {
11223 try {
11224 var status = xhr.status
11225 return (status !== null && status !== 0)
11226 } catch (e) {
11227 return false
11228 }
11229}
11230
11231ClientRequest.prototype._onXHRProgress = function () {
11232 var self = this
11233
11234 if (!statusValid(self._xhr) || self._destroyed)
11235 return
11236
11237 if (!self._response)
11238 self._connect()
11239
11240 self._response._onXHRProgress()
11241}
11242
11243ClientRequest.prototype._connect = function () {
11244 var self = this
11245
11246 if (self._destroyed)
11247 return
11248
11249 self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer)
11250 self._response.on('error', function(err) {
11251 self.emit('error', err)
11252 })
11253
11254 self.emit('response', self._response)
11255}
11256
11257ClientRequest.prototype._write = function (chunk, encoding, cb) {
11258 var self = this
11259
11260 self._body.push(chunk)
11261 cb()
11262}
11263
11264ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
11265 var self = this
11266 self._destroyed = true
11267 global.clearTimeout(self._fetchTimer)
11268 if (self._response)
11269 self._response._destroyed = true
11270 if (self._xhr)
11271 self._xhr.abort()
11272 else if (self._fetchAbortController)
11273 self._fetchAbortController.abort()
11274}
11275
11276ClientRequest.prototype.end = function (data, encoding, cb) {
11277 var self = this
11278 if (typeof data === 'function') {
11279 cb = data
11280 data = undefined
11281 }
11282
11283 stream.Writable.prototype.end.call(self, data, encoding, cb)
11284}
11285
11286ClientRequest.prototype.flushHeaders = function () {}
11287ClientRequest.prototype.setTimeout = function () {}
11288ClientRequest.prototype.setNoDelay = function () {}
11289ClientRequest.prototype.setSocketKeepAlive = function () {}
11290
11291// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
11292var unsafeHeaders = [
11293 'accept-charset',
11294 'accept-encoding',
11295 'access-control-request-headers',
11296 'access-control-request-method',
11297 'connection',
11298 'content-length',
11299 'cookie',
11300 'cookie2',
11301 'date',
11302 'dnt',
11303 'expect',
11304 'host',
11305 'keep-alive',
11306 'origin',
11307 'referer',
11308 'te',
11309 'trailer',
11310 'transfer-encoding',
11311 'upgrade',
11312 'via'
11313]
11314
11315}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
11316
11317},{"./capability":71,"./response":73,"_process":64,"buffer":22,"inherits":30,"readable-stream":83,"to-arraybuffer":86}],73:[function(require,module,exports){
11318(function (process,global,Buffer){
11319var capability = require('./capability')
11320var inherits = require('inherits')
11321var stream = require('readable-stream')
11322
11323var rStates = exports.readyStates = {
11324 UNSENT: 0,
11325 OPENED: 1,
11326 HEADERS_RECEIVED: 2,
11327 LOADING: 3,
11328 DONE: 4
11329}
11330
11331var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {
11332 var self = this
11333 stream.Readable.call(self)
11334
11335 self._mode = mode
11336 self.headers = {}
11337 self.rawHeaders = []
11338 self.trailers = {}
11339 self.rawTrailers = []
11340
11341 // Fake the 'close' event, but only once 'end' fires
11342 self.on('end', function () {
11343 // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
11344 process.nextTick(function () {
11345 self.emit('close')
11346 })
11347 })
11348
11349 if (mode === 'fetch') {
11350 self._fetchResponse = response
11351
11352 self.url = response.url
11353 self.statusCode = response.status
11354 self.statusMessage = response.statusText
11355
11356 response.headers.forEach(function (header, key){
11357 self.headers[key.toLowerCase()] = header
11358 self.rawHeaders.push(key, header)
11359 })
11360
11361 if (capability.writableStream) {
11362 var writable = new WritableStream({
11363 write: function (chunk) {
11364 return new Promise(function (resolve, reject) {
11365 if (self._destroyed) {
11366 reject()
11367 } else if(self.push(new Buffer(chunk))) {
11368 resolve()
11369 } else {
11370 self._resumeFetch = resolve
11371 }
11372 })
11373 },
11374 close: function () {
11375 global.clearTimeout(fetchTimer)
11376 if (!self._destroyed)
11377 self.push(null)
11378 },
11379 abort: function (err) {
11380 if (!self._destroyed)
11381 self.emit('error', err)
11382 }
11383 })
11384
11385 try {
11386 response.body.pipeTo(writable).catch(function (err) {
11387 global.clearTimeout(fetchTimer)
11388 if (!self._destroyed)
11389 self.emit('error', err)
11390 })
11391 return
11392 } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
11393 }
11394 // fallback for when writableStream or pipeTo aren't available
11395 var reader = response.body.getReader()
11396 function read () {
11397 reader.read().then(function (result) {
11398 if (self._destroyed)
11399 return
11400 if (result.done) {
11401 global.clearTimeout(fetchTimer)
11402 self.push(null)
11403 return
11404 }
11405 self.push(new Buffer(result.value))
11406 read()
11407 }).catch(function (err) {
11408 global.clearTimeout(fetchTimer)
11409 if (!self._destroyed)
11410 self.emit('error', err)
11411 })
11412 }
11413 read()
11414 } else {
11415 self._xhr = xhr
11416 self._pos = 0
11417
11418 self.url = xhr.responseURL
11419 self.statusCode = xhr.status
11420 self.statusMessage = xhr.statusText
11421 var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
11422 headers.forEach(function (header) {
11423 var matches = header.match(/^([^:]+):\s*(.*)/)
11424 if (matches) {
11425 var key = matches[1].toLowerCase()
11426 if (key === 'set-cookie') {
11427 if (self.headers[key] === undefined) {
11428 self.headers[key] = []
11429 }
11430 self.headers[key].push(matches[2])
11431 } else if (self.headers[key] !== undefined) {
11432 self.headers[key] += ', ' + matches[2]
11433 } else {
11434 self.headers[key] = matches[2]
11435 }
11436 self.rawHeaders.push(matches[1], matches[2])
11437 }
11438 })
11439
11440 self._charset = 'x-user-defined'
11441 if (!capability.overrideMimeType) {
11442 var mimeType = self.rawHeaders['mime-type']
11443 if (mimeType) {
11444 var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
11445 if (charsetMatch) {
11446 self._charset = charsetMatch[1].toLowerCase()
11447 }
11448 }
11449 if (!self._charset)
11450 self._charset = 'utf-8' // best guess
11451 }
11452 }
11453}
11454
11455inherits(IncomingMessage, stream.Readable)
11456
11457IncomingMessage.prototype._read = function () {
11458 var self = this
11459
11460 var resolve = self._resumeFetch
11461 if (resolve) {
11462 self._resumeFetch = null
11463 resolve()
11464 }
11465}
11466
11467IncomingMessage.prototype._onXHRProgress = function () {
11468 var self = this
11469
11470 var xhr = self._xhr
11471
11472 var response = null
11473 switch (self._mode) {
11474 case 'text:vbarray': // For IE9
11475 if (xhr.readyState !== rStates.DONE)
11476 break
11477 try {
11478 // This fails in IE8
11479 response = new global.VBArray(xhr.responseBody).toArray()
11480 } catch (e) {}
11481 if (response !== null) {
11482 self.push(new Buffer(response))
11483 break
11484 }
11485 // Falls through in IE8
11486 case 'text':
11487 try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
11488 response = xhr.responseText
11489 } catch (e) {
11490 self._mode = 'text:vbarray'
11491 break
11492 }
11493 if (response.length > self._pos) {
11494 var newData = response.substr(self._pos)
11495 if (self._charset === 'x-user-defined') {
11496 var buffer = new Buffer(newData.length)
11497 for (var i = 0; i < newData.length; i++)
11498 buffer[i] = newData.charCodeAt(i) & 0xff
11499
11500 self.push(buffer)
11501 } else {
11502 self.push(newData, self._charset)
11503 }
11504 self._pos = response.length
11505 }
11506 break
11507 case 'arraybuffer':
11508 if (xhr.readyState !== rStates.DONE || !xhr.response)
11509 break
11510 response = xhr.response
11511 self.push(new Buffer(new Uint8Array(response)))
11512 break
11513 case 'moz-chunked-arraybuffer': // take whole
11514 response = xhr.response
11515 if (xhr.readyState !== rStates.LOADING || !response)
11516 break
11517 self.push(new Buffer(new Uint8Array(response)))
11518 break
11519 case 'ms-stream':
11520 response = xhr.response
11521 if (xhr.readyState !== rStates.LOADING)
11522 break
11523 var reader = new global.MSStreamReader()
11524 reader.onprogress = function () {
11525 if (reader.result.byteLength > self._pos) {
11526 self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))))
11527 self._pos = reader.result.byteLength
11528 }
11529 }
11530 reader.onload = function () {
11531 self.push(null)
11532 }
11533 // reader.onerror = ??? // TODO: this
11534 reader.readAsArrayBuffer(response)
11535 break
11536 }
11537
11538 // The ms-stream case handles end separately in reader.onload()
11539 if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
11540 self.push(null)
11541 }
11542}
11543
11544}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
11545
11546},{"./capability":71,"_process":64,"buffer":22,"inherits":30,"readable-stream":83}],74:[function(require,module,exports){
11547(function (process){
11548'use strict';
11549
11550if (!process.version ||
11551 process.version.indexOf('v0.') === 0 ||
11552 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
11553 module.exports = { nextTick: nextTick };
11554} else {
11555 module.exports = process
11556}
11557
11558function nextTick(fn, arg1, arg2, arg3) {
11559 if (typeof fn !== 'function') {
11560 throw new TypeError('"callback" argument must be a function');
11561 }
11562 var len = arguments.length;
11563 var args, i;
11564 switch (len) {
11565 case 0:
11566 case 1:
11567 return process.nextTick(fn);
11568 case 2:
11569 return process.nextTick(function afterTickOne() {
11570 fn.call(null, arg1);
11571 });
11572 case 3:
11573 return process.nextTick(function afterTickTwo() {
11574 fn.call(null, arg1, arg2);
11575 });
11576 case 4:
11577 return process.nextTick(function afterTickThree() {
11578 fn.call(null, arg1, arg2, arg3);
11579 });
11580 default:
11581 args = new Array(len - 1);
11582 i = 0;
11583 while (i < args.length) {
11584 args[i++] = arguments[i];
11585 }
11586 return process.nextTick(function afterTick() {
11587 fn.apply(null, args);
11588 });
11589 }
11590}
11591
11592
11593}).call(this,require('_process'))
11594
11595},{"_process":64}],75:[function(require,module,exports){
11596// Copyright Joyent, Inc. and other Node contributors.
11597//
11598// Permission is hereby granted, free of charge, to any person obtaining a
11599// copy of this software and associated documentation files (the
11600// "Software"), to deal in the Software without restriction, including
11601// without limitation the rights to use, copy, modify, merge, publish,
11602// distribute, sublicense, and/or sell copies of the Software, and to permit
11603// persons to whom the Software is furnished to do so, subject to the
11604// following conditions:
11605//
11606// The above copyright notice and this permission notice shall be included
11607// in all copies or substantial portions of the Software.
11608//
11609// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11610// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11611// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11612// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11613// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11614// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11615// USE OR OTHER DEALINGS IN THE SOFTWARE.
11616
11617// a duplex stream is just a stream that is both readable and writable.
11618// Since JS doesn't have multiple prototypal inheritance, this class
11619// prototypally inherits from Readable, and then parasitically from
11620// Writable.
11621
11622'use strict';
11623
11624/*<replacement>*/
11625
11626var pna = require('process-nextick-args');
11627/*</replacement>*/
11628
11629/*<replacement>*/
11630var objectKeys = Object.keys || function (obj) {
11631 var keys = [];
11632 for (var key in obj) {
11633 keys.push(key);
11634 }return keys;
11635};
11636/*</replacement>*/
11637
11638module.exports = Duplex;
11639
11640/*<replacement>*/
11641var util = require('core-util-is');
11642util.inherits = require('inherits');
11643/*</replacement>*/
11644
11645var Readable = require('./_stream_readable');
11646var Writable = require('./_stream_writable');
11647
11648util.inherits(Duplex, Readable);
11649
11650{
11651 // avoid scope creep, the keys array can then be collected
11652 var keys = objectKeys(Writable.prototype);
11653 for (var v = 0; v < keys.length; v++) {
11654 var method = keys[v];
11655 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
11656 }
11657}
11658
11659function Duplex(options) {
11660 if (!(this instanceof Duplex)) return new Duplex(options);
11661
11662 Readable.call(this, options);
11663 Writable.call(this, options);
11664
11665 if (options && options.readable === false) this.readable = false;
11666
11667 if (options && options.writable === false) this.writable = false;
11668
11669 this.allowHalfOpen = true;
11670 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
11671
11672 this.once('end', onend);
11673}
11674
11675Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
11676 // making it explicit this property is not enumerable
11677 // because otherwise some prototype manipulation in
11678 // userland will fail
11679 enumerable: false,
11680 get: function () {
11681 return this._writableState.highWaterMark;
11682 }
11683});
11684
11685// the no-half-open enforcer
11686function onend() {
11687 // if we allow half-open state, or if the writable side ended,
11688 // then we're ok.
11689 if (this.allowHalfOpen || this._writableState.ended) return;
11690
11691 // no more data can be written.
11692 // But allow more writes to happen in this tick.
11693 pna.nextTick(onEndNT, this);
11694}
11695
11696function onEndNT(self) {
11697 self.end();
11698}
11699
11700Object.defineProperty(Duplex.prototype, 'destroyed', {
11701 get: function () {
11702 if (this._readableState === undefined || this._writableState === undefined) {
11703 return false;
11704 }
11705 return this._readableState.destroyed && this._writableState.destroyed;
11706 },
11707 set: function (value) {
11708 // we ignore the value if the stream
11709 // has not been initialized yet
11710 if (this._readableState === undefined || this._writableState === undefined) {
11711 return;
11712 }
11713
11714 // backward compatibility, the user is explicitly
11715 // managing destroyed
11716 this._readableState.destroyed = value;
11717 this._writableState.destroyed = value;
11718 }
11719});
11720
11721Duplex.prototype._destroy = function (err, cb) {
11722 this.push(null);
11723 this.end();
11724
11725 pna.nextTick(cb, err);
11726};
11727},{"./_stream_readable":77,"./_stream_writable":79,"core-util-is":25,"inherits":30,"process-nextick-args":74}],76:[function(require,module,exports){
11728// Copyright Joyent, Inc. and other Node contributors.
11729//
11730// Permission is hereby granted, free of charge, to any person obtaining a
11731// copy of this software and associated documentation files (the
11732// "Software"), to deal in the Software without restriction, including
11733// without limitation the rights to use, copy, modify, merge, publish,
11734// distribute, sublicense, and/or sell copies of the Software, and to permit
11735// persons to whom the Software is furnished to do so, subject to the
11736// following conditions:
11737//
11738// The above copyright notice and this permission notice shall be included
11739// in all copies or substantial portions of the Software.
11740//
11741// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11742// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11743// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11744// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11745// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11746// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11747// USE OR OTHER DEALINGS IN THE SOFTWARE.
11748
11749// a passthrough stream.
11750// basically just the most minimal sort of Transform stream.
11751// Every written chunk gets output as-is.
11752
11753'use strict';
11754
11755module.exports = PassThrough;
11756
11757var Transform = require('./_stream_transform');
11758
11759/*<replacement>*/
11760var util = require('core-util-is');
11761util.inherits = require('inherits');
11762/*</replacement>*/
11763
11764util.inherits(PassThrough, Transform);
11765
11766function PassThrough(options) {
11767 if (!(this instanceof PassThrough)) return new PassThrough(options);
11768
11769 Transform.call(this, options);
11770}
11771
11772PassThrough.prototype._transform = function (chunk, encoding, cb) {
11773 cb(null, chunk);
11774};
11775},{"./_stream_transform":78,"core-util-is":25,"inherits":30}],77:[function(require,module,exports){
11776(function (process,global){
11777// Copyright Joyent, Inc. and other Node contributors.
11778//
11779// Permission is hereby granted, free of charge, to any person obtaining a
11780// copy of this software and associated documentation files (the
11781// "Software"), to deal in the Software without restriction, including
11782// without limitation the rights to use, copy, modify, merge, publish,
11783// distribute, sublicense, and/or sell copies of the Software, and to permit
11784// persons to whom the Software is furnished to do so, subject to the
11785// following conditions:
11786//
11787// The above copyright notice and this permission notice shall be included
11788// in all copies or substantial portions of the Software.
11789//
11790// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11791// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11792// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11793// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11794// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11795// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11796// USE OR OTHER DEALINGS IN THE SOFTWARE.
11797
11798'use strict';
11799
11800/*<replacement>*/
11801
11802var pna = require('process-nextick-args');
11803/*</replacement>*/
11804
11805module.exports = Readable;
11806
11807/*<replacement>*/
11808var isArray = require('isarray');
11809/*</replacement>*/
11810
11811/*<replacement>*/
11812var Duplex;
11813/*</replacement>*/
11814
11815Readable.ReadableState = ReadableState;
11816
11817/*<replacement>*/
11818var EE = require('events').EventEmitter;
11819
11820var EElistenerCount = function (emitter, type) {
11821 return emitter.listeners(type).length;
11822};
11823/*</replacement>*/
11824
11825/*<replacement>*/
11826var Stream = require('./internal/streams/stream');
11827/*</replacement>*/
11828
11829/*<replacement>*/
11830
11831var Buffer = require('safe-buffer').Buffer;
11832var OurUint8Array = global.Uint8Array || function () {};
11833function _uint8ArrayToBuffer(chunk) {
11834 return Buffer.from(chunk);
11835}
11836function _isUint8Array(obj) {
11837 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
11838}
11839
11840/*</replacement>*/
11841
11842/*<replacement>*/
11843var util = require('core-util-is');
11844util.inherits = require('inherits');
11845/*</replacement>*/
11846
11847/*<replacement>*/
11848var debugUtil = require('util');
11849var debug = void 0;
11850if (debugUtil && debugUtil.debuglog) {
11851 debug = debugUtil.debuglog('stream');
11852} else {
11853 debug = function () {};
11854}
11855/*</replacement>*/
11856
11857var BufferList = require('./internal/streams/BufferList');
11858var destroyImpl = require('./internal/streams/destroy');
11859var StringDecoder;
11860
11861util.inherits(Readable, Stream);
11862
11863var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
11864
11865function prependListener(emitter, event, fn) {
11866 // Sadly this is not cacheable as some libraries bundle their own
11867 // event emitter implementation with them.
11868 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
11869
11870 // This is a hack to make sure that our error handler is attached before any
11871 // userland ones. NEVER DO THIS. This is here only because this code needs
11872 // to continue to work with older versions of Node.js that do not include
11873 // the prependListener() method. The goal is to eventually remove this hack.
11874 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
11875}
11876
11877function ReadableState(options, stream) {
11878 Duplex = Duplex || require('./_stream_duplex');
11879
11880 options = options || {};
11881
11882 // Duplex streams are both readable and writable, but share
11883 // the same options object.
11884 // However, some cases require setting options to different
11885 // values for the readable and the writable sides of the duplex stream.
11886 // These options can be provided separately as readableXXX and writableXXX.
11887 var isDuplex = stream instanceof Duplex;
11888
11889 // object stream flag. Used to make read(n) ignore n and to
11890 // make all the buffer merging and length checks go away
11891 this.objectMode = !!options.objectMode;
11892
11893 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
11894
11895 // the point at which it stops calling _read() to fill the buffer
11896 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11897 var hwm = options.highWaterMark;
11898 var readableHwm = options.readableHighWaterMark;
11899 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
11900
11901 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
11902
11903 // cast to ints.
11904 this.highWaterMark = Math.floor(this.highWaterMark);
11905
11906 // A linked list is used to store data chunks instead of an array because the
11907 // linked list can remove elements from the beginning faster than
11908 // array.shift()
11909 this.buffer = new BufferList();
11910 this.length = 0;
11911 this.pipes = null;
11912 this.pipesCount = 0;
11913 this.flowing = null;
11914 this.ended = false;
11915 this.endEmitted = false;
11916 this.reading = false;
11917
11918 // a flag to be able to tell if the event 'readable'/'data' is emitted
11919 // immediately, or on a later tick. We set this to true at first, because
11920 // any actions that shouldn't happen until "later" should generally also
11921 // not happen before the first read call.
11922 this.sync = true;
11923
11924 // whenever we return null, then we set a flag to say
11925 // that we're awaiting a 'readable' event emission.
11926 this.needReadable = false;
11927 this.emittedReadable = false;
11928 this.readableListening = false;
11929 this.resumeScheduled = false;
11930
11931 // has it been destroyed
11932 this.destroyed = false;
11933
11934 // Crypto is kind of old and crusty. Historically, its default string
11935 // encoding is 'binary' so we have to make this configurable.
11936 // Everything else in the universe uses 'utf8', though.
11937 this.defaultEncoding = options.defaultEncoding || 'utf8';
11938
11939 // the number of writers that are awaiting a drain event in .pipe()s
11940 this.awaitDrain = 0;
11941
11942 // if true, a maybeReadMore has been scheduled
11943 this.readingMore = false;
11944
11945 this.decoder = null;
11946 this.encoding = null;
11947 if (options.encoding) {
11948 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
11949 this.decoder = new StringDecoder(options.encoding);
11950 this.encoding = options.encoding;
11951 }
11952}
11953
11954function Readable(options) {
11955 Duplex = Duplex || require('./_stream_duplex');
11956
11957 if (!(this instanceof Readable)) return new Readable(options);
11958
11959 this._readableState = new ReadableState(options, this);
11960
11961 // legacy
11962 this.readable = true;
11963
11964 if (options) {
11965 if (typeof options.read === 'function') this._read = options.read;
11966
11967 if (typeof options.destroy === 'function') this._destroy = options.destroy;
11968 }
11969
11970 Stream.call(this);
11971}
11972
11973Object.defineProperty(Readable.prototype, 'destroyed', {
11974 get: function () {
11975 if (this._readableState === undefined) {
11976 return false;
11977 }
11978 return this._readableState.destroyed;
11979 },
11980 set: function (value) {
11981 // we ignore the value if the stream
11982 // has not been initialized yet
11983 if (!this._readableState) {
11984 return;
11985 }
11986
11987 // backward compatibility, the user is explicitly
11988 // managing destroyed
11989 this._readableState.destroyed = value;
11990 }
11991});
11992
11993Readable.prototype.destroy = destroyImpl.destroy;
11994Readable.prototype._undestroy = destroyImpl.undestroy;
11995Readable.prototype._destroy = function (err, cb) {
11996 this.push(null);
11997 cb(err);
11998};
11999
12000// Manually shove something into the read() buffer.
12001// This returns true if the highWaterMark has not been hit yet,
12002// similar to how Writable.write() returns true if you should
12003// write() some more.
12004Readable.prototype.push = function (chunk, encoding) {
12005 var state = this._readableState;
12006 var skipChunkCheck;
12007
12008 if (!state.objectMode) {
12009 if (typeof chunk === 'string') {
12010 encoding = encoding || state.defaultEncoding;
12011 if (encoding !== state.encoding) {
12012 chunk = Buffer.from(chunk, encoding);
12013 encoding = '';
12014 }
12015 skipChunkCheck = true;
12016 }
12017 } else {
12018 skipChunkCheck = true;
12019 }
12020
12021 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
12022};
12023
12024// Unshift should *always* be something directly out of read()
12025Readable.prototype.unshift = function (chunk) {
12026 return readableAddChunk(this, chunk, null, true, false);
12027};
12028
12029function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
12030 var state = stream._readableState;
12031 if (chunk === null) {
12032 state.reading = false;
12033 onEofChunk(stream, state);
12034 } else {
12035 var er;
12036 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
12037 if (er) {
12038 stream.emit('error', er);
12039 } else if (state.objectMode || chunk && chunk.length > 0) {
12040 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
12041 chunk = _uint8ArrayToBuffer(chunk);
12042 }
12043
12044 if (addToFront) {
12045 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
12046 } else if (state.ended) {
12047 stream.emit('error', new Error('stream.push() after EOF'));
12048 } else {
12049 state.reading = false;
12050 if (state.decoder && !encoding) {
12051 chunk = state.decoder.write(chunk);
12052 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
12053 } else {
12054 addChunk(stream, state, chunk, false);
12055 }
12056 }
12057 } else if (!addToFront) {
12058 state.reading = false;
12059 }
12060 }
12061
12062 return needMoreData(state);
12063}
12064
12065function addChunk(stream, state, chunk, addToFront) {
12066 if (state.flowing && state.length === 0 && !state.sync) {
12067 stream.emit('data', chunk);
12068 stream.read(0);
12069 } else {
12070 // update the buffer info.
12071 state.length += state.objectMode ? 1 : chunk.length;
12072 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
12073
12074 if (state.needReadable) emitReadable(stream);
12075 }
12076 maybeReadMore(stream, state);
12077}
12078
12079function chunkInvalid(state, chunk) {
12080 var er;
12081 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
12082 er = new TypeError('Invalid non-string/buffer chunk');
12083 }
12084 return er;
12085}
12086
12087// if it's past the high water mark, we can push in some more.
12088// Also, if we have no data yet, we can stand some
12089// more bytes. This is to work around cases where hwm=0,
12090// such as the repl. Also, if the push() triggered a
12091// readable event, and the user called read(largeNumber) such that
12092// needReadable was set, then we ought to push more, so that another
12093// 'readable' event will be triggered.
12094function needMoreData(state) {
12095 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
12096}
12097
12098Readable.prototype.isPaused = function () {
12099 return this._readableState.flowing === false;
12100};
12101
12102// backwards compatibility.
12103Readable.prototype.setEncoding = function (enc) {
12104 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
12105 this._readableState.decoder = new StringDecoder(enc);
12106 this._readableState.encoding = enc;
12107 return this;
12108};
12109
12110// Don't raise the hwm > 8MB
12111var MAX_HWM = 0x800000;
12112function computeNewHighWaterMark(n) {
12113 if (n >= MAX_HWM) {
12114 n = MAX_HWM;
12115 } else {
12116 // Get the next highest power of 2 to prevent increasing hwm excessively in
12117 // tiny amounts
12118 n--;
12119 n |= n >>> 1;
12120 n |= n >>> 2;
12121 n |= n >>> 4;
12122 n |= n >>> 8;
12123 n |= n >>> 16;
12124 n++;
12125 }
12126 return n;
12127}
12128
12129// This function is designed to be inlinable, so please take care when making
12130// changes to the function body.
12131function howMuchToRead(n, state) {
12132 if (n <= 0 || state.length === 0 && state.ended) return 0;
12133 if (state.objectMode) return 1;
12134 if (n !== n) {
12135 // Only flow one buffer at a time
12136 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
12137 }
12138 // If we're asking for more than the current hwm, then raise the hwm.
12139 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
12140 if (n <= state.length) return n;
12141 // Don't have enough
12142 if (!state.ended) {
12143 state.needReadable = true;
12144 return 0;
12145 }
12146 return state.length;
12147}
12148
12149// you can override either this method, or the async _read(n) below.
12150Readable.prototype.read = function (n) {
12151 debug('read', n);
12152 n = parseInt(n, 10);
12153 var state = this._readableState;
12154 var nOrig = n;
12155
12156 if (n !== 0) state.emittedReadable = false;
12157
12158 // if we're doing read(0) to trigger a readable event, but we
12159 // already have a bunch of data in the buffer, then just trigger
12160 // the 'readable' event and move on.
12161 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
12162 debug('read: emitReadable', state.length, state.ended);
12163 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
12164 return null;
12165 }
12166
12167 n = howMuchToRead(n, state);
12168
12169 // if we've ended, and we're now clear, then finish it up.
12170 if (n === 0 && state.ended) {
12171 if (state.length === 0) endReadable(this);
12172 return null;
12173 }
12174
12175 // All the actual chunk generation logic needs to be
12176 // *below* the call to _read. The reason is that in certain
12177 // synthetic stream cases, such as passthrough streams, _read
12178 // may be a completely synchronous operation which may change
12179 // the state of the read buffer, providing enough data when
12180 // before there was *not* enough.
12181 //
12182 // So, the steps are:
12183 // 1. Figure out what the state of things will be after we do
12184 // a read from the buffer.
12185 //
12186 // 2. If that resulting state will trigger a _read, then call _read.
12187 // Note that this may be asynchronous, or synchronous. Yes, it is
12188 // deeply ugly to write APIs this way, but that still doesn't mean
12189 // that the Readable class should behave improperly, as streams are
12190 // designed to be sync/async agnostic.
12191 // Take note if the _read call is sync or async (ie, if the read call
12192 // has returned yet), so that we know whether or not it's safe to emit
12193 // 'readable' etc.
12194 //
12195 // 3. Actually pull the requested chunks out of the buffer and return.
12196
12197 // if we need a readable event, then we need to do some reading.
12198 var doRead = state.needReadable;
12199 debug('need readable', doRead);
12200
12201 // if we currently have less than the highWaterMark, then also read some
12202 if (state.length === 0 || state.length - n < state.highWaterMark) {
12203 doRead = true;
12204 debug('length less than watermark', doRead);
12205 }
12206
12207 // however, if we've ended, then there's no point, and if we're already
12208 // reading, then it's unnecessary.
12209 if (state.ended || state.reading) {
12210 doRead = false;
12211 debug('reading or ended', doRead);
12212 } else if (doRead) {
12213 debug('do read');
12214 state.reading = true;
12215 state.sync = true;
12216 // if the length is currently zero, then we *need* a readable event.
12217 if (state.length === 0) state.needReadable = true;
12218 // call internal read method
12219 this._read(state.highWaterMark);
12220 state.sync = false;
12221 // If _read pushed data synchronously, then `reading` will be false,
12222 // and we need to re-evaluate how much data we can return to the user.
12223 if (!state.reading) n = howMuchToRead(nOrig, state);
12224 }
12225
12226 var ret;
12227 if (n > 0) ret = fromList(n, state);else ret = null;
12228
12229 if (ret === null) {
12230 state.needReadable = true;
12231 n = 0;
12232 } else {
12233 state.length -= n;
12234 }
12235
12236 if (state.length === 0) {
12237 // If we have nothing in the buffer, then we want to know
12238 // as soon as we *do* get something into the buffer.
12239 if (!state.ended) state.needReadable = true;
12240
12241 // If we tried to read() past the EOF, then emit end on the next tick.
12242 if (nOrig !== n && state.ended) endReadable(this);
12243 }
12244
12245 if (ret !== null) this.emit('data', ret);
12246
12247 return ret;
12248};
12249
12250function onEofChunk(stream, state) {
12251 if (state.ended) return;
12252 if (state.decoder) {
12253 var chunk = state.decoder.end();
12254 if (chunk && chunk.length) {
12255 state.buffer.push(chunk);
12256 state.length += state.objectMode ? 1 : chunk.length;
12257 }
12258 }
12259 state.ended = true;
12260
12261 // emit 'readable' now to make sure it gets picked up.
12262 emitReadable(stream);
12263}
12264
12265// Don't emit readable right away in sync mode, because this can trigger
12266// another read() call => stack overflow. This way, it might trigger
12267// a nextTick recursion warning, but that's not so bad.
12268function emitReadable(stream) {
12269 var state = stream._readableState;
12270 state.needReadable = false;
12271 if (!state.emittedReadable) {
12272 debug('emitReadable', state.flowing);
12273 state.emittedReadable = true;
12274 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
12275 }
12276}
12277
12278function emitReadable_(stream) {
12279 debug('emit readable');
12280 stream.emit('readable');
12281 flow(stream);
12282}
12283
12284// at this point, the user has presumably seen the 'readable' event,
12285// and called read() to consume some data. that may have triggered
12286// in turn another _read(n) call, in which case reading = true if
12287// it's in progress.
12288// However, if we're not ended, or reading, and the length < hwm,
12289// then go ahead and try to read some more preemptively.
12290function maybeReadMore(stream, state) {
12291 if (!state.readingMore) {
12292 state.readingMore = true;
12293 pna.nextTick(maybeReadMore_, stream, state);
12294 }
12295}
12296
12297function maybeReadMore_(stream, state) {
12298 var len = state.length;
12299 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
12300 debug('maybeReadMore read 0');
12301 stream.read(0);
12302 if (len === state.length)
12303 // didn't get any data, stop spinning.
12304 break;else len = state.length;
12305 }
12306 state.readingMore = false;
12307}
12308
12309// abstract method. to be overridden in specific implementation classes.
12310// call cb(er, data) where data is <= n in length.
12311// for virtual (non-string, non-buffer) streams, "length" is somewhat
12312// arbitrary, and perhaps not very meaningful.
12313Readable.prototype._read = function (n) {
12314 this.emit('error', new Error('_read() is not implemented'));
12315};
12316
12317Readable.prototype.pipe = function (dest, pipeOpts) {
12318 var src = this;
12319 var state = this._readableState;
12320
12321 switch (state.pipesCount) {
12322 case 0:
12323 state.pipes = dest;
12324 break;
12325 case 1:
12326 state.pipes = [state.pipes, dest];
12327 break;
12328 default:
12329 state.pipes.push(dest);
12330 break;
12331 }
12332 state.pipesCount += 1;
12333 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
12334
12335 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
12336
12337 var endFn = doEnd ? onend : unpipe;
12338 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
12339
12340 dest.on('unpipe', onunpipe);
12341 function onunpipe(readable, unpipeInfo) {
12342 debug('onunpipe');
12343 if (readable === src) {
12344 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
12345 unpipeInfo.hasUnpiped = true;
12346 cleanup();
12347 }
12348 }
12349 }
12350
12351 function onend() {
12352 debug('onend');
12353 dest.end();
12354 }
12355
12356 // when the dest drains, it reduces the awaitDrain counter
12357 // on the source. This would be more elegant with a .once()
12358 // handler in flow(), but adding and removing repeatedly is
12359 // too slow.
12360 var ondrain = pipeOnDrain(src);
12361 dest.on('drain', ondrain);
12362
12363 var cleanedUp = false;
12364 function cleanup() {
12365 debug('cleanup');
12366 // cleanup event handlers once the pipe is broken
12367 dest.removeListener('close', onclose);
12368 dest.removeListener('finish', onfinish);
12369 dest.removeListener('drain', ondrain);
12370 dest.removeListener('error', onerror);
12371 dest.removeListener('unpipe', onunpipe);
12372 src.removeListener('end', onend);
12373 src.removeListener('end', unpipe);
12374 src.removeListener('data', ondata);
12375
12376 cleanedUp = true;
12377
12378 // if the reader is waiting for a drain event from this
12379 // specific writer, then it would cause it to never start
12380 // flowing again.
12381 // So, if this is awaiting a drain, then we just call it now.
12382 // If we don't know, then assume that we are waiting for one.
12383 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
12384 }
12385
12386 // If the user pushes more data while we're writing to dest then we'll end up
12387 // in ondata again. However, we only want to increase awaitDrain once because
12388 // dest will only emit one 'drain' event for the multiple writes.
12389 // => Introduce a guard on increasing awaitDrain.
12390 var increasedAwaitDrain = false;
12391 src.on('data', ondata);
12392 function ondata(chunk) {
12393 debug('ondata');
12394 increasedAwaitDrain = false;
12395 var ret = dest.write(chunk);
12396 if (false === ret && !increasedAwaitDrain) {
12397 // If the user unpiped during `dest.write()`, it is possible
12398 // to get stuck in a permanently paused state if that write
12399 // also returned false.
12400 // => Check whether `dest` is still a piping destination.
12401 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
12402 debug('false write response, pause', src._readableState.awaitDrain);
12403 src._readableState.awaitDrain++;
12404 increasedAwaitDrain = true;
12405 }
12406 src.pause();
12407 }
12408 }
12409
12410 // if the dest has an error, then stop piping into it.
12411 // however, don't suppress the throwing behavior for this.
12412 function onerror(er) {
12413 debug('onerror', er);
12414 unpipe();
12415 dest.removeListener('error', onerror);
12416 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
12417 }
12418
12419 // Make sure our error handler is attached before userland ones.
12420 prependListener(dest, 'error', onerror);
12421
12422 // Both close and finish should trigger unpipe, but only once.
12423 function onclose() {
12424 dest.removeListener('finish', onfinish);
12425 unpipe();
12426 }
12427 dest.once('close', onclose);
12428 function onfinish() {
12429 debug('onfinish');
12430 dest.removeListener('close', onclose);
12431 unpipe();
12432 }
12433 dest.once('finish', onfinish);
12434
12435 function unpipe() {
12436 debug('unpipe');
12437 src.unpipe(dest);
12438 }
12439
12440 // tell the dest that it's being piped to
12441 dest.emit('pipe', src);
12442
12443 // start the flow if it hasn't been started already.
12444 if (!state.flowing) {
12445 debug('pipe resume');
12446 src.resume();
12447 }
12448
12449 return dest;
12450};
12451
12452function pipeOnDrain(src) {
12453 return function () {
12454 var state = src._readableState;
12455 debug('pipeOnDrain', state.awaitDrain);
12456 if (state.awaitDrain) state.awaitDrain--;
12457 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
12458 state.flowing = true;
12459 flow(src);
12460 }
12461 };
12462}
12463
12464Readable.prototype.unpipe = function (dest) {
12465 var state = this._readableState;
12466 var unpipeInfo = { hasUnpiped: false };
12467
12468 // if we're not piping anywhere, then do nothing.
12469 if (state.pipesCount === 0) return this;
12470
12471 // just one destination. most common case.
12472 if (state.pipesCount === 1) {
12473 // passed in one, but it's not the right one.
12474 if (dest && dest !== state.pipes) return this;
12475
12476 if (!dest) dest = state.pipes;
12477
12478 // got a match.
12479 state.pipes = null;
12480 state.pipesCount = 0;
12481 state.flowing = false;
12482 if (dest) dest.emit('unpipe', this, unpipeInfo);
12483 return this;
12484 }
12485
12486 // slow case. multiple pipe destinations.
12487
12488 if (!dest) {
12489 // remove all.
12490 var dests = state.pipes;
12491 var len = state.pipesCount;
12492 state.pipes = null;
12493 state.pipesCount = 0;
12494 state.flowing = false;
12495
12496 for (var i = 0; i < len; i++) {
12497 dests[i].emit('unpipe', this, unpipeInfo);
12498 }return this;
12499 }
12500
12501 // try to find the right one.
12502 var index = indexOf(state.pipes, dest);
12503 if (index === -1) return this;
12504
12505 state.pipes.splice(index, 1);
12506 state.pipesCount -= 1;
12507 if (state.pipesCount === 1) state.pipes = state.pipes[0];
12508
12509 dest.emit('unpipe', this, unpipeInfo);
12510
12511 return this;
12512};
12513
12514// set up data events if they are asked for
12515// Ensure readable listeners eventually get something
12516Readable.prototype.on = function (ev, fn) {
12517 var res = Stream.prototype.on.call(this, ev, fn);
12518
12519 if (ev === 'data') {
12520 // Start flowing on next tick if stream isn't explicitly paused
12521 if (this._readableState.flowing !== false) this.resume();
12522 } else if (ev === 'readable') {
12523 var state = this._readableState;
12524 if (!state.endEmitted && !state.readableListening) {
12525 state.readableListening = state.needReadable = true;
12526 state.emittedReadable = false;
12527 if (!state.reading) {
12528 pna.nextTick(nReadingNextTick, this);
12529 } else if (state.length) {
12530 emitReadable(this);
12531 }
12532 }
12533 }
12534
12535 return res;
12536};
12537Readable.prototype.addListener = Readable.prototype.on;
12538
12539function nReadingNextTick(self) {
12540 debug('readable nexttick read 0');
12541 self.read(0);
12542}
12543
12544// pause() and resume() are remnants of the legacy readable stream API
12545// If the user uses them, then switch into old mode.
12546Readable.prototype.resume = function () {
12547 var state = this._readableState;
12548 if (!state.flowing) {
12549 debug('resume');
12550 state.flowing = true;
12551 resume(this, state);
12552 }
12553 return this;
12554};
12555
12556function resume(stream, state) {
12557 if (!state.resumeScheduled) {
12558 state.resumeScheduled = true;
12559 pna.nextTick(resume_, stream, state);
12560 }
12561}
12562
12563function resume_(stream, state) {
12564 if (!state.reading) {
12565 debug('resume read 0');
12566 stream.read(0);
12567 }
12568
12569 state.resumeScheduled = false;
12570 state.awaitDrain = 0;
12571 stream.emit('resume');
12572 flow(stream);
12573 if (state.flowing && !state.reading) stream.read(0);
12574}
12575
12576Readable.prototype.pause = function () {
12577 debug('call pause flowing=%j', this._readableState.flowing);
12578 if (false !== this._readableState.flowing) {
12579 debug('pause');
12580 this._readableState.flowing = false;
12581 this.emit('pause');
12582 }
12583 return this;
12584};
12585
12586function flow(stream) {
12587 var state = stream._readableState;
12588 debug('flow', state.flowing);
12589 while (state.flowing && stream.read() !== null) {}
12590}
12591
12592// wrap an old-style stream as the async data source.
12593// This is *not* part of the readable stream interface.
12594// It is an ugly unfortunate mess of history.
12595Readable.prototype.wrap = function (stream) {
12596 var _this = this;
12597
12598 var state = this._readableState;
12599 var paused = false;
12600
12601 stream.on('end', function () {
12602 debug('wrapped end');
12603 if (state.decoder && !state.ended) {
12604 var chunk = state.decoder.end();
12605 if (chunk && chunk.length) _this.push(chunk);
12606 }
12607
12608 _this.push(null);
12609 });
12610
12611 stream.on('data', function (chunk) {
12612 debug('wrapped data');
12613 if (state.decoder) chunk = state.decoder.write(chunk);
12614
12615 // don't skip over falsy values in objectMode
12616 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
12617
12618 var ret = _this.push(chunk);
12619 if (!ret) {
12620 paused = true;
12621 stream.pause();
12622 }
12623 });
12624
12625 // proxy all the other methods.
12626 // important when wrapping filters and duplexes.
12627 for (var i in stream) {
12628 if (this[i] === undefined && typeof stream[i] === 'function') {
12629 this[i] = function (method) {
12630 return function () {
12631 return stream[method].apply(stream, arguments);
12632 };
12633 }(i);
12634 }
12635 }
12636
12637 // proxy certain important events.
12638 for (var n = 0; n < kProxyEvents.length; n++) {
12639 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
12640 }
12641
12642 // when we try to consume some more bytes, simply unpause the
12643 // underlying stream.
12644 this._read = function (n) {
12645 debug('wrapped _read', n);
12646 if (paused) {
12647 paused = false;
12648 stream.resume();
12649 }
12650 };
12651
12652 return this;
12653};
12654
12655Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
12656 // making it explicit this property is not enumerable
12657 // because otherwise some prototype manipulation in
12658 // userland will fail
12659 enumerable: false,
12660 get: function () {
12661 return this._readableState.highWaterMark;
12662 }
12663});
12664
12665// exposed for testing purposes only.
12666Readable._fromList = fromList;
12667
12668// Pluck off n bytes from an array of buffers.
12669// Length is the combined lengths of all the buffers in the list.
12670// This function is designed to be inlinable, so please take care when making
12671// changes to the function body.
12672function fromList(n, state) {
12673 // nothing buffered
12674 if (state.length === 0) return null;
12675
12676 var ret;
12677 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
12678 // read it all, truncate the list
12679 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
12680 state.buffer.clear();
12681 } else {
12682 // read part of list
12683 ret = fromListPartial(n, state.buffer, state.decoder);
12684 }
12685
12686 return ret;
12687}
12688
12689// Extracts only enough buffered data to satisfy the amount requested.
12690// This function is designed to be inlinable, so please take care when making
12691// changes to the function body.
12692function fromListPartial(n, list, hasStrings) {
12693 var ret;
12694 if (n < list.head.data.length) {
12695 // slice is the same for buffers and strings
12696 ret = list.head.data.slice(0, n);
12697 list.head.data = list.head.data.slice(n);
12698 } else if (n === list.head.data.length) {
12699 // first chunk is a perfect match
12700 ret = list.shift();
12701 } else {
12702 // result spans more than one buffer
12703 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
12704 }
12705 return ret;
12706}
12707
12708// Copies a specified amount of characters from the list of buffered data
12709// chunks.
12710// This function is designed to be inlinable, so please take care when making
12711// changes to the function body.
12712function copyFromBufferString(n, list) {
12713 var p = list.head;
12714 var c = 1;
12715 var ret = p.data;
12716 n -= ret.length;
12717 while (p = p.next) {
12718 var str = p.data;
12719 var nb = n > str.length ? str.length : n;
12720 if (nb === str.length) ret += str;else ret += str.slice(0, n);
12721 n -= nb;
12722 if (n === 0) {
12723 if (nb === str.length) {
12724 ++c;
12725 if (p.next) list.head = p.next;else list.head = list.tail = null;
12726 } else {
12727 list.head = p;
12728 p.data = str.slice(nb);
12729 }
12730 break;
12731 }
12732 ++c;
12733 }
12734 list.length -= c;
12735 return ret;
12736}
12737
12738// Copies a specified amount of bytes from the list of buffered data chunks.
12739// This function is designed to be inlinable, so please take care when making
12740// changes to the function body.
12741function copyFromBuffer(n, list) {
12742 var ret = Buffer.allocUnsafe(n);
12743 var p = list.head;
12744 var c = 1;
12745 p.data.copy(ret);
12746 n -= p.data.length;
12747 while (p = p.next) {
12748 var buf = p.data;
12749 var nb = n > buf.length ? buf.length : n;
12750 buf.copy(ret, ret.length - n, 0, nb);
12751 n -= nb;
12752 if (n === 0) {
12753 if (nb === buf.length) {
12754 ++c;
12755 if (p.next) list.head = p.next;else list.head = list.tail = null;
12756 } else {
12757 list.head = p;
12758 p.data = buf.slice(nb);
12759 }
12760 break;
12761 }
12762 ++c;
12763 }
12764 list.length -= c;
12765 return ret;
12766}
12767
12768function endReadable(stream) {
12769 var state = stream._readableState;
12770
12771 // If we get here before consuming all the bytes, then that is a
12772 // bug in node. Should never happen.
12773 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
12774
12775 if (!state.endEmitted) {
12776 state.ended = true;
12777 pna.nextTick(endReadableNT, state, stream);
12778 }
12779}
12780
12781function endReadableNT(state, stream) {
12782 // Check that we didn't get one last unshift.
12783 if (!state.endEmitted && state.length === 0) {
12784 state.endEmitted = true;
12785 stream.readable = false;
12786 stream.emit('end');
12787 }
12788}
12789
12790function indexOf(xs, x) {
12791 for (var i = 0, l = xs.length; i < l; i++) {
12792 if (xs[i] === x) return i;
12793 }
12794 return -1;
12795}
12796}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
12797
12798},{"./_stream_duplex":75,"./internal/streams/BufferList":80,"./internal/streams/destroy":81,"./internal/streams/stream":82,"_process":64,"core-util-is":25,"events":26,"inherits":30,"isarray":32,"process-nextick-args":74,"safe-buffer":69,"string_decoder/":84,"util":21}],78:[function(require,module,exports){
12799// Copyright Joyent, Inc. and other Node contributors.
12800//
12801// Permission is hereby granted, free of charge, to any person obtaining a
12802// copy of this software and associated documentation files (the
12803// "Software"), to deal in the Software without restriction, including
12804// without limitation the rights to use, copy, modify, merge, publish,
12805// distribute, sublicense, and/or sell copies of the Software, and to permit
12806// persons to whom the Software is furnished to do so, subject to the
12807// following conditions:
12808//
12809// The above copyright notice and this permission notice shall be included
12810// in all copies or substantial portions of the Software.
12811//
12812// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12813// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12814// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12815// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12816// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12817// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12818// USE OR OTHER DEALINGS IN THE SOFTWARE.
12819
12820// a transform stream is a readable/writable stream where you do
12821// something with the data. Sometimes it's called a "filter",
12822// but that's not a great name for it, since that implies a thing where
12823// some bits pass through, and others are simply ignored. (That would
12824// be a valid example of a transform, of course.)
12825//
12826// While the output is causally related to the input, it's not a
12827// necessarily symmetric or synchronous transformation. For example,
12828// a zlib stream might take multiple plain-text writes(), and then
12829// emit a single compressed chunk some time in the future.
12830//
12831// Here's how this works:
12832//
12833// The Transform stream has all the aspects of the readable and writable
12834// stream classes. When you write(chunk), that calls _write(chunk,cb)
12835// internally, and returns false if there's a lot of pending writes
12836// buffered up. When you call read(), that calls _read(n) until
12837// there's enough pending readable data buffered up.
12838//
12839// In a transform stream, the written data is placed in a buffer. When
12840// _read(n) is called, it transforms the queued up data, calling the
12841// buffered _write cb's as it consumes chunks. If consuming a single
12842// written chunk would result in multiple output chunks, then the first
12843// outputted bit calls the readcb, and subsequent chunks just go into
12844// the read buffer, and will cause it to emit 'readable' if necessary.
12845//
12846// This way, back-pressure is actually determined by the reading side,
12847// since _read has to be called to start processing a new chunk. However,
12848// a pathological inflate type of transform can cause excessive buffering
12849// here. For example, imagine a stream where every byte of input is
12850// interpreted as an integer from 0-255, and then results in that many
12851// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12852// 1kb of data being output. In this case, you could write a very small
12853// amount of input, and end up with a very large amount of output. In
12854// such a pathological inflating mechanism, there'd be no way to tell
12855// the system to stop doing the transform. A single 4MB write could
12856// cause the system to run out of memory.
12857//
12858// However, even in such a pathological case, only a single written chunk
12859// would be consumed, and then the rest would wait (un-transformed) until
12860// the results of the previous transformed chunk were consumed.
12861
12862'use strict';
12863
12864module.exports = Transform;
12865
12866var Duplex = require('./_stream_duplex');
12867
12868/*<replacement>*/
12869var util = require('core-util-is');
12870util.inherits = require('inherits');
12871/*</replacement>*/
12872
12873util.inherits(Transform, Duplex);
12874
12875function afterTransform(er, data) {
12876 var ts = this._transformState;
12877 ts.transforming = false;
12878
12879 var cb = ts.writecb;
12880
12881 if (!cb) {
12882 return this.emit('error', new Error('write callback called multiple times'));
12883 }
12884
12885 ts.writechunk = null;
12886 ts.writecb = null;
12887
12888 if (data != null) // single equals check for both `null` and `undefined`
12889 this.push(data);
12890
12891 cb(er);
12892
12893 var rs = this._readableState;
12894 rs.reading = false;
12895 if (rs.needReadable || rs.length < rs.highWaterMark) {
12896 this._read(rs.highWaterMark);
12897 }
12898}
12899
12900function Transform(options) {
12901 if (!(this instanceof Transform)) return new Transform(options);
12902
12903 Duplex.call(this, options);
12904
12905 this._transformState = {
12906 afterTransform: afterTransform.bind(this),
12907 needTransform: false,
12908 transforming: false,
12909 writecb: null,
12910 writechunk: null,
12911 writeencoding: null
12912 };
12913
12914 // start out asking for a readable event once data is transformed.
12915 this._readableState.needReadable = true;
12916
12917 // we have implemented the _read method, and done the other things
12918 // that Readable wants before the first _read call, so unset the
12919 // sync guard flag.
12920 this._readableState.sync = false;
12921
12922 if (options) {
12923 if (typeof options.transform === 'function') this._transform = options.transform;
12924
12925 if (typeof options.flush === 'function') this._flush = options.flush;
12926 }
12927
12928 // When the writable side finishes, then flush out anything remaining.
12929 this.on('prefinish', prefinish);
12930}
12931
12932function prefinish() {
12933 var _this = this;
12934
12935 if (typeof this._flush === 'function') {
12936 this._flush(function (er, data) {
12937 done(_this, er, data);
12938 });
12939 } else {
12940 done(this, null, null);
12941 }
12942}
12943
12944Transform.prototype.push = function (chunk, encoding) {
12945 this._transformState.needTransform = false;
12946 return Duplex.prototype.push.call(this, chunk, encoding);
12947};
12948
12949// This is the part where you do stuff!
12950// override this function in implementation classes.
12951// 'chunk' is an input chunk.
12952//
12953// Call `push(newChunk)` to pass along transformed output
12954// to the readable side. You may call 'push' zero or more times.
12955//
12956// Call `cb(err)` when you are done with this chunk. If you pass
12957// an error, then that'll put the hurt on the whole operation. If you
12958// never call cb(), then you'll never get another chunk.
12959Transform.prototype._transform = function (chunk, encoding, cb) {
12960 throw new Error('_transform() is not implemented');
12961};
12962
12963Transform.prototype._write = function (chunk, encoding, cb) {
12964 var ts = this._transformState;
12965 ts.writecb = cb;
12966 ts.writechunk = chunk;
12967 ts.writeencoding = encoding;
12968 if (!ts.transforming) {
12969 var rs = this._readableState;
12970 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
12971 }
12972};
12973
12974// Doesn't matter what the args are here.
12975// _transform does all the work.
12976// That we got here means that the readable side wants more data.
12977Transform.prototype._read = function (n) {
12978 var ts = this._transformState;
12979
12980 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
12981 ts.transforming = true;
12982 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12983 } else {
12984 // mark that we need a transform, so that any data that comes in
12985 // will get processed, now that we've asked for it.
12986 ts.needTransform = true;
12987 }
12988};
12989
12990Transform.prototype._destroy = function (err, cb) {
12991 var _this2 = this;
12992
12993 Duplex.prototype._destroy.call(this, err, function (err2) {
12994 cb(err2);
12995 _this2.emit('close');
12996 });
12997};
12998
12999function done(stream, er, data) {
13000 if (er) return stream.emit('error', er);
13001
13002 if (data != null) // single equals check for both `null` and `undefined`
13003 stream.push(data);
13004
13005 // if there's nothing in the write buffer, then that means
13006 // that nothing more will ever be provided
13007 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
13008
13009 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
13010
13011 return stream.push(null);
13012}
13013},{"./_stream_duplex":75,"core-util-is":25,"inherits":30}],79:[function(require,module,exports){
13014(function (process,global,setImmediate){
13015// Copyright Joyent, Inc. and other Node contributors.
13016//
13017// Permission is hereby granted, free of charge, to any person obtaining a
13018// copy of this software and associated documentation files (the
13019// "Software"), to deal in the Software without restriction, including
13020// without limitation the rights to use, copy, modify, merge, publish,
13021// distribute, sublicense, and/or sell copies of the Software, and to permit
13022// persons to whom the Software is furnished to do so, subject to the
13023// following conditions:
13024//
13025// The above copyright notice and this permission notice shall be included
13026// in all copies or substantial portions of the Software.
13027//
13028// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13029// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13030// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13031// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13032// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13033// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13034// USE OR OTHER DEALINGS IN THE SOFTWARE.
13035
13036// A bit simpler than readable streams.
13037// Implement an async ._write(chunk, encoding, cb), and it'll handle all
13038// the drain event emission and buffering.
13039
13040'use strict';
13041
13042/*<replacement>*/
13043
13044var pna = require('process-nextick-args');
13045/*</replacement>*/
13046
13047module.exports = Writable;
13048
13049/* <replacement> */
13050function WriteReq(chunk, encoding, cb) {
13051 this.chunk = chunk;
13052 this.encoding = encoding;
13053 this.callback = cb;
13054 this.next = null;
13055}
13056
13057// It seems a linked list but it is not
13058// there will be only 2 of these for each stream
13059function CorkedRequest(state) {
13060 var _this = this;
13061
13062 this.next = null;
13063 this.entry = null;
13064 this.finish = function () {
13065 onCorkedFinish(_this, state);
13066 };
13067}
13068/* </replacement> */
13069
13070/*<replacement>*/
13071var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
13072/*</replacement>*/
13073
13074/*<replacement>*/
13075var Duplex;
13076/*</replacement>*/
13077
13078Writable.WritableState = WritableState;
13079
13080/*<replacement>*/
13081var util = require('core-util-is');
13082util.inherits = require('inherits');
13083/*</replacement>*/
13084
13085/*<replacement>*/
13086var internalUtil = {
13087 deprecate: require('util-deprecate')
13088};
13089/*</replacement>*/
13090
13091/*<replacement>*/
13092var Stream = require('./internal/streams/stream');
13093/*</replacement>*/
13094
13095/*<replacement>*/
13096
13097var Buffer = require('safe-buffer').Buffer;
13098var OurUint8Array = global.Uint8Array || function () {};
13099function _uint8ArrayToBuffer(chunk) {
13100 return Buffer.from(chunk);
13101}
13102function _isUint8Array(obj) {
13103 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
13104}
13105
13106/*</replacement>*/
13107
13108var destroyImpl = require('./internal/streams/destroy');
13109
13110util.inherits(Writable, Stream);
13111
13112function nop() {}
13113
13114function WritableState(options, stream) {
13115 Duplex = Duplex || require('./_stream_duplex');
13116
13117 options = options || {};
13118
13119 // Duplex streams are both readable and writable, but share
13120 // the same options object.
13121 // However, some cases require setting options to different
13122 // values for the readable and the writable sides of the duplex stream.
13123 // These options can be provided separately as readableXXX and writableXXX.
13124 var isDuplex = stream instanceof Duplex;
13125
13126 // object stream flag to indicate whether or not this stream
13127 // contains buffers or objects.
13128 this.objectMode = !!options.objectMode;
13129
13130 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
13131
13132 // the point at which write() starts returning false
13133 // Note: 0 is a valid value, means that we always return false if
13134 // the entire buffer is not flushed immediately on write()
13135 var hwm = options.highWaterMark;
13136 var writableHwm = options.writableHighWaterMark;
13137 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
13138
13139 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
13140
13141 // cast to ints.
13142 this.highWaterMark = Math.floor(this.highWaterMark);
13143
13144 // if _final has been called
13145 this.finalCalled = false;
13146
13147 // drain event flag.
13148 this.needDrain = false;
13149 // at the start of calling end()
13150 this.ending = false;
13151 // when end() has been called, and returned
13152 this.ended = false;
13153 // when 'finish' is emitted
13154 this.finished = false;
13155
13156 // has it been destroyed
13157 this.destroyed = false;
13158
13159 // should we decode strings into buffers before passing to _write?
13160 // this is here so that some node-core streams can optimize string
13161 // handling at a lower level.
13162 var noDecode = options.decodeStrings === false;
13163 this.decodeStrings = !noDecode;
13164
13165 // Crypto is kind of old and crusty. Historically, its default string
13166 // encoding is 'binary' so we have to make this configurable.
13167 // Everything else in the universe uses 'utf8', though.
13168 this.defaultEncoding = options.defaultEncoding || 'utf8';
13169
13170 // not an actual buffer we keep track of, but a measurement
13171 // of how much we're waiting to get pushed to some underlying
13172 // socket or file.
13173 this.length = 0;
13174
13175 // a flag to see when we're in the middle of a write.
13176 this.writing = false;
13177
13178 // when true all writes will be buffered until .uncork() call
13179 this.corked = 0;
13180
13181 // a flag to be able to tell if the onwrite cb is called immediately,
13182 // or on a later tick. We set this to true at first, because any
13183 // actions that shouldn't happen until "later" should generally also
13184 // not happen before the first write call.
13185 this.sync = true;
13186
13187 // a flag to know if we're processing previously buffered items, which
13188 // may call the _write() callback in the same tick, so that we don't
13189 // end up in an overlapped onwrite situation.
13190 this.bufferProcessing = false;
13191
13192 // the callback that's passed to _write(chunk,cb)
13193 this.onwrite = function (er) {
13194 onwrite(stream, er);
13195 };
13196
13197 // the callback that the user supplies to write(chunk,encoding,cb)
13198 this.writecb = null;
13199
13200 // the amount that is being written when _write is called.
13201 this.writelen = 0;
13202
13203 this.bufferedRequest = null;
13204 this.lastBufferedRequest = null;
13205
13206 // number of pending user-supplied write callbacks
13207 // this must be 0 before 'finish' can be emitted
13208 this.pendingcb = 0;
13209
13210 // emit prefinish if the only thing we're waiting for is _write cbs
13211 // This is relevant for synchronous Transform streams
13212 this.prefinished = false;
13213
13214 // True if the error was already emitted and should not be thrown again
13215 this.errorEmitted = false;
13216
13217 // count buffered requests
13218 this.bufferedRequestCount = 0;
13219
13220 // allocate the first CorkedRequest, there is always
13221 // one allocated and free to use, and we maintain at most two
13222 this.corkedRequestsFree = new CorkedRequest(this);
13223}
13224
13225WritableState.prototype.getBuffer = function getBuffer() {
13226 var current = this.bufferedRequest;
13227 var out = [];
13228 while (current) {
13229 out.push(current);
13230 current = current.next;
13231 }
13232 return out;
13233};
13234
13235(function () {
13236 try {
13237 Object.defineProperty(WritableState.prototype, 'buffer', {
13238 get: internalUtil.deprecate(function () {
13239 return this.getBuffer();
13240 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
13241 });
13242 } catch (_) {}
13243})();
13244
13245// Test _writableState for inheritance to account for Duplex streams,
13246// whose prototype chain only points to Readable.
13247var realHasInstance;
13248if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
13249 realHasInstance = Function.prototype[Symbol.hasInstance];
13250 Object.defineProperty(Writable, Symbol.hasInstance, {
13251 value: function (object) {
13252 if (realHasInstance.call(this, object)) return true;
13253 if (this !== Writable) return false;
13254
13255 return object && object._writableState instanceof WritableState;
13256 }
13257 });
13258} else {
13259 realHasInstance = function (object) {
13260 return object instanceof this;
13261 };
13262}
13263
13264function Writable(options) {
13265 Duplex = Duplex || require('./_stream_duplex');
13266
13267 // Writable ctor is applied to Duplexes, too.
13268 // `realHasInstance` is necessary because using plain `instanceof`
13269 // would return false, as no `_writableState` property is attached.
13270
13271 // Trying to use the custom `instanceof` for Writable here will also break the
13272 // Node.js LazyTransform implementation, which has a non-trivial getter for
13273 // `_writableState` that would lead to infinite recursion.
13274 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
13275 return new Writable(options);
13276 }
13277
13278 this._writableState = new WritableState(options, this);
13279
13280 // legacy.
13281 this.writable = true;
13282
13283 if (options) {
13284 if (typeof options.write === 'function') this._write = options.write;
13285
13286 if (typeof options.writev === 'function') this._writev = options.writev;
13287
13288 if (typeof options.destroy === 'function') this._destroy = options.destroy;
13289
13290 if (typeof options.final === 'function') this._final = options.final;
13291 }
13292
13293 Stream.call(this);
13294}
13295
13296// Otherwise people can pipe Writable streams, which is just wrong.
13297Writable.prototype.pipe = function () {
13298 this.emit('error', new Error('Cannot pipe, not readable'));
13299};
13300
13301function writeAfterEnd(stream, cb) {
13302 var er = new Error('write after end');
13303 // TODO: defer error events consistently everywhere, not just the cb
13304 stream.emit('error', er);
13305 pna.nextTick(cb, er);
13306}
13307
13308// Checks that a user-supplied chunk is valid, especially for the particular
13309// mode the stream is in. Currently this means that `null` is never accepted
13310// and undefined/non-string values are only allowed in object mode.
13311function validChunk(stream, state, chunk, cb) {
13312 var valid = true;
13313 var er = false;
13314
13315 if (chunk === null) {
13316 er = new TypeError('May not write null values to stream');
13317 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
13318 er = new TypeError('Invalid non-string/buffer chunk');
13319 }
13320 if (er) {
13321 stream.emit('error', er);
13322 pna.nextTick(cb, er);
13323 valid = false;
13324 }
13325 return valid;
13326}
13327
13328Writable.prototype.write = function (chunk, encoding, cb) {
13329 var state = this._writableState;
13330 var ret = false;
13331 var isBuf = !state.objectMode && _isUint8Array(chunk);
13332
13333 if (isBuf && !Buffer.isBuffer(chunk)) {
13334 chunk = _uint8ArrayToBuffer(chunk);
13335 }
13336
13337 if (typeof encoding === 'function') {
13338 cb = encoding;
13339 encoding = null;
13340 }
13341
13342 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
13343
13344 if (typeof cb !== 'function') cb = nop;
13345
13346 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
13347 state.pendingcb++;
13348 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
13349 }
13350
13351 return ret;
13352};
13353
13354Writable.prototype.cork = function () {
13355 var state = this._writableState;
13356
13357 state.corked++;
13358};
13359
13360Writable.prototype.uncork = function () {
13361 var state = this._writableState;
13362
13363 if (state.corked) {
13364 state.corked--;
13365
13366 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
13367 }
13368};
13369
13370Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
13371 // node::ParseEncoding() requires lower case.
13372 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
13373 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
13374 this._writableState.defaultEncoding = encoding;
13375 return this;
13376};
13377
13378function decodeChunk(state, chunk, encoding) {
13379 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
13380 chunk = Buffer.from(chunk, encoding);
13381 }
13382 return chunk;
13383}
13384
13385Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
13386 // making it explicit this property is not enumerable
13387 // because otherwise some prototype manipulation in
13388 // userland will fail
13389 enumerable: false,
13390 get: function () {
13391 return this._writableState.highWaterMark;
13392 }
13393});
13394
13395// if we're already writing something, then just put this
13396// in the queue, and wait our turn. Otherwise, call _write
13397// If we return false, then we need a drain event, so set that flag.
13398function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
13399 if (!isBuf) {
13400 var newChunk = decodeChunk(state, chunk, encoding);
13401 if (chunk !== newChunk) {
13402 isBuf = true;
13403 encoding = 'buffer';
13404 chunk = newChunk;
13405 }
13406 }
13407 var len = state.objectMode ? 1 : chunk.length;
13408
13409 state.length += len;
13410
13411 var ret = state.length < state.highWaterMark;
13412 // we must ensure that previous needDrain will not be reset to false.
13413 if (!ret) state.needDrain = true;
13414
13415 if (state.writing || state.corked) {
13416 var last = state.lastBufferedRequest;
13417 state.lastBufferedRequest = {
13418 chunk: chunk,
13419 encoding: encoding,
13420 isBuf: isBuf,
13421 callback: cb,
13422 next: null
13423 };
13424 if (last) {
13425 last.next = state.lastBufferedRequest;
13426 } else {
13427 state.bufferedRequest = state.lastBufferedRequest;
13428 }
13429 state.bufferedRequestCount += 1;
13430 } else {
13431 doWrite(stream, state, false, len, chunk, encoding, cb);
13432 }
13433
13434 return ret;
13435}
13436
13437function doWrite(stream, state, writev, len, chunk, encoding, cb) {
13438 state.writelen = len;
13439 state.writecb = cb;
13440 state.writing = true;
13441 state.sync = true;
13442 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
13443 state.sync = false;
13444}
13445
13446function onwriteError(stream, state, sync, er, cb) {
13447 --state.pendingcb;
13448
13449 if (sync) {
13450 // defer the callback if we are being called synchronously
13451 // to avoid piling up things on the stack
13452 pna.nextTick(cb, er);
13453 // this can emit finish, and it will always happen
13454 // after error
13455 pna.nextTick(finishMaybe, stream, state);
13456 stream._writableState.errorEmitted = true;
13457 stream.emit('error', er);
13458 } else {
13459 // the caller expect this to happen before if
13460 // it is async
13461 cb(er);
13462 stream._writableState.errorEmitted = true;
13463 stream.emit('error', er);
13464 // this can emit finish, but finish must
13465 // always follow error
13466 finishMaybe(stream, state);
13467 }
13468}
13469
13470function onwriteStateUpdate(state) {
13471 state.writing = false;
13472 state.writecb = null;
13473 state.length -= state.writelen;
13474 state.writelen = 0;
13475}
13476
13477function onwrite(stream, er) {
13478 var state = stream._writableState;
13479 var sync = state.sync;
13480 var cb = state.writecb;
13481
13482 onwriteStateUpdate(state);
13483
13484 if (er) onwriteError(stream, state, sync, er, cb);else {
13485 // Check if we're actually ready to finish, but don't emit yet
13486 var finished = needFinish(state);
13487
13488 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
13489 clearBuffer(stream, state);
13490 }
13491
13492 if (sync) {
13493 /*<replacement>*/
13494 asyncWrite(afterWrite, stream, state, finished, cb);
13495 /*</replacement>*/
13496 } else {
13497 afterWrite(stream, state, finished, cb);
13498 }
13499 }
13500}
13501
13502function afterWrite(stream, state, finished, cb) {
13503 if (!finished) onwriteDrain(stream, state);
13504 state.pendingcb--;
13505 cb();
13506 finishMaybe(stream, state);
13507}
13508
13509// Must force callback to be called on nextTick, so that we don't
13510// emit 'drain' before the write() consumer gets the 'false' return
13511// value, and has a chance to attach a 'drain' listener.
13512function onwriteDrain(stream, state) {
13513 if (state.length === 0 && state.needDrain) {
13514 state.needDrain = false;
13515 stream.emit('drain');
13516 }
13517}
13518
13519// if there's something in the buffer waiting, then process it
13520function clearBuffer(stream, state) {
13521 state.bufferProcessing = true;
13522 var entry = state.bufferedRequest;
13523
13524 if (stream._writev && entry && entry.next) {
13525 // Fast case, write everything using _writev()
13526 var l = state.bufferedRequestCount;
13527 var buffer = new Array(l);
13528 var holder = state.corkedRequestsFree;
13529 holder.entry = entry;
13530
13531 var count = 0;
13532 var allBuffers = true;
13533 while (entry) {
13534 buffer[count] = entry;
13535 if (!entry.isBuf) allBuffers = false;
13536 entry = entry.next;
13537 count += 1;
13538 }
13539 buffer.allBuffers = allBuffers;
13540
13541 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
13542
13543 // doWrite is almost always async, defer these to save a bit of time
13544 // as the hot path ends with doWrite
13545 state.pendingcb++;
13546 state.lastBufferedRequest = null;
13547 if (holder.next) {
13548 state.corkedRequestsFree = holder.next;
13549 holder.next = null;
13550 } else {
13551 state.corkedRequestsFree = new CorkedRequest(state);
13552 }
13553 state.bufferedRequestCount = 0;
13554 } else {
13555 // Slow case, write chunks one-by-one
13556 while (entry) {
13557 var chunk = entry.chunk;
13558 var encoding = entry.encoding;
13559 var cb = entry.callback;
13560 var len = state.objectMode ? 1 : chunk.length;
13561
13562 doWrite(stream, state, false, len, chunk, encoding, cb);
13563 entry = entry.next;
13564 state.bufferedRequestCount--;
13565 // if we didn't call the onwrite immediately, then
13566 // it means that we need to wait until it does.
13567 // also, that means that the chunk and cb are currently
13568 // being processed, so move the buffer counter past them.
13569 if (state.writing) {
13570 break;
13571 }
13572 }
13573
13574 if (entry === null) state.lastBufferedRequest = null;
13575 }
13576
13577 state.bufferedRequest = entry;
13578 state.bufferProcessing = false;
13579}
13580
13581Writable.prototype._write = function (chunk, encoding, cb) {
13582 cb(new Error('_write() is not implemented'));
13583};
13584
13585Writable.prototype._writev = null;
13586
13587Writable.prototype.end = function (chunk, encoding, cb) {
13588 var state = this._writableState;
13589
13590 if (typeof chunk === 'function') {
13591 cb = chunk;
13592 chunk = null;
13593 encoding = null;
13594 } else if (typeof encoding === 'function') {
13595 cb = encoding;
13596 encoding = null;
13597 }
13598
13599 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
13600
13601 // .end() fully uncorks
13602 if (state.corked) {
13603 state.corked = 1;
13604 this.uncork();
13605 }
13606
13607 // ignore unnecessary end() calls.
13608 if (!state.ending && !state.finished) endWritable(this, state, cb);
13609};
13610
13611function needFinish(state) {
13612 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
13613}
13614function callFinal(stream, state) {
13615 stream._final(function (err) {
13616 state.pendingcb--;
13617 if (err) {
13618 stream.emit('error', err);
13619 }
13620 state.prefinished = true;
13621 stream.emit('prefinish');
13622 finishMaybe(stream, state);
13623 });
13624}
13625function prefinish(stream, state) {
13626 if (!state.prefinished && !state.finalCalled) {
13627 if (typeof stream._final === 'function') {
13628 state.pendingcb++;
13629 state.finalCalled = true;
13630 pna.nextTick(callFinal, stream, state);
13631 } else {
13632 state.prefinished = true;
13633 stream.emit('prefinish');
13634 }
13635 }
13636}
13637
13638function finishMaybe(stream, state) {
13639 var need = needFinish(state);
13640 if (need) {
13641 prefinish(stream, state);
13642 if (state.pendingcb === 0) {
13643 state.finished = true;
13644 stream.emit('finish');
13645 }
13646 }
13647 return need;
13648}
13649
13650function endWritable(stream, state, cb) {
13651 state.ending = true;
13652 finishMaybe(stream, state);
13653 if (cb) {
13654 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
13655 }
13656 state.ended = true;
13657 stream.writable = false;
13658}
13659
13660function onCorkedFinish(corkReq, state, err) {
13661 var entry = corkReq.entry;
13662 corkReq.entry = null;
13663 while (entry) {
13664 var cb = entry.callback;
13665 state.pendingcb--;
13666 cb(err);
13667 entry = entry.next;
13668 }
13669 if (state.corkedRequestsFree) {
13670 state.corkedRequestsFree.next = corkReq;
13671 } else {
13672 state.corkedRequestsFree = corkReq;
13673 }
13674}
13675
13676Object.defineProperty(Writable.prototype, 'destroyed', {
13677 get: function () {
13678 if (this._writableState === undefined) {
13679 return false;
13680 }
13681 return this._writableState.destroyed;
13682 },
13683 set: function (value) {
13684 // we ignore the value if the stream
13685 // has not been initialized yet
13686 if (!this._writableState) {
13687 return;
13688 }
13689
13690 // backward compatibility, the user is explicitly
13691 // managing destroyed
13692 this._writableState.destroyed = value;
13693 }
13694});
13695
13696Writable.prototype.destroy = destroyImpl.destroy;
13697Writable.prototype._undestroy = destroyImpl.undestroy;
13698Writable.prototype._destroy = function (err, cb) {
13699 this.end();
13700 cb(err);
13701};
13702}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
13703
13704},{"./_stream_duplex":75,"./internal/streams/destroy":81,"./internal/streams/stream":82,"_process":64,"core-util-is":25,"inherits":30,"process-nextick-args":74,"safe-buffer":69,"timers":85,"util-deprecate":89}],80:[function(require,module,exports){
13705'use strict';
13706
13707function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13708
13709var Buffer = require('safe-buffer').Buffer;
13710var util = require('util');
13711
13712function copyBuffer(src, target, offset) {
13713 src.copy(target, offset);
13714}
13715
13716module.exports = function () {
13717 function BufferList() {
13718 _classCallCheck(this, BufferList);
13719
13720 this.head = null;
13721 this.tail = null;
13722 this.length = 0;
13723 }
13724
13725 BufferList.prototype.push = function push(v) {
13726 var entry = { data: v, next: null };
13727 if (this.length > 0) this.tail.next = entry;else this.head = entry;
13728 this.tail = entry;
13729 ++this.length;
13730 };
13731
13732 BufferList.prototype.unshift = function unshift(v) {
13733 var entry = { data: v, next: this.head };
13734 if (this.length === 0) this.tail = entry;
13735 this.head = entry;
13736 ++this.length;
13737 };
13738
13739 BufferList.prototype.shift = function shift() {
13740 if (this.length === 0) return;
13741 var ret = this.head.data;
13742 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
13743 --this.length;
13744 return ret;
13745 };
13746
13747 BufferList.prototype.clear = function clear() {
13748 this.head = this.tail = null;
13749 this.length = 0;
13750 };
13751
13752 BufferList.prototype.join = function join(s) {
13753 if (this.length === 0) return '';
13754 var p = this.head;
13755 var ret = '' + p.data;
13756 while (p = p.next) {
13757 ret += s + p.data;
13758 }return ret;
13759 };
13760
13761 BufferList.prototype.concat = function concat(n) {
13762 if (this.length === 0) return Buffer.alloc(0);
13763 if (this.length === 1) return this.head.data;
13764 var ret = Buffer.allocUnsafe(n >>> 0);
13765 var p = this.head;
13766 var i = 0;
13767 while (p) {
13768 copyBuffer(p.data, ret, i);
13769 i += p.data.length;
13770 p = p.next;
13771 }
13772 return ret;
13773 };
13774
13775 return BufferList;
13776}();
13777
13778if (util && util.inspect && util.inspect.custom) {
13779 module.exports.prototype[util.inspect.custom] = function () {
13780 var obj = util.inspect({ length: this.length });
13781 return this.constructor.name + ' ' + obj;
13782 };
13783}
13784},{"safe-buffer":69,"util":21}],81:[function(require,module,exports){
13785'use strict';
13786
13787/*<replacement>*/
13788
13789var pna = require('process-nextick-args');
13790/*</replacement>*/
13791
13792// undocumented cb() API, needed for core, not for public API
13793function destroy(err, cb) {
13794 var _this = this;
13795
13796 var readableDestroyed = this._readableState && this._readableState.destroyed;
13797 var writableDestroyed = this._writableState && this._writableState.destroyed;
13798
13799 if (readableDestroyed || writableDestroyed) {
13800 if (cb) {
13801 cb(err);
13802 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
13803 pna.nextTick(emitErrorNT, this, err);
13804 }
13805 return this;
13806 }
13807
13808 // we set destroyed to true before firing error callbacks in order
13809 // to make it re-entrance safe in case destroy() is called within callbacks
13810
13811 if (this._readableState) {
13812 this._readableState.destroyed = true;
13813 }
13814
13815 // if this is a duplex stream mark the writable part as destroyed as well
13816 if (this._writableState) {
13817 this._writableState.destroyed = true;
13818 }
13819
13820 this._destroy(err || null, function (err) {
13821 if (!cb && err) {
13822 pna.nextTick(emitErrorNT, _this, err);
13823 if (_this._writableState) {
13824 _this._writableState.errorEmitted = true;
13825 }
13826 } else if (cb) {
13827 cb(err);
13828 }
13829 });
13830
13831 return this;
13832}
13833
13834function undestroy() {
13835 if (this._readableState) {
13836 this._readableState.destroyed = false;
13837 this._readableState.reading = false;
13838 this._readableState.ended = false;
13839 this._readableState.endEmitted = false;
13840 }
13841
13842 if (this._writableState) {
13843 this._writableState.destroyed = false;
13844 this._writableState.ended = false;
13845 this._writableState.ending = false;
13846 this._writableState.finished = false;
13847 this._writableState.errorEmitted = false;
13848 }
13849}
13850
13851function emitErrorNT(self, err) {
13852 self.emit('error', err);
13853}
13854
13855module.exports = {
13856 destroy: destroy,
13857 undestroy: undestroy
13858};
13859},{"process-nextick-args":74}],82:[function(require,module,exports){
13860module.exports = require('events').EventEmitter;
13861
13862},{"events":26}],83:[function(require,module,exports){
13863exports = module.exports = require('./lib/_stream_readable.js');
13864exports.Stream = exports;
13865exports.Readable = exports;
13866exports.Writable = require('./lib/_stream_writable.js');
13867exports.Duplex = require('./lib/_stream_duplex.js');
13868exports.Transform = require('./lib/_stream_transform.js');
13869exports.PassThrough = require('./lib/_stream_passthrough.js');
13870
13871},{"./lib/_stream_duplex.js":75,"./lib/_stream_passthrough.js":76,"./lib/_stream_readable.js":77,"./lib/_stream_transform.js":78,"./lib/_stream_writable.js":79}],84:[function(require,module,exports){
13872// Copyright Joyent, Inc. and other Node contributors.
13873//
13874// Permission is hereby granted, free of charge, to any person obtaining a
13875// copy of this software and associated documentation files (the
13876// "Software"), to deal in the Software without restriction, including
13877// without limitation the rights to use, copy, modify, merge, publish,
13878// distribute, sublicense, and/or sell copies of the Software, and to permit
13879// persons to whom the Software is furnished to do so, subject to the
13880// following conditions:
13881//
13882// The above copyright notice and this permission notice shall be included
13883// in all copies or substantial portions of the Software.
13884//
13885// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13886// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13887// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13888// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13889// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13890// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13891// USE OR OTHER DEALINGS IN THE SOFTWARE.
13892
13893'use strict';
13894
13895/*<replacement>*/
13896
13897var Buffer = require('safe-buffer').Buffer;
13898/*</replacement>*/
13899
13900var isEncoding = Buffer.isEncoding || function (encoding) {
13901 encoding = '' + encoding;
13902 switch (encoding && encoding.toLowerCase()) {
13903 case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
13904 return true;
13905 default:
13906 return false;
13907 }
13908};
13909
13910function _normalizeEncoding(enc) {
13911 if (!enc) return 'utf8';
13912 var retried;
13913 while (true) {
13914 switch (enc) {
13915 case 'utf8':
13916 case 'utf-8':
13917 return 'utf8';
13918 case 'ucs2':
13919 case 'ucs-2':
13920 case 'utf16le':
13921 case 'utf-16le':
13922 return 'utf16le';
13923 case 'latin1':
13924 case 'binary':
13925 return 'latin1';
13926 case 'base64':
13927 case 'ascii':
13928 case 'hex':
13929 return enc;
13930 default:
13931 if (retried) return; // undefined
13932 enc = ('' + enc).toLowerCase();
13933 retried = true;
13934 }
13935 }
13936};
13937
13938// Do not cache `Buffer.isEncoding` when checking encoding names as some
13939// modules monkey-patch it to support additional encodings
13940function normalizeEncoding(enc) {
13941 var nenc = _normalizeEncoding(enc);
13942 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
13943 return nenc || enc;
13944}
13945
13946// StringDecoder provides an interface for efficiently splitting a series of
13947// buffers into a series of JS strings without breaking apart multi-byte
13948// characters.
13949exports.StringDecoder = StringDecoder;
13950function StringDecoder(encoding) {
13951 this.encoding = normalizeEncoding(encoding);
13952 var nb;
13953 switch (this.encoding) {
13954 case 'utf16le':
13955 this.text = utf16Text;
13956 this.end = utf16End;
13957 nb = 4;
13958 break;
13959 case 'utf8':
13960 this.fillLast = utf8FillLast;
13961 nb = 4;
13962 break;
13963 case 'base64':
13964 this.text = base64Text;
13965 this.end = base64End;
13966 nb = 3;
13967 break;
13968 default:
13969 this.write = simpleWrite;
13970 this.end = simpleEnd;
13971 return;
13972 }
13973 this.lastNeed = 0;
13974 this.lastTotal = 0;
13975 this.lastChar = Buffer.allocUnsafe(nb);
13976}
13977
13978StringDecoder.prototype.write = function (buf) {
13979 if (buf.length === 0) return '';
13980 var r;
13981 var i;
13982 if (this.lastNeed) {
13983 r = this.fillLast(buf);
13984 if (r === undefined) return '';
13985 i = this.lastNeed;
13986 this.lastNeed = 0;
13987 } else {
13988 i = 0;
13989 }
13990 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
13991 return r || '';
13992};
13993
13994StringDecoder.prototype.end = utf8End;
13995
13996// Returns only complete characters in a Buffer
13997StringDecoder.prototype.text = utf8Text;
13998
13999// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
14000StringDecoder.prototype.fillLast = function (buf) {
14001 if (this.lastNeed <= buf.length) {
14002 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
14003 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
14004 }
14005 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
14006 this.lastNeed -= buf.length;
14007};
14008
14009// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
14010// continuation byte. If an invalid byte is detected, -2 is returned.
14011function utf8CheckByte(byte) {
14012 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
14013 return byte >> 6 === 0x02 ? -1 : -2;
14014}
14015
14016// Checks at most 3 bytes at the end of a Buffer in order to detect an
14017// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
14018// needed to complete the UTF-8 character (if applicable) are returned.
14019function utf8CheckIncomplete(self, buf, i) {
14020 var j = buf.length - 1;
14021 if (j < i) return 0;
14022 var nb = utf8CheckByte(buf[j]);
14023 if (nb >= 0) {
14024 if (nb > 0) self.lastNeed = nb - 1;
14025 return nb;
14026 }
14027 if (--j < i || nb === -2) return 0;
14028 nb = utf8CheckByte(buf[j]);
14029 if (nb >= 0) {
14030 if (nb > 0) self.lastNeed = nb - 2;
14031 return nb;
14032 }
14033 if (--j < i || nb === -2) return 0;
14034 nb = utf8CheckByte(buf[j]);
14035 if (nb >= 0) {
14036 if (nb > 0) {
14037 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
14038 }
14039 return nb;
14040 }
14041 return 0;
14042}
14043
14044// Validates as many continuation bytes for a multi-byte UTF-8 character as
14045// needed or are available. If we see a non-continuation byte where we expect
14046// one, we "replace" the validated continuation bytes we've seen so far with
14047// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
14048// behavior. The continuation byte check is included three times in the case
14049// where all of the continuation bytes for a character exist in the same buffer.
14050// It is also done this way as a slight performance increase instead of using a
14051// loop.
14052function utf8CheckExtraBytes(self, buf, p) {
14053 if ((buf[0] & 0xC0) !== 0x80) {
14054 self.lastNeed = 0;
14055 return '\ufffd';
14056 }
14057 if (self.lastNeed > 1 && buf.length > 1) {
14058 if ((buf[1] & 0xC0) !== 0x80) {
14059 self.lastNeed = 1;
14060 return '\ufffd';
14061 }
14062 if (self.lastNeed > 2 && buf.length > 2) {
14063 if ((buf[2] & 0xC0) !== 0x80) {
14064 self.lastNeed = 2;
14065 return '\ufffd';
14066 }
14067 }
14068 }
14069}
14070
14071// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
14072function utf8FillLast(buf) {
14073 var p = this.lastTotal - this.lastNeed;
14074 var r = utf8CheckExtraBytes(this, buf, p);
14075 if (r !== undefined) return r;
14076 if (this.lastNeed <= buf.length) {
14077 buf.copy(this.lastChar, p, 0, this.lastNeed);
14078 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
14079 }
14080 buf.copy(this.lastChar, p, 0, buf.length);
14081 this.lastNeed -= buf.length;
14082}
14083
14084// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
14085// partial character, the character's bytes are buffered until the required
14086// number of bytes are available.
14087function utf8Text(buf, i) {
14088 var total = utf8CheckIncomplete(this, buf, i);
14089 if (!this.lastNeed) return buf.toString('utf8', i);
14090 this.lastTotal = total;
14091 var end = buf.length - (total - this.lastNeed);
14092 buf.copy(this.lastChar, 0, end);
14093 return buf.toString('utf8', i, end);
14094}
14095
14096// For UTF-8, a replacement character is added when ending on a partial
14097// character.
14098function utf8End(buf) {
14099 var r = buf && buf.length ? this.write(buf) : '';
14100 if (this.lastNeed) return r + '\ufffd';
14101 return r;
14102}
14103
14104// UTF-16LE typically needs two bytes per character, but even if we have an even
14105// number of bytes available, we need to check if we end on a leading/high
14106// surrogate. In that case, we need to wait for the next two bytes in order to
14107// decode the last character properly.
14108function utf16Text(buf, i) {
14109 if ((buf.length - i) % 2 === 0) {
14110 var r = buf.toString('utf16le', i);
14111 if (r) {
14112 var c = r.charCodeAt(r.length - 1);
14113 if (c >= 0xD800 && c <= 0xDBFF) {
14114 this.lastNeed = 2;
14115 this.lastTotal = 4;
14116 this.lastChar[0] = buf[buf.length - 2];
14117 this.lastChar[1] = buf[buf.length - 1];
14118 return r.slice(0, -1);
14119 }
14120 }
14121 return r;
14122 }
14123 this.lastNeed = 1;
14124 this.lastTotal = 2;
14125 this.lastChar[0] = buf[buf.length - 1];
14126 return buf.toString('utf16le', i, buf.length - 1);
14127}
14128
14129// For UTF-16LE we do not explicitly append special replacement characters if we
14130// end on a partial character, we simply let v8 handle that.
14131function utf16End(buf) {
14132 var r = buf && buf.length ? this.write(buf) : '';
14133 if (this.lastNeed) {
14134 var end = this.lastTotal - this.lastNeed;
14135 return r + this.lastChar.toString('utf16le', 0, end);
14136 }
14137 return r;
14138}
14139
14140function base64Text(buf, i) {
14141 var n = (buf.length - i) % 3;
14142 if (n === 0) return buf.toString('base64', i);
14143 this.lastNeed = 3 - n;
14144 this.lastTotal = 3;
14145 if (n === 1) {
14146 this.lastChar[0] = buf[buf.length - 1];
14147 } else {
14148 this.lastChar[0] = buf[buf.length - 2];
14149 this.lastChar[1] = buf[buf.length - 1];
14150 }
14151 return buf.toString('base64', i, buf.length - n);
14152}
14153
14154function base64End(buf) {
14155 var r = buf && buf.length ? this.write(buf) : '';
14156 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
14157 return r;
14158}
14159
14160// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
14161function simpleWrite(buf) {
14162 return buf.toString(this.encoding);
14163}
14164
14165function simpleEnd(buf) {
14166 return buf && buf.length ? this.write(buf) : '';
14167}
14168},{"safe-buffer":69}],85:[function(require,module,exports){
14169(function (setImmediate,clearImmediate){
14170var nextTick = require('process/browser.js').nextTick;
14171var apply = Function.prototype.apply;
14172var slice = Array.prototype.slice;
14173var immediateIds = {};
14174var nextImmediateId = 0;
14175
14176// DOM APIs, for completeness
14177
14178exports.setTimeout = function() {
14179 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
14180};
14181exports.setInterval = function() {
14182 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
14183};
14184exports.clearTimeout =
14185exports.clearInterval = function(timeout) { timeout.close(); };
14186
14187function Timeout(id, clearFn) {
14188 this._id = id;
14189 this._clearFn = clearFn;
14190}
14191Timeout.prototype.unref = Timeout.prototype.ref = function() {};
14192Timeout.prototype.close = function() {
14193 this._clearFn.call(window, this._id);
14194};
14195
14196// Does not start the time, just sets up the members needed.
14197exports.enroll = function(item, msecs) {
14198 clearTimeout(item._idleTimeoutId);
14199 item._idleTimeout = msecs;
14200};
14201
14202exports.unenroll = function(item) {
14203 clearTimeout(item._idleTimeoutId);
14204 item._idleTimeout = -1;
14205};
14206
14207exports._unrefActive = exports.active = function(item) {
14208 clearTimeout(item._idleTimeoutId);
14209
14210 var msecs = item._idleTimeout;
14211 if (msecs >= 0) {
14212 item._idleTimeoutId = setTimeout(function onTimeout() {
14213 if (item._onTimeout)
14214 item._onTimeout();
14215 }, msecs);
14216 }
14217};
14218
14219// That's not how node.js implements it but the exposed api is the same.
14220exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
14221 var id = nextImmediateId++;
14222 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
14223
14224 immediateIds[id] = true;
14225
14226 nextTick(function onNextTick() {
14227 if (immediateIds[id]) {
14228 // fn.call() is faster so we optimize for the common use-case
14229 // @see http://jsperf.com/call-apply-segu
14230 if (args) {
14231 fn.apply(null, args);
14232 } else {
14233 fn.call(null);
14234 }
14235 // Prevent ids from leaking
14236 exports.clearImmediate(id);
14237 }
14238 });
14239
14240 return id;
14241};
14242
14243exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
14244 delete immediateIds[id];
14245};
14246}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
14247
14248},{"process/browser.js":64,"timers":85}],86:[function(require,module,exports){
14249var Buffer = require('buffer').Buffer
14250
14251module.exports = function (buf) {
14252 // If the buffer is backed by a Uint8Array, a faster version will work
14253 if (buf instanceof Uint8Array) {
14254 // If the buffer isn't a subarray, return the underlying ArrayBuffer
14255 if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
14256 return buf.buffer
14257 } else if (typeof buf.buffer.slice === 'function') {
14258 // Otherwise we need to get a proper copy
14259 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
14260 }
14261 }
14262
14263 if (Buffer.isBuffer(buf)) {
14264 // This is the slow version that will work with any Buffer
14265 // implementation (even in old browsers)
14266 var arrayCopy = new Uint8Array(buf.length)
14267 var len = buf.length
14268 for (var i = 0; i < len; i++) {
14269 arrayCopy[i] = buf[i]
14270 }
14271 return arrayCopy.buffer
14272 } else {
14273 throw new Error('Argument must be a Buffer')
14274 }
14275}
14276
14277},{"buffer":22}],87:[function(require,module,exports){
14278// Copyright Joyent, Inc. and other Node contributors.
14279//
14280// Permission is hereby granted, free of charge, to any person obtaining a
14281// copy of this software and associated documentation files (the
14282// "Software"), to deal in the Software without restriction, including
14283// without limitation the rights to use, copy, modify, merge, publish,
14284// distribute, sublicense, and/or sell copies of the Software, and to permit
14285// persons to whom the Software is furnished to do so, subject to the
14286// following conditions:
14287//
14288// The above copyright notice and this permission notice shall be included
14289// in all copies or substantial portions of the Software.
14290//
14291// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14292// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14293// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14294// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14295// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14296// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14297// USE OR OTHER DEALINGS IN THE SOFTWARE.
14298
14299'use strict';
14300
14301var punycode = require('punycode');
14302var util = require('./util');
14303
14304exports.parse = urlParse;
14305exports.resolve = urlResolve;
14306exports.resolveObject = urlResolveObject;
14307exports.format = urlFormat;
14308
14309exports.Url = Url;
14310
14311function Url() {
14312 this.protocol = null;
14313 this.slashes = null;
14314 this.auth = null;
14315 this.host = null;
14316 this.port = null;
14317 this.hostname = null;
14318 this.hash = null;
14319 this.search = null;
14320 this.query = null;
14321 this.pathname = null;
14322 this.path = null;
14323 this.href = null;
14324}
14325
14326// Reference: RFC 3986, RFC 1808, RFC 2396
14327
14328// define these here so at least they only have to be
14329// compiled once on the first module load.
14330var protocolPattern = /^([a-z0-9.+-]+:)/i,
14331 portPattern = /:[0-9]*$/,
14332
14333 // Special case for a simple path URL
14334 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
14335
14336 // RFC 2396: characters reserved for delimiting URLs.
14337 // We actually just auto-escape these.
14338 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
14339
14340 // RFC 2396: characters not allowed for various reasons.
14341 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
14342
14343 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
14344 autoEscape = ['\''].concat(unwise),
14345 // Characters that are never ever allowed in a hostname.
14346 // Note that any invalid chars are also handled, but these
14347 // are the ones that are *expected* to be seen, so we fast-path
14348 // them.
14349 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
14350 hostEndingChars = ['/', '?', '#'],
14351 hostnameMaxLen = 255,
14352 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
14353 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
14354 // protocols that can allow "unsafe" and "unwise" chars.
14355 unsafeProtocol = {
14356 'javascript': true,
14357 'javascript:': true
14358 },
14359 // protocols that never have a hostname.
14360 hostlessProtocol = {
14361 'javascript': true,
14362 'javascript:': true
14363 },
14364 // protocols that always contain a // bit.
14365 slashedProtocol = {
14366 'http': true,
14367 'https': true,
14368 'ftp': true,
14369 'gopher': true,
14370 'file': true,
14371 'http:': true,
14372 'https:': true,
14373 'ftp:': true,
14374 'gopher:': true,
14375 'file:': true
14376 },
14377 querystring = require('querystring');
14378
14379function urlParse(url, parseQueryString, slashesDenoteHost) {
14380 if (url && util.isObject(url) && url instanceof Url) return url;
14381
14382 var u = new Url;
14383 u.parse(url, parseQueryString, slashesDenoteHost);
14384 return u;
14385}
14386
14387Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
14388 if (!util.isString(url)) {
14389 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
14390 }
14391
14392 // Copy chrome, IE, opera backslash-handling behavior.
14393 // Back slashes before the query string get converted to forward slashes
14394 // See: https://code.google.com/p/chromium/issues/detail?id=25916
14395 var queryIndex = url.indexOf('?'),
14396 splitter =
14397 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
14398 uSplit = url.split(splitter),
14399 slashRegex = /\\/g;
14400 uSplit[0] = uSplit[0].replace(slashRegex, '/');
14401 url = uSplit.join(splitter);
14402
14403 var rest = url;
14404
14405 // trim before proceeding.
14406 // This is to support parse stuff like " http://foo.com \n"
14407 rest = rest.trim();
14408
14409 if (!slashesDenoteHost && url.split('#').length === 1) {
14410 // Try fast path regexp
14411 var simplePath = simplePathPattern.exec(rest);
14412 if (simplePath) {
14413 this.path = rest;
14414 this.href = rest;
14415 this.pathname = simplePath[1];
14416 if (simplePath[2]) {
14417 this.search = simplePath[2];
14418 if (parseQueryString) {
14419 this.query = querystring.parse(this.search.substr(1));
14420 } else {
14421 this.query = this.search.substr(1);
14422 }
14423 } else if (parseQueryString) {
14424 this.search = '';
14425 this.query = {};
14426 }
14427 return this;
14428 }
14429 }
14430
14431 var proto = protocolPattern.exec(rest);
14432 if (proto) {
14433 proto = proto[0];
14434 var lowerProto = proto.toLowerCase();
14435 this.protocol = lowerProto;
14436 rest = rest.substr(proto.length);
14437 }
14438
14439 // figure out if it's got a host
14440 // user@server is *always* interpreted as a hostname, and url
14441 // resolution will treat //foo/bar as host=foo,path=bar because that's
14442 // how the browser resolves relative URLs.
14443 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
14444 var slashes = rest.substr(0, 2) === '//';
14445 if (slashes && !(proto && hostlessProtocol[proto])) {
14446 rest = rest.substr(2);
14447 this.slashes = true;
14448 }
14449 }
14450
14451 if (!hostlessProtocol[proto] &&
14452 (slashes || (proto && !slashedProtocol[proto]))) {
14453
14454 // there's a hostname.
14455 // the first instance of /, ?, ;, or # ends the host.
14456 //
14457 // If there is an @ in the hostname, then non-host chars *are* allowed
14458 // to the left of the last @ sign, unless some host-ending character
14459 // comes *before* the @-sign.
14460 // URLs are obnoxious.
14461 //
14462 // ex:
14463 // http://a@b@c/ => user:a@b host:c
14464 // http://a@b?@c => user:a host:c path:/?@c
14465
14466 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
14467 // Review our test case against browsers more comprehensively.
14468
14469 // find the first instance of any hostEndingChars
14470 var hostEnd = -1;
14471 for (var i = 0; i < hostEndingChars.length; i++) {
14472 var hec = rest.indexOf(hostEndingChars[i]);
14473 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
14474 hostEnd = hec;
14475 }
14476
14477 // at this point, either we have an explicit point where the
14478 // auth portion cannot go past, or the last @ char is the decider.
14479 var auth, atSign;
14480 if (hostEnd === -1) {
14481 // atSign can be anywhere.
14482 atSign = rest.lastIndexOf('@');
14483 } else {
14484 // atSign must be in auth portion.
14485 // http://a@b/c@d => host:b auth:a path:/c@d
14486 atSign = rest.lastIndexOf('@', hostEnd);
14487 }
14488
14489 // Now we have a portion which is definitely the auth.
14490 // Pull that off.
14491 if (atSign !== -1) {
14492 auth = rest.slice(0, atSign);
14493 rest = rest.slice(atSign + 1);
14494 this.auth = decodeURIComponent(auth);
14495 }
14496
14497 // the host is the remaining to the left of the first non-host char
14498 hostEnd = -1;
14499 for (var i = 0; i < nonHostChars.length; i++) {
14500 var hec = rest.indexOf(nonHostChars[i]);
14501 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
14502 hostEnd = hec;
14503 }
14504 // if we still have not hit it, then the entire thing is a host.
14505 if (hostEnd === -1)
14506 hostEnd = rest.length;
14507
14508 this.host = rest.slice(0, hostEnd);
14509 rest = rest.slice(hostEnd);
14510
14511 // pull out port.
14512 this.parseHost();
14513
14514 // we've indicated that there is a hostname,
14515 // so even if it's empty, it has to be present.
14516 this.hostname = this.hostname || '';
14517
14518 // if hostname begins with [ and ends with ]
14519 // assume that it's an IPv6 address.
14520 var ipv6Hostname = this.hostname[0] === '[' &&
14521 this.hostname[this.hostname.length - 1] === ']';
14522
14523 // validate a little.
14524 if (!ipv6Hostname) {
14525 var hostparts = this.hostname.split(/\./);
14526 for (var i = 0, l = hostparts.length; i < l; i++) {
14527 var part = hostparts[i];
14528 if (!part) continue;
14529 if (!part.match(hostnamePartPattern)) {
14530 var newpart = '';
14531 for (var j = 0, k = part.length; j < k; j++) {
14532 if (part.charCodeAt(j) > 127) {
14533 // we replace non-ASCII char with a temporary placeholder
14534 // we need this to make sure size of hostname is not
14535 // broken by replacing non-ASCII by nothing
14536 newpart += 'x';
14537 } else {
14538 newpart += part[j];
14539 }
14540 }
14541 // we test again with ASCII char only
14542 if (!newpart.match(hostnamePartPattern)) {
14543 var validParts = hostparts.slice(0, i);
14544 var notHost = hostparts.slice(i + 1);
14545 var bit = part.match(hostnamePartStart);
14546 if (bit) {
14547 validParts.push(bit[1]);
14548 notHost.unshift(bit[2]);
14549 }
14550 if (notHost.length) {
14551 rest = '/' + notHost.join('.') + rest;
14552 }
14553 this.hostname = validParts.join('.');
14554 break;
14555 }
14556 }
14557 }
14558 }
14559
14560 if (this.hostname.length > hostnameMaxLen) {
14561 this.hostname = '';
14562 } else {
14563 // hostnames are always lower case.
14564 this.hostname = this.hostname.toLowerCase();
14565 }
14566
14567 if (!ipv6Hostname) {
14568 // IDNA Support: Returns a punycoded representation of "domain".
14569 // It only converts parts of the domain name that
14570 // have non-ASCII characters, i.e. it doesn't matter if
14571 // you call it with a domain that already is ASCII-only.
14572 this.hostname = punycode.toASCII(this.hostname);
14573 }
14574
14575 var p = this.port ? ':' + this.port : '';
14576 var h = this.hostname || '';
14577 this.host = h + p;
14578 this.href += this.host;
14579
14580 // strip [ and ] from the hostname
14581 // the host field still retains them, though
14582 if (ipv6Hostname) {
14583 this.hostname = this.hostname.substr(1, this.hostname.length - 2);
14584 if (rest[0] !== '/') {
14585 rest = '/' + rest;
14586 }
14587 }
14588 }
14589
14590 // now rest is set to the post-host stuff.
14591 // chop off any delim chars.
14592 if (!unsafeProtocol[lowerProto]) {
14593
14594 // First, make 100% sure that any "autoEscape" chars get
14595 // escaped, even if encodeURIComponent doesn't think they
14596 // need to be.
14597 for (var i = 0, l = autoEscape.length; i < l; i++) {
14598 var ae = autoEscape[i];
14599 if (rest.indexOf(ae) === -1)
14600 continue;
14601 var esc = encodeURIComponent(ae);
14602 if (esc === ae) {
14603 esc = escape(ae);
14604 }
14605 rest = rest.split(ae).join(esc);
14606 }
14607 }
14608
14609
14610 // chop off from the tail first.
14611 var hash = rest.indexOf('#');
14612 if (hash !== -1) {
14613 // got a fragment string.
14614 this.hash = rest.substr(hash);
14615 rest = rest.slice(0, hash);
14616 }
14617 var qm = rest.indexOf('?');
14618 if (qm !== -1) {
14619 this.search = rest.substr(qm);
14620 this.query = rest.substr(qm + 1);
14621 if (parseQueryString) {
14622 this.query = querystring.parse(this.query);
14623 }
14624 rest = rest.slice(0, qm);
14625 } else if (parseQueryString) {
14626 // no query string, but parseQueryString still requested
14627 this.search = '';
14628 this.query = {};
14629 }
14630 if (rest) this.pathname = rest;
14631 if (slashedProtocol[lowerProto] &&
14632 this.hostname && !this.pathname) {
14633 this.pathname = '/';
14634 }
14635
14636 //to support http.request
14637 if (this.pathname || this.search) {
14638 var p = this.pathname || '';
14639 var s = this.search || '';
14640 this.path = p + s;
14641 }
14642
14643 // finally, reconstruct the href based on what has been validated.
14644 this.href = this.format();
14645 return this;
14646};
14647
14648// format a parsed object into a url string
14649function urlFormat(obj) {
14650 // ensure it's an object, and not a string url.
14651 // If it's an obj, this is a no-op.
14652 // this way, you can call url_format() on strings
14653 // to clean up potentially wonky urls.
14654 if (util.isString(obj)) obj = urlParse(obj);
14655 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
14656 return obj.format();
14657}
14658
14659Url.prototype.format = function() {
14660 var auth = this.auth || '';
14661 if (auth) {
14662 auth = encodeURIComponent(auth);
14663 auth = auth.replace(/%3A/i, ':');
14664 auth += '@';
14665 }
14666
14667 var protocol = this.protocol || '',
14668 pathname = this.pathname || '',
14669 hash = this.hash || '',
14670 host = false,
14671 query = '';
14672
14673 if (this.host) {
14674 host = auth + this.host;
14675 } else if (this.hostname) {
14676 host = auth + (this.hostname.indexOf(':') === -1 ?
14677 this.hostname :
14678 '[' + this.hostname + ']');
14679 if (this.port) {
14680 host += ':' + this.port;
14681 }
14682 }
14683
14684 if (this.query &&
14685 util.isObject(this.query) &&
14686 Object.keys(this.query).length) {
14687 query = querystring.stringify(this.query);
14688 }
14689
14690 var search = this.search || (query && ('?' + query)) || '';
14691
14692 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
14693
14694 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
14695 // unless they had them to begin with.
14696 if (this.slashes ||
14697 (!protocol || slashedProtocol[protocol]) && host !== false) {
14698 host = '//' + (host || '');
14699 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
14700 } else if (!host) {
14701 host = '';
14702 }
14703
14704 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
14705 if (search && search.charAt(0) !== '?') search = '?' + search;
14706
14707 pathname = pathname.replace(/[?#]/g, function(match) {
14708 return encodeURIComponent(match);
14709 });
14710 search = search.replace('#', '%23');
14711
14712 return protocol + host + pathname + search + hash;
14713};
14714
14715function urlResolve(source, relative) {
14716 return urlParse(source, false, true).resolve(relative);
14717}
14718
14719Url.prototype.resolve = function(relative) {
14720 return this.resolveObject(urlParse(relative, false, true)).format();
14721};
14722
14723function urlResolveObject(source, relative) {
14724 if (!source) return relative;
14725 return urlParse(source, false, true).resolveObject(relative);
14726}
14727
14728Url.prototype.resolveObject = function(relative) {
14729 if (util.isString(relative)) {
14730 var rel = new Url();
14731 rel.parse(relative, false, true);
14732 relative = rel;
14733 }
14734
14735 var result = new Url();
14736 var tkeys = Object.keys(this);
14737 for (var tk = 0; tk < tkeys.length; tk++) {
14738 var tkey = tkeys[tk];
14739 result[tkey] = this[tkey];
14740 }
14741
14742 // hash is always overridden, no matter what.
14743 // even href="" will remove it.
14744 result.hash = relative.hash;
14745
14746 // if the relative url is empty, then there's nothing left to do here.
14747 if (relative.href === '') {
14748 result.href = result.format();
14749 return result;
14750 }
14751
14752 // hrefs like //foo/bar always cut to the protocol.
14753 if (relative.slashes && !relative.protocol) {
14754 // take everything except the protocol from relative
14755 var rkeys = Object.keys(relative);
14756 for (var rk = 0; rk < rkeys.length; rk++) {
14757 var rkey = rkeys[rk];
14758 if (rkey !== 'protocol')
14759 result[rkey] = relative[rkey];
14760 }
14761
14762 //urlParse appends trailing / to urls like http://www.example.com
14763 if (slashedProtocol[result.protocol] &&
14764 result.hostname && !result.pathname) {
14765 result.path = result.pathname = '/';
14766 }
14767
14768 result.href = result.format();
14769 return result;
14770 }
14771
14772 if (relative.protocol && relative.protocol !== result.protocol) {
14773 // if it's a known url protocol, then changing
14774 // the protocol does weird things
14775 // first, if it's not file:, then we MUST have a host,
14776 // and if there was a path
14777 // to begin with, then we MUST have a path.
14778 // if it is file:, then the host is dropped,
14779 // because that's known to be hostless.
14780 // anything else is assumed to be absolute.
14781 if (!slashedProtocol[relative.protocol]) {
14782 var keys = Object.keys(relative);
14783 for (var v = 0; v < keys.length; v++) {
14784 var k = keys[v];
14785 result[k] = relative[k];
14786 }
14787 result.href = result.format();
14788 return result;
14789 }
14790
14791 result.protocol = relative.protocol;
14792 if (!relative.host && !hostlessProtocol[relative.protocol]) {
14793 var relPath = (relative.pathname || '').split('/');
14794 while (relPath.length && !(relative.host = relPath.shift()));
14795 if (!relative.host) relative.host = '';
14796 if (!relative.hostname) relative.hostname = '';
14797 if (relPath[0] !== '') relPath.unshift('');
14798 if (relPath.length < 2) relPath.unshift('');
14799 result.pathname = relPath.join('/');
14800 } else {
14801 result.pathname = relative.pathname;
14802 }
14803 result.search = relative.search;
14804 result.query = relative.query;
14805 result.host = relative.host || '';
14806 result.auth = relative.auth;
14807 result.hostname = relative.hostname || relative.host;
14808 result.port = relative.port;
14809 // to support http.request
14810 if (result.pathname || result.search) {
14811 var p = result.pathname || '';
14812 var s = result.search || '';
14813 result.path = p + s;
14814 }
14815 result.slashes = result.slashes || relative.slashes;
14816 result.href = result.format();
14817 return result;
14818 }
14819
14820 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
14821 isRelAbs = (
14822 relative.host ||
14823 relative.pathname && relative.pathname.charAt(0) === '/'
14824 ),
14825 mustEndAbs = (isRelAbs || isSourceAbs ||
14826 (result.host && relative.pathname)),
14827 removeAllDots = mustEndAbs,
14828 srcPath = result.pathname && result.pathname.split('/') || [],
14829 relPath = relative.pathname && relative.pathname.split('/') || [],
14830 psychotic = result.protocol && !slashedProtocol[result.protocol];
14831
14832 // if the url is a non-slashed url, then relative
14833 // links like ../.. should be able
14834 // to crawl up to the hostname, as well. This is strange.
14835 // result.protocol has already been set by now.
14836 // Later on, put the first path part into the host field.
14837 if (psychotic) {
14838 result.hostname = '';
14839 result.port = null;
14840 if (result.host) {
14841 if (srcPath[0] === '') srcPath[0] = result.host;
14842 else srcPath.unshift(result.host);
14843 }
14844 result.host = '';
14845 if (relative.protocol) {
14846 relative.hostname = null;
14847 relative.port = null;
14848 if (relative.host) {
14849 if (relPath[0] === '') relPath[0] = relative.host;
14850 else relPath.unshift(relative.host);
14851 }
14852 relative.host = null;
14853 }
14854 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
14855 }
14856
14857 if (isRelAbs) {
14858 // it's absolute.
14859 result.host = (relative.host || relative.host === '') ?
14860 relative.host : result.host;
14861 result.hostname = (relative.hostname || relative.hostname === '') ?
14862 relative.hostname : result.hostname;
14863 result.search = relative.search;
14864 result.query = relative.query;
14865 srcPath = relPath;
14866 // fall through to the dot-handling below.
14867 } else if (relPath.length) {
14868 // it's relative
14869 // throw away the existing file, and take the new path instead.
14870 if (!srcPath) srcPath = [];
14871 srcPath.pop();
14872 srcPath = srcPath.concat(relPath);
14873 result.search = relative.search;
14874 result.query = relative.query;
14875 } else if (!util.isNullOrUndefined(relative.search)) {
14876 // just pull out the search.
14877 // like href='?foo'.
14878 // Put this after the other two cases because it simplifies the booleans
14879 if (psychotic) {
14880 result.hostname = result.host = srcPath.shift();
14881 //occationaly the auth can get stuck only in host
14882 //this especially happens in cases like
14883 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
14884 var authInHost = result.host && result.host.indexOf('@') > 0 ?
14885 result.host.split('@') : false;
14886 if (authInHost) {
14887 result.auth = authInHost.shift();
14888 result.host = result.hostname = authInHost.shift();
14889 }
14890 }
14891 result.search = relative.search;
14892 result.query = relative.query;
14893 //to support http.request
14894 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
14895 result.path = (result.pathname ? result.pathname : '') +
14896 (result.search ? result.search : '');
14897 }
14898 result.href = result.format();
14899 return result;
14900 }
14901
14902 if (!srcPath.length) {
14903 // no path at all. easy.
14904 // we've already handled the other stuff above.
14905 result.pathname = null;
14906 //to support http.request
14907 if (result.search) {
14908 result.path = '/' + result.search;
14909 } else {
14910 result.path = null;
14911 }
14912 result.href = result.format();
14913 return result;
14914 }
14915
14916 // if a url ENDs in . or .., then it must get a trailing slash.
14917 // however, if it ends in anything else non-slashy,
14918 // then it must NOT get a trailing slash.
14919 var last = srcPath.slice(-1)[0];
14920 var hasTrailingSlash = (
14921 (result.host || relative.host || srcPath.length > 1) &&
14922 (last === '.' || last === '..') || last === '');
14923
14924 // strip single dots, resolve double dots to parent dir
14925 // if the path tries to go above the root, `up` ends up > 0
14926 var up = 0;
14927 for (var i = srcPath.length; i >= 0; i--) {
14928 last = srcPath[i];
14929 if (last === '.') {
14930 srcPath.splice(i, 1);
14931 } else if (last === '..') {
14932 srcPath.splice(i, 1);
14933 up++;
14934 } else if (up) {
14935 srcPath.splice(i, 1);
14936 up--;
14937 }
14938 }
14939
14940 // if the path is allowed to go above the root, restore leading ..s
14941 if (!mustEndAbs && !removeAllDots) {
14942 for (; up--; up) {
14943 srcPath.unshift('..');
14944 }
14945 }
14946
14947 if (mustEndAbs && srcPath[0] !== '' &&
14948 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
14949 srcPath.unshift('');
14950 }
14951
14952 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
14953 srcPath.push('');
14954 }
14955
14956 var isAbsolute = srcPath[0] === '' ||
14957 (srcPath[0] && srcPath[0].charAt(0) === '/');
14958
14959 // put the host back
14960 if (psychotic) {
14961 result.hostname = result.host = isAbsolute ? '' :
14962 srcPath.length ? srcPath.shift() : '';
14963 //occationaly the auth can get stuck only in host
14964 //this especially happens in cases like
14965 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
14966 var authInHost = result.host && result.host.indexOf('@') > 0 ?
14967 result.host.split('@') : false;
14968 if (authInHost) {
14969 result.auth = authInHost.shift();
14970 result.host = result.hostname = authInHost.shift();
14971 }
14972 }
14973
14974 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
14975
14976 if (mustEndAbs && !isAbsolute) {
14977 srcPath.unshift('');
14978 }
14979
14980 if (!srcPath.length) {
14981 result.pathname = null;
14982 result.path = null;
14983 } else {
14984 result.pathname = srcPath.join('/');
14985 }
14986
14987 //to support request.http
14988 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
14989 result.path = (result.pathname ? result.pathname : '') +
14990 (result.search ? result.search : '');
14991 }
14992 result.auth = relative.auth || result.auth;
14993 result.slashes = result.slashes || relative.slashes;
14994 result.href = result.format();
14995 return result;
14996};
14997
14998Url.prototype.parseHost = function() {
14999 var host = this.host;
15000 var port = portPattern.exec(host);
15001 if (port) {
15002 port = port[0];
15003 if (port !== ':') {
15004 this.port = port.substr(1);
15005 }
15006 host = host.substr(0, host.length - port.length);
15007 }
15008 if (host) this.hostname = host;
15009};
15010
15011},{"./util":88,"punycode":65,"querystring":68}],88:[function(require,module,exports){
15012'use strict';
15013
15014module.exports = {
15015 isString: function(arg) {
15016 return typeof(arg) === 'string';
15017 },
15018 isObject: function(arg) {
15019 return typeof(arg) === 'object' && arg !== null;
15020 },
15021 isNull: function(arg) {
15022 return arg === null;
15023 },
15024 isNullOrUndefined: function(arg) {
15025 return arg == null;
15026 }
15027};
15028
15029},{}],89:[function(require,module,exports){
15030(function (global){
15031
15032/**
15033 * Module exports.
15034 */
15035
15036module.exports = deprecate;
15037
15038/**
15039 * Mark that a method should not be used.
15040 * Returns a modified function which warns once by default.
15041 *
15042 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
15043 *
15044 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
15045 * will throw an Error when invoked.
15046 *
15047 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
15048 * will invoke `console.trace()` instead of `console.error()`.
15049 *
15050 * @param {Function} fn - the function to deprecate
15051 * @param {String} msg - the string to print to the console when `fn` is invoked
15052 * @returns {Function} a new "deprecated" version of `fn`
15053 * @api public
15054 */
15055
15056function deprecate (fn, msg) {
15057 if (config('noDeprecation')) {
15058 return fn;
15059 }
15060
15061 var warned = false;
15062 function deprecated() {
15063 if (!warned) {
15064 if (config('throwDeprecation')) {
15065 throw new Error(msg);
15066 } else if (config('traceDeprecation')) {
15067 console.trace(msg);
15068 } else {
15069 console.warn(msg);
15070 }
15071 warned = true;
15072 }
15073 return fn.apply(this, arguments);
15074 }
15075
15076 return deprecated;
15077}
15078
15079/**
15080 * Checks `localStorage` for boolean values for the given `name`.
15081 *
15082 * @param {String} name
15083 * @returns {Boolean}
15084 * @api private
15085 */
15086
15087function config (name) {
15088 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
15089 try {
15090 if (!global.localStorage) return false;
15091 } catch (_) {
15092 return false;
15093 }
15094 var val = global.localStorage[name];
15095 if (null == val) return false;
15096 return String(val).toLowerCase() === 'true';
15097}
15098
15099}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15100
15101},{}],90:[function(require,module,exports){
15102module.exports = extend
15103
15104var hasOwnProperty = Object.prototype.hasOwnProperty;
15105
15106function extend() {
15107 var target = {}
15108
15109 for (var i = 0; i < arguments.length; i++) {
15110 var source = arguments[i]
15111
15112 for (var key in source) {
15113 if (hasOwnProperty.call(source, key)) {
15114 target[key] = source[key]
15115 }
15116 }
15117 }
15118
15119 return target
15120}
15121
15122},{}]},{},[3])(3)
15123});
15124//# sourceMappingURL=ref-parser.js.map