├── assets ├── .DS_Store ├── icon128.png ├── icon16.png └── icon48.png ├── .gitignore ├── README.md ├── rules.json ├── manifest.json ├── src ├── GeneratePDF.js ├── DocSendDownloader.js └── ModifyDocSendView.js ├── service_worker.js └── modules └── blob-stream.js /assets/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdesilva/DocSendDownloader/HEAD/assets/.DS_Store -------------------------------------------------------------------------------- /assets/icon128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdesilva/DocSendDownloader/HEAD/assets/icon128.png -------------------------------------------------------------------------------- /assets/icon16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdesilva/DocSendDownloader/HEAD/assets/icon16.png -------------------------------------------------------------------------------- /assets/icon48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdesilva/DocSendDownloader/HEAD/assets/icon48.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # For development 2 | /ignore 3 | .env 4 | /_metadata 5 | 6 | # Logs 7 | logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | pnpm-debug.log* 13 | lerna-debug.log* 14 | 15 | node_modules 16 | dist 17 | dist-ssr 18 | *.local 19 | 20 | # Editor directories and files 21 | .vscode/* 22 | !.vscode/extensions.json 23 | .idea 24 | .DS_Store 25 | *.suo 26 | *.ntvs* 27 | *.njsproj 28 | *.sln 29 | *.sw? -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DocSend Slide Deck Downloader 2 | A Chrome extension to download DocSend slides as a PDF. 3 | 4 | https://chromewebstore.google.com/detail/docsend-slide-deck-downlo/bgifpnagflkdlbakcljjokaijnmgecnm 5 | 6 | ## Installation from source 7 | 8 | 1. Clone this repository to your machine 9 | 2. Navigate to `chrome://extensions/` on Google Chrome. 10 | 3. Toggle Developer Mode on the top right if not toggled already. 11 | 4. Click Load unpacked and navigate to the directory of this repository and select it. 12 | 13 | ## Usage 14 | 15 | Navigate to any DocSend slide deck page and click on the extension icon on the top right of Google Chrome to generate a PDF of the slide deck. 16 | -------------------------------------------------------------------------------- /rules.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": 1, 4 | "priority": 1, 5 | "action": { 6 | "type": "modifyHeaders", 7 | "responseHeaders": [ 8 | { 9 | "header": "Access-Control-Allow-Origin", 10 | "operation": "set", 11 | "value": "*" 12 | }, 13 | { 14 | "header": "Access-Control-Allow-Methods", 15 | "operation": "set", 16 | "value": "GET, OPTIONS" 17 | } 18 | ] 19 | }, 20 | "condition": { 21 | "urlFilter": "|https://*cloudfront.net/*", 22 | "resourceTypes": ["image", "xmlhttprequest"] 23 | 24 | } 25 | } 26 | ] -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "DocSend Slide Deck Downloader", 3 | "version": "2.0", 4 | "description": "Download any DocSend slide deck as a PDF", 5 | "permissions": ["declarativeNetRequestWithHostAccess", "scripting"], 6 | "host_permissions": [ 7 | "*://*.docsend.com/", 8 | "*://*.cloudfront.net/*", 9 | "*://*.docsend.dropbox.com/*" 10 | ], 11 | "background": { 12 | "service_worker": "service_worker.js", 13 | "type": "module" 14 | }, 15 | "declarative_net_request": { 16 | "rule_resources": [ 17 | { 18 | "id": "ruleset_1", 19 | "enabled": true, 20 | "path": "rules.json" 21 | } 22 | ] 23 | }, 24 | "action": { 25 | "default_title": "Download a DocSend slide deck as a PDF" 26 | }, 27 | "icons": { 28 | "16": "./assets/icon16.png", 29 | "48": "./assets/icon48.png", 30 | "128": "./assets/icon128.png" 31 | }, 32 | "manifest_version": 3 33 | } 34 | -------------------------------------------------------------------------------- /src/GeneratePDF.js: -------------------------------------------------------------------------------- 1 | let startTime; 2 | let numSlidesComplete = 0; 3 | const doc = new PDFDocument({layout:'landscape', margin: 0, autoFirstPage: false}); 4 | const stream = doc.pipe(blobStream()); 5 | 6 | const getImageAsBlob = async (url) => 7 | await fetch(url) 8 | .then((response) =>{ 9 | numSlidesComplete++; 10 | showCustomAlert(`Generating slide deck as PDF: ${numSlidesComplete}/${numSlides} slides complete...`); 11 | return response.blob(); 12 | }) 13 | .then(blob => new Promise((resolve, reject) => { 14 | const reader = new FileReader(); 15 | reader.onloadend = () => resolve(reader.result); 16 | reader.onerror = reject; 17 | reader.readAsDataURL(blob); 18 | })) 19 | .catch((e) => { 20 | console.error("Error fetching slide deck images.") 21 | }) 22 | 23 | const addSlidesToPDF = async (imageUrls) =>{ 24 | for (let i=0; i { 26 | const img = doc.openImage(data); 27 | doc.addPage({size: [img.width, img.height]}); 28 | doc.image(img, 0, 0); 29 | 30 | }) 31 | } 32 | } 33 | 34 | const buildPdf = async (imageUrls) => { 35 | startTime = new Date().getTime(); 36 | await addSlidesToPDF(imageUrls); 37 | doc.end(); 38 | } -------------------------------------------------------------------------------- /service_worker.js: -------------------------------------------------------------------------------- 1 | let connection; 2 | let jobInProgress = false; 3 | let jobComplete = false; 4 | 5 | const scriptsToInject = [ 6 | "./modules/pdfkit.js", 7 | "./modules/blob-stream.js", 8 | "./src/ModifyDocSendView.js", 9 | "./src/GeneratePDF.js", 10 | "./src/DocSendDownloader.js" 11 | ]; 12 | 13 | const executeJob = () => { 14 | jobInProgress = true; 15 | chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { 16 | const currentTabId = tabs[0].id; 17 | 18 | chrome.scripting 19 | .executeScript({ 20 | target: { 21 | tabId: currentTabId, 22 | }, 23 | files: scriptsToInject 24 | }) 25 | .then(() => { 26 | connection = chrome.tabs.connect(currentTabId); 27 | connection.postMessage({requestType: "GENERATE_PDF"}); 28 | connection.onMessage.addListener((message) => { 29 | if (message.requestType == "SET_JOB_COMPLETE") { 30 | jobInProgress = false; 31 | jobComplete = true; 32 | } 33 | }) 34 | }) 35 | }) 36 | } 37 | 38 | chrome.action.onClicked.addListener(() => { 39 | if (jobComplete || jobInProgress) { 40 | try { 41 | connection.postMessage({requestType: "CHECK_PROGRESS"}); 42 | } 43 | catch { 44 | //Connection closed, start new job 45 | executeJob(); 46 | } 47 | } 48 | else if (!jobInProgress && !jobComplete) { 49 | executeJob(); 50 | } 51 | }) -------------------------------------------------------------------------------- /src/DocSendDownloader.js: -------------------------------------------------------------------------------- 1 | let connection; 2 | let numSlides = parseInt((document.getElementsByClassName("page-label")[0].innerHTML).split(" ")[0]); 3 | let baseUrl = window.location.href; 4 | let metadataEndpoint = baseUrl.charAt(baseUrl.length-1) == "/" ? baseUrl + "page_data/" : baseUrl + "/page_data/"; 5 | let slideImageUrls = []; 6 | 7 | let slideDeckAlreadyDownloaded = false; //cannot download the slide deck more than once on the same session 8 | let slideDeckGenerationInProgress = false; 9 | 10 | let userIsAuthenticated = () => { 11 | //If prompt doesn't exist, user has entered their email address to access slide deck. 12 | if (document.getElementById("prompt") == null) { 13 | return true; 14 | } else { 15 | return false; 16 | } 17 | } 18 | 19 | let getSlideImageUrls = async () => { 20 | for(let i=1; i<=numSlides; i++) { 21 | let url = metadataEndpoint + String(i); 22 | await fetch(url) 23 | .then((response) => { 24 | return response.json(); 25 | }) 26 | .then((data) => { 27 | slideImageUrls.push(data.imageUrl); 28 | }) 29 | } 30 | } 31 | 32 | let generateSlideDeckPdf = async () => { 33 | await getSlideImageUrls(); 34 | buildPdf(slideImageUrls); 35 | } 36 | 37 | chrome.runtime.onConnect.addListener((port) => { 38 | connection = port; 39 | port.onMessage.addListener((message) => { 40 | if (userIsAuthenticated()) { 41 | if (message.requestType == "GENERATE_PDF") { 42 | slideDeckGenerationInProgress = true; 43 | slideDeckAlreadyDownloaded = true; 44 | showCustomAlert(`Generating slide deck as PDF: 0/${numSlides} slides complete...`); 45 | generateSlideDeckPdf(); 46 | } 47 | else if (message.requestType == "CHECK_PROGRESS") { 48 | if (slideDeckGenerationInProgress) { 49 | showCustomAlert("Please wait. Still generating slide deck as PDF..."); 50 | } 51 | else if (slideDeckAlreadyDownloaded) { 52 | showDefaultAlert("Slide deck was already downloaded during this session. Please reload the page to download again.") 53 | } else { 54 | showDefaultAlert("ERROR: Slide deck download progress unknown. Please try again."); 55 | } 56 | } 57 | } else { 58 | showDefaultAlert("You must be signed in to download this slide deck as a PDF.") 59 | } 60 | }) 61 | }) 62 | 63 | 64 | stream.on("finish", () => { 65 | slideDeckGenerationInProgress = false; 66 | let blobUrl = stream.toBlobURL('application/pdf'); 67 | let totalTime = new Date().getTime() - startTime; 68 | initiateDownload(blobUrl); 69 | hideCustomAlert(); 70 | showDefaultAlert("Done ! Slide deck PDF generated in " + String(totalTime) + " ms."); 71 | connection.postMessage({requestType: "SET_JOB_COMPLETE"}); 72 | }) -------------------------------------------------------------------------------- /src/ModifyDocSendView.js: -------------------------------------------------------------------------------- 1 | // Get the pre-existing alert container elements. Default alerts fade after some pre-defined time. 2 | let defaultAlertContainer = document.getElementsByClassName("row flash flash-notice")[0]; 3 | let defaultAlertTextElement = document.getElementsByClassName("alert_content alert_content--with-close")[0]; 4 | 5 | // Intialize a custom alert container. These alerts do not fade. 6 | let customAlertContainer = document.createElement("div"); 7 | let customAlertContainerText = document.createElement("div"); 8 | 9 | customAlertContainer.className = "row alert alert-info"; 10 | customAlertContainer.style = "display: none;" 11 | customAlertContainerText.className = "alert_content"; 12 | customAlertContainerText.style = "display: flex;flex-direction: row;justify-content: center;align-items: center;"; 13 | 14 | customAlertContainer.appendChild(customAlertContainerText); 15 | document.body.insertBefore(customAlertContainer, document.body.firstChild); 16 | 17 | let loadingIconSVG = ''; 18 | 19 | let initiateDownload = (url) => { 20 | const filename = document.getElementsByClassName("contact-card_description").length === 1 ? document.getElementsByClassName("contact-card_description")[0].innerText.substring(1, document.getElementsByClassName("contact-card_description")[0].innerText.length-1) + " Deck" : document.getElementsByClassName("contact-card_email").length === 1 ? document.getElementsByClassName("contact-card_email")[0].href.split("@")[1].split(".")[0] + " Deck" : "slidedeck"; 21 | let downloadLink = document.createElement('a'); 22 | downloadLink.href = url; 23 | downloadLink.setAttribute('download', `${filename}.pdf`); 24 | downloadLink.click(); 25 | } 26 | 27 | 28 | let showDefaultAlert = (message) => { 29 | defaultAlertTextElement.innerHTML = message; 30 | defaultAlertContainer.setAttribute("style", "display:block;"); 31 | } 32 | 33 | 34 | let showCustomAlert = (message) => { 35 | customAlertContainerText.innerHTML = message; 36 | customAlertContainer.style = "display: block; padding: 10px; margin-bottom: 0px;"; 37 | } 38 | 39 | let hideDefaultAlert = () => { 40 | defaultAlertTextElement.innerHTML = ""; 41 | defaultAlertContainer.setAttribute("style", "display:none;"); 42 | } 43 | 44 | let hideCustomAlert = () => { 45 | customAlertContainer.style = "display: none;"; 46 | } 47 | -------------------------------------------------------------------------------- /modules/blob-stream.js: -------------------------------------------------------------------------------- 1 | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.blobStream=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 161 | * @license MIT 162 | */ 163 | 164 | var base64 = require('base64-js') 165 | var ieee754 = require('ieee754') 166 | var isArray = require('is-array') 167 | 168 | exports.Buffer = Buffer 169 | exports.SlowBuffer = Buffer 170 | exports.INSPECT_MAX_BYTES = 50 171 | Buffer.poolSize = 8192 // not used by this implementation 172 | 173 | var kMaxLength = 0x3fffffff 174 | 175 | /** 176 | * If `Buffer.TYPED_ARRAY_SUPPORT`: 177 | * === true Use Uint8Array implementation (fastest) 178 | * === false Use Object implementation (most compatible, even IE6) 179 | * 180 | * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, 181 | * Opera 11.6+, iOS 4.2+. 182 | * 183 | * Note: 184 | * 185 | * - Implementation must support adding new properties to `Uint8Array` instances. 186 | * Firefox 4-29 lacked support, fixed in Firefox 30+. 187 | * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. 188 | * 189 | * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. 190 | * 191 | * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of 192 | * incorrect length in some situations. 193 | * 194 | * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will 195 | * get the Object implementation, which is slower but will work correctly. 196 | */ 197 | Buffer.TYPED_ARRAY_SUPPORT = (function () { 198 | try { 199 | var buf = new ArrayBuffer(0) 200 | var arr = new Uint8Array(buf) 201 | arr.foo = function () { return 42 } 202 | return 42 === arr.foo() && // typed array instances can be augmented 203 | typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` 204 | new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` 205 | } catch (e) { 206 | return false 207 | } 208 | })() 209 | 210 | /** 211 | * Class: Buffer 212 | * ============= 213 | * 214 | * The Buffer constructor returns instances of `Uint8Array` that are augmented 215 | * with function properties for all the node `Buffer` API functions. We use 216 | * `Uint8Array` so that square bracket notation works as expected -- it returns 217 | * a single octet. 218 | * 219 | * By augmenting the instances, we can avoid modifying the `Uint8Array` 220 | * prototype. 221 | */ 222 | function Buffer (subject, encoding, noZero) { 223 | if (!(this instanceof Buffer)) 224 | return new Buffer(subject, encoding, noZero) 225 | 226 | var type = typeof subject 227 | 228 | // Find the length 229 | var length 230 | if (type === 'number') 231 | length = subject > 0 ? subject >>> 0 : 0 232 | else if (type === 'string') { 233 | if (encoding === 'base64') 234 | subject = base64clean(subject) 235 | length = Buffer.byteLength(subject, encoding) 236 | } else if (type === 'object' && subject !== null) { // assume object is array-like 237 | if (subject.type === 'Buffer' && isArray(subject.data)) 238 | subject = subject.data 239 | length = +subject.length > 0 ? Math.floor(+subject.length) : 0 240 | } else 241 | throw new TypeError('must start with number, buffer, array or string') 242 | 243 | if (this.length > kMaxLength) 244 | throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 245 | 'size: 0x' + kMaxLength.toString(16) + ' bytes') 246 | 247 | var buf 248 | if (Buffer.TYPED_ARRAY_SUPPORT) { 249 | // Preferred: Return an augmented `Uint8Array` instance for best performance 250 | buf = Buffer._augment(new Uint8Array(length)) 251 | } else { 252 | // Fallback: Return THIS instance of Buffer (created by `new`) 253 | buf = this 254 | buf.length = length 255 | buf._isBuffer = true 256 | } 257 | 258 | var i 259 | if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { 260 | // Speed optimization -- use set if we're copying from a typed array 261 | buf._set(subject) 262 | } else if (isArrayish(subject)) { 263 | // Treat array-ish objects as a byte array 264 | if (Buffer.isBuffer(subject)) { 265 | for (i = 0; i < length; i++) 266 | buf[i] = subject.readUInt8(i) 267 | } else { 268 | for (i = 0; i < length; i++) 269 | buf[i] = ((subject[i] % 256) + 256) % 256 270 | } 271 | } else if (type === 'string') { 272 | buf.write(subject, 0, encoding) 273 | } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) { 274 | for (i = 0; i < length; i++) { 275 | buf[i] = 0 276 | } 277 | } 278 | 279 | return buf 280 | } 281 | 282 | Buffer.isBuffer = function (b) { 283 | return !!(b != null && b._isBuffer) 284 | } 285 | 286 | Buffer.compare = function (a, b) { 287 | if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) 288 | throw new TypeError('Arguments must be Buffers') 289 | 290 | var x = a.length 291 | var y = b.length 292 | for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} 293 | if (i !== len) { 294 | x = a[i] 295 | y = b[i] 296 | } 297 | if (x < y) return -1 298 | if (y < x) return 1 299 | return 0 300 | } 301 | 302 | Buffer.isEncoding = function (encoding) { 303 | switch (String(encoding).toLowerCase()) { 304 | case 'hex': 305 | case 'utf8': 306 | case 'utf-8': 307 | case 'ascii': 308 | case 'binary': 309 | case 'base64': 310 | case 'raw': 311 | case 'ucs2': 312 | case 'ucs-2': 313 | case 'utf16le': 314 | case 'utf-16le': 315 | return true 316 | default: 317 | return false 318 | } 319 | } 320 | 321 | Buffer.concat = function (list, totalLength) { 322 | if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])') 323 | 324 | if (list.length === 0) { 325 | return new Buffer(0) 326 | } else if (list.length === 1) { 327 | return list[0] 328 | } 329 | 330 | var i 331 | if (totalLength === undefined) { 332 | totalLength = 0 333 | for (i = 0; i < list.length; i++) { 334 | totalLength += list[i].length 335 | } 336 | } 337 | 338 | var buf = new Buffer(totalLength) 339 | var pos = 0 340 | for (i = 0; i < list.length; i++) { 341 | var item = list[i] 342 | item.copy(buf, pos) 343 | pos += item.length 344 | } 345 | return buf 346 | } 347 | 348 | Buffer.byteLength = function (str, encoding) { 349 | var ret 350 | str = str + '' 351 | switch (encoding || 'utf8') { 352 | case 'ascii': 353 | case 'binary': 354 | case 'raw': 355 | ret = str.length 356 | break 357 | case 'ucs2': 358 | case 'ucs-2': 359 | case 'utf16le': 360 | case 'utf-16le': 361 | ret = str.length * 2 362 | break 363 | case 'hex': 364 | ret = str.length >>> 1 365 | break 366 | case 'utf8': 367 | case 'utf-8': 368 | ret = utf8ToBytes(str).length 369 | break 370 | case 'base64': 371 | ret = base64ToBytes(str).length 372 | break 373 | default: 374 | ret = str.length 375 | } 376 | return ret 377 | } 378 | 379 | // pre-set for values that may exist in the future 380 | Buffer.prototype.length = undefined 381 | Buffer.prototype.parent = undefined 382 | 383 | // toString(encoding, start=0, end=buffer.length) 384 | Buffer.prototype.toString = function (encoding, start, end) { 385 | var loweredCase = false 386 | 387 | start = start >>> 0 388 | end = end === undefined || end === Infinity ? this.length : end >>> 0 389 | 390 | if (!encoding) encoding = 'utf8' 391 | if (start < 0) start = 0 392 | if (end > this.length) end = this.length 393 | if (end <= start) return '' 394 | 395 | while (true) { 396 | switch (encoding) { 397 | case 'hex': 398 | return hexSlice(this, start, end) 399 | 400 | case 'utf8': 401 | case 'utf-8': 402 | return utf8Slice(this, start, end) 403 | 404 | case 'ascii': 405 | return asciiSlice(this, start, end) 406 | 407 | case 'binary': 408 | return binarySlice(this, start, end) 409 | 410 | case 'base64': 411 | return base64Slice(this, start, end) 412 | 413 | case 'ucs2': 414 | case 'ucs-2': 415 | case 'utf16le': 416 | case 'utf-16le': 417 | return utf16leSlice(this, start, end) 418 | 419 | default: 420 | if (loweredCase) 421 | throw new TypeError('Unknown encoding: ' + encoding) 422 | encoding = (encoding + '').toLowerCase() 423 | loweredCase = true 424 | } 425 | } 426 | } 427 | 428 | Buffer.prototype.equals = function (b) { 429 | if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') 430 | return Buffer.compare(this, b) === 0 431 | } 432 | 433 | Buffer.prototype.inspect = function () { 434 | var str = '' 435 | var max = exports.INSPECT_MAX_BYTES 436 | if (this.length > 0) { 437 | str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') 438 | if (this.length > max) 439 | str += ' ... ' 440 | } 441 | return '' 442 | } 443 | 444 | Buffer.prototype.compare = function (b) { 445 | if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') 446 | return Buffer.compare(this, b) 447 | } 448 | 449 | // `get` will be removed in Node 0.13+ 450 | Buffer.prototype.get = function (offset) { 451 | console.log('.get() is deprecated. Access using array indexes instead.') 452 | return this.readUInt8(offset) 453 | } 454 | 455 | // `set` will be removed in Node 0.13+ 456 | Buffer.prototype.set = function (v, offset) { 457 | console.log('.set() is deprecated. Access using array indexes instead.') 458 | return this.writeUInt8(v, offset) 459 | } 460 | 461 | function hexWrite (buf, string, offset, length) { 462 | offset = Number(offset) || 0 463 | var remaining = buf.length - offset 464 | if (!length) { 465 | length = remaining 466 | } else { 467 | length = Number(length) 468 | if (length > remaining) { 469 | length = remaining 470 | } 471 | } 472 | 473 | // must be an even number of digits 474 | var strLen = string.length 475 | if (strLen % 2 !== 0) throw new Error('Invalid hex string') 476 | 477 | if (length > strLen / 2) { 478 | length = strLen / 2 479 | } 480 | for (var i = 0; i < length; i++) { 481 | var byte = parseInt(string.substr(i * 2, 2), 16) 482 | if (isNaN(byte)) throw new Error('Invalid hex string') 483 | buf[offset + i] = byte 484 | } 485 | return i 486 | } 487 | 488 | function utf8Write (buf, string, offset, length) { 489 | var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) 490 | return charsWritten 491 | } 492 | 493 | function asciiWrite (buf, string, offset, length) { 494 | var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) 495 | return charsWritten 496 | } 497 | 498 | function binaryWrite (buf, string, offset, length) { 499 | return asciiWrite(buf, string, offset, length) 500 | } 501 | 502 | function base64Write (buf, string, offset, length) { 503 | var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) 504 | return charsWritten 505 | } 506 | 507 | function utf16leWrite (buf, string, offset, length) { 508 | var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length) 509 | return charsWritten 510 | } 511 | 512 | Buffer.prototype.write = function (string, offset, length, encoding) { 513 | // Support both (string, offset, length, encoding) 514 | // and the legacy (string, encoding, offset, length) 515 | if (isFinite(offset)) { 516 | if (!isFinite(length)) { 517 | encoding = length 518 | length = undefined 519 | } 520 | } else { // legacy 521 | var swap = encoding 522 | encoding = offset 523 | offset = length 524 | length = swap 525 | } 526 | 527 | offset = Number(offset) || 0 528 | var remaining = this.length - offset 529 | if (!length) { 530 | length = remaining 531 | } else { 532 | length = Number(length) 533 | if (length > remaining) { 534 | length = remaining 535 | } 536 | } 537 | encoding = String(encoding || 'utf8').toLowerCase() 538 | 539 | var ret 540 | switch (encoding) { 541 | case 'hex': 542 | ret = hexWrite(this, string, offset, length) 543 | break 544 | case 'utf8': 545 | case 'utf-8': 546 | ret = utf8Write(this, string, offset, length) 547 | break 548 | case 'ascii': 549 | ret = asciiWrite(this, string, offset, length) 550 | break 551 | case 'binary': 552 | ret = binaryWrite(this, string, offset, length) 553 | break 554 | case 'base64': 555 | ret = base64Write(this, string, offset, length) 556 | break 557 | case 'ucs2': 558 | case 'ucs-2': 559 | case 'utf16le': 560 | case 'utf-16le': 561 | ret = utf16leWrite(this, string, offset, length) 562 | break 563 | default: 564 | throw new TypeError('Unknown encoding: ' + encoding) 565 | } 566 | return ret 567 | } 568 | 569 | Buffer.prototype.toJSON = function () { 570 | return { 571 | type: 'Buffer', 572 | data: Array.prototype.slice.call(this._arr || this, 0) 573 | } 574 | } 575 | 576 | function base64Slice (buf, start, end) { 577 | if (start === 0 && end === buf.length) { 578 | return base64.fromByteArray(buf) 579 | } else { 580 | return base64.fromByteArray(buf.slice(start, end)) 581 | } 582 | } 583 | 584 | function utf8Slice (buf, start, end) { 585 | var res = '' 586 | var tmp = '' 587 | end = Math.min(buf.length, end) 588 | 589 | for (var i = start; i < end; i++) { 590 | if (buf[i] <= 0x7F) { 591 | res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) 592 | tmp = '' 593 | } else { 594 | tmp += '%' + buf[i].toString(16) 595 | } 596 | } 597 | 598 | return res + decodeUtf8Char(tmp) 599 | } 600 | 601 | function asciiSlice (buf, start, end) { 602 | var ret = '' 603 | end = Math.min(buf.length, end) 604 | 605 | for (var i = start; i < end; i++) { 606 | ret += String.fromCharCode(buf[i]) 607 | } 608 | return ret 609 | } 610 | 611 | function binarySlice (buf, start, end) { 612 | return asciiSlice(buf, start, end) 613 | } 614 | 615 | function hexSlice (buf, start, end) { 616 | var len = buf.length 617 | 618 | if (!start || start < 0) start = 0 619 | if (!end || end < 0 || end > len) end = len 620 | 621 | var out = '' 622 | for (var i = start; i < end; i++) { 623 | out += toHex(buf[i]) 624 | } 625 | return out 626 | } 627 | 628 | function utf16leSlice (buf, start, end) { 629 | var bytes = buf.slice(start, end) 630 | var res = '' 631 | for (var i = 0; i < bytes.length; i += 2) { 632 | res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) 633 | } 634 | return res 635 | } 636 | 637 | Buffer.prototype.slice = function (start, end) { 638 | var len = this.length 639 | start = ~~start 640 | end = end === undefined ? len : ~~end 641 | 642 | if (start < 0) { 643 | start += len; 644 | if (start < 0) 645 | start = 0 646 | } else if (start > len) { 647 | start = len 648 | } 649 | 650 | if (end < 0) { 651 | end += len 652 | if (end < 0) 653 | end = 0 654 | } else if (end > len) { 655 | end = len 656 | } 657 | 658 | if (end < start) 659 | end = start 660 | 661 | if (Buffer.TYPED_ARRAY_SUPPORT) { 662 | return Buffer._augment(this.subarray(start, end)) 663 | } else { 664 | var sliceLen = end - start 665 | var newBuf = new Buffer(sliceLen, undefined, true) 666 | for (var i = 0; i < sliceLen; i++) { 667 | newBuf[i] = this[i + start] 668 | } 669 | return newBuf 670 | } 671 | } 672 | 673 | /* 674 | * Need to make sure that buffer isn't trying to write out of bounds. 675 | */ 676 | function checkOffset (offset, ext, length) { 677 | if ((offset % 1) !== 0 || offset < 0) 678 | throw new RangeError('offset is not uint') 679 | if (offset + ext > length) 680 | throw new RangeError('Trying to access beyond buffer length') 681 | } 682 | 683 | Buffer.prototype.readUInt8 = function (offset, noAssert) { 684 | if (!noAssert) 685 | checkOffset(offset, 1, this.length) 686 | return this[offset] 687 | } 688 | 689 | Buffer.prototype.readUInt16LE = function (offset, noAssert) { 690 | if (!noAssert) 691 | checkOffset(offset, 2, this.length) 692 | return this[offset] | (this[offset + 1] << 8) 693 | } 694 | 695 | Buffer.prototype.readUInt16BE = function (offset, noAssert) { 696 | if (!noAssert) 697 | checkOffset(offset, 2, this.length) 698 | return (this[offset] << 8) | this[offset + 1] 699 | } 700 | 701 | Buffer.prototype.readUInt32LE = function (offset, noAssert) { 702 | if (!noAssert) 703 | checkOffset(offset, 4, this.length) 704 | 705 | return ((this[offset]) | 706 | (this[offset + 1] << 8) | 707 | (this[offset + 2] << 16)) + 708 | (this[offset + 3] * 0x1000000) 709 | } 710 | 711 | Buffer.prototype.readUInt32BE = function (offset, noAssert) { 712 | if (!noAssert) 713 | checkOffset(offset, 4, this.length) 714 | 715 | return (this[offset] * 0x1000000) + 716 | ((this[offset + 1] << 16) | 717 | (this[offset + 2] << 8) | 718 | this[offset + 3]) 719 | } 720 | 721 | Buffer.prototype.readInt8 = function (offset, noAssert) { 722 | if (!noAssert) 723 | checkOffset(offset, 1, this.length) 724 | if (!(this[offset] & 0x80)) 725 | return (this[offset]) 726 | return ((0xff - this[offset] + 1) * -1) 727 | } 728 | 729 | Buffer.prototype.readInt16LE = function (offset, noAssert) { 730 | if (!noAssert) 731 | checkOffset(offset, 2, this.length) 732 | var val = this[offset] | (this[offset + 1] << 8) 733 | return (val & 0x8000) ? val | 0xFFFF0000 : val 734 | } 735 | 736 | Buffer.prototype.readInt16BE = function (offset, noAssert) { 737 | if (!noAssert) 738 | checkOffset(offset, 2, this.length) 739 | var val = this[offset + 1] | (this[offset] << 8) 740 | return (val & 0x8000) ? val | 0xFFFF0000 : val 741 | } 742 | 743 | Buffer.prototype.readInt32LE = function (offset, noAssert) { 744 | if (!noAssert) 745 | checkOffset(offset, 4, this.length) 746 | 747 | return (this[offset]) | 748 | (this[offset + 1] << 8) | 749 | (this[offset + 2] << 16) | 750 | (this[offset + 3] << 24) 751 | } 752 | 753 | Buffer.prototype.readInt32BE = function (offset, noAssert) { 754 | if (!noAssert) 755 | checkOffset(offset, 4, this.length) 756 | 757 | return (this[offset] << 24) | 758 | (this[offset + 1] << 16) | 759 | (this[offset + 2] << 8) | 760 | (this[offset + 3]) 761 | } 762 | 763 | Buffer.prototype.readFloatLE = function (offset, noAssert) { 764 | if (!noAssert) 765 | checkOffset(offset, 4, this.length) 766 | return ieee754.read(this, offset, true, 23, 4) 767 | } 768 | 769 | Buffer.prototype.readFloatBE = function (offset, noAssert) { 770 | if (!noAssert) 771 | checkOffset(offset, 4, this.length) 772 | return ieee754.read(this, offset, false, 23, 4) 773 | } 774 | 775 | Buffer.prototype.readDoubleLE = function (offset, noAssert) { 776 | if (!noAssert) 777 | checkOffset(offset, 8, this.length) 778 | return ieee754.read(this, offset, true, 52, 8) 779 | } 780 | 781 | Buffer.prototype.readDoubleBE = function (offset, noAssert) { 782 | if (!noAssert) 783 | checkOffset(offset, 8, this.length) 784 | return ieee754.read(this, offset, false, 52, 8) 785 | } 786 | 787 | function checkInt (buf, value, offset, ext, max, min) { 788 | if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') 789 | if (value > max || value < min) throw new TypeError('value is out of bounds') 790 | if (offset + ext > buf.length) throw new TypeError('index out of range') 791 | } 792 | 793 | Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { 794 | value = +value 795 | offset = offset >>> 0 796 | if (!noAssert) 797 | checkInt(this, value, offset, 1, 0xff, 0) 798 | if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) 799 | this[offset] = value 800 | return offset + 1 801 | } 802 | 803 | function objectWriteUInt16 (buf, value, offset, littleEndian) { 804 | if (value < 0) value = 0xffff + value + 1 805 | for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { 806 | buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> 807 | (littleEndian ? i : 1 - i) * 8 808 | } 809 | } 810 | 811 | Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { 812 | value = +value 813 | offset = offset >>> 0 814 | if (!noAssert) 815 | checkInt(this, value, offset, 2, 0xffff, 0) 816 | if (Buffer.TYPED_ARRAY_SUPPORT) { 817 | this[offset] = value 818 | this[offset + 1] = (value >>> 8) 819 | } else objectWriteUInt16(this, value, offset, true) 820 | return offset + 2 821 | } 822 | 823 | Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { 824 | value = +value 825 | offset = offset >>> 0 826 | if (!noAssert) 827 | checkInt(this, value, offset, 2, 0xffff, 0) 828 | if (Buffer.TYPED_ARRAY_SUPPORT) { 829 | this[offset] = (value >>> 8) 830 | this[offset + 1] = value 831 | } else objectWriteUInt16(this, value, offset, false) 832 | return offset + 2 833 | } 834 | 835 | function objectWriteUInt32 (buf, value, offset, littleEndian) { 836 | if (value < 0) value = 0xffffffff + value + 1 837 | for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { 838 | buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff 839 | } 840 | } 841 | 842 | Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { 843 | value = +value 844 | offset = offset >>> 0 845 | if (!noAssert) 846 | checkInt(this, value, offset, 4, 0xffffffff, 0) 847 | if (Buffer.TYPED_ARRAY_SUPPORT) { 848 | this[offset + 3] = (value >>> 24) 849 | this[offset + 2] = (value >>> 16) 850 | this[offset + 1] = (value >>> 8) 851 | this[offset] = value 852 | } else objectWriteUInt32(this, value, offset, true) 853 | return offset + 4 854 | } 855 | 856 | Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { 857 | value = +value 858 | offset = offset >>> 0 859 | if (!noAssert) 860 | checkInt(this, value, offset, 4, 0xffffffff, 0) 861 | if (Buffer.TYPED_ARRAY_SUPPORT) { 862 | this[offset] = (value >>> 24) 863 | this[offset + 1] = (value >>> 16) 864 | this[offset + 2] = (value >>> 8) 865 | this[offset + 3] = value 866 | } else objectWriteUInt32(this, value, offset, false) 867 | return offset + 4 868 | } 869 | 870 | Buffer.prototype.writeInt8 = function (value, offset, noAssert) { 871 | value = +value 872 | offset = offset >>> 0 873 | if (!noAssert) 874 | checkInt(this, value, offset, 1, 0x7f, -0x80) 875 | if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) 876 | if (value < 0) value = 0xff + value + 1 877 | this[offset] = value 878 | return offset + 1 879 | } 880 | 881 | Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { 882 | value = +value 883 | offset = offset >>> 0 884 | if (!noAssert) 885 | checkInt(this, value, offset, 2, 0x7fff, -0x8000) 886 | if (Buffer.TYPED_ARRAY_SUPPORT) { 887 | this[offset] = value 888 | this[offset + 1] = (value >>> 8) 889 | } else objectWriteUInt16(this, value, offset, true) 890 | return offset + 2 891 | } 892 | 893 | Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { 894 | value = +value 895 | offset = offset >>> 0 896 | if (!noAssert) 897 | checkInt(this, value, offset, 2, 0x7fff, -0x8000) 898 | if (Buffer.TYPED_ARRAY_SUPPORT) { 899 | this[offset] = (value >>> 8) 900 | this[offset + 1] = value 901 | } else objectWriteUInt16(this, value, offset, false) 902 | return offset + 2 903 | } 904 | 905 | Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { 906 | value = +value 907 | offset = offset >>> 0 908 | if (!noAssert) 909 | checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) 910 | if (Buffer.TYPED_ARRAY_SUPPORT) { 911 | this[offset] = value 912 | this[offset + 1] = (value >>> 8) 913 | this[offset + 2] = (value >>> 16) 914 | this[offset + 3] = (value >>> 24) 915 | } else objectWriteUInt32(this, value, offset, true) 916 | return offset + 4 917 | } 918 | 919 | Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { 920 | value = +value 921 | offset = offset >>> 0 922 | if (!noAssert) 923 | checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) 924 | if (value < 0) value = 0xffffffff + value + 1 925 | if (Buffer.TYPED_ARRAY_SUPPORT) { 926 | this[offset] = (value >>> 24) 927 | this[offset + 1] = (value >>> 16) 928 | this[offset + 2] = (value >>> 8) 929 | this[offset + 3] = value 930 | } else objectWriteUInt32(this, value, offset, false) 931 | return offset + 4 932 | } 933 | 934 | function checkIEEE754 (buf, value, offset, ext, max, min) { 935 | if (value > max || value < min) throw new TypeError('value is out of bounds') 936 | if (offset + ext > buf.length) throw new TypeError('index out of range') 937 | } 938 | 939 | function writeFloat (buf, value, offset, littleEndian, noAssert) { 940 | if (!noAssert) 941 | checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) 942 | ieee754.write(buf, value, offset, littleEndian, 23, 4) 943 | return offset + 4 944 | } 945 | 946 | Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { 947 | return writeFloat(this, value, offset, true, noAssert) 948 | } 949 | 950 | Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { 951 | return writeFloat(this, value, offset, false, noAssert) 952 | } 953 | 954 | function writeDouble (buf, value, offset, littleEndian, noAssert) { 955 | if (!noAssert) 956 | checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) 957 | ieee754.write(buf, value, offset, littleEndian, 52, 8) 958 | return offset + 8 959 | } 960 | 961 | Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { 962 | return writeDouble(this, value, offset, true, noAssert) 963 | } 964 | 965 | Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { 966 | return writeDouble(this, value, offset, false, noAssert) 967 | } 968 | 969 | // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) 970 | Buffer.prototype.copy = function (target, target_start, start, end) { 971 | var source = this 972 | 973 | if (!start) start = 0 974 | if (!end && end !== 0) end = this.length 975 | if (!target_start) target_start = 0 976 | 977 | // Copy 0 bytes; we're done 978 | if (end === start) return 979 | if (target.length === 0 || source.length === 0) return 980 | 981 | // Fatal error conditions 982 | if (end < start) throw new TypeError('sourceEnd < sourceStart') 983 | if (target_start < 0 || target_start >= target.length) 984 | throw new TypeError('targetStart out of bounds') 985 | if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds') 986 | if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds') 987 | 988 | // Are we oob? 989 | if (end > this.length) 990 | end = this.length 991 | if (target.length - target_start < end - start) 992 | end = target.length - target_start + start 993 | 994 | var len = end - start 995 | 996 | if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { 997 | for (var i = 0; i < len; i++) { 998 | target[i + target_start] = this[i + start] 999 | } 1000 | } else { 1001 | target._set(this.subarray(start, start + len), target_start) 1002 | } 1003 | } 1004 | 1005 | // fill(value, start=0, end=buffer.length) 1006 | Buffer.prototype.fill = function (value, start, end) { 1007 | if (!value) value = 0 1008 | if (!start) start = 0 1009 | if (!end) end = this.length 1010 | 1011 | if (end < start) throw new TypeError('end < start') 1012 | 1013 | // Fill 0 bytes; we're done 1014 | if (end === start) return 1015 | if (this.length === 0) return 1016 | 1017 | if (start < 0 || start >= this.length) throw new TypeError('start out of bounds') 1018 | if (end < 0 || end > this.length) throw new TypeError('end out of bounds') 1019 | 1020 | var i 1021 | if (typeof value === 'number') { 1022 | for (i = start; i < end; i++) { 1023 | this[i] = value 1024 | } 1025 | } else { 1026 | var bytes = utf8ToBytes(value.toString()) 1027 | var len = bytes.length 1028 | for (i = start; i < end; i++) { 1029 | this[i] = bytes[i % len] 1030 | } 1031 | } 1032 | 1033 | return this 1034 | } 1035 | 1036 | /** 1037 | * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. 1038 | * Added in Node 0.12. Only available in browsers that support ArrayBuffer. 1039 | */ 1040 | Buffer.prototype.toArrayBuffer = function () { 1041 | if (typeof Uint8Array !== 'undefined') { 1042 | if (Buffer.TYPED_ARRAY_SUPPORT) { 1043 | return (new Buffer(this)).buffer 1044 | } else { 1045 | var buf = new Uint8Array(this.length) 1046 | for (var i = 0, len = buf.length; i < len; i += 1) { 1047 | buf[i] = this[i] 1048 | } 1049 | return buf.buffer 1050 | } 1051 | } else { 1052 | throw new TypeError('Buffer.toArrayBuffer not supported in this browser') 1053 | } 1054 | } 1055 | 1056 | // HELPER FUNCTIONS 1057 | // ================ 1058 | 1059 | var BP = Buffer.prototype 1060 | 1061 | /** 1062 | * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods 1063 | */ 1064 | Buffer._augment = function (arr) { 1065 | arr.constructor = Buffer 1066 | arr._isBuffer = true 1067 | 1068 | // save reference to original Uint8Array get/set methods before overwriting 1069 | arr._get = arr.get 1070 | arr._set = arr.set 1071 | 1072 | // deprecated, will be removed in node 0.13+ 1073 | arr.get = BP.get 1074 | arr.set = BP.set 1075 | 1076 | arr.write = BP.write 1077 | arr.toString = BP.toString 1078 | arr.toLocaleString = BP.toString 1079 | arr.toJSON = BP.toJSON 1080 | arr.equals = BP.equals 1081 | arr.compare = BP.compare 1082 | arr.copy = BP.copy 1083 | arr.slice = BP.slice 1084 | arr.readUInt8 = BP.readUInt8 1085 | arr.readUInt16LE = BP.readUInt16LE 1086 | arr.readUInt16BE = BP.readUInt16BE 1087 | arr.readUInt32LE = BP.readUInt32LE 1088 | arr.readUInt32BE = BP.readUInt32BE 1089 | arr.readInt8 = BP.readInt8 1090 | arr.readInt16LE = BP.readInt16LE 1091 | arr.readInt16BE = BP.readInt16BE 1092 | arr.readInt32LE = BP.readInt32LE 1093 | arr.readInt32BE = BP.readInt32BE 1094 | arr.readFloatLE = BP.readFloatLE 1095 | arr.readFloatBE = BP.readFloatBE 1096 | arr.readDoubleLE = BP.readDoubleLE 1097 | arr.readDoubleBE = BP.readDoubleBE 1098 | arr.writeUInt8 = BP.writeUInt8 1099 | arr.writeUInt16LE = BP.writeUInt16LE 1100 | arr.writeUInt16BE = BP.writeUInt16BE 1101 | arr.writeUInt32LE = BP.writeUInt32LE 1102 | arr.writeUInt32BE = BP.writeUInt32BE 1103 | arr.writeInt8 = BP.writeInt8 1104 | arr.writeInt16LE = BP.writeInt16LE 1105 | arr.writeInt16BE = BP.writeInt16BE 1106 | arr.writeInt32LE = BP.writeInt32LE 1107 | arr.writeInt32BE = BP.writeInt32BE 1108 | arr.writeFloatLE = BP.writeFloatLE 1109 | arr.writeFloatBE = BP.writeFloatBE 1110 | arr.writeDoubleLE = BP.writeDoubleLE 1111 | arr.writeDoubleBE = BP.writeDoubleBE 1112 | arr.fill = BP.fill 1113 | arr.inspect = BP.inspect 1114 | arr.toArrayBuffer = BP.toArrayBuffer 1115 | 1116 | return arr 1117 | } 1118 | 1119 | var INVALID_BASE64_RE = /[^+\/0-9A-z]/g 1120 | 1121 | function base64clean (str) { 1122 | // Node strips out invalid characters like \n and \t from the string, base64-js does not 1123 | str = stringtrim(str).replace(INVALID_BASE64_RE, '') 1124 | // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not 1125 | while (str.length % 4 !== 0) { 1126 | str = str + '=' 1127 | } 1128 | return str 1129 | } 1130 | 1131 | function stringtrim (str) { 1132 | if (str.trim) return str.trim() 1133 | return str.replace(/^\s+|\s+$/g, '') 1134 | } 1135 | 1136 | function isArrayish (subject) { 1137 | return isArray(subject) || Buffer.isBuffer(subject) || 1138 | subject && typeof subject === 'object' && 1139 | typeof subject.length === 'number' 1140 | } 1141 | 1142 | function toHex (n) { 1143 | if (n < 16) return '0' + n.toString(16) 1144 | return n.toString(16) 1145 | } 1146 | 1147 | function utf8ToBytes (str) { 1148 | var byteArray = [] 1149 | for (var i = 0; i < str.length; i++) { 1150 | var b = str.charCodeAt(i) 1151 | if (b <= 0x7F) { 1152 | byteArray.push(b) 1153 | } else { 1154 | var start = i 1155 | if (b >= 0xD800 && b <= 0xDFFF) i++ 1156 | var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') 1157 | for (var j = 0; j < h.length; j++) { 1158 | byteArray.push(parseInt(h[j], 16)) 1159 | } 1160 | } 1161 | } 1162 | return byteArray 1163 | } 1164 | 1165 | function asciiToBytes (str) { 1166 | var byteArray = [] 1167 | for (var i = 0; i < str.length; i++) { 1168 | // Node's code seems to be doing this and not & 0x7F.. 1169 | byteArray.push(str.charCodeAt(i) & 0xFF) 1170 | } 1171 | return byteArray 1172 | } 1173 | 1174 | function utf16leToBytes (str) { 1175 | var c, hi, lo 1176 | var byteArray = [] 1177 | for (var i = 0; i < str.length; i++) { 1178 | c = str.charCodeAt(i) 1179 | hi = c >> 8 1180 | lo = c % 256 1181 | byteArray.push(lo) 1182 | byteArray.push(hi) 1183 | } 1184 | 1185 | return byteArray 1186 | } 1187 | 1188 | function base64ToBytes (str) { 1189 | return base64.toByteArray(str) 1190 | } 1191 | 1192 | function blitBuffer (src, dst, offset, length) { 1193 | for (var i = 0; i < length; i++) { 1194 | if ((i + offset >= dst.length) || (i >= src.length)) 1195 | break 1196 | dst[i + offset] = src[i] 1197 | } 1198 | return i 1199 | } 1200 | 1201 | function decodeUtf8Char (str) { 1202 | try { 1203 | return decodeURIComponent(str) 1204 | } catch (err) { 1205 | return String.fromCharCode(0xFFFD) // UTF 8 invalid char 1206 | } 1207 | } 1208 | 1209 | },{"base64-js":4,"ieee754":5,"is-array":6}],4:[function(require,module,exports){ 1210 | var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; 1211 | 1212 | ;(function (exports) { 1213 | 'use strict'; 1214 | 1215 | var Arr = (typeof Uint8Array !== 'undefined') 1216 | ? Uint8Array 1217 | : Array 1218 | 1219 | var PLUS = '+'.charCodeAt(0) 1220 | var SLASH = '/'.charCodeAt(0) 1221 | var NUMBER = '0'.charCodeAt(0) 1222 | var LOWER = 'a'.charCodeAt(0) 1223 | var UPPER = 'A'.charCodeAt(0) 1224 | 1225 | function decode (elt) { 1226 | var code = elt.charCodeAt(0) 1227 | if (code === PLUS) 1228 | return 62 // '+' 1229 | if (code === SLASH) 1230 | return 63 // '/' 1231 | if (code < NUMBER) 1232 | return -1 //no match 1233 | if (code < NUMBER + 10) 1234 | return code - NUMBER + 26 + 26 1235 | if (code < UPPER + 26) 1236 | return code - UPPER 1237 | if (code < LOWER + 26) 1238 | return code - LOWER + 26 1239 | } 1240 | 1241 | function b64ToByteArray (b64) { 1242 | var i, j, l, tmp, placeHolders, arr 1243 | 1244 | if (b64.length % 4 > 0) { 1245 | throw new Error('Invalid string. Length must be a multiple of 4') 1246 | } 1247 | 1248 | // the number of equal signs (place holders) 1249 | // if there are two placeholders, than the two characters before it 1250 | // represent one byte 1251 | // if there is only one, then the three characters before it represent 2 bytes 1252 | // this is just a cheap hack to not do indexOf twice 1253 | var len = b64.length 1254 | placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 1255 | 1256 | // base64 is 4/3 + up to two characters of the original data 1257 | arr = new Arr(b64.length * 3 / 4 - placeHolders) 1258 | 1259 | // if there are placeholders, only get up to the last complete 4 chars 1260 | l = placeHolders > 0 ? b64.length - 4 : b64.length 1261 | 1262 | var L = 0 1263 | 1264 | function push (v) { 1265 | arr[L++] = v 1266 | } 1267 | 1268 | for (i = 0, j = 0; i < l; i += 4, j += 3) { 1269 | tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) 1270 | push((tmp & 0xFF0000) >> 16) 1271 | push((tmp & 0xFF00) >> 8) 1272 | push(tmp & 0xFF) 1273 | } 1274 | 1275 | if (placeHolders === 2) { 1276 | tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) 1277 | push(tmp & 0xFF) 1278 | } else if (placeHolders === 1) { 1279 | tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) 1280 | push((tmp >> 8) & 0xFF) 1281 | push(tmp & 0xFF) 1282 | } 1283 | 1284 | return arr 1285 | } 1286 | 1287 | function uint8ToBase64 (uint8) { 1288 | var i, 1289 | extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes 1290 | output = "", 1291 | temp, length 1292 | 1293 | function encode (num) { 1294 | return lookup.charAt(num) 1295 | } 1296 | 1297 | function tripletToBase64 (num) { 1298 | return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) 1299 | } 1300 | 1301 | // go through the array every three bytes, we'll deal with trailing stuff later 1302 | for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { 1303 | temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) 1304 | output += tripletToBase64(temp) 1305 | } 1306 | 1307 | // pad the end with zeros, but make sure to not forget the extra bytes 1308 | switch (extraBytes) { 1309 | case 1: 1310 | temp = uint8[uint8.length - 1] 1311 | output += encode(temp >> 2) 1312 | output += encode((temp << 4) & 0x3F) 1313 | output += '==' 1314 | break 1315 | case 2: 1316 | temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) 1317 | output += encode(temp >> 10) 1318 | output += encode((temp >> 4) & 0x3F) 1319 | output += encode((temp << 2) & 0x3F) 1320 | output += '=' 1321 | break 1322 | } 1323 | 1324 | return output 1325 | } 1326 | 1327 | exports.toByteArray = b64ToByteArray 1328 | exports.fromByteArray = uint8ToBase64 1329 | }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) 1330 | 1331 | },{}],5:[function(require,module,exports){ 1332 | exports.read = function(buffer, offset, isLE, mLen, nBytes) { 1333 | var e, m, 1334 | eLen = nBytes * 8 - mLen - 1, 1335 | eMax = (1 << eLen) - 1, 1336 | eBias = eMax >> 1, 1337 | nBits = -7, 1338 | i = isLE ? (nBytes - 1) : 0, 1339 | d = isLE ? -1 : 1, 1340 | s = buffer[offset + i]; 1341 | 1342 | i += d; 1343 | 1344 | e = s & ((1 << (-nBits)) - 1); 1345 | s >>= (-nBits); 1346 | nBits += eLen; 1347 | for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); 1348 | 1349 | m = e & ((1 << (-nBits)) - 1); 1350 | e >>= (-nBits); 1351 | nBits += mLen; 1352 | for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); 1353 | 1354 | if (e === 0) { 1355 | e = 1 - eBias; 1356 | } else if (e === eMax) { 1357 | return m ? NaN : ((s ? -1 : 1) * Infinity); 1358 | } else { 1359 | m = m + Math.pow(2, mLen); 1360 | e = e - eBias; 1361 | } 1362 | return (s ? -1 : 1) * m * Math.pow(2, e - mLen); 1363 | }; 1364 | 1365 | exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { 1366 | var e, m, c, 1367 | eLen = nBytes * 8 - mLen - 1, 1368 | eMax = (1 << eLen) - 1, 1369 | eBias = eMax >> 1, 1370 | rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), 1371 | i = isLE ? 0 : (nBytes - 1), 1372 | d = isLE ? 1 : -1, 1373 | s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; 1374 | 1375 | value = Math.abs(value); 1376 | 1377 | if (isNaN(value) || value === Infinity) { 1378 | m = isNaN(value) ? 1 : 0; 1379 | e = eMax; 1380 | } else { 1381 | e = Math.floor(Math.log(value) / Math.LN2); 1382 | if (value * (c = Math.pow(2, -e)) < 1) { 1383 | e--; 1384 | c *= 2; 1385 | } 1386 | if (e + eBias >= 1) { 1387 | value += rt / c; 1388 | } else { 1389 | value += rt * Math.pow(2, 1 - eBias); 1390 | } 1391 | if (value * c >= 2) { 1392 | e++; 1393 | c /= 2; 1394 | } 1395 | 1396 | if (e + eBias >= eMax) { 1397 | m = 0; 1398 | e = eMax; 1399 | } else if (e + eBias >= 1) { 1400 | m = (value * c - 1) * Math.pow(2, mLen); 1401 | e = e + eBias; 1402 | } else { 1403 | m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); 1404 | e = 0; 1405 | } 1406 | } 1407 | 1408 | for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); 1409 | 1410 | e = (e << mLen) | m; 1411 | eLen += mLen; 1412 | for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); 1413 | 1414 | buffer[offset + i - d] |= s * 128; 1415 | }; 1416 | 1417 | },{}],6:[function(require,module,exports){ 1418 | 1419 | /** 1420 | * isArray 1421 | */ 1422 | 1423 | var isArray = Array.isArray; 1424 | 1425 | /** 1426 | * toString 1427 | */ 1428 | 1429 | var str = Object.prototype.toString; 1430 | 1431 | /** 1432 | * Whether or not the given `val` 1433 | * is an array. 1434 | * 1435 | * example: 1436 | * 1437 | * isArray([]); 1438 | * // > true 1439 | * isArray(arguments); 1440 | * // > false 1441 | * isArray(''); 1442 | * // > false 1443 | * 1444 | * @param {mixed} val 1445 | * @return {bool} 1446 | */ 1447 | 1448 | module.exports = isArray || function (val) { 1449 | return !! val && '[object Array]' == str.call(val); 1450 | }; 1451 | 1452 | },{}],7:[function(require,module,exports){ 1453 | // Copyright Joyent, Inc. and other Node contributors. 1454 | // 1455 | // Permission is hereby granted, free of charge, to any person obtaining a 1456 | // copy of this software and associated documentation files (the 1457 | // "Software"), to deal in the Software without restriction, including 1458 | // without limitation the rights to use, copy, modify, merge, publish, 1459 | // distribute, sublicense, and/or sell copies of the Software, and to permit 1460 | // persons to whom the Software is furnished to do so, subject to the 1461 | // following conditions: 1462 | // 1463 | // The above copyright notice and this permission notice shall be included 1464 | // in all copies or substantial portions of the Software. 1465 | // 1466 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 1467 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 1468 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 1469 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 1470 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 1471 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 1472 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 1473 | 1474 | function EventEmitter() { 1475 | this._events = this._events || {}; 1476 | this._maxListeners = this._maxListeners || undefined; 1477 | } 1478 | module.exports = EventEmitter; 1479 | 1480 | // Backwards-compat with node 0.10.x 1481 | EventEmitter.EventEmitter = EventEmitter; 1482 | 1483 | EventEmitter.prototype._events = undefined; 1484 | EventEmitter.prototype._maxListeners = undefined; 1485 | 1486 | // By default EventEmitters will print a warning if more than 10 listeners are 1487 | // added to it. This is a useful default which helps finding memory leaks. 1488 | EventEmitter.defaultMaxListeners = 10; 1489 | 1490 | // Obviously not all Emitters should be limited to 10. This function allows 1491 | // that to be increased. Set to zero for unlimited. 1492 | EventEmitter.prototype.setMaxListeners = function(n) { 1493 | if (!isNumber(n) || n < 0 || isNaN(n)) 1494 | throw TypeError('n must be a positive number'); 1495 | this._maxListeners = n; 1496 | return this; 1497 | }; 1498 | 1499 | EventEmitter.prototype.emit = function(type) { 1500 | var er, handler, len, args, i, listeners; 1501 | 1502 | if (!this._events) 1503 | this._events = {}; 1504 | 1505 | // If there is no 'error' event listener then throw. 1506 | if (type === 'error') { 1507 | if (!this._events.error || 1508 | (isObject(this._events.error) && !this._events.error.length)) { 1509 | er = arguments[1]; 1510 | if (er instanceof Error) { 1511 | throw er; // Unhandled 'error' event 1512 | } 1513 | throw TypeError('Uncaught, unspecified "error" event.'); 1514 | } 1515 | } 1516 | 1517 | handler = this._events[type]; 1518 | 1519 | if (isUndefined(handler)) 1520 | return false; 1521 | 1522 | if (isFunction(handler)) { 1523 | switch (arguments.length) { 1524 | // fast cases 1525 | case 1: 1526 | handler.call(this); 1527 | break; 1528 | case 2: 1529 | handler.call(this, arguments[1]); 1530 | break; 1531 | case 3: 1532 | handler.call(this, arguments[1], arguments[2]); 1533 | break; 1534 | // slower 1535 | default: 1536 | len = arguments.length; 1537 | args = new Array(len - 1); 1538 | for (i = 1; i < len; i++) 1539 | args[i - 1] = arguments[i]; 1540 | handler.apply(this, args); 1541 | } 1542 | } else if (isObject(handler)) { 1543 | len = arguments.length; 1544 | args = new Array(len - 1); 1545 | for (i = 1; i < len; i++) 1546 | args[i - 1] = arguments[i]; 1547 | 1548 | listeners = handler.slice(); 1549 | len = listeners.length; 1550 | for (i = 0; i < len; i++) 1551 | listeners[i].apply(this, args); 1552 | } 1553 | 1554 | return true; 1555 | }; 1556 | 1557 | EventEmitter.prototype.addListener = function(type, listener) { 1558 | var m; 1559 | 1560 | if (!isFunction(listener)) 1561 | throw TypeError('listener must be a function'); 1562 | 1563 | if (!this._events) 1564 | this._events = {}; 1565 | 1566 | // To avoid recursion in the case that type === "newListener"! Before 1567 | // adding it to the listeners, first emit "newListener". 1568 | if (this._events.newListener) 1569 | this.emit('newListener', type, 1570 | isFunction(listener.listener) ? 1571 | listener.listener : listener); 1572 | 1573 | if (!this._events[type]) 1574 | // Optimize the case of one listener. Don't need the extra array object. 1575 | this._events[type] = listener; 1576 | else if (isObject(this._events[type])) 1577 | // If we've already got an array, just append. 1578 | this._events[type].push(listener); 1579 | else 1580 | // Adding the second element, need to change to array. 1581 | this._events[type] = [this._events[type], listener]; 1582 | 1583 | // Check for listener leak 1584 | if (isObject(this._events[type]) && !this._events[type].warned) { 1585 | var m; 1586 | if (!isUndefined(this._maxListeners)) { 1587 | m = this._maxListeners; 1588 | } else { 1589 | m = EventEmitter.defaultMaxListeners; 1590 | } 1591 | 1592 | if (m && m > 0 && this._events[type].length > m) { 1593 | this._events[type].warned = true; 1594 | console.error('(node) warning: possible EventEmitter memory ' + 1595 | 'leak detected. %d listeners added. ' + 1596 | 'Use emitter.setMaxListeners() to increase limit.', 1597 | this._events[type].length); 1598 | if (typeof console.trace === 'function') { 1599 | // not supported in IE 10 1600 | console.trace(); 1601 | } 1602 | } 1603 | } 1604 | 1605 | return this; 1606 | }; 1607 | 1608 | EventEmitter.prototype.on = EventEmitter.prototype.addListener; 1609 | 1610 | EventEmitter.prototype.once = function(type, listener) { 1611 | if (!isFunction(listener)) 1612 | throw TypeError('listener must be a function'); 1613 | 1614 | var fired = false; 1615 | 1616 | function g() { 1617 | this.removeListener(type, g); 1618 | 1619 | if (!fired) { 1620 | fired = true; 1621 | listener.apply(this, arguments); 1622 | } 1623 | } 1624 | 1625 | g.listener = listener; 1626 | this.on(type, g); 1627 | 1628 | return this; 1629 | }; 1630 | 1631 | // emits a 'removeListener' event iff the listener was removed 1632 | EventEmitter.prototype.removeListener = function(type, listener) { 1633 | var list, position, length, i; 1634 | 1635 | if (!isFunction(listener)) 1636 | throw TypeError('listener must be a function'); 1637 | 1638 | if (!this._events || !this._events[type]) 1639 | return this; 1640 | 1641 | list = this._events[type]; 1642 | length = list.length; 1643 | position = -1; 1644 | 1645 | if (list === listener || 1646 | (isFunction(list.listener) && list.listener === listener)) { 1647 | delete this._events[type]; 1648 | if (this._events.removeListener) 1649 | this.emit('removeListener', type, listener); 1650 | 1651 | } else if (isObject(list)) { 1652 | for (i = length; i-- > 0;) { 1653 | if (list[i] === listener || 1654 | (list[i].listener && list[i].listener === listener)) { 1655 | position = i; 1656 | break; 1657 | } 1658 | } 1659 | 1660 | if (position < 0) 1661 | return this; 1662 | 1663 | if (list.length === 1) { 1664 | list.length = 0; 1665 | delete this._events[type]; 1666 | } else { 1667 | list.splice(position, 1); 1668 | } 1669 | 1670 | if (this._events.removeListener) 1671 | this.emit('removeListener', type, listener); 1672 | } 1673 | 1674 | return this; 1675 | }; 1676 | 1677 | EventEmitter.prototype.removeAllListeners = function(type) { 1678 | var key, listeners; 1679 | 1680 | if (!this._events) 1681 | return this; 1682 | 1683 | // not listening for removeListener, no need to emit 1684 | if (!this._events.removeListener) { 1685 | if (arguments.length === 0) 1686 | this._events = {}; 1687 | else if (this._events[type]) 1688 | delete this._events[type]; 1689 | return this; 1690 | } 1691 | 1692 | // emit removeListener for all listeners on all events 1693 | if (arguments.length === 0) { 1694 | for (key in this._events) { 1695 | if (key === 'removeListener') continue; 1696 | this.removeAllListeners(key); 1697 | } 1698 | this.removeAllListeners('removeListener'); 1699 | this._events = {}; 1700 | return this; 1701 | } 1702 | 1703 | listeners = this._events[type]; 1704 | 1705 | if (isFunction(listeners)) { 1706 | this.removeListener(type, listeners); 1707 | } else { 1708 | // LIFO order 1709 | while (listeners.length) 1710 | this.removeListener(type, listeners[listeners.length - 1]); 1711 | } 1712 | delete this._events[type]; 1713 | 1714 | return this; 1715 | }; 1716 | 1717 | EventEmitter.prototype.listeners = function(type) { 1718 | var ret; 1719 | if (!this._events || !this._events[type]) 1720 | ret = []; 1721 | else if (isFunction(this._events[type])) 1722 | ret = [this._events[type]]; 1723 | else 1724 | ret = this._events[type].slice(); 1725 | return ret; 1726 | }; 1727 | 1728 | EventEmitter.listenerCount = function(emitter, type) { 1729 | var ret; 1730 | if (!emitter._events || !emitter._events[type]) 1731 | ret = 0; 1732 | else if (isFunction(emitter._events[type])) 1733 | ret = 1; 1734 | else 1735 | ret = emitter._events[type].length; 1736 | return ret; 1737 | }; 1738 | 1739 | function isFunction(arg) { 1740 | return typeof arg === 'function'; 1741 | } 1742 | 1743 | function isNumber(arg) { 1744 | return typeof arg === 'number'; 1745 | } 1746 | 1747 | function isObject(arg) { 1748 | return typeof arg === 'object' && arg !== null; 1749 | } 1750 | 1751 | function isUndefined(arg) { 1752 | return arg === void 0; 1753 | } 1754 | 1755 | },{}],8:[function(require,module,exports){ 1756 | if (typeof Object.create === 'function') { 1757 | // implementation from standard node.js 'util' module 1758 | module.exports = function inherits(ctor, superCtor) { 1759 | ctor.super_ = superCtor 1760 | ctor.prototype = Object.create(superCtor.prototype, { 1761 | constructor: { 1762 | value: ctor, 1763 | enumerable: false, 1764 | writable: true, 1765 | configurable: true 1766 | } 1767 | }); 1768 | }; 1769 | } else { 1770 | // old school shim for old browsers 1771 | module.exports = function inherits(ctor, superCtor) { 1772 | ctor.super_ = superCtor 1773 | var TempCtor = function () {} 1774 | TempCtor.prototype = superCtor.prototype 1775 | ctor.prototype = new TempCtor() 1776 | ctor.prototype.constructor = ctor 1777 | } 1778 | } 1779 | 1780 | },{}],9:[function(require,module,exports){ 1781 | module.exports = Array.isArray || function (arr) { 1782 | return Object.prototype.toString.call(arr) == '[object Array]'; 1783 | }; 1784 | 1785 | },{}],10:[function(require,module,exports){ 1786 | // shim for using process in browser 1787 | 1788 | var process = module.exports = {}; 1789 | 1790 | process.nextTick = (function () { 1791 | var canSetImmediate = typeof window !== 'undefined' 1792 | && window.setImmediate; 1793 | var canMutationObserver = typeof window !== 'undefined' 1794 | && window.MutationObserver; 1795 | var canPost = typeof window !== 'undefined' 1796 | && window.postMessage && window.addEventListener 1797 | ; 1798 | 1799 | if (canSetImmediate) { 1800 | return function (f) { return window.setImmediate(f) }; 1801 | } 1802 | 1803 | var queue = []; 1804 | 1805 | if (canMutationObserver) { 1806 | var hiddenDiv = document.createElement("div"); 1807 | var observer = new MutationObserver(function () { 1808 | var queueList = queue.slice(); 1809 | queue.length = 0; 1810 | queueList.forEach(function (fn) { 1811 | fn(); 1812 | }); 1813 | }); 1814 | 1815 | observer.observe(hiddenDiv, { attributes: true }); 1816 | 1817 | return function nextTick(fn) { 1818 | if (!queue.length) { 1819 | hiddenDiv.setAttribute('yes', 'no'); 1820 | } 1821 | queue.push(fn); 1822 | }; 1823 | } 1824 | 1825 | if (canPost) { 1826 | window.addEventListener('message', function (ev) { 1827 | var source = ev.source; 1828 | if ((source === window || source === null) && ev.data === 'process-tick') { 1829 | ev.stopPropagation(); 1830 | if (queue.length > 0) { 1831 | var fn = queue.shift(); 1832 | fn(); 1833 | } 1834 | } 1835 | }, true); 1836 | 1837 | return function nextTick(fn) { 1838 | queue.push(fn); 1839 | window.postMessage('process-tick', '*'); 1840 | }; 1841 | } 1842 | 1843 | return function nextTick(fn) { 1844 | setTimeout(fn, 0); 1845 | }; 1846 | })(); 1847 | 1848 | process.title = 'browser'; 1849 | process.browser = true; 1850 | process.env = {}; 1851 | process.argv = []; 1852 | 1853 | function noop() {} 1854 | 1855 | process.on = noop; 1856 | process.addListener = noop; 1857 | process.once = noop; 1858 | process.off = noop; 1859 | process.removeListener = noop; 1860 | process.removeAllListeners = noop; 1861 | process.emit = noop; 1862 | 1863 | process.binding = function (name) { 1864 | throw new Error('process.binding is not supported'); 1865 | }; 1866 | 1867 | // TODO(shtylman) 1868 | process.cwd = function () { return '/' }; 1869 | process.chdir = function (dir) { 1870 | throw new Error('process.chdir is not supported'); 1871 | }; 1872 | 1873 | },{}],11:[function(require,module,exports){ 1874 | module.exports = require("./lib/_stream_duplex.js") 1875 | 1876 | },{"./lib/_stream_duplex.js":12}],12:[function(require,module,exports){ 1877 | (function (process){ 1878 | // Copyright Joyent, Inc. and other Node contributors. 1879 | // 1880 | // Permission is hereby granted, free of charge, to any person obtaining a 1881 | // copy of this software and associated documentation files (the 1882 | // "Software"), to deal in the Software without restriction, including 1883 | // without limitation the rights to use, copy, modify, merge, publish, 1884 | // distribute, sublicense, and/or sell copies of the Software, and to permit 1885 | // persons to whom the Software is furnished to do so, subject to the 1886 | // following conditions: 1887 | // 1888 | // The above copyright notice and this permission notice shall be included 1889 | // in all copies or substantial portions of the Software. 1890 | // 1891 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 1892 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 1893 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 1894 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 1895 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 1896 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 1897 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 1898 | 1899 | // a duplex stream is just a stream that is both readable and writable. 1900 | // Since JS doesn't have multiple prototypal inheritance, this class 1901 | // prototypally inherits from Readable, and then parasitically from 1902 | // Writable. 1903 | 1904 | module.exports = Duplex; 1905 | 1906 | /**/ 1907 | var objectKeys = Object.keys || function (obj) { 1908 | var keys = []; 1909 | for (var key in obj) keys.push(key); 1910 | return keys; 1911 | } 1912 | /**/ 1913 | 1914 | 1915 | /**/ 1916 | var util = require('core-util-is'); 1917 | util.inherits = require('inherits'); 1918 | /**/ 1919 | 1920 | var Readable = require('./_stream_readable'); 1921 | var Writable = require('./_stream_writable'); 1922 | 1923 | util.inherits(Duplex, Readable); 1924 | 1925 | forEach(objectKeys(Writable.prototype), function(method) { 1926 | if (!Duplex.prototype[method]) 1927 | Duplex.prototype[method] = Writable.prototype[method]; 1928 | }); 1929 | 1930 | function Duplex(options) { 1931 | if (!(this instanceof Duplex)) 1932 | return new Duplex(options); 1933 | 1934 | Readable.call(this, options); 1935 | Writable.call(this, options); 1936 | 1937 | if (options && options.readable === false) 1938 | this.readable = false; 1939 | 1940 | if (options && options.writable === false) 1941 | this.writable = false; 1942 | 1943 | this.allowHalfOpen = true; 1944 | if (options && options.allowHalfOpen === false) 1945 | this.allowHalfOpen = false; 1946 | 1947 | this.once('end', onend); 1948 | } 1949 | 1950 | // the no-half-open enforcer 1951 | function onend() { 1952 | // if we allow half-open state, or if the writable side ended, 1953 | // then we're ok. 1954 | if (this.allowHalfOpen || this._writableState.ended) 1955 | return; 1956 | 1957 | // no more data can be written. 1958 | // But allow more writes to happen in this tick. 1959 | process.nextTick(this.end.bind(this)); 1960 | } 1961 | 1962 | function forEach (xs, f) { 1963 | for (var i = 0, l = xs.length; i < l; i++) { 1964 | f(xs[i], i); 1965 | } 1966 | } 1967 | 1968 | }).call(this,require('_process')) 1969 | },{"./_stream_readable":14,"./_stream_writable":16,"_process":10,"core-util-is":17,"inherits":8}],13:[function(require,module,exports){ 1970 | // Copyright Joyent, Inc. and other Node contributors. 1971 | // 1972 | // Permission is hereby granted, free of charge, to any person obtaining a 1973 | // copy of this software and associated documentation files (the 1974 | // "Software"), to deal in the Software without restriction, including 1975 | // without limitation the rights to use, copy, modify, merge, publish, 1976 | // distribute, sublicense, and/or sell copies of the Software, and to permit 1977 | // persons to whom the Software is furnished to do so, subject to the 1978 | // following conditions: 1979 | // 1980 | // The above copyright notice and this permission notice shall be included 1981 | // in all copies or substantial portions of the Software. 1982 | // 1983 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 1984 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 1985 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 1986 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 1987 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 1988 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 1989 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 1990 | 1991 | // a passthrough stream. 1992 | // basically just the most minimal sort of Transform stream. 1993 | // Every written chunk gets output as-is. 1994 | 1995 | module.exports = PassThrough; 1996 | 1997 | var Transform = require('./_stream_transform'); 1998 | 1999 | /**/ 2000 | var util = require('core-util-is'); 2001 | util.inherits = require('inherits'); 2002 | /**/ 2003 | 2004 | util.inherits(PassThrough, Transform); 2005 | 2006 | function PassThrough(options) { 2007 | if (!(this instanceof PassThrough)) 2008 | return new PassThrough(options); 2009 | 2010 | Transform.call(this, options); 2011 | } 2012 | 2013 | PassThrough.prototype._transform = function(chunk, encoding, cb) { 2014 | cb(null, chunk); 2015 | }; 2016 | 2017 | },{"./_stream_transform":15,"core-util-is":17,"inherits":8}],14:[function(require,module,exports){ 2018 | (function (process){ 2019 | // Copyright Joyent, Inc. and other Node contributors. 2020 | // 2021 | // Permission is hereby granted, free of charge, to any person obtaining a 2022 | // copy of this software and associated documentation files (the 2023 | // "Software"), to deal in the Software without restriction, including 2024 | // without limitation the rights to use, copy, modify, merge, publish, 2025 | // distribute, sublicense, and/or sell copies of the Software, and to permit 2026 | // persons to whom the Software is furnished to do so, subject to the 2027 | // following conditions: 2028 | // 2029 | // The above copyright notice and this permission notice shall be included 2030 | // in all copies or substantial portions of the Software. 2031 | // 2032 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 2033 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 2034 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 2035 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 2036 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 2037 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 2038 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 2039 | 2040 | module.exports = Readable; 2041 | 2042 | /**/ 2043 | var isArray = require('isarray'); 2044 | /**/ 2045 | 2046 | 2047 | /**/ 2048 | var Buffer = require('buffer').Buffer; 2049 | /**/ 2050 | 2051 | Readable.ReadableState = ReadableState; 2052 | 2053 | var EE = require('events').EventEmitter; 2054 | 2055 | /**/ 2056 | if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { 2057 | return emitter.listeners(type).length; 2058 | }; 2059 | /**/ 2060 | 2061 | var Stream = require('stream'); 2062 | 2063 | /**/ 2064 | var util = require('core-util-is'); 2065 | util.inherits = require('inherits'); 2066 | /**/ 2067 | 2068 | var StringDecoder; 2069 | 2070 | util.inherits(Readable, Stream); 2071 | 2072 | function ReadableState(options, stream) { 2073 | options = options || {}; 2074 | 2075 | // the point at which it stops calling _read() to fill the buffer 2076 | // Note: 0 is a valid value, means "don't call _read preemptively ever" 2077 | var hwm = options.highWaterMark; 2078 | this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; 2079 | 2080 | // cast to ints. 2081 | this.highWaterMark = ~~this.highWaterMark; 2082 | 2083 | this.buffer = []; 2084 | this.length = 0; 2085 | this.pipes = null; 2086 | this.pipesCount = 0; 2087 | this.flowing = false; 2088 | this.ended = false; 2089 | this.endEmitted = false; 2090 | this.reading = false; 2091 | 2092 | // In streams that never have any data, and do push(null) right away, 2093 | // the consumer can miss the 'end' event if they do some I/O before 2094 | // consuming the stream. So, we don't emit('end') until some reading 2095 | // happens. 2096 | this.calledRead = false; 2097 | 2098 | // a flag to be able to tell if the onwrite cb is called immediately, 2099 | // or on a later tick. We set this to true at first, becuase any 2100 | // actions that shouldn't happen until "later" should generally also 2101 | // not happen before the first write call. 2102 | this.sync = true; 2103 | 2104 | // whenever we return null, then we set a flag to say 2105 | // that we're awaiting a 'readable' event emission. 2106 | this.needReadable = false; 2107 | this.emittedReadable = false; 2108 | this.readableListening = false; 2109 | 2110 | 2111 | // object stream flag. Used to make read(n) ignore n and to 2112 | // make all the buffer merging and length checks go away 2113 | this.objectMode = !!options.objectMode; 2114 | 2115 | // Crypto is kind of old and crusty. Historically, its default string 2116 | // encoding is 'binary' so we have to make this configurable. 2117 | // Everything else in the universe uses 'utf8', though. 2118 | this.defaultEncoding = options.defaultEncoding || 'utf8'; 2119 | 2120 | // when piping, we only care about 'readable' events that happen 2121 | // after read()ing all the bytes and not getting any pushback. 2122 | this.ranOut = false; 2123 | 2124 | // the number of writers that are awaiting a drain event in .pipe()s 2125 | this.awaitDrain = 0; 2126 | 2127 | // if true, a maybeReadMore has been scheduled 2128 | this.readingMore = false; 2129 | 2130 | this.decoder = null; 2131 | this.encoding = null; 2132 | if (options.encoding) { 2133 | if (!StringDecoder) 2134 | StringDecoder = require('string_decoder/').StringDecoder; 2135 | this.decoder = new StringDecoder(options.encoding); 2136 | this.encoding = options.encoding; 2137 | } 2138 | } 2139 | 2140 | function Readable(options) { 2141 | if (!(this instanceof Readable)) 2142 | return new Readable(options); 2143 | 2144 | this._readableState = new ReadableState(options, this); 2145 | 2146 | // legacy 2147 | this.readable = true; 2148 | 2149 | Stream.call(this); 2150 | } 2151 | 2152 | // Manually shove something into the read() buffer. 2153 | // This returns true if the highWaterMark has not been hit yet, 2154 | // similar to how Writable.write() returns true if you should 2155 | // write() some more. 2156 | Readable.prototype.push = function(chunk, encoding) { 2157 | var state = this._readableState; 2158 | 2159 | if (typeof chunk === 'string' && !state.objectMode) { 2160 | encoding = encoding || state.defaultEncoding; 2161 | if (encoding !== state.encoding) { 2162 | chunk = new Buffer(chunk, encoding); 2163 | encoding = ''; 2164 | } 2165 | } 2166 | 2167 | return readableAddChunk(this, state, chunk, encoding, false); 2168 | }; 2169 | 2170 | // Unshift should *always* be something directly out of read() 2171 | Readable.prototype.unshift = function(chunk) { 2172 | var state = this._readableState; 2173 | return readableAddChunk(this, state, chunk, '', true); 2174 | }; 2175 | 2176 | function readableAddChunk(stream, state, chunk, encoding, addToFront) { 2177 | var er = chunkInvalid(state, chunk); 2178 | if (er) { 2179 | stream.emit('error', er); 2180 | } else if (chunk === null || chunk === undefined) { 2181 | state.reading = false; 2182 | if (!state.ended) 2183 | onEofChunk(stream, state); 2184 | } else if (state.objectMode || chunk && chunk.length > 0) { 2185 | if (state.ended && !addToFront) { 2186 | var e = new Error('stream.push() after EOF'); 2187 | stream.emit('error', e); 2188 | } else if (state.endEmitted && addToFront) { 2189 | var e = new Error('stream.unshift() after end event'); 2190 | stream.emit('error', e); 2191 | } else { 2192 | if (state.decoder && !addToFront && !encoding) 2193 | chunk = state.decoder.write(chunk); 2194 | 2195 | // update the buffer info. 2196 | state.length += state.objectMode ? 1 : chunk.length; 2197 | if (addToFront) { 2198 | state.buffer.unshift(chunk); 2199 | } else { 2200 | state.reading = false; 2201 | state.buffer.push(chunk); 2202 | } 2203 | 2204 | if (state.needReadable) 2205 | emitReadable(stream); 2206 | 2207 | maybeReadMore(stream, state); 2208 | } 2209 | } else if (!addToFront) { 2210 | state.reading = false; 2211 | } 2212 | 2213 | return needMoreData(state); 2214 | } 2215 | 2216 | 2217 | 2218 | // if it's past the high water mark, we can push in some more. 2219 | // Also, if we have no data yet, we can stand some 2220 | // more bytes. This is to work around cases where hwm=0, 2221 | // such as the repl. Also, if the push() triggered a 2222 | // readable event, and the user called read(largeNumber) such that 2223 | // needReadable was set, then we ought to push more, so that another 2224 | // 'readable' event will be triggered. 2225 | function needMoreData(state) { 2226 | return !state.ended && 2227 | (state.needReadable || 2228 | state.length < state.highWaterMark || 2229 | state.length === 0); 2230 | } 2231 | 2232 | // backwards compatibility. 2233 | Readable.prototype.setEncoding = function(enc) { 2234 | if (!StringDecoder) 2235 | StringDecoder = require('string_decoder/').StringDecoder; 2236 | this._readableState.decoder = new StringDecoder(enc); 2237 | this._readableState.encoding = enc; 2238 | }; 2239 | 2240 | // Don't raise the hwm > 128MB 2241 | var MAX_HWM = 0x800000; 2242 | function roundUpToNextPowerOf2(n) { 2243 | if (n >= MAX_HWM) { 2244 | n = MAX_HWM; 2245 | } else { 2246 | // Get the next highest power of 2 2247 | n--; 2248 | for (var p = 1; p < 32; p <<= 1) n |= n >> p; 2249 | n++; 2250 | } 2251 | return n; 2252 | } 2253 | 2254 | function howMuchToRead(n, state) { 2255 | if (state.length === 0 && state.ended) 2256 | return 0; 2257 | 2258 | if (state.objectMode) 2259 | return n === 0 ? 0 : 1; 2260 | 2261 | if (n === null || isNaN(n)) { 2262 | // only flow one buffer at a time 2263 | if (state.flowing && state.buffer.length) 2264 | return state.buffer[0].length; 2265 | else 2266 | return state.length; 2267 | } 2268 | 2269 | if (n <= 0) 2270 | return 0; 2271 | 2272 | // If we're asking for more than the target buffer level, 2273 | // then raise the water mark. Bump up to the next highest 2274 | // power of 2, to prevent increasing it excessively in tiny 2275 | // amounts. 2276 | if (n > state.highWaterMark) 2277 | state.highWaterMark = roundUpToNextPowerOf2(n); 2278 | 2279 | // don't have that much. return null, unless we've ended. 2280 | if (n > state.length) { 2281 | if (!state.ended) { 2282 | state.needReadable = true; 2283 | return 0; 2284 | } else 2285 | return state.length; 2286 | } 2287 | 2288 | return n; 2289 | } 2290 | 2291 | // you can override either this method, or the async _read(n) below. 2292 | Readable.prototype.read = function(n) { 2293 | var state = this._readableState; 2294 | state.calledRead = true; 2295 | var nOrig = n; 2296 | var ret; 2297 | 2298 | if (typeof n !== 'number' || n > 0) 2299 | state.emittedReadable = false; 2300 | 2301 | // if we're doing read(0) to trigger a readable event, but we 2302 | // already have a bunch of data in the buffer, then just trigger 2303 | // the 'readable' event and move on. 2304 | if (n === 0 && 2305 | state.needReadable && 2306 | (state.length >= state.highWaterMark || state.ended)) { 2307 | emitReadable(this); 2308 | return null; 2309 | } 2310 | 2311 | n = howMuchToRead(n, state); 2312 | 2313 | // if we've ended, and we're now clear, then finish it up. 2314 | if (n === 0 && state.ended) { 2315 | ret = null; 2316 | 2317 | // In cases where the decoder did not receive enough data 2318 | // to produce a full chunk, then immediately received an 2319 | // EOF, state.buffer will contain [, ]. 2320 | // howMuchToRead will see this and coerce the amount to 2321 | // read to zero (because it's looking at the length of the 2322 | // first in state.buffer), and we'll end up here. 2323 | // 2324 | // This can only happen via state.decoder -- no other venue 2325 | // exists for pushing a zero-length chunk into state.buffer 2326 | // and triggering this behavior. In this case, we return our 2327 | // remaining data and end the stream, if appropriate. 2328 | if (state.length > 0 && state.decoder) { 2329 | ret = fromList(n, state); 2330 | state.length -= ret.length; 2331 | } 2332 | 2333 | if (state.length === 0) 2334 | endReadable(this); 2335 | 2336 | return ret; 2337 | } 2338 | 2339 | // All the actual chunk generation logic needs to be 2340 | // *below* the call to _read. The reason is that in certain 2341 | // synthetic stream cases, such as passthrough streams, _read 2342 | // may be a completely synchronous operation which may change 2343 | // the state of the read buffer, providing enough data when 2344 | // before there was *not* enough. 2345 | // 2346 | // So, the steps are: 2347 | // 1. Figure out what the state of things will be after we do 2348 | // a read from the buffer. 2349 | // 2350 | // 2. If that resulting state will trigger a _read, then call _read. 2351 | // Note that this may be asynchronous, or synchronous. Yes, it is 2352 | // deeply ugly to write APIs this way, but that still doesn't mean 2353 | // that the Readable class should behave improperly, as streams are 2354 | // designed to be sync/async agnostic. 2355 | // Take note if the _read call is sync or async (ie, if the read call 2356 | // has returned yet), so that we know whether or not it's safe to emit 2357 | // 'readable' etc. 2358 | // 2359 | // 3. Actually pull the requested chunks out of the buffer and return. 2360 | 2361 | // if we need a readable event, then we need to do some reading. 2362 | var doRead = state.needReadable; 2363 | 2364 | // if we currently have less than the highWaterMark, then also read some 2365 | if (state.length - n <= state.highWaterMark) 2366 | doRead = true; 2367 | 2368 | // however, if we've ended, then there's no point, and if we're already 2369 | // reading, then it's unnecessary. 2370 | if (state.ended || state.reading) 2371 | doRead = false; 2372 | 2373 | if (doRead) { 2374 | state.reading = true; 2375 | state.sync = true; 2376 | // if the length is currently zero, then we *need* a readable event. 2377 | if (state.length === 0) 2378 | state.needReadable = true; 2379 | // call internal read method 2380 | this._read(state.highWaterMark); 2381 | state.sync = false; 2382 | } 2383 | 2384 | // If _read called its callback synchronously, then `reading` 2385 | // will be false, and we need to re-evaluate how much data we 2386 | // can return to the user. 2387 | if (doRead && !state.reading) 2388 | n = howMuchToRead(nOrig, state); 2389 | 2390 | if (n > 0) 2391 | ret = fromList(n, state); 2392 | else 2393 | ret = null; 2394 | 2395 | if (ret === null) { 2396 | state.needReadable = true; 2397 | n = 0; 2398 | } 2399 | 2400 | state.length -= n; 2401 | 2402 | // If we have nothing in the buffer, then we want to know 2403 | // as soon as we *do* get something into the buffer. 2404 | if (state.length === 0 && !state.ended) 2405 | state.needReadable = true; 2406 | 2407 | // If we happened to read() exactly the remaining amount in the 2408 | // buffer, and the EOF has been seen at this point, then make sure 2409 | // that we emit 'end' on the very next tick. 2410 | if (state.ended && !state.endEmitted && state.length === 0) 2411 | endReadable(this); 2412 | 2413 | return ret; 2414 | }; 2415 | 2416 | function chunkInvalid(state, chunk) { 2417 | var er = null; 2418 | if (!Buffer.isBuffer(chunk) && 2419 | 'string' !== typeof chunk && 2420 | chunk !== null && 2421 | chunk !== undefined && 2422 | !state.objectMode) { 2423 | er = new TypeError('Invalid non-string/buffer chunk'); 2424 | } 2425 | return er; 2426 | } 2427 | 2428 | 2429 | function onEofChunk(stream, state) { 2430 | if (state.decoder && !state.ended) { 2431 | var chunk = state.decoder.end(); 2432 | if (chunk && chunk.length) { 2433 | state.buffer.push(chunk); 2434 | state.length += state.objectMode ? 1 : chunk.length; 2435 | } 2436 | } 2437 | state.ended = true; 2438 | 2439 | // if we've ended and we have some data left, then emit 2440 | // 'readable' now to make sure it gets picked up. 2441 | if (state.length > 0) 2442 | emitReadable(stream); 2443 | else 2444 | endReadable(stream); 2445 | } 2446 | 2447 | // Don't emit readable right away in sync mode, because this can trigger 2448 | // another read() call => stack overflow. This way, it might trigger 2449 | // a nextTick recursion warning, but that's not so bad. 2450 | function emitReadable(stream) { 2451 | var state = stream._readableState; 2452 | state.needReadable = false; 2453 | if (state.emittedReadable) 2454 | return; 2455 | 2456 | state.emittedReadable = true; 2457 | if (state.sync) 2458 | process.nextTick(function() { 2459 | emitReadable_(stream); 2460 | }); 2461 | else 2462 | emitReadable_(stream); 2463 | } 2464 | 2465 | function emitReadable_(stream) { 2466 | stream.emit('readable'); 2467 | } 2468 | 2469 | 2470 | // at this point, the user has presumably seen the 'readable' event, 2471 | // and called read() to consume some data. that may have triggered 2472 | // in turn another _read(n) call, in which case reading = true if 2473 | // it's in progress. 2474 | // However, if we're not ended, or reading, and the length < hwm, 2475 | // then go ahead and try to read some more preemptively. 2476 | function maybeReadMore(stream, state) { 2477 | if (!state.readingMore) { 2478 | state.readingMore = true; 2479 | process.nextTick(function() { 2480 | maybeReadMore_(stream, state); 2481 | }); 2482 | } 2483 | } 2484 | 2485 | function maybeReadMore_(stream, state) { 2486 | var len = state.length; 2487 | while (!state.reading && !state.flowing && !state.ended && 2488 | state.length < state.highWaterMark) { 2489 | stream.read(0); 2490 | if (len === state.length) 2491 | // didn't get any data, stop spinning. 2492 | break; 2493 | else 2494 | len = state.length; 2495 | } 2496 | state.readingMore = false; 2497 | } 2498 | 2499 | // abstract method. to be overridden in specific implementation classes. 2500 | // call cb(er, data) where data is <= n in length. 2501 | // for virtual (non-string, non-buffer) streams, "length" is somewhat 2502 | // arbitrary, and perhaps not very meaningful. 2503 | Readable.prototype._read = function(n) { 2504 | this.emit('error', new Error('not implemented')); 2505 | }; 2506 | 2507 | Readable.prototype.pipe = function(dest, pipeOpts) { 2508 | var src = this; 2509 | var state = this._readableState; 2510 | 2511 | switch (state.pipesCount) { 2512 | case 0: 2513 | state.pipes = dest; 2514 | break; 2515 | case 1: 2516 | state.pipes = [state.pipes, dest]; 2517 | break; 2518 | default: 2519 | state.pipes.push(dest); 2520 | break; 2521 | } 2522 | state.pipesCount += 1; 2523 | 2524 | var doEnd = (!pipeOpts || pipeOpts.end !== false) && 2525 | dest !== process.stdout && 2526 | dest !== process.stderr; 2527 | 2528 | var endFn = doEnd ? onend : cleanup; 2529 | if (state.endEmitted) 2530 | process.nextTick(endFn); 2531 | else 2532 | src.once('end', endFn); 2533 | 2534 | dest.on('unpipe', onunpipe); 2535 | function onunpipe(readable) { 2536 | if (readable !== src) return; 2537 | cleanup(); 2538 | } 2539 | 2540 | function onend() { 2541 | dest.end(); 2542 | } 2543 | 2544 | // when the dest drains, it reduces the awaitDrain counter 2545 | // on the source. This would be more elegant with a .once() 2546 | // handler in flow(), but adding and removing repeatedly is 2547 | // too slow. 2548 | var ondrain = pipeOnDrain(src); 2549 | dest.on('drain', ondrain); 2550 | 2551 | function cleanup() { 2552 | // cleanup event handlers once the pipe is broken 2553 | dest.removeListener('close', onclose); 2554 | dest.removeListener('finish', onfinish); 2555 | dest.removeListener('drain', ondrain); 2556 | dest.removeListener('error', onerror); 2557 | dest.removeListener('unpipe', onunpipe); 2558 | src.removeListener('end', onend); 2559 | src.removeListener('end', cleanup); 2560 | 2561 | // if the reader is waiting for a drain event from this 2562 | // specific writer, then it would cause it to never start 2563 | // flowing again. 2564 | // So, if this is awaiting a drain, then we just call it now. 2565 | // If we don't know, then assume that we are waiting for one. 2566 | if (!dest._writableState || dest._writableState.needDrain) 2567 | ondrain(); 2568 | } 2569 | 2570 | // if the dest has an error, then stop piping into it. 2571 | // however, don't suppress the throwing behavior for this. 2572 | function onerror(er) { 2573 | unpipe(); 2574 | dest.removeListener('error', onerror); 2575 | if (EE.listenerCount(dest, 'error') === 0) 2576 | dest.emit('error', er); 2577 | } 2578 | // This is a brutally ugly hack to make sure that our error handler 2579 | // is attached before any userland ones. NEVER DO THIS. 2580 | if (!dest._events || !dest._events.error) 2581 | dest.on('error', onerror); 2582 | else if (isArray(dest._events.error)) 2583 | dest._events.error.unshift(onerror); 2584 | else 2585 | dest._events.error = [onerror, dest._events.error]; 2586 | 2587 | 2588 | 2589 | // Both close and finish should trigger unpipe, but only once. 2590 | function onclose() { 2591 | dest.removeListener('finish', onfinish); 2592 | unpipe(); 2593 | } 2594 | dest.once('close', onclose); 2595 | function onfinish() { 2596 | dest.removeListener('close', onclose); 2597 | unpipe(); 2598 | } 2599 | dest.once('finish', onfinish); 2600 | 2601 | function unpipe() { 2602 | src.unpipe(dest); 2603 | } 2604 | 2605 | // tell the dest that it's being piped to 2606 | dest.emit('pipe', src); 2607 | 2608 | // start the flow if it hasn't been started already. 2609 | if (!state.flowing) { 2610 | // the handler that waits for readable events after all 2611 | // the data gets sucked out in flow. 2612 | // This would be easier to follow with a .once() handler 2613 | // in flow(), but that is too slow. 2614 | this.on('readable', pipeOnReadable); 2615 | 2616 | state.flowing = true; 2617 | process.nextTick(function() { 2618 | flow(src); 2619 | }); 2620 | } 2621 | 2622 | return dest; 2623 | }; 2624 | 2625 | function pipeOnDrain(src) { 2626 | return function() { 2627 | var dest = this; 2628 | var state = src._readableState; 2629 | state.awaitDrain--; 2630 | if (state.awaitDrain === 0) 2631 | flow(src); 2632 | }; 2633 | } 2634 | 2635 | function flow(src) { 2636 | var state = src._readableState; 2637 | var chunk; 2638 | state.awaitDrain = 0; 2639 | 2640 | function write(dest, i, list) { 2641 | var written = dest.write(chunk); 2642 | if (false === written) { 2643 | state.awaitDrain++; 2644 | } 2645 | } 2646 | 2647 | while (state.pipesCount && null !== (chunk = src.read())) { 2648 | 2649 | if (state.pipesCount === 1) 2650 | write(state.pipes, 0, null); 2651 | else 2652 | forEach(state.pipes, write); 2653 | 2654 | src.emit('data', chunk); 2655 | 2656 | // if anyone needs a drain, then we have to wait for that. 2657 | if (state.awaitDrain > 0) 2658 | return; 2659 | } 2660 | 2661 | // if every destination was unpiped, either before entering this 2662 | // function, or in the while loop, then stop flowing. 2663 | // 2664 | // NB: This is a pretty rare edge case. 2665 | if (state.pipesCount === 0) { 2666 | state.flowing = false; 2667 | 2668 | // if there were data event listeners added, then switch to old mode. 2669 | if (EE.listenerCount(src, 'data') > 0) 2670 | emitDataEvents(src); 2671 | return; 2672 | } 2673 | 2674 | // at this point, no one needed a drain, so we just ran out of data 2675 | // on the next readable event, start it over again. 2676 | state.ranOut = true; 2677 | } 2678 | 2679 | function pipeOnReadable() { 2680 | if (this._readableState.ranOut) { 2681 | this._readableState.ranOut = false; 2682 | flow(this); 2683 | } 2684 | } 2685 | 2686 | 2687 | Readable.prototype.unpipe = function(dest) { 2688 | var state = this._readableState; 2689 | 2690 | // if we're not piping anywhere, then do nothing. 2691 | if (state.pipesCount === 0) 2692 | return this; 2693 | 2694 | // just one destination. most common case. 2695 | if (state.pipesCount === 1) { 2696 | // passed in one, but it's not the right one. 2697 | if (dest && dest !== state.pipes) 2698 | return this; 2699 | 2700 | if (!dest) 2701 | dest = state.pipes; 2702 | 2703 | // got a match. 2704 | state.pipes = null; 2705 | state.pipesCount = 0; 2706 | this.removeListener('readable', pipeOnReadable); 2707 | state.flowing = false; 2708 | if (dest) 2709 | dest.emit('unpipe', this); 2710 | return this; 2711 | } 2712 | 2713 | // slow case. multiple pipe destinations. 2714 | 2715 | if (!dest) { 2716 | // remove all. 2717 | var dests = state.pipes; 2718 | var len = state.pipesCount; 2719 | state.pipes = null; 2720 | state.pipesCount = 0; 2721 | this.removeListener('readable', pipeOnReadable); 2722 | state.flowing = false; 2723 | 2724 | for (var i = 0; i < len; i++) 2725 | dests[i].emit('unpipe', this); 2726 | return this; 2727 | } 2728 | 2729 | // try to find the right one. 2730 | var i = indexOf(state.pipes, dest); 2731 | if (i === -1) 2732 | return this; 2733 | 2734 | state.pipes.splice(i, 1); 2735 | state.pipesCount -= 1; 2736 | if (state.pipesCount === 1) 2737 | state.pipes = state.pipes[0]; 2738 | 2739 | dest.emit('unpipe', this); 2740 | 2741 | return this; 2742 | }; 2743 | 2744 | // set up data events if they are asked for 2745 | // Ensure readable listeners eventually get something 2746 | Readable.prototype.on = function(ev, fn) { 2747 | var res = Stream.prototype.on.call(this, ev, fn); 2748 | 2749 | if (ev === 'data' && !this._readableState.flowing) 2750 | emitDataEvents(this); 2751 | 2752 | if (ev === 'readable' && this.readable) { 2753 | var state = this._readableState; 2754 | if (!state.readableListening) { 2755 | state.readableListening = true; 2756 | state.emittedReadable = false; 2757 | state.needReadable = true; 2758 | if (!state.reading) { 2759 | this.read(0); 2760 | } else if (state.length) { 2761 | emitReadable(this, state); 2762 | } 2763 | } 2764 | } 2765 | 2766 | return res; 2767 | }; 2768 | Readable.prototype.addListener = Readable.prototype.on; 2769 | 2770 | // pause() and resume() are remnants of the legacy readable stream API 2771 | // If the user uses them, then switch into old mode. 2772 | Readable.prototype.resume = function() { 2773 | emitDataEvents(this); 2774 | this.read(0); 2775 | this.emit('resume'); 2776 | }; 2777 | 2778 | Readable.prototype.pause = function() { 2779 | emitDataEvents(this, true); 2780 | this.emit('pause'); 2781 | }; 2782 | 2783 | function emitDataEvents(stream, startPaused) { 2784 | var state = stream._readableState; 2785 | 2786 | if (state.flowing) { 2787 | // https://github.com/isaacs/readable-stream/issues/16 2788 | throw new Error('Cannot switch to old mode now.'); 2789 | } 2790 | 2791 | var paused = startPaused || false; 2792 | var readable = false; 2793 | 2794 | // convert to an old-style stream. 2795 | stream.readable = true; 2796 | stream.pipe = Stream.prototype.pipe; 2797 | stream.on = stream.addListener = Stream.prototype.on; 2798 | 2799 | stream.on('readable', function() { 2800 | readable = true; 2801 | 2802 | var c; 2803 | while (!paused && (null !== (c = stream.read()))) 2804 | stream.emit('data', c); 2805 | 2806 | if (c === null) { 2807 | readable = false; 2808 | stream._readableState.needReadable = true; 2809 | } 2810 | }); 2811 | 2812 | stream.pause = function() { 2813 | paused = true; 2814 | this.emit('pause'); 2815 | }; 2816 | 2817 | stream.resume = function() { 2818 | paused = false; 2819 | if (readable) 2820 | process.nextTick(function() { 2821 | stream.emit('readable'); 2822 | }); 2823 | else 2824 | this.read(0); 2825 | this.emit('resume'); 2826 | }; 2827 | 2828 | // now make it start, just in case it hadn't already. 2829 | stream.emit('readable'); 2830 | } 2831 | 2832 | // wrap an old-style stream as the async data source. 2833 | // This is *not* part of the readable stream interface. 2834 | // It is an ugly unfortunate mess of history. 2835 | Readable.prototype.wrap = function(stream) { 2836 | var state = this._readableState; 2837 | var paused = false; 2838 | 2839 | var self = this; 2840 | stream.on('end', function() { 2841 | if (state.decoder && !state.ended) { 2842 | var chunk = state.decoder.end(); 2843 | if (chunk && chunk.length) 2844 | self.push(chunk); 2845 | } 2846 | 2847 | self.push(null); 2848 | }); 2849 | 2850 | stream.on('data', function(chunk) { 2851 | if (state.decoder) 2852 | chunk = state.decoder.write(chunk); 2853 | 2854 | // don't skip over falsy values in objectMode 2855 | //if (state.objectMode && util.isNullOrUndefined(chunk)) 2856 | if (state.objectMode && (chunk === null || chunk === undefined)) 2857 | return; 2858 | else if (!state.objectMode && (!chunk || !chunk.length)) 2859 | return; 2860 | 2861 | var ret = self.push(chunk); 2862 | if (!ret) { 2863 | paused = true; 2864 | stream.pause(); 2865 | } 2866 | }); 2867 | 2868 | // proxy all the other methods. 2869 | // important when wrapping filters and duplexes. 2870 | for (var i in stream) { 2871 | if (typeof stream[i] === 'function' && 2872 | typeof this[i] === 'undefined') { 2873 | this[i] = function(method) { return function() { 2874 | return stream[method].apply(stream, arguments); 2875 | }}(i); 2876 | } 2877 | } 2878 | 2879 | // proxy certain important events. 2880 | var events = ['error', 'close', 'destroy', 'pause', 'resume']; 2881 | forEach(events, function(ev) { 2882 | stream.on(ev, self.emit.bind(self, ev)); 2883 | }); 2884 | 2885 | // when we try to consume some more bytes, simply unpause the 2886 | // underlying stream. 2887 | self._read = function(n) { 2888 | if (paused) { 2889 | paused = false; 2890 | stream.resume(); 2891 | } 2892 | }; 2893 | 2894 | return self; 2895 | }; 2896 | 2897 | 2898 | 2899 | // exposed for testing purposes only. 2900 | Readable._fromList = fromList; 2901 | 2902 | // Pluck off n bytes from an array of buffers. 2903 | // Length is the combined lengths of all the buffers in the list. 2904 | function fromList(n, state) { 2905 | var list = state.buffer; 2906 | var length = state.length; 2907 | var stringMode = !!state.decoder; 2908 | var objectMode = !!state.objectMode; 2909 | var ret; 2910 | 2911 | // nothing in the list, definitely empty. 2912 | if (list.length === 0) 2913 | return null; 2914 | 2915 | if (length === 0) 2916 | ret = null; 2917 | else if (objectMode) 2918 | ret = list.shift(); 2919 | else if (!n || n >= length) { 2920 | // read it all, truncate the array. 2921 | if (stringMode) 2922 | ret = list.join(''); 2923 | else 2924 | ret = Buffer.concat(list, length); 2925 | list.length = 0; 2926 | } else { 2927 | // read just some of it. 2928 | if (n < list[0].length) { 2929 | // just take a part of the first list item. 2930 | // slice is the same for buffers and strings. 2931 | var buf = list[0]; 2932 | ret = buf.slice(0, n); 2933 | list[0] = buf.slice(n); 2934 | } else if (n === list[0].length) { 2935 | // first list is a perfect match 2936 | ret = list.shift(); 2937 | } else { 2938 | // complex case. 2939 | // we have enough to cover it, but it spans past the first buffer. 2940 | if (stringMode) 2941 | ret = ''; 2942 | else 2943 | ret = new Buffer(n); 2944 | 2945 | var c = 0; 2946 | for (var i = 0, l = list.length; i < l && c < n; i++) { 2947 | var buf = list[0]; 2948 | var cpy = Math.min(n - c, buf.length); 2949 | 2950 | if (stringMode) 2951 | ret += buf.slice(0, cpy); 2952 | else 2953 | buf.copy(ret, c, 0, cpy); 2954 | 2955 | if (cpy < buf.length) 2956 | list[0] = buf.slice(cpy); 2957 | else 2958 | list.shift(); 2959 | 2960 | c += cpy; 2961 | } 2962 | } 2963 | } 2964 | 2965 | return ret; 2966 | } 2967 | 2968 | function endReadable(stream) { 2969 | var state = stream._readableState; 2970 | 2971 | // If we get here before consuming all the bytes, then that is a 2972 | // bug in node. Should never happen. 2973 | if (state.length > 0) 2974 | throw new Error('endReadable called on non-empty stream'); 2975 | 2976 | if (!state.endEmitted && state.calledRead) { 2977 | state.ended = true; 2978 | process.nextTick(function() { 2979 | // Check that we didn't get one last unshift. 2980 | if (!state.endEmitted && state.length === 0) { 2981 | state.endEmitted = true; 2982 | stream.readable = false; 2983 | stream.emit('end'); 2984 | } 2985 | }); 2986 | } 2987 | } 2988 | 2989 | function forEach (xs, f) { 2990 | for (var i = 0, l = xs.length; i < l; i++) { 2991 | f(xs[i], i); 2992 | } 2993 | } 2994 | 2995 | function indexOf (xs, x) { 2996 | for (var i = 0, l = xs.length; i < l; i++) { 2997 | if (xs[i] === x) return i; 2998 | } 2999 | return -1; 3000 | } 3001 | 3002 | }).call(this,require('_process')) 3003 | },{"_process":10,"buffer":3,"core-util-is":17,"events":7,"inherits":8,"isarray":9,"stream":22,"string_decoder/":23}],15:[function(require,module,exports){ 3004 | // Copyright Joyent, Inc. and other Node contributors. 3005 | // 3006 | // Permission is hereby granted, free of charge, to any person obtaining a 3007 | // copy of this software and associated documentation files (the 3008 | // "Software"), to deal in the Software without restriction, including 3009 | // without limitation the rights to use, copy, modify, merge, publish, 3010 | // distribute, sublicense, and/or sell copies of the Software, and to permit 3011 | // persons to whom the Software is furnished to do so, subject to the 3012 | // following conditions: 3013 | // 3014 | // The above copyright notice and this permission notice shall be included 3015 | // in all copies or substantial portions of the Software. 3016 | // 3017 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 3018 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 3019 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 3020 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 3021 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 3022 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 3023 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 3024 | 3025 | 3026 | // a transform stream is a readable/writable stream where you do 3027 | // something with the data. Sometimes it's called a "filter", 3028 | // but that's not a great name for it, since that implies a thing where 3029 | // some bits pass through, and others are simply ignored. (That would 3030 | // be a valid example of a transform, of course.) 3031 | // 3032 | // While the output is causally related to the input, it's not a 3033 | // necessarily symmetric or synchronous transformation. For example, 3034 | // a zlib stream might take multiple plain-text writes(), and then 3035 | // emit a single compressed chunk some time in the future. 3036 | // 3037 | // Here's how this works: 3038 | // 3039 | // The Transform stream has all the aspects of the readable and writable 3040 | // stream classes. When you write(chunk), that calls _write(chunk,cb) 3041 | // internally, and returns false if there's a lot of pending writes 3042 | // buffered up. When you call read(), that calls _read(n) until 3043 | // there's enough pending readable data buffered up. 3044 | // 3045 | // In a transform stream, the written data is placed in a buffer. When 3046 | // _read(n) is called, it transforms the queued up data, calling the 3047 | // buffered _write cb's as it consumes chunks. If consuming a single 3048 | // written chunk would result in multiple output chunks, then the first 3049 | // outputted bit calls the readcb, and subsequent chunks just go into 3050 | // the read buffer, and will cause it to emit 'readable' if necessary. 3051 | // 3052 | // This way, back-pressure is actually determined by the reading side, 3053 | // since _read has to be called to start processing a new chunk. However, 3054 | // a pathological inflate type of transform can cause excessive buffering 3055 | // here. For example, imagine a stream where every byte of input is 3056 | // interpreted as an integer from 0-255, and then results in that many 3057 | // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in 3058 | // 1kb of data being output. In this case, you could write a very small 3059 | // amount of input, and end up with a very large amount of output. In 3060 | // such a pathological inflating mechanism, there'd be no way to tell 3061 | // the system to stop doing the transform. A single 4MB write could 3062 | // cause the system to run out of memory. 3063 | // 3064 | // However, even in such a pathological case, only a single written chunk 3065 | // would be consumed, and then the rest would wait (un-transformed) until 3066 | // the results of the previous transformed chunk were consumed. 3067 | 3068 | module.exports = Transform; 3069 | 3070 | var Duplex = require('./_stream_duplex'); 3071 | 3072 | /**/ 3073 | var util = require('core-util-is'); 3074 | util.inherits = require('inherits'); 3075 | /**/ 3076 | 3077 | util.inherits(Transform, Duplex); 3078 | 3079 | 3080 | function TransformState(options, stream) { 3081 | this.afterTransform = function(er, data) { 3082 | return afterTransform(stream, er, data); 3083 | }; 3084 | 3085 | this.needTransform = false; 3086 | this.transforming = false; 3087 | this.writecb = null; 3088 | this.writechunk = null; 3089 | } 3090 | 3091 | function afterTransform(stream, er, data) { 3092 | var ts = stream._transformState; 3093 | ts.transforming = false; 3094 | 3095 | var cb = ts.writecb; 3096 | 3097 | if (!cb) 3098 | return stream.emit('error', new Error('no writecb in Transform class')); 3099 | 3100 | ts.writechunk = null; 3101 | ts.writecb = null; 3102 | 3103 | if (data !== null && data !== undefined) 3104 | stream.push(data); 3105 | 3106 | if (cb) 3107 | cb(er); 3108 | 3109 | var rs = stream._readableState; 3110 | rs.reading = false; 3111 | if (rs.needReadable || rs.length < rs.highWaterMark) { 3112 | stream._read(rs.highWaterMark); 3113 | } 3114 | } 3115 | 3116 | 3117 | function Transform(options) { 3118 | if (!(this instanceof Transform)) 3119 | return new Transform(options); 3120 | 3121 | Duplex.call(this, options); 3122 | 3123 | var ts = this._transformState = new TransformState(options, this); 3124 | 3125 | // when the writable side finishes, then flush out anything remaining. 3126 | var stream = this; 3127 | 3128 | // start out asking for a readable event once data is transformed. 3129 | this._readableState.needReadable = true; 3130 | 3131 | // we have implemented the _read method, and done the other things 3132 | // that Readable wants before the first _read call, so unset the 3133 | // sync guard flag. 3134 | this._readableState.sync = false; 3135 | 3136 | this.once('finish', function() { 3137 | if ('function' === typeof this._flush) 3138 | this._flush(function(er) { 3139 | done(stream, er); 3140 | }); 3141 | else 3142 | done(stream); 3143 | }); 3144 | } 3145 | 3146 | Transform.prototype.push = function(chunk, encoding) { 3147 | this._transformState.needTransform = false; 3148 | return Duplex.prototype.push.call(this, chunk, encoding); 3149 | }; 3150 | 3151 | // This is the part where you do stuff! 3152 | // override this function in implementation classes. 3153 | // 'chunk' is an input chunk. 3154 | // 3155 | // Call `push(newChunk)` to pass along transformed output 3156 | // to the readable side. You may call 'push' zero or more times. 3157 | // 3158 | // Call `cb(err)` when you are done with this chunk. If you pass 3159 | // an error, then that'll put the hurt on the whole operation. If you 3160 | // never call cb(), then you'll never get another chunk. 3161 | Transform.prototype._transform = function(chunk, encoding, cb) { 3162 | throw new Error('not implemented'); 3163 | }; 3164 | 3165 | Transform.prototype._write = function(chunk, encoding, cb) { 3166 | var ts = this._transformState; 3167 | ts.writecb = cb; 3168 | ts.writechunk = chunk; 3169 | ts.writeencoding = encoding; 3170 | if (!ts.transforming) { 3171 | var rs = this._readableState; 3172 | if (ts.needTransform || 3173 | rs.needReadable || 3174 | rs.length < rs.highWaterMark) 3175 | this._read(rs.highWaterMark); 3176 | } 3177 | }; 3178 | 3179 | // Doesn't matter what the args are here. 3180 | // _transform does all the work. 3181 | // That we got here means that the readable side wants more data. 3182 | Transform.prototype._read = function(n) { 3183 | var ts = this._transformState; 3184 | 3185 | if (ts.writechunk !== null && ts.writecb && !ts.transforming) { 3186 | ts.transforming = true; 3187 | this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); 3188 | } else { 3189 | // mark that we need a transform, so that any data that comes in 3190 | // will get processed, now that we've asked for it. 3191 | ts.needTransform = true; 3192 | } 3193 | }; 3194 | 3195 | 3196 | function done(stream, er) { 3197 | if (er) 3198 | return stream.emit('error', er); 3199 | 3200 | // if there's nothing in the write buffer, then that means 3201 | // that nothing more will ever be provided 3202 | var ws = stream._writableState; 3203 | var rs = stream._readableState; 3204 | var ts = stream._transformState; 3205 | 3206 | if (ws.length) 3207 | throw new Error('calling transform done when ws.length != 0'); 3208 | 3209 | if (ts.transforming) 3210 | throw new Error('calling transform done when still transforming'); 3211 | 3212 | return stream.push(null); 3213 | } 3214 | 3215 | },{"./_stream_duplex":12,"core-util-is":17,"inherits":8}],16:[function(require,module,exports){ 3216 | (function (process){ 3217 | // Copyright Joyent, Inc. and other Node contributors. 3218 | // 3219 | // Permission is hereby granted, free of charge, to any person obtaining a 3220 | // copy of this software and associated documentation files (the 3221 | // "Software"), to deal in the Software without restriction, including 3222 | // without limitation the rights to use, copy, modify, merge, publish, 3223 | // distribute, sublicense, and/or sell copies of the Software, and to permit 3224 | // persons to whom the Software is furnished to do so, subject to the 3225 | // following conditions: 3226 | // 3227 | // The above copyright notice and this permission notice shall be included 3228 | // in all copies or substantial portions of the Software. 3229 | // 3230 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 3231 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 3232 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 3233 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 3234 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 3235 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 3236 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 3237 | 3238 | // A bit simpler than readable streams. 3239 | // Implement an async ._write(chunk, cb), and it'll handle all 3240 | // the drain event emission and buffering. 3241 | 3242 | module.exports = Writable; 3243 | 3244 | /**/ 3245 | var Buffer = require('buffer').Buffer; 3246 | /**/ 3247 | 3248 | Writable.WritableState = WritableState; 3249 | 3250 | 3251 | /**/ 3252 | var util = require('core-util-is'); 3253 | util.inherits = require('inherits'); 3254 | /**/ 3255 | 3256 | var Stream = require('stream'); 3257 | 3258 | util.inherits(Writable, Stream); 3259 | 3260 | function WriteReq(chunk, encoding, cb) { 3261 | this.chunk = chunk; 3262 | this.encoding = encoding; 3263 | this.callback = cb; 3264 | } 3265 | 3266 | function WritableState(options, stream) { 3267 | options = options || {}; 3268 | 3269 | // the point at which write() starts returning false 3270 | // Note: 0 is a valid value, means that we always return false if 3271 | // the entire buffer is not flushed immediately on write() 3272 | var hwm = options.highWaterMark; 3273 | this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; 3274 | 3275 | // object stream flag to indicate whether or not this stream 3276 | // contains buffers or objects. 3277 | this.objectMode = !!options.objectMode; 3278 | 3279 | // cast to ints. 3280 | this.highWaterMark = ~~this.highWaterMark; 3281 | 3282 | this.needDrain = false; 3283 | // at the start of calling end() 3284 | this.ending = false; 3285 | // when end() has been called, and returned 3286 | this.ended = false; 3287 | // when 'finish' is emitted 3288 | this.finished = false; 3289 | 3290 | // should we decode strings into buffers before passing to _write? 3291 | // this is here so that some node-core streams can optimize string 3292 | // handling at a lower level. 3293 | var noDecode = options.decodeStrings === false; 3294 | this.decodeStrings = !noDecode; 3295 | 3296 | // Crypto is kind of old and crusty. Historically, its default string 3297 | // encoding is 'binary' so we have to make this configurable. 3298 | // Everything else in the universe uses 'utf8', though. 3299 | this.defaultEncoding = options.defaultEncoding || 'utf8'; 3300 | 3301 | // not an actual buffer we keep track of, but a measurement 3302 | // of how much we're waiting to get pushed to some underlying 3303 | // socket or file. 3304 | this.length = 0; 3305 | 3306 | // a flag to see when we're in the middle of a write. 3307 | this.writing = false; 3308 | 3309 | // a flag to be able to tell if the onwrite cb is called immediately, 3310 | // or on a later tick. We set this to true at first, becuase any 3311 | // actions that shouldn't happen until "later" should generally also 3312 | // not happen before the first write call. 3313 | this.sync = true; 3314 | 3315 | // a flag to know if we're processing previously buffered items, which 3316 | // may call the _write() callback in the same tick, so that we don't 3317 | // end up in an overlapped onwrite situation. 3318 | this.bufferProcessing = false; 3319 | 3320 | // the callback that's passed to _write(chunk,cb) 3321 | this.onwrite = function(er) { 3322 | onwrite(stream, er); 3323 | }; 3324 | 3325 | // the callback that the user supplies to write(chunk,encoding,cb) 3326 | this.writecb = null; 3327 | 3328 | // the amount that is being written when _write is called. 3329 | this.writelen = 0; 3330 | 3331 | this.buffer = []; 3332 | 3333 | // True if the error was already emitted and should not be thrown again 3334 | this.errorEmitted = false; 3335 | } 3336 | 3337 | function Writable(options) { 3338 | var Duplex = require('./_stream_duplex'); 3339 | 3340 | // Writable ctor is applied to Duplexes, though they're not 3341 | // instanceof Writable, they're instanceof Readable. 3342 | if (!(this instanceof Writable) && !(this instanceof Duplex)) 3343 | return new Writable(options); 3344 | 3345 | this._writableState = new WritableState(options, this); 3346 | 3347 | // legacy. 3348 | this.writable = true; 3349 | 3350 | Stream.call(this); 3351 | } 3352 | 3353 | // Otherwise people can pipe Writable streams, which is just wrong. 3354 | Writable.prototype.pipe = function() { 3355 | this.emit('error', new Error('Cannot pipe. Not readable.')); 3356 | }; 3357 | 3358 | 3359 | function writeAfterEnd(stream, state, cb) { 3360 | var er = new Error('write after end'); 3361 | // TODO: defer error events consistently everywhere, not just the cb 3362 | stream.emit('error', er); 3363 | process.nextTick(function() { 3364 | cb(er); 3365 | }); 3366 | } 3367 | 3368 | // If we get something that is not a buffer, string, null, or undefined, 3369 | // and we're not in objectMode, then that's an error. 3370 | // Otherwise stream chunks are all considered to be of length=1, and the 3371 | // watermarks determine how many objects to keep in the buffer, rather than 3372 | // how many bytes or characters. 3373 | function validChunk(stream, state, chunk, cb) { 3374 | var valid = true; 3375 | if (!Buffer.isBuffer(chunk) && 3376 | 'string' !== typeof chunk && 3377 | chunk !== null && 3378 | chunk !== undefined && 3379 | !state.objectMode) { 3380 | var er = new TypeError('Invalid non-string/buffer chunk'); 3381 | stream.emit('error', er); 3382 | process.nextTick(function() { 3383 | cb(er); 3384 | }); 3385 | valid = false; 3386 | } 3387 | return valid; 3388 | } 3389 | 3390 | Writable.prototype.write = function(chunk, encoding, cb) { 3391 | var state = this._writableState; 3392 | var ret = false; 3393 | 3394 | if (typeof encoding === 'function') { 3395 | cb = encoding; 3396 | encoding = null; 3397 | } 3398 | 3399 | if (Buffer.isBuffer(chunk)) 3400 | encoding = 'buffer'; 3401 | else if (!encoding) 3402 | encoding = state.defaultEncoding; 3403 | 3404 | if (typeof cb !== 'function') 3405 | cb = function() {}; 3406 | 3407 | if (state.ended) 3408 | writeAfterEnd(this, state, cb); 3409 | else if (validChunk(this, state, chunk, cb)) 3410 | ret = writeOrBuffer(this, state, chunk, encoding, cb); 3411 | 3412 | return ret; 3413 | }; 3414 | 3415 | function decodeChunk(state, chunk, encoding) { 3416 | if (!state.objectMode && 3417 | state.decodeStrings !== false && 3418 | typeof chunk === 'string') { 3419 | chunk = new Buffer(chunk, encoding); 3420 | } 3421 | return chunk; 3422 | } 3423 | 3424 | // if we're already writing something, then just put this 3425 | // in the queue, and wait our turn. Otherwise, call _write 3426 | // If we return false, then we need a drain event, so set that flag. 3427 | function writeOrBuffer(stream, state, chunk, encoding, cb) { 3428 | chunk = decodeChunk(state, chunk, encoding); 3429 | if (Buffer.isBuffer(chunk)) 3430 | encoding = 'buffer'; 3431 | var len = state.objectMode ? 1 : chunk.length; 3432 | 3433 | state.length += len; 3434 | 3435 | var ret = state.length < state.highWaterMark; 3436 | // we must ensure that previous needDrain will not be reset to false. 3437 | if (!ret) 3438 | state.needDrain = true; 3439 | 3440 | if (state.writing) 3441 | state.buffer.push(new WriteReq(chunk, encoding, cb)); 3442 | else 3443 | doWrite(stream, state, len, chunk, encoding, cb); 3444 | 3445 | return ret; 3446 | } 3447 | 3448 | function doWrite(stream, state, len, chunk, encoding, cb) { 3449 | state.writelen = len; 3450 | state.writecb = cb; 3451 | state.writing = true; 3452 | state.sync = true; 3453 | stream._write(chunk, encoding, state.onwrite); 3454 | state.sync = false; 3455 | } 3456 | 3457 | function onwriteError(stream, state, sync, er, cb) { 3458 | if (sync) 3459 | process.nextTick(function() { 3460 | cb(er); 3461 | }); 3462 | else 3463 | cb(er); 3464 | 3465 | stream._writableState.errorEmitted = true; 3466 | stream.emit('error', er); 3467 | } 3468 | 3469 | function onwriteStateUpdate(state) { 3470 | state.writing = false; 3471 | state.writecb = null; 3472 | state.length -= state.writelen; 3473 | state.writelen = 0; 3474 | } 3475 | 3476 | function onwrite(stream, er) { 3477 | var state = stream._writableState; 3478 | var sync = state.sync; 3479 | var cb = state.writecb; 3480 | 3481 | onwriteStateUpdate(state); 3482 | 3483 | if (er) 3484 | onwriteError(stream, state, sync, er, cb); 3485 | else { 3486 | // Check if we're actually ready to finish, but don't emit yet 3487 | var finished = needFinish(stream, state); 3488 | 3489 | if (!finished && !state.bufferProcessing && state.buffer.length) 3490 | clearBuffer(stream, state); 3491 | 3492 | if (sync) { 3493 | process.nextTick(function() { 3494 | afterWrite(stream, state, finished, cb); 3495 | }); 3496 | } else { 3497 | afterWrite(stream, state, finished, cb); 3498 | } 3499 | } 3500 | } 3501 | 3502 | function afterWrite(stream, state, finished, cb) { 3503 | if (!finished) 3504 | onwriteDrain(stream, state); 3505 | cb(); 3506 | if (finished) 3507 | finishMaybe(stream, state); 3508 | } 3509 | 3510 | // Must force callback to be called on nextTick, so that we don't 3511 | // emit 'drain' before the write() consumer gets the 'false' return 3512 | // value, and has a chance to attach a 'drain' listener. 3513 | function onwriteDrain(stream, state) { 3514 | if (state.length === 0 && state.needDrain) { 3515 | state.needDrain = false; 3516 | stream.emit('drain'); 3517 | } 3518 | } 3519 | 3520 | 3521 | // if there's something in the buffer waiting, then process it 3522 | function clearBuffer(stream, state) { 3523 | state.bufferProcessing = true; 3524 | 3525 | for (var c = 0; c < state.buffer.length; c++) { 3526 | var entry = state.buffer[c]; 3527 | var chunk = entry.chunk; 3528 | var encoding = entry.encoding; 3529 | var cb = entry.callback; 3530 | var len = state.objectMode ? 1 : chunk.length; 3531 | 3532 | doWrite(stream, state, len, chunk, encoding, cb); 3533 | 3534 | // if we didn't call the onwrite immediately, then 3535 | // it means that we need to wait until it does. 3536 | // also, that means that the chunk and cb are currently 3537 | // being processed, so move the buffer counter past them. 3538 | if (state.writing) { 3539 | c++; 3540 | break; 3541 | } 3542 | } 3543 | 3544 | state.bufferProcessing = false; 3545 | if (c < state.buffer.length) 3546 | state.buffer = state.buffer.slice(c); 3547 | else 3548 | state.buffer.length = 0; 3549 | } 3550 | 3551 | Writable.prototype._write = function(chunk, encoding, cb) { 3552 | cb(new Error('not implemented')); 3553 | }; 3554 | 3555 | Writable.prototype.end = function(chunk, encoding, cb) { 3556 | var state = this._writableState; 3557 | 3558 | if (typeof chunk === 'function') { 3559 | cb = chunk; 3560 | chunk = null; 3561 | encoding = null; 3562 | } else if (typeof encoding === 'function') { 3563 | cb = encoding; 3564 | encoding = null; 3565 | } 3566 | 3567 | if (typeof chunk !== 'undefined' && chunk !== null) 3568 | this.write(chunk, encoding); 3569 | 3570 | // ignore unnecessary end() calls. 3571 | if (!state.ending && !state.finished) 3572 | endWritable(this, state, cb); 3573 | }; 3574 | 3575 | 3576 | function needFinish(stream, state) { 3577 | return (state.ending && 3578 | state.length === 0 && 3579 | !state.finished && 3580 | !state.writing); 3581 | } 3582 | 3583 | function finishMaybe(stream, state) { 3584 | var need = needFinish(stream, state); 3585 | if (need) { 3586 | state.finished = true; 3587 | stream.emit('finish'); 3588 | } 3589 | return need; 3590 | } 3591 | 3592 | function endWritable(stream, state, cb) { 3593 | state.ending = true; 3594 | finishMaybe(stream, state); 3595 | if (cb) { 3596 | if (state.finished) 3597 | process.nextTick(cb); 3598 | else 3599 | stream.once('finish', cb); 3600 | } 3601 | state.ended = true; 3602 | } 3603 | 3604 | }).call(this,require('_process')) 3605 | },{"./_stream_duplex":12,"_process":10,"buffer":3,"core-util-is":17,"inherits":8,"stream":22}],17:[function(require,module,exports){ 3606 | (function (Buffer){ 3607 | // Copyright Joyent, Inc. and other Node contributors. 3608 | // 3609 | // Permission is hereby granted, free of charge, to any person obtaining a 3610 | // copy of this software and associated documentation files (the 3611 | // "Software"), to deal in the Software without restriction, including 3612 | // without limitation the rights to use, copy, modify, merge, publish, 3613 | // distribute, sublicense, and/or sell copies of the Software, and to permit 3614 | // persons to whom the Software is furnished to do so, subject to the 3615 | // following conditions: 3616 | // 3617 | // The above copyright notice and this permission notice shall be included 3618 | // in all copies or substantial portions of the Software. 3619 | // 3620 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 3621 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 3622 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 3623 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 3624 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 3625 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 3626 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 3627 | 3628 | // NOTE: These type checking functions intentionally don't use `instanceof` 3629 | // because it is fragile and can be easily faked with `Object.create()`. 3630 | function isArray(ar) { 3631 | return Array.isArray(ar); 3632 | } 3633 | exports.isArray = isArray; 3634 | 3635 | function isBoolean(arg) { 3636 | return typeof arg === 'boolean'; 3637 | } 3638 | exports.isBoolean = isBoolean; 3639 | 3640 | function isNull(arg) { 3641 | return arg === null; 3642 | } 3643 | exports.isNull = isNull; 3644 | 3645 | function isNullOrUndefined(arg) { 3646 | return arg == null; 3647 | } 3648 | exports.isNullOrUndefined = isNullOrUndefined; 3649 | 3650 | function isNumber(arg) { 3651 | return typeof arg === 'number'; 3652 | } 3653 | exports.isNumber = isNumber; 3654 | 3655 | function isString(arg) { 3656 | return typeof arg === 'string'; 3657 | } 3658 | exports.isString = isString; 3659 | 3660 | function isSymbol(arg) { 3661 | return typeof arg === 'symbol'; 3662 | } 3663 | exports.isSymbol = isSymbol; 3664 | 3665 | function isUndefined(arg) { 3666 | return arg === void 0; 3667 | } 3668 | exports.isUndefined = isUndefined; 3669 | 3670 | function isRegExp(re) { 3671 | return isObject(re) && objectToString(re) === '[object RegExp]'; 3672 | } 3673 | exports.isRegExp = isRegExp; 3674 | 3675 | function isObject(arg) { 3676 | return typeof arg === 'object' && arg !== null; 3677 | } 3678 | exports.isObject = isObject; 3679 | 3680 | function isDate(d) { 3681 | return isObject(d) && objectToString(d) === '[object Date]'; 3682 | } 3683 | exports.isDate = isDate; 3684 | 3685 | function isError(e) { 3686 | return isObject(e) && 3687 | (objectToString(e) === '[object Error]' || e instanceof Error); 3688 | } 3689 | exports.isError = isError; 3690 | 3691 | function isFunction(arg) { 3692 | return typeof arg === 'function'; 3693 | } 3694 | exports.isFunction = isFunction; 3695 | 3696 | function isPrimitive(arg) { 3697 | return arg === null || 3698 | typeof arg === 'boolean' || 3699 | typeof arg === 'number' || 3700 | typeof arg === 'string' || 3701 | typeof arg === 'symbol' || // ES6 symbol 3702 | typeof arg === 'undefined'; 3703 | } 3704 | exports.isPrimitive = isPrimitive; 3705 | 3706 | function isBuffer(arg) { 3707 | return Buffer.isBuffer(arg); 3708 | } 3709 | exports.isBuffer = isBuffer; 3710 | 3711 | function objectToString(o) { 3712 | return Object.prototype.toString.call(o); 3713 | } 3714 | }).call(this,require("buffer").Buffer) 3715 | },{"buffer":3}],18:[function(require,module,exports){ 3716 | module.exports = require("./lib/_stream_passthrough.js") 3717 | 3718 | },{"./lib/_stream_passthrough.js":13}],19:[function(require,module,exports){ 3719 | var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify 3720 | exports = module.exports = require('./lib/_stream_readable.js'); 3721 | exports.Stream = Stream; 3722 | exports.Readable = exports; 3723 | exports.Writable = require('./lib/_stream_writable.js'); 3724 | exports.Duplex = require('./lib/_stream_duplex.js'); 3725 | exports.Transform = require('./lib/_stream_transform.js'); 3726 | exports.PassThrough = require('./lib/_stream_passthrough.js'); 3727 | 3728 | },{"./lib/_stream_duplex.js":12,"./lib/_stream_passthrough.js":13,"./lib/_stream_readable.js":14,"./lib/_stream_transform.js":15,"./lib/_stream_writable.js":16,"stream":22}],20:[function(require,module,exports){ 3729 | module.exports = require("./lib/_stream_transform.js") 3730 | 3731 | },{"./lib/_stream_transform.js":15}],21:[function(require,module,exports){ 3732 | module.exports = require("./lib/_stream_writable.js") 3733 | 3734 | },{"./lib/_stream_writable.js":16}],22:[function(require,module,exports){ 3735 | // Copyright Joyent, Inc. and other Node contributors. 3736 | // 3737 | // Permission is hereby granted, free of charge, to any person obtaining a 3738 | // copy of this software and associated documentation files (the 3739 | // "Software"), to deal in the Software without restriction, including 3740 | // without limitation the rights to use, copy, modify, merge, publish, 3741 | // distribute, sublicense, and/or sell copies of the Software, and to permit 3742 | // persons to whom the Software is furnished to do so, subject to the 3743 | // following conditions: 3744 | // 3745 | // The above copyright notice and this permission notice shall be included 3746 | // in all copies or substantial portions of the Software. 3747 | // 3748 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 3749 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 3750 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 3751 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 3752 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 3753 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 3754 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 3755 | 3756 | module.exports = Stream; 3757 | 3758 | var EE = require('events').EventEmitter; 3759 | var inherits = require('inherits'); 3760 | 3761 | inherits(Stream, EE); 3762 | Stream.Readable = require('readable-stream/readable.js'); 3763 | Stream.Writable = require('readable-stream/writable.js'); 3764 | Stream.Duplex = require('readable-stream/duplex.js'); 3765 | Stream.Transform = require('readable-stream/transform.js'); 3766 | Stream.PassThrough = require('readable-stream/passthrough.js'); 3767 | 3768 | // Backwards-compat with node 0.4.x 3769 | Stream.Stream = Stream; 3770 | 3771 | 3772 | 3773 | // old-style streams. Note that the pipe method (the only relevant 3774 | // part of this class) is overridden in the Readable class. 3775 | 3776 | function Stream() { 3777 | EE.call(this); 3778 | } 3779 | 3780 | Stream.prototype.pipe = function(dest, options) { 3781 | var source = this; 3782 | 3783 | function ondata(chunk) { 3784 | if (dest.writable) { 3785 | if (false === dest.write(chunk) && source.pause) { 3786 | source.pause(); 3787 | } 3788 | } 3789 | } 3790 | 3791 | source.on('data', ondata); 3792 | 3793 | function ondrain() { 3794 | if (source.readable && source.resume) { 3795 | source.resume(); 3796 | } 3797 | } 3798 | 3799 | dest.on('drain', ondrain); 3800 | 3801 | // If the 'end' option is not supplied, dest.end() will be called when 3802 | // source gets the 'end' or 'close' events. Only dest.end() once. 3803 | if (!dest._isStdio && (!options || options.end !== false)) { 3804 | source.on('end', onend); 3805 | source.on('close', onclose); 3806 | } 3807 | 3808 | var didOnEnd = false; 3809 | function onend() { 3810 | if (didOnEnd) return; 3811 | didOnEnd = true; 3812 | 3813 | dest.end(); 3814 | } 3815 | 3816 | 3817 | function onclose() { 3818 | if (didOnEnd) return; 3819 | didOnEnd = true; 3820 | 3821 | if (typeof dest.destroy === 'function') dest.destroy(); 3822 | } 3823 | 3824 | // don't leave dangling pipes when there are errors. 3825 | function onerror(er) { 3826 | cleanup(); 3827 | if (EE.listenerCount(this, 'error') === 0) { 3828 | throw er; // Unhandled stream error in pipe. 3829 | } 3830 | } 3831 | 3832 | source.on('error', onerror); 3833 | dest.on('error', onerror); 3834 | 3835 | // remove all the event listeners that were added. 3836 | function cleanup() { 3837 | source.removeListener('data', ondata); 3838 | dest.removeListener('drain', ondrain); 3839 | 3840 | source.removeListener('end', onend); 3841 | source.removeListener('close', onclose); 3842 | 3843 | source.removeListener('error', onerror); 3844 | dest.removeListener('error', onerror); 3845 | 3846 | source.removeListener('end', cleanup); 3847 | source.removeListener('close', cleanup); 3848 | 3849 | dest.removeListener('close', cleanup); 3850 | } 3851 | 3852 | source.on('end', cleanup); 3853 | source.on('close', cleanup); 3854 | 3855 | dest.on('close', cleanup); 3856 | 3857 | dest.emit('pipe', source); 3858 | 3859 | // Allow for unix-like usage: A.pipe(B).pipe(C) 3860 | return dest; 3861 | }; 3862 | 3863 | },{"events":7,"inherits":8,"readable-stream/duplex.js":11,"readable-stream/passthrough.js":18,"readable-stream/readable.js":19,"readable-stream/transform.js":20,"readable-stream/writable.js":21}],23:[function(require,module,exports){ 3864 | // Copyright Joyent, Inc. and other Node contributors. 3865 | // 3866 | // Permission is hereby granted, free of charge, to any person obtaining a 3867 | // copy of this software and associated documentation files (the 3868 | // "Software"), to deal in the Software without restriction, including 3869 | // without limitation the rights to use, copy, modify, merge, publish, 3870 | // distribute, sublicense, and/or sell copies of the Software, and to permit 3871 | // persons to whom the Software is furnished to do so, subject to the 3872 | // following conditions: 3873 | // 3874 | // The above copyright notice and this permission notice shall be included 3875 | // in all copies or substantial portions of the Software. 3876 | // 3877 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 3878 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 3879 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 3880 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 3881 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 3882 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 3883 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 3884 | 3885 | var Buffer = require('buffer').Buffer; 3886 | 3887 | var isBufferEncoding = Buffer.isEncoding 3888 | || function(encoding) { 3889 | switch (encoding && encoding.toLowerCase()) { 3890 | 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': return true; 3891 | default: return false; 3892 | } 3893 | } 3894 | 3895 | 3896 | function assertEncoding(encoding) { 3897 | if (encoding && !isBufferEncoding(encoding)) { 3898 | throw new Error('Unknown encoding: ' + encoding); 3899 | } 3900 | } 3901 | 3902 | // StringDecoder provides an interface for efficiently splitting a series of 3903 | // buffers into a series of JS strings without breaking apart multi-byte 3904 | // characters. CESU-8 is handled as part of the UTF-8 encoding. 3905 | // 3906 | // @TODO Handling all encodings inside a single object makes it very difficult 3907 | // to reason about this code, so it should be split up in the future. 3908 | // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code 3909 | // points as used by CESU-8. 3910 | var StringDecoder = exports.StringDecoder = function(encoding) { 3911 | this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); 3912 | assertEncoding(encoding); 3913 | switch (this.encoding) { 3914 | case 'utf8': 3915 | // CESU-8 represents each of Surrogate Pair by 3-bytes 3916 | this.surrogateSize = 3; 3917 | break; 3918 | case 'ucs2': 3919 | case 'utf16le': 3920 | // UTF-16 represents each of Surrogate Pair by 2-bytes 3921 | this.surrogateSize = 2; 3922 | this.detectIncompleteChar = utf16DetectIncompleteChar; 3923 | break; 3924 | case 'base64': 3925 | // Base-64 stores 3 bytes in 4 chars, and pads the remainder. 3926 | this.surrogateSize = 3; 3927 | this.detectIncompleteChar = base64DetectIncompleteChar; 3928 | break; 3929 | default: 3930 | this.write = passThroughWrite; 3931 | return; 3932 | } 3933 | 3934 | // Enough space to store all bytes of a single character. UTF-8 needs 4 3935 | // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). 3936 | this.charBuffer = new Buffer(6); 3937 | // Number of bytes received for the current incomplete multi-byte character. 3938 | this.charReceived = 0; 3939 | // Number of bytes expected for the current incomplete multi-byte character. 3940 | this.charLength = 0; 3941 | }; 3942 | 3943 | 3944 | // write decodes the given buffer and returns it as JS string that is 3945 | // guaranteed to not contain any partial multi-byte characters. Any partial 3946 | // character found at the end of the buffer is buffered up, and will be 3947 | // returned when calling write again with the remaining bytes. 3948 | // 3949 | // Note: Converting a Buffer containing an orphan surrogate to a String 3950 | // currently works, but converting a String to a Buffer (via `new Buffer`, or 3951 | // Buffer#write) will replace incomplete surrogates with the unicode 3952 | // replacement character. See https://codereview.chromium.org/121173009/ . 3953 | StringDecoder.prototype.write = function(buffer) { 3954 | var charStr = ''; 3955 | // if our last write ended with an incomplete multibyte character 3956 | while (this.charLength) { 3957 | // determine how many remaining bytes this buffer has to offer for this char 3958 | var available = (buffer.length >= this.charLength - this.charReceived) ? 3959 | this.charLength - this.charReceived : 3960 | buffer.length; 3961 | 3962 | // add the new bytes to the char buffer 3963 | buffer.copy(this.charBuffer, this.charReceived, 0, available); 3964 | this.charReceived += available; 3965 | 3966 | if (this.charReceived < this.charLength) { 3967 | // still not enough chars in this buffer? wait for more ... 3968 | return ''; 3969 | } 3970 | 3971 | // remove bytes belonging to the current character from the buffer 3972 | buffer = buffer.slice(available, buffer.length); 3973 | 3974 | // get the character that was split 3975 | charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); 3976 | 3977 | // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character 3978 | var charCode = charStr.charCodeAt(charStr.length - 1); 3979 | if (charCode >= 0xD800 && charCode <= 0xDBFF) { 3980 | this.charLength += this.surrogateSize; 3981 | charStr = ''; 3982 | continue; 3983 | } 3984 | this.charReceived = this.charLength = 0; 3985 | 3986 | // if there are no more bytes in this buffer, just emit our char 3987 | if (buffer.length === 0) { 3988 | return charStr; 3989 | } 3990 | break; 3991 | } 3992 | 3993 | // determine and set charLength / charReceived 3994 | this.detectIncompleteChar(buffer); 3995 | 3996 | var end = buffer.length; 3997 | if (this.charLength) { 3998 | // buffer the incomplete character bytes we got 3999 | buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); 4000 | end -= this.charReceived; 4001 | } 4002 | 4003 | charStr += buffer.toString(this.encoding, 0, end); 4004 | 4005 | var end = charStr.length - 1; 4006 | var charCode = charStr.charCodeAt(end); 4007 | // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character 4008 | if (charCode >= 0xD800 && charCode <= 0xDBFF) { 4009 | var size = this.surrogateSize; 4010 | this.charLength += size; 4011 | this.charReceived += size; 4012 | this.charBuffer.copy(this.charBuffer, size, 0, size); 4013 | buffer.copy(this.charBuffer, 0, 0, size); 4014 | return charStr.substring(0, end); 4015 | } 4016 | 4017 | // or just emit the charStr 4018 | return charStr; 4019 | }; 4020 | 4021 | // detectIncompleteChar determines if there is an incomplete UTF-8 character at 4022 | // the end of the given buffer. If so, it sets this.charLength to the byte 4023 | // length that character, and sets this.charReceived to the number of bytes 4024 | // that are available for this character. 4025 | StringDecoder.prototype.detectIncompleteChar = function(buffer) { 4026 | // determine how many bytes we have to check at the end of this buffer 4027 | var i = (buffer.length >= 3) ? 3 : buffer.length; 4028 | 4029 | // Figure out if one of the last i bytes of our buffer announces an 4030 | // incomplete char. 4031 | for (; i > 0; i--) { 4032 | var c = buffer[buffer.length - i]; 4033 | 4034 | // See http://en.wikipedia.org/wiki/UTF-8#Description 4035 | 4036 | // 110XXXXX 4037 | if (i == 1 && c >> 5 == 0x06) { 4038 | this.charLength = 2; 4039 | break; 4040 | } 4041 | 4042 | // 1110XXXX 4043 | if (i <= 2 && c >> 4 == 0x0E) { 4044 | this.charLength = 3; 4045 | break; 4046 | } 4047 | 4048 | // 11110XXX 4049 | if (i <= 3 && c >> 3 == 0x1E) { 4050 | this.charLength = 4; 4051 | break; 4052 | } 4053 | } 4054 | this.charReceived = i; 4055 | }; 4056 | 4057 | StringDecoder.prototype.end = function(buffer) { 4058 | var res = ''; 4059 | if (buffer && buffer.length) 4060 | res = this.write(buffer); 4061 | 4062 | if (this.charReceived) { 4063 | var cr = this.charReceived; 4064 | var buf = this.charBuffer; 4065 | var enc = this.encoding; 4066 | res += buf.slice(0, cr).toString(enc); 4067 | } 4068 | 4069 | return res; 4070 | }; 4071 | 4072 | function passThroughWrite(buffer) { 4073 | return buffer.toString(this.encoding); 4074 | } 4075 | 4076 | function utf16DetectIncompleteChar(buffer) { 4077 | this.charReceived = buffer.length % 2; 4078 | this.charLength = this.charReceived ? 2 : 0; 4079 | } 4080 | 4081 | function base64DetectIncompleteChar(buffer) { 4082 | this.charReceived = buffer.length % 3; 4083 | this.charLength = this.charReceived ? 3 : 0; 4084 | } 4085 | 4086 | },{"buffer":3}],24:[function(require,module,exports){ 4087 | module.exports = function isBuffer(arg) { 4088 | return arg && typeof arg === 'object' 4089 | && typeof arg.copy === 'function' 4090 | && typeof arg.fill === 'function' 4091 | && typeof arg.readUInt8 === 'function'; 4092 | } 4093 | },{}],25:[function(require,module,exports){ 4094 | (function (process,global){ 4095 | // Copyright Joyent, Inc. and other Node contributors. 4096 | // 4097 | // Permission is hereby granted, free of charge, to any person obtaining a 4098 | // copy of this software and associated documentation files (the 4099 | // "Software"), to deal in the Software without restriction, including 4100 | // without limitation the rights to use, copy, modify, merge, publish, 4101 | // distribute, sublicense, and/or sell copies of the Software, and to permit 4102 | // persons to whom the Software is furnished to do so, subject to the 4103 | // following conditions: 4104 | // 4105 | // The above copyright notice and this permission notice shall be included 4106 | // in all copies or substantial portions of the Software. 4107 | // 4108 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 4109 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 4110 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 4111 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 4112 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 4113 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 4114 | // USE OR OTHER DEALINGS IN THE SOFTWARE. 4115 | 4116 | var formatRegExp = /%[sdj%]/g; 4117 | exports.format = function(f) { 4118 | if (!isString(f)) { 4119 | var objects = []; 4120 | for (var i = 0; i < arguments.length; i++) { 4121 | objects.push(inspect(arguments[i])); 4122 | } 4123 | return objects.join(' '); 4124 | } 4125 | 4126 | var i = 1; 4127 | var args = arguments; 4128 | var len = args.length; 4129 | var str = String(f).replace(formatRegExp, function(x) { 4130 | if (x === '%%') return '%'; 4131 | if (i >= len) return x; 4132 | switch (x) { 4133 | case '%s': return String(args[i++]); 4134 | case '%d': return Number(args[i++]); 4135 | case '%j': 4136 | try { 4137 | return JSON.stringify(args[i++]); 4138 | } catch (_) { 4139 | return '[Circular]'; 4140 | } 4141 | default: 4142 | return x; 4143 | } 4144 | }); 4145 | for (var x = args[i]; i < len; x = args[++i]) { 4146 | if (isNull(x) || !isObject(x)) { 4147 | str += ' ' + x; 4148 | } else { 4149 | str += ' ' + inspect(x); 4150 | } 4151 | } 4152 | return str; 4153 | }; 4154 | 4155 | 4156 | // Mark that a method should not be used. 4157 | // Returns a modified function which warns once by default. 4158 | // If --no-deprecation is set, then it is a no-op. 4159 | exports.deprecate = function(fn, msg) { 4160 | // Allow for deprecating things in the process of starting up. 4161 | if (isUndefined(global.process)) { 4162 | return function() { 4163 | return exports.deprecate(fn, msg).apply(this, arguments); 4164 | }; 4165 | } 4166 | 4167 | if (process.noDeprecation === true) { 4168 | return fn; 4169 | } 4170 | 4171 | var warned = false; 4172 | function deprecated() { 4173 | if (!warned) { 4174 | if (process.throwDeprecation) { 4175 | throw new Error(msg); 4176 | } else if (process.traceDeprecation) { 4177 | console.trace(msg); 4178 | } else { 4179 | console.error(msg); 4180 | } 4181 | warned = true; 4182 | } 4183 | return fn.apply(this, arguments); 4184 | } 4185 | 4186 | return deprecated; 4187 | }; 4188 | 4189 | 4190 | var debugs = {}; 4191 | var debugEnviron; 4192 | exports.debuglog = function(set) { 4193 | if (isUndefined(debugEnviron)) 4194 | debugEnviron = process.env.NODE_DEBUG || ''; 4195 | set = set.toUpperCase(); 4196 | if (!debugs[set]) { 4197 | if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { 4198 | var pid = process.pid; 4199 | debugs[set] = function() { 4200 | var msg = exports.format.apply(exports, arguments); 4201 | console.error('%s %d: %s', set, pid, msg); 4202 | }; 4203 | } else { 4204 | debugs[set] = function() {}; 4205 | } 4206 | } 4207 | return debugs[set]; 4208 | }; 4209 | 4210 | 4211 | /** 4212 | * Echos the value of a value. Trys to print the value out 4213 | * in the best way possible given the different types. 4214 | * 4215 | * @param {Object} obj The object to print out. 4216 | * @param {Object} opts Optional options object that alters the output. 4217 | */ 4218 | /* legacy: obj, showHidden, depth, colors*/ 4219 | function inspect(obj, opts) { 4220 | // default options 4221 | var ctx = { 4222 | seen: [], 4223 | stylize: stylizeNoColor 4224 | }; 4225 | // legacy... 4226 | if (arguments.length >= 3) ctx.depth = arguments[2]; 4227 | if (arguments.length >= 4) ctx.colors = arguments[3]; 4228 | if (isBoolean(opts)) { 4229 | // legacy... 4230 | ctx.showHidden = opts; 4231 | } else if (opts) { 4232 | // got an "options" object 4233 | exports._extend(ctx, opts); 4234 | } 4235 | // set default options 4236 | if (isUndefined(ctx.showHidden)) ctx.showHidden = false; 4237 | if (isUndefined(ctx.depth)) ctx.depth = 2; 4238 | if (isUndefined(ctx.colors)) ctx.colors = false; 4239 | if (isUndefined(ctx.customInspect)) ctx.customInspect = true; 4240 | if (ctx.colors) ctx.stylize = stylizeWithColor; 4241 | return formatValue(ctx, obj, ctx.depth); 4242 | } 4243 | exports.inspect = inspect; 4244 | 4245 | 4246 | // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics 4247 | inspect.colors = { 4248 | 'bold' : [1, 22], 4249 | 'italic' : [3, 23], 4250 | 'underline' : [4, 24], 4251 | 'inverse' : [7, 27], 4252 | 'white' : [37, 39], 4253 | 'grey' : [90, 39], 4254 | 'black' : [30, 39], 4255 | 'blue' : [34, 39], 4256 | 'cyan' : [36, 39], 4257 | 'green' : [32, 39], 4258 | 'magenta' : [35, 39], 4259 | 'red' : [31, 39], 4260 | 'yellow' : [33, 39] 4261 | }; 4262 | 4263 | // Don't use 'blue' not visible on cmd.exe 4264 | inspect.styles = { 4265 | 'special': 'cyan', 4266 | 'number': 'yellow', 4267 | 'boolean': 'yellow', 4268 | 'undefined': 'grey', 4269 | 'null': 'bold', 4270 | 'string': 'green', 4271 | 'date': 'magenta', 4272 | // "name": intentionally not styling 4273 | 'regexp': 'red' 4274 | }; 4275 | 4276 | 4277 | function stylizeWithColor(str, styleType) { 4278 | var style = inspect.styles[styleType]; 4279 | 4280 | if (style) { 4281 | return '\u001b[' + inspect.colors[style][0] + 'm' + str + 4282 | '\u001b[' + inspect.colors[style][1] + 'm'; 4283 | } else { 4284 | return str; 4285 | } 4286 | } 4287 | 4288 | 4289 | function stylizeNoColor(str, styleType) { 4290 | return str; 4291 | } 4292 | 4293 | 4294 | function arrayToHash(array) { 4295 | var hash = {}; 4296 | 4297 | array.forEach(function(val, idx) { 4298 | hash[val] = true; 4299 | }); 4300 | 4301 | return hash; 4302 | } 4303 | 4304 | 4305 | function formatValue(ctx, value, recurseTimes) { 4306 | // Provide a hook for user-specified inspect functions. 4307 | // Check that value is an object with an inspect function on it 4308 | if (ctx.customInspect && 4309 | value && 4310 | isFunction(value.inspect) && 4311 | // Filter out the util module, it's inspect function is special 4312 | value.inspect !== exports.inspect && 4313 | // Also filter out any prototype objects using the circular check. 4314 | !(value.constructor && value.constructor.prototype === value)) { 4315 | var ret = value.inspect(recurseTimes, ctx); 4316 | if (!isString(ret)) { 4317 | ret = formatValue(ctx, ret, recurseTimes); 4318 | } 4319 | return ret; 4320 | } 4321 | 4322 | // Primitive types cannot have properties 4323 | var primitive = formatPrimitive(ctx, value); 4324 | if (primitive) { 4325 | return primitive; 4326 | } 4327 | 4328 | // Look up the keys of the object. 4329 | var keys = Object.keys(value); 4330 | var visibleKeys = arrayToHash(keys); 4331 | 4332 | if (ctx.showHidden) { 4333 | keys = Object.getOwnPropertyNames(value); 4334 | } 4335 | 4336 | // IE doesn't make error fields non-enumerable 4337 | // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx 4338 | if (isError(value) 4339 | && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { 4340 | return formatError(value); 4341 | } 4342 | 4343 | // Some type of object without properties can be shortcutted. 4344 | if (keys.length === 0) { 4345 | if (isFunction(value)) { 4346 | var name = value.name ? ': ' + value.name : ''; 4347 | return ctx.stylize('[Function' + name + ']', 'special'); 4348 | } 4349 | if (isRegExp(value)) { 4350 | return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); 4351 | } 4352 | if (isDate(value)) { 4353 | return ctx.stylize(Date.prototype.toString.call(value), 'date'); 4354 | } 4355 | if (isError(value)) { 4356 | return formatError(value); 4357 | } 4358 | } 4359 | 4360 | var base = '', array = false, braces = ['{', '}']; 4361 | 4362 | // Make Array say that they are Array 4363 | if (isArray(value)) { 4364 | array = true; 4365 | braces = ['[', ']']; 4366 | } 4367 | 4368 | // Make functions say that they are functions 4369 | if (isFunction(value)) { 4370 | var n = value.name ? ': ' + value.name : ''; 4371 | base = ' [Function' + n + ']'; 4372 | } 4373 | 4374 | // Make RegExps say that they are RegExps 4375 | if (isRegExp(value)) { 4376 | base = ' ' + RegExp.prototype.toString.call(value); 4377 | } 4378 | 4379 | // Make dates with properties first say the date 4380 | if (isDate(value)) { 4381 | base = ' ' + Date.prototype.toUTCString.call(value); 4382 | } 4383 | 4384 | // Make error with message first say the error 4385 | if (isError(value)) { 4386 | base = ' ' + formatError(value); 4387 | } 4388 | 4389 | if (keys.length === 0 && (!array || value.length == 0)) { 4390 | return braces[0] + base + braces[1]; 4391 | } 4392 | 4393 | if (recurseTimes < 0) { 4394 | if (isRegExp(value)) { 4395 | return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); 4396 | } else { 4397 | return ctx.stylize('[Object]', 'special'); 4398 | } 4399 | } 4400 | 4401 | ctx.seen.push(value); 4402 | 4403 | var output; 4404 | if (array) { 4405 | output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); 4406 | } else { 4407 | output = keys.map(function(key) { 4408 | return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); 4409 | }); 4410 | } 4411 | 4412 | ctx.seen.pop(); 4413 | 4414 | return reduceToSingleString(output, base, braces); 4415 | } 4416 | 4417 | 4418 | function formatPrimitive(ctx, value) { 4419 | if (isUndefined(value)) 4420 | return ctx.stylize('undefined', 'undefined'); 4421 | if (isString(value)) { 4422 | var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') 4423 | .replace(/'/g, "\\'") 4424 | .replace(/\\"/g, '"') + '\''; 4425 | return ctx.stylize(simple, 'string'); 4426 | } 4427 | if (isNumber(value)) 4428 | return ctx.stylize('' + value, 'number'); 4429 | if (isBoolean(value)) 4430 | return ctx.stylize('' + value, 'boolean'); 4431 | // For some reason typeof null is "object", so special case here. 4432 | if (isNull(value)) 4433 | return ctx.stylize('null', 'null'); 4434 | } 4435 | 4436 | 4437 | function formatError(value) { 4438 | return '[' + Error.prototype.toString.call(value) + ']'; 4439 | } 4440 | 4441 | 4442 | function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { 4443 | var output = []; 4444 | for (var i = 0, l = value.length; i < l; ++i) { 4445 | if (hasOwnProperty(value, String(i))) { 4446 | output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, 4447 | String(i), true)); 4448 | } else { 4449 | output.push(''); 4450 | } 4451 | } 4452 | keys.forEach(function(key) { 4453 | if (!key.match(/^\d+$/)) { 4454 | output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, 4455 | key, true)); 4456 | } 4457 | }); 4458 | return output; 4459 | } 4460 | 4461 | 4462 | function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { 4463 | var name, str, desc; 4464 | desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; 4465 | if (desc.get) { 4466 | if (desc.set) { 4467 | str = ctx.stylize('[Getter/Setter]', 'special'); 4468 | } else { 4469 | str = ctx.stylize('[Getter]', 'special'); 4470 | } 4471 | } else { 4472 | if (desc.set) { 4473 | str = ctx.stylize('[Setter]', 'special'); 4474 | } 4475 | } 4476 | if (!hasOwnProperty(visibleKeys, key)) { 4477 | name = '[' + key + ']'; 4478 | } 4479 | if (!str) { 4480 | if (ctx.seen.indexOf(desc.value) < 0) { 4481 | if (isNull(recurseTimes)) { 4482 | str = formatValue(ctx, desc.value, null); 4483 | } else { 4484 | str = formatValue(ctx, desc.value, recurseTimes - 1); 4485 | } 4486 | if (str.indexOf('\n') > -1) { 4487 | if (array) { 4488 | str = str.split('\n').map(function(line) { 4489 | return ' ' + line; 4490 | }).join('\n').substr(2); 4491 | } else { 4492 | str = '\n' + str.split('\n').map(function(line) { 4493 | return ' ' + line; 4494 | }).join('\n'); 4495 | } 4496 | } 4497 | } else { 4498 | str = ctx.stylize('[Circular]', 'special'); 4499 | } 4500 | } 4501 | if (isUndefined(name)) { 4502 | if (array && key.match(/^\d+$/)) { 4503 | return str; 4504 | } 4505 | name = JSON.stringify('' + key); 4506 | if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { 4507 | name = name.substr(1, name.length - 2); 4508 | name = ctx.stylize(name, 'name'); 4509 | } else { 4510 | name = name.replace(/'/g, "\\'") 4511 | .replace(/\\"/g, '"') 4512 | .replace(/(^"|"$)/g, "'"); 4513 | name = ctx.stylize(name, 'string'); 4514 | } 4515 | } 4516 | 4517 | return name + ': ' + str; 4518 | } 4519 | 4520 | 4521 | function reduceToSingleString(output, base, braces) { 4522 | var numLinesEst = 0; 4523 | var length = output.reduce(function(prev, cur) { 4524 | numLinesEst++; 4525 | if (cur.indexOf('\n') >= 0) numLinesEst++; 4526 | return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; 4527 | }, 0); 4528 | 4529 | if (length > 60) { 4530 | return braces[0] + 4531 | (base === '' ? '' : base + '\n ') + 4532 | ' ' + 4533 | output.join(',\n ') + 4534 | ' ' + 4535 | braces[1]; 4536 | } 4537 | 4538 | return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; 4539 | } 4540 | 4541 | 4542 | // NOTE: These type checking functions intentionally don't use `instanceof` 4543 | // because it is fragile and can be easily faked with `Object.create()`. 4544 | function isArray(ar) { 4545 | return Array.isArray(ar); 4546 | } 4547 | exports.isArray = isArray; 4548 | 4549 | function isBoolean(arg) { 4550 | return typeof arg === 'boolean'; 4551 | } 4552 | exports.isBoolean = isBoolean; 4553 | 4554 | function isNull(arg) { 4555 | return arg === null; 4556 | } 4557 | exports.isNull = isNull; 4558 | 4559 | function isNullOrUndefined(arg) { 4560 | return arg == null; 4561 | } 4562 | exports.isNullOrUndefined = isNullOrUndefined; 4563 | 4564 | function isNumber(arg) { 4565 | return typeof arg === 'number'; 4566 | } 4567 | exports.isNumber = isNumber; 4568 | 4569 | function isString(arg) { 4570 | return typeof arg === 'string'; 4571 | } 4572 | exports.isString = isString; 4573 | 4574 | function isSymbol(arg) { 4575 | return typeof arg === 'symbol'; 4576 | } 4577 | exports.isSymbol = isSymbol; 4578 | 4579 | function isUndefined(arg) { 4580 | return arg === void 0; 4581 | } 4582 | exports.isUndefined = isUndefined; 4583 | 4584 | function isRegExp(re) { 4585 | return isObject(re) && objectToString(re) === '[object RegExp]'; 4586 | } 4587 | exports.isRegExp = isRegExp; 4588 | 4589 | function isObject(arg) { 4590 | return typeof arg === 'object' && arg !== null; 4591 | } 4592 | exports.isObject = isObject; 4593 | 4594 | function isDate(d) { 4595 | return isObject(d) && objectToString(d) === '[object Date]'; 4596 | } 4597 | exports.isDate = isDate; 4598 | 4599 | function isError(e) { 4600 | return isObject(e) && 4601 | (objectToString(e) === '[object Error]' || e instanceof Error); 4602 | } 4603 | exports.isError = isError; 4604 | 4605 | function isFunction(arg) { 4606 | return typeof arg === 'function'; 4607 | } 4608 | exports.isFunction = isFunction; 4609 | 4610 | function isPrimitive(arg) { 4611 | return arg === null || 4612 | typeof arg === 'boolean' || 4613 | typeof arg === 'number' || 4614 | typeof arg === 'string' || 4615 | typeof arg === 'symbol' || // ES6 symbol 4616 | typeof arg === 'undefined'; 4617 | } 4618 | exports.isPrimitive = isPrimitive; 4619 | 4620 | exports.isBuffer = require('./support/isBuffer'); 4621 | 4622 | function objectToString(o) { 4623 | return Object.prototype.toString.call(o); 4624 | } 4625 | 4626 | 4627 | function pad(n) { 4628 | return n < 10 ? '0' + n.toString(10) : n.toString(10); 4629 | } 4630 | 4631 | 4632 | var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 4633 | 'Oct', 'Nov', 'Dec']; 4634 | 4635 | // 26 Feb 16:19:34 4636 | function timestamp() { 4637 | var d = new Date(); 4638 | var time = [pad(d.getHours()), 4639 | pad(d.getMinutes()), 4640 | pad(d.getSeconds())].join(':'); 4641 | return [d.getDate(), months[d.getMonth()], time].join(' '); 4642 | } 4643 | 4644 | 4645 | // log is just a thin wrapper to console.log that prepends a timestamp 4646 | exports.log = function() { 4647 | console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); 4648 | }; 4649 | 4650 | 4651 | /** 4652 | * Inherit the prototype methods from one constructor into another. 4653 | * 4654 | * The Function.prototype.inherits from lang.js rewritten as a standalone 4655 | * function (not on Function.prototype). NOTE: If this file is to be loaded 4656 | * during bootstrapping this function needs to be rewritten using some native 4657 | * functions as prototype setup using normal JavaScript does not work as 4658 | * expected during bootstrapping (see mirror.js in r114903). 4659 | * 4660 | * @param {function} ctor Constructor function which needs to inherit the 4661 | * prototype. 4662 | * @param {function} superCtor Constructor function to inherit prototype from. 4663 | */ 4664 | exports.inherits = require('inherits'); 4665 | 4666 | exports._extend = function(origin, add) { 4667 | // Don't do anything if add isn't an object 4668 | if (!add || !isObject(add)) return origin; 4669 | 4670 | var keys = Object.keys(add); 4671 | var i = keys.length; 4672 | while (i--) { 4673 | origin[keys[i]] = add[keys[i]]; 4674 | } 4675 | return origin; 4676 | }; 4677 | 4678 | function hasOwnProperty(obj, prop) { 4679 | return Object.prototype.hasOwnProperty.call(obj, prop); 4680 | } 4681 | 4682 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 4683 | },{"./support/isBuffer":24,"_process":10,"inherits":8}]},{},[2])(2) 4684 | }); --------------------------------------------------------------------------------